commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
e9b422c74382d88787114796e7e4b6dfd2b25225
|
codesharer/app.py
|
codesharer/app.py
|
from flask import Flask
from flaskext.redis import Redis
def create_app():
from codesharer.apps.classifier.views import frontend
app = Flask(__name__)
app.config.from_object('codesharer.conf.Config')
app.register_module(frontend)
db = Redis(app)
db.init_app(app)
app.db = db
return app
|
from flask import Flask
from flaskext.redis import Redis
def create_app():
from codesharer.apps.snippets.views import frontend
app = Flask(__name__)
app.config.from_object('codesharer.conf.Config')
app.register_module(frontend)
db = Redis(app)
db.init_app(app)
app.db = db
return app
|
Correct path to frontend views
|
Correct path to frontend views
|
Python
|
apache-2.0
|
disqus/codebox,disqus/codebox
|
a8a0dd55a5289825aae34aa45765ea328811523e
|
spotpy/unittests/test_fast.py
|
spotpy/unittests/test_fast.py
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(203,len(results))
if __name__ == '__main__':
unittest.main()
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
# Test only untder Python 3 as Python >2.7.10 results in a strange fft error
if sys.version_info >= (3, 5):
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(203,len(results))
if __name__ == '__main__':
unittest.main()
|
Exclude Fast test for Python 2
|
Exclude Fast test for Python 2
|
Python
|
mit
|
bees4ever/spotpy,bees4ever/spotpy,thouska/spotpy,thouska/spotpy,bees4ever/spotpy,thouska/spotpy
|
e736482bec7be7871bd4edd270f8c064961c20fc
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto",
"flask",
"httpretty>=0.6.1",
"requests",
"xmltodict",
"six",
"werkzeug",
]
import sys
if sys.version_info < (2, 7):
# No buildint OrderedDict before 2.7
install_requires.append('ordereddict')
setup(
name='moto',
version='0.4.1',
description='A library that allows your python tests to easily'
' mock out the boto library',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/moto',
entry_points={
'console_scripts': [
'moto_server = moto.server:main',
],
},
packages=find_packages(exclude=("tests", "tests.*")),
install_requires=install_requires,
license="Apache",
test_suite="tests",
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Testing",
],
)
|
#!/usr/bin/env python
from __future__ import unicode_literals
from setuptools import setup, find_packages
install_requires = [
"Jinja2",
"boto>=2.20.0",
"flask",
"httpretty>=0.6.1",
"requests",
"xmltodict",
"six",
"werkzeug",
]
import sys
if sys.version_info < (2, 7):
# No buildint OrderedDict before 2.7
install_requires.append('ordereddict')
setup(
name='moto',
version='0.4.1',
description='A library that allows your python tests to easily'
' mock out the boto library',
author='Steve Pulec',
author_email='spulec@gmail',
url='https://github.com/spulec/moto',
entry_points={
'console_scripts': [
'moto_server = moto.server:main',
],
},
packages=find_packages(exclude=("tests", "tests.*")),
install_requires=install_requires,
license="Apache",
test_suite="tests",
classifiers=[
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"License :: OSI Approved :: Apache Software License",
"Topic :: Software Development :: Testing",
],
)
|
Update minimum support boto version.
|
Update minimum support boto version.
boto 2.20.0 introduces kinesis. alternatively, this requirement could be
relaxed by using conditional imports.
|
Python
|
apache-2.0
|
gjtempleton/moto,botify-labs/moto,dbfr3qs/moto,botify-labs/moto,heddle317/moto,braintreeps/moto,spulec/moto,rocky4570/moto,ZuluPro/moto,kennethd/moto,okomestudio/moto,Affirm/moto,alexdebrie/moto,Brett55/moto,riccardomc/moto,2mf/moto,heddle317/moto,rocky4570/moto,dbfr3qs/moto,botify-labs/moto,dbfr3qs/moto,2rs2ts/moto,jszwedko/moto,ImmobilienScout24/moto,okomestudio/moto,Affirm/moto,kefo/moto,gjtempleton/moto,whummer/moto,heddle317/moto,okomestudio/moto,ZuluPro/moto,whummer/moto,william-richard/moto,spulec/moto,jrydberg/moto,william-richard/moto,rouge8/moto,ludia/moto,2rs2ts/moto,okomestudio/moto,botify-labs/moto,behanceops/moto,heddle317/moto,gjtempleton/moto,2rs2ts/moto,jotes/moto,okomestudio/moto,spulec/moto,pior/moto,im-auld/moto,zonk1024/moto,spulec/moto,spulec/moto,kefo/moto,Brett55/moto,silveregg/moto,rocky4570/moto,william-richard/moto,ZuluPro/moto,okomestudio/moto,tootedom/moto,Affirm/moto,Brett55/moto,rocky4570/moto,heddle317/moto,whummer/moto,kefo/moto,william-richard/moto,EarthmanT/moto,dbfr3qs/moto,rocky4570/moto,Brett55/moto,Affirm/moto,dbfr3qs/moto,whummer/moto,ZuluPro/moto,william-richard/moto,gjtempleton/moto,dbfr3qs/moto,araines/moto,rocky4570/moto,william-richard/moto,gjtempleton/moto,botify-labs/moto,IlyaSukhanov/moto,Brett55/moto,whummer/moto,ZuluPro/moto,2rs2ts/moto,kefo/moto,whummer/moto,mrucci/moto,2rs2ts/moto,spulec/moto,botify-labs/moto,kefo/moto,Affirm/moto,Brett55/moto,ZuluPro/moto,Affirm/moto
|
522b197500bffb748dc2daf3bf0ea448b3094af7
|
example_config.py
|
example_config.py
|
"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# This should automatically be set by heroku if you've added a database to
# your app.
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class DevelopmentConfig(Config):
DEBUG = True
|
"""
File to easily switch between configurations between production and
development, etc.
"""
import os
# You must set each of these in your heroku environment with the heroku
# config:set command. See README.md for more information.
HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID',
'GITHUB_SECRET', 'DATABASE_URL',
'SQLALCHEMY_DATABASE_URI')
class Config(object):
DEBUG = False
CSRF_ENABLED = True
GITHUB_CLIENT_ID = 'replace-me'
GITHUB_SECRET = 'replace-me'
HEROKU = False
SECRET_KEY = 'not-a-good-value'
# This should automatically be set by heroku if you've added a database to
# your app.
SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']
class DevelopmentConfig(Config):
DEBUG = True
|
Add another missing heroku config variable
|
Add another missing heroku config variable
|
Python
|
agpl-3.0
|
paulocheque/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms,pluralsight/guides-cms,pluralsight/guides-cms,paulocheque/guides-cms
|
52841517a575ba7df354b809cb23bc2851c9fcd4
|
exec_proc.py
|
exec_proc.py
|
#!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from subprocess import Popen,PIPE
import shlex
import logging
class ExecProc:
def __init__(self):
self.command = None
self.debug = False
def setDebug(self,debug):
self.debug = debug
def setCommand(self,command):
if type(command) != str:
raise ValueError
self.command = command
def execute(self):
if self.command == None:
raise ValueError
# Remove Carriage Returns
command = self.command.strip('\r')
args = shlex.split(command)
if self.debug == True:
logging.info("command=\"%s\"",args)
p = Popen(args,stdout=PIPE)
o,e = p.communicate()
if self.debug == True:
logging.info("output=\"%s\"",o)
logging.info(':'.join(x.encode('hex') for x in o))
return o
|
#!/usr/bin/env python
# Copyright 2014 Boundary, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from subprocess import Popen,PIPE
import shlex
import logging
class ExecProc:
def __init__(self):
self.command = None
self.debug = False
def setDebug(self,debug):
self.debug = debug
def setCommand(self,command):
if type(command) != str:
raise ValueError
self.command = command
def execute(self):
if self.command == None:
raise ValueError
# Remove Carriage Returns
args = shlex.split(self.command)
if self.debug == True:
logging.info("command=\"%s\"",args)
p = Popen(args,stdout=PIPE)
o,e = p.communicate()
o = o.strip('\r')
if self.debug == True:
logging.info("output=\"%s\"",o)
logging.info(':'.join(x.encode('hex') for x in o))
return o
|
Remove carriage returns from the output
|
Remove carriage returns from the output
|
Python
|
apache-2.0
|
jdgwartney/boundary-plugin-shell,boundary/boundary-plugin-shell,boundary/boundary-plugin-shell,jdgwartney/boundary-plugin-shell
|
5ab0c1c1323b2b12a19ef58de4c03236db84644d
|
cellcounter/accounts/urls.py
|
cellcounter/accounts/urls.py
|
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/done/$', views.password_reset_done, name='password-reset-done'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$',
'django.contrib.auth.views.password_reset_confirm', {
'template_name': 'accounts/reset_confirm.html',
'post_reset_redirect': 'password-reset-done',
},
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
from django.conf.urls import patterns, url
from cellcounter.accounts import views
urlpatterns = patterns('',
url('^new/$', views.RegistrationView.as_view(), name='register'),
url('^(?P<pk>[0-9]+)/$', views.UserDetailView.as_view(), name='user-detail'),
url('^(?P<pk>[0-9]+)/delete/$', views.UserDeleteView.as_view(), name='user-delete'),
url('^(?P<pk>[0-9]+)/edit/$', views.UserUpdateView.as_view(), name='user-update'),
url('^password/reset/$', views.PasswordResetView.as_view(),
name='password-reset'),
url('^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[\d\w\-]+)/$',
views.PasswordResetConfirmView.as_view(),
name='password-reset-confirm'),
url('^password/change/$', views.PasswordChangeView.as_view(), name='change-password'),
)
|
Remove old views and replace with new PasswordResetConfirmView
|
Remove old views and replace with new PasswordResetConfirmView
|
Python
|
mit
|
haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter
|
f0acf5023db56e8011a6872f230514a69ec9f311
|
extractor.py
|
extractor.py
|
import extractor.ui.mainapplication as ui
import Tkinter as tk
def main():
root = tk.Tk()
root.title('SNES Wolfenstein 3D Extractor')
root.minsize(400, 100)
ui.MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
main()
|
import extractor.ui.mainapplication as ui
import Tkinter as tk
def main():
## root = tk.Tk()
## root.title('SNES Wolfenstein 3D Extractor')
## root.minsize(400, 100)
## ui.MainApplication(root).pack(side="top", fill="both", expand=True)
## root.mainloop()
ui.MainApplication().mainloop()
main()
|
Use new MainApplication Tk class.
|
Use new MainApplication Tk class.
|
Python
|
mit
|
adambiser/snes-wolf3d-extractor
|
5e53f1e86fc7c4f1c7b42479684ac393c997ce52
|
client/test/test-unrealcv.py
|
client/test/test-unrealcv.py
|
# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realistic_rendering import TestRealisticRendering
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
suites = []
load = unittest.TestLoader().loadTestsFromTestCase
s = load(TestMessageServer); suites.append(s)
s = load(TestClientWithDummyServer); suites.append(s)
if not args.travis:
s = load(TestCommands); suites.append(s)
s = load(TestRealisticRendering); suites.append(s)
suite_obj = unittest.TestSuite(suites)
unittest.TextTestRunner(verbosity = 2).run(suite_obj)
|
# TODO: Test robustness, test speed
import unittest, time, sys
from common_conf import *
from test_server import EchoServer, MessageServer
import argparse
import threading
from test_server import TestMessageServer
from test_client import TestClientWithDummyServer
from test_commands import TestCommands
from test_realistic_rendering import TestRealisticRendering
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--travis', action='store_true') # Only run test availabe to travis CI
args = parser.parse_args()
suites = []
load = unittest.TestLoader().loadTestsFromTestCase
s = load(TestMessageServer); suites.append(s)
s = load(TestClientWithDummyServer); suites.append(s)
if not args.travis:
s = load(TestCommands); suites.append(s)
s = load(TestRealisticRendering); suites.append(s)
suite_obj = unittest.TestSuite(suites)
ret = not unittest.TextTestRunner(verbosity = 2).run(suite_obj).wasSucessful()
sys.exit(ret)
|
Fix exit code of unittest.
|
Fix exit code of unittest.
|
Python
|
mit
|
qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,qiuwch/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv
|
ce9da309294f2520f297980d80773160f050e8bf
|
yubico/yubico_exceptions.py
|
yubico/yubico_exceptions.py
|
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
__all___ = [
'YubicoError',
'StatusCodeError',
'InvalidClientIdError',
'SignatureVerificationError'
]
class YubicoError(Exception):
""" Base class for Yubico related exceptions. """
pass
class StatusCodeError(YubicoError):
def __init__(self, status_code):
self.status_code = status_code
def __str__(self):
return ('Yubico server returned the following status code: %s' %
(self.status_code))
class InvalidClientIdError(YubicoError):
def __init__(self, client_id):
self.client_id = client_id
def __str__(self):
return 'The client with ID %s does not exist' % (self.client_id)
class SignatureVerificationError(YubicoError):
def __init__(self, generated_signature, response_signature):
self.generated_signature = generated_signature
self.response_signature = response_signature
def __str__(self):
return repr('Server response message signature verification failed' +
'(expected %s, got %s)' % (self.generated_signature,
self.response_signature))
|
Add __all__ in exceptions module.
|
Add __all__ in exceptions module.
|
Python
|
bsd-3-clause
|
Kami/python-yubico-client
|
b20320301eb311bb1345061a8b74ac63495051b1
|
tastydocs/urls.py
|
tastydocs/urls.py
|
from django.conf.urls.defaults import patterns
from views import doc
urlpatterns = patterns(
'',
(r'^api$', doc),
(r'^example/(?P<resource_name>\w+)/', 'tastydocs.views.example_data'),
)
|
from django.conf.urls.defaults import patterns
from views import doc
urlpatterns = patterns(
'',
(r'^api/$', doc),
(r'^example/(?P<resource_name>\w+)/', 'tastydocs.views.example_data'),
)
|
Add trailing slash to /docs/api/ url pattern. This provides more flexibility for end users in that they can choose to navigate to /docs/api or /docs/api/ successfully. Without the trailing slash in the url pattern, /docs/api/ returns a 404.
|
Add trailing slash to /docs/api/ url pattern. This provides more flexibility for end users in that they can choose to navigate to /docs/api or /docs/api/ successfully. Without the trailing slash in the url pattern, /docs/api/ returns a 404.
|
Python
|
bsd-3-clause
|
juanique/django-tastydocs,juanique/django-tastydocs,juanique/django-tastydocs,juanique/django-tastydocs
|
682f45ffd222dc582ee770a0326c962540657c68
|
django_twilio/models.py
|
django_twilio/models.py
|
# -*- coding: utf-8 -*-
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class Caller(models.Model):
"""A caller is defined uniquely by their phone number.
:param bool blacklisted: Designates whether the caller can use our
services.
:param char phone_number: Unique phone number in `E.164
<http://en.wikipedia.org/wiki/E.164>`_ format.
"""
blacklisted = models.BooleanField()
phone_number = PhoneNumberField(unique=True)
def __unicode__(self):
return str(self.phone_number) + ' (blacklisted)' if self.blacklisted else ''
|
# -*- coding: utf-8 -*-
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
class Caller(models.Model):
"""A caller is defined uniquely by their phone number.
:param bool blacklisted: Designates whether the caller can use our
services.
:param char phone_number: Unique phone number in `E.164
<http://en.wikipedia.org/wiki/E.164>`_ format.
"""
blacklisted = models.BooleanField()
phone_number = PhoneNumberField(unique=True)
def __unicode__(self):
name = str(self.phone_number)
if self.blacklisted:
name += ' (blacklisted)'
return name
|
Fix an error in __unicode__
|
Fix an error in __unicode__
__unicode__ name displaying incorrectly - FIXED
|
Python
|
unlicense
|
rdegges/django-twilio,aditweb/django-twilio
|
946f8ff1c475ebf6f339c4df5eb5f7069c5633e9
|
apps/core/views.py
|
apps/core/views.py
|
from django.views.generic.detail import ContextMixin
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from apps.categories.models import Category
from apps.books.models import Book
class BaseView(ContextMixin):
"""docstring for BaseView"""
model = Book
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
info = {
'list_book_recommendations': Book.objects.all()[0:5],
'list_top_review': Book.objects.all()[0:5],
'list_category': Category.objects.all()
}
context.update(info)
return context
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
super().dispatch(request, *args, **kwargs)
|
from django.views.generic.detail import ContextMixin
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from apps.categories.models import Category
from apps.books.models import Book
class BaseView(ContextMixin):
"""docstring for BaseView"""
model = Book
def get_context_data(self, **kwargs):
context = super(BaseView, self).get_context_data(**kwargs)
info = {
'list_book_recommendations': Book.objects.all()[0:5],
'list_top_review': Book.objects.all()[0:5],
'list_category': Category.objects.all()
}
context.update(info)
return context
class LoginRequiredMixin(object):
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super().dispatch(request, *args, **kwargs)
|
Fix did not return HttpResponse when comment
|
Fix did not return HttpResponse when comment
|
Python
|
mit
|
vuonghv/brs,vuonghv/brs,vuonghv/brs,vuonghv/brs
|
4a782f94e8fe5a26e2998408c2cb013f2aebe9ac
|
contentcuration/contentcuration/migrations/0091_auto_20180724_2243.py
|
contentcuration/contentcuration/migrations/0091_auto_20180724_2243.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-07-24 22:43
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contentcuration', '0090_auto_20180724_1625'),
]
operations = [
migrations.AlterField(
model_name='channel',
name='content_defaults',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
migrations.AlterField(
model_name='user',
name='content_defaults',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-07-24 22:43
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('contentcuration', '0089_auto_20180706_2242'),
]
operations = [
migrations.AlterField(
model_name='channel',
name='content_defaults',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
migrations.AlterField(
model_name='user',
name='content_defaults',
field=django.contrib.postgres.fields.jsonb.JSONField(default=dict),
),
]
|
Remove reference to old, bad migration that was in my local tree.
|
Remove reference to old, bad migration that was in my local tree.
|
Python
|
mit
|
jayoshih/content-curation,jayoshih/content-curation,jayoshih/content-curation,fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,DXCanas/content-curation,fle-internal/content-curation,fle-internal/content-curation,jayoshih/content-curation,DXCanas/content-curation,DXCanas/content-curation
|
69a8528801ae5c3fdde57b9766917fcf8690c54e
|
telephus/translate.py
|
telephus/translate.py
|
class APIMismatch(Exception):
pass
def translateArgs(request, api_version):
args = request.args
if request.method == 'system_add_keyspace' \
or request.method == 'system_update_keyspace':
args = adapt_ksdef_rf(args[0]) + args[1:]
return args
def postProcess(results, method):
if method == 'describe_keyspace':
results = adapt_ksdef_rf(results)
elif method == 'describe_keyspaces':
results = map(adapt_ksdef_rf, results)
return results
def adapt_ksdef_rf(ksdef):
"""
try to always have both KsDef.strategy_options['replication_factor'] and
KsDef.replication_factor available, and let the thrift api code and client
code work out what they want to use.
"""
if getattr(ksdef, 'strategy_options', None) is None:
ksdef.strategy_options = {}
if 'replication_factor' in ksdef.strategy_options:
if ksdef.replication_factor is None:
ksdef.replication_factor = int(ksdef.strategy_options['replication_factor'])
elif ksdef.replication_factor is not None:
ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor)
return ksdef
|
class APIMismatch(Exception):
pass
def translateArgs(request, api_version):
args = request.args
if request.method == 'system_add_keyspace' \
or request.method == 'system_update_keyspace':
adapted_ksdef = adapt_ksdef_rf(args[0])
args = (adapted_ksdef,) + args[1:]
return args
def postProcess(results, method):
if method == 'describe_keyspace':
results = adapt_ksdef_rf(results)
elif method == 'describe_keyspaces':
results = map(adapt_ksdef_rf, results)
return results
def adapt_ksdef_rf(ksdef):
"""
try to always have both KsDef.strategy_options['replication_factor'] and
KsDef.replication_factor available, and let the thrift api code and client
code work out what they want to use.
"""
if getattr(ksdef, 'strategy_options', None) is None:
ksdef.strategy_options = {}
if 'replication_factor' in ksdef.strategy_options:
if ksdef.replication_factor is None:
ksdef.replication_factor = int(ksdef.strategy_options['replication_factor'])
elif ksdef.replication_factor is not None:
ksdef.strategy_options['replication_factor'] = str(ksdef.replication_factor)
return ksdef
|
Fix args manipulation in when translating ksdefs
|
Fix args manipulation in when translating ksdefs
|
Python
|
mit
|
Metaswitch/Telephus,driftx/Telephus,ClearwaterCore/Telephus,driftx/Telephus,Metaswitch/Telephus,ClearwaterCore/Telephus
|
172768dacc224f3c14e85f8e732209efe9ce075a
|
app/soc/models/project_survey.py
|
app/soc/models/project_survey.py
|
#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the ProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <[email protected]>',
'"Lennard de Rijk" <[email protected]>',
]
from soc.models.survey import Survey
class ProjectSurvey(Survey):
"""Survey for Students that have a StudentProject.
"""
def __init__(self, *args, **kwargs):
super(ProjectSurvey, self).__init__(*args, **kwargs)
# TODO: prefix has to be set to gsoc_program once data has been transferred
self.prefix = 'program'
self.taking_access = 'student'
|
#!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This module contains the ProjectSurvey model.
"""
__authors__ = [
'"Daniel Diniz" <[email protected]>',
'"Lennard de Rijk" <[email protected]>',
]
from soc.models.survey import Survey
class ProjectSurvey(Survey):
"""Survey for Students that have a StudentProject.
"""
def __init__(self, *args, **kwargs):
super(ProjectSurvey, self).__init__(*args, **kwargs)
self.prefix = 'gsoc_program'
self.taking_access = 'student'
|
Set the default prefix for ProjectSurveys to gsoc_program.
|
Set the default prefix for ProjectSurveys to gsoc_program.
|
Python
|
apache-2.0
|
SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange
|
48e15b8f99bb0714b7ec465a0131e452c67004e5
|
Chapter4_TheGreatestTheoremNeverTold/top_pic_comments.py
|
Chapter4_TheGreatestTheoremNeverTold/top_pic_comments.py
|
import sys
import numpy as np
from IPython.core.display import Image
import praw
reddit = praw.Reddit("BayesianMethodsForHackers")
subreddit = reddit.get_subreddit( "pics" )
top_submissions = subreddit.get_top()
n_pic = int( sys.argv[1] ) if sys.argv[1] else 1
i = 0
while i < n_pic:
top_submission = top_submissions.next()
while "i.imgur.com" not in top_submission.url:
#make sure it is linking to an image, not a webpage.
top_submission = top_submissions.next()
i+=1
print "Title of submission: \n", top_submission.title
top_post_url = top_submission.url
#top_submission.replace_more_comments(limit=5, threshold=0)
print top_post_url
upvotes = []
downvotes = []
contents = []
_all_comments = top_submission.comments
all_comments=[]
for comment in _all_comments:
try:
upvotes.append( comment.ups )
downvotes.append( comment.downs )
contents.append( comment.body )
except Exception as e:
continue
votes = np.array( [ upvotes, downvotes] ).T
|
import sys
import numpy as np
from IPython.core.display import Image
import praw
reddit = praw.Reddit("BayesianMethodsForHackers")
subreddit = reddit.get_subreddit( "pics" )
top_submissions = subreddit.get_top()
n_pic = int( sys.argv[1] ) if len(sys.argv) > 1 else 1
i = 0
while i < n_pic:
top_submission = top_submissions.next()
while "i.imgur.com" not in top_submission.url:
#make sure it is linking to an image, not a webpage.
top_submission = top_submissions.next()
i+=1
print "Title of submission: \n", top_submission.title
top_post_url = top_submission.url
#top_submission.replace_more_comments(limit=5, threshold=0)
print top_post_url
upvotes = []
downvotes = []
contents = []
_all_comments = top_submission.comments
all_comments=[]
for comment in _all_comments:
try:
upvotes.append( comment.ups )
downvotes.append( comment.downs )
contents.append( comment.body )
except Exception as e:
continue
votes = np.array( [ upvotes, downvotes] ).T
|
Fix index to list when there is no 2nd element
|
Fix index to list when there is no 2nd element
|
Python
|
mit
|
chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,jrmontag/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ViralLeadership/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,lexual/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,chengwliu/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,aitatanit/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ifduyue/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,Fillll/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,alkalait/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,ultinomics/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,shhong/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers,noelevans/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
|
afd27c62049e87eaefbfb5f38c6b61b461656384
|
formulae/token.py
|
formulae/token.py
|
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
|
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __hash__(self):
return hash((self.type, self.lexeme, self.literal))
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return (
self.type == other.type
and self.lexeme == other.lexeme
and self.literal == other.literal
)
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
|
Add hash and eq methods to Token
|
Add hash and eq methods to Token
|
Python
|
mit
|
bambinos/formulae
|
d012763c57450555d45385ed9b254f500388618e
|
automata/render.py
|
automata/render.py
|
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnimatedGif:
""" Setup various rendering things
"""
def __init__(self, dpi=100, colors="Purples"):
self.frames = []
self.fig = plt.figure(dpi=dpi)
plt.axis("off")
self.colors = colors
self.dimensions = None
def append(self, universe):
if not self.dimensions:
if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]):
raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values")
self.dimensions = universe.shape
if self.dimensions != universe.shape:
raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape))
self.frames.append((plt.imshow(universe, cmap=self.colors),))
def render(self, filename, interval=300):
im_ani = animation.ArtistAnimation(
self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True
)
im_ani.save(filename, writer="imagemagick")
|
import matplotlib
matplotlib.use('Agg')
import matplotlib.colors
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class AnimatedGif:
""" Setup various rendering things
"""
def __init__(self, dpi=100, colors="Purples"):
self.frames = []
self.fig = plt.figure(dpi=dpi)
plt.axis("off")
self.colors = colors
self.normalize = matplotlib.colors.Normalize()
self.dimensions = None
def append(self, universe):
if not self.dimensions:
if len(universe.shape) != 2 and not (len(universe.shape) == 3 and universe.shape[2] in [3, 4]):
raise ValueError("Only handles 2D arrays of numbers, or 2D arrays of RGB(A) values")
self.dimensions = universe.shape
if self.dimensions != universe.shape:
raise ValueError("Shape changed from {} to {}".format(self.dimensions, universe.shape))
self.frames.append((plt.imshow(universe, norm=self.normalize, cmap=self.colors),))
def render(self, filename, interval=300):
im_ani = animation.ArtistAnimation(
self.fig, self.frames, interval=interval, repeat_delay=3000, blit=True
)
im_ani.save(filename, writer="imagemagick")
|
Use the same normlization for whole gif
|
Use the same normlization for whole gif
|
Python
|
apache-2.0
|
stevearm/automata
|
ce7c31f3dd97716051b72951c7c745dd2c63efcd
|
plugins/audit_logs/server/__init__.py
|
plugins/audit_logs/server/__init__.py
|
import cherrypy
import logging
from girder import auditLogger
from girder.models.model_base import Model
from girder.api.rest import getCurrentUser
class Record(Model):
def initialize(self):
self.name = 'audit_log_record'
def validate(self, doc):
return doc
class AuditLogHandler(logging.Handler):
def handle(self, record):
user = getCurrentUser()
Record().save({
'type': record.msg,
'details': record.details,
'ip': cherrypy.request.remote.ip,
'userId': user and user['_id']
})
def load(info):
auditLogger.addHandler(AuditLogHandler())
|
import cherrypy
import datetime
import logging
from girder import auditLogger
from girder.models.model_base import Model
from girder.api.rest import getCurrentUser
class Record(Model):
def initialize(self):
self.name = 'audit_log_record'
def validate(self, doc):
return doc
class AuditLogHandler(logging.Handler):
def handle(self, record):
user = getCurrentUser()
Record().save({
'type': record.msg,
'details': record.details,
'ip': cherrypy.request.remote.ip,
'userId': user and user['_id'],
'when': datetime.datetime.utcnow()
})
def load(info):
auditLogger.addHandler(AuditLogHandler())
|
Include timestamp in audit logs
|
Include timestamp in audit logs
|
Python
|
apache-2.0
|
RafaelPalomar/girder,data-exp-lab/girder,RafaelPalomar/girder,data-exp-lab/girder,girder/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,manthey/girder,jbeezley/girder,manthey/girder,girder/girder,data-exp-lab/girder,kotfic/girder,RafaelPalomar/girder,Kitware/girder,Kitware/girder,data-exp-lab/girder,kotfic/girder,girder/girder,manthey/girder,jbeezley/girder,data-exp-lab/girder,manthey/girder,girder/girder,Kitware/girder,RafaelPalomar/girder,kotfic/girder,kotfic/girder,jbeezley/girder,jbeezley/girder
|
3453b7961fae365f833199c88c7395428fcdf788
|
tensorpy/constants.py
|
tensorpy/constants.py
|
""" Defining constants for tensorpy use """
DOWNLOADS_FOLDER = "downloads_folder" # Folder created for downloaded files
MIN_W_H = 50 # Minimum width/height for classifying images on a page
MAX_THREADS = 4 # Total threads to spin up for classifying images on a page
MAX_IMAGES_PER_PAGE = 15 # Limit of image classifications per page
|
""" Defining constants for tensorpy use """
DOWNLOADS_FOLDER = "downloads_folder" # Folder created for downloaded files
MIN_W_H = 50 # Minimum width/height for classifying images on a page
MAX_THREADS = 3 # Total threads to spin up for classifying images on a page
MAX_IMAGES_PER_PAGE = 15 # Limit of image classifications per page
|
Set default max threads for multithreading to 3
|
Set default max threads for multithreading to 3
|
Python
|
mit
|
TensorPy/TensorPy,TensorPy/TensorPy
|
b2069b2b4a07d82cc6831dde0e396d7dae79d23e
|
autopidact/view.py
|
autopidact/view.py
|
from gi.repository import Gtk, GdkPixbuf, GLib
import cv2
class View(Gtk.Window):
def __init__(self, title, camera, interval=200):
Gtk.Window.__init__(self)
self.set_title(title)
self.cam = camera
self.img = Gtk.Image()
self.add(self.img)
GLib.timeout_add(interval, self.update)
def update(self):
if self.cam.isReady():
frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB)
self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None))
else:
print('not ready')
|
from gi.repository import Gtk, GdkPixbuf, GLib
import cv2
class View(Gtk.Window):
def __init__(self, title, camera, interval=200):
Gtk.Window.__init__(self)
self.set_title(title)
self.set_size_request(640, 480)
self.set_resizable(False)
self.cam = camera
self.img = Gtk.Image()
self.add(self.img)
GLib.timeout_add(interval, self.update)
def update(self):
if self.cam.isReady():
frame = cv2.cvtColor(self.cam.getFrame(), cv2.COLOR_BGR2RGB)
self.img.set_from_pixbuf(GdkPixbuf.Pixbuf.new_from_data(frame.data, GdkPixbuf.Colorspace.RGB, False, 8, frame.shape[1], frame.shape[0], frame.strides[0], None, None))
else:
print('not ready')
|
Set an initial size and disallow resizing
|
Set an initial size and disallow resizing
|
Python
|
mit
|
fkmclane/AutoPidact
|
fb01aa54032b7ab73dcd5a3e73d4ece5f36517e2
|
locations/tasks.py
|
locations/tasks.py
|
from future.standard_library import install_aliases
install_aliases() # noqa
from urllib.parse import urlparse
from celery.task import Task
from django.conf import settings
from seed_services_client import IdentityStoreApiClient
from .models import Parish
class SyncLocations(Task):
"""
Has a look at all the identity store identities, and ensures that all of
the locations assigned to identities appear in the list of locations.
"""
def get_identities(self, client):
"""
Returns an iterator over all the identities in the identity store
specified by 'client'.
"""
identities = client.get_identities()
while True:
for identity in identities.get('results', []):
yield identity
if identities.get('next') is not None:
qs = urlparse(identities['next']).query
identities = client.get_identities(params=qs)
else:
break
def run(self, **kwargs):
l = self.get_logger(**kwargs)
l.info('Starting location import')
imported_count = 0
client = IdentityStoreApiClient(
settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL)
for identity in self.get_identities(client):
parish = identity.get('details', {}).get('parish')
if parish is not None:
_, created = Parish.objects.get_or_create(name=parish.title())
if created:
imported_count += 1
l.info('Imported {} locations'.format(imported_count))
return imported_count
sync_locations = SyncLocations()
|
from future.standard_library import install_aliases
install_aliases() # noqa
from urllib.parse import urlparse
from celery.task import Task
from django.conf import settings
from seed_services_client import IdentityStoreApiClient
from .models import Parish
class SyncLocations(Task):
"""
Has a look at all the identity store identities, and ensures that all of
the locations assigned to identities appear in the list of locations.
"""
def get_identities(self, client):
"""
Returns an iterator over all the identities in the identity store
specified by 'client'.
"""
identities = client.get_identities()
while True:
for identity in identities.get('results', []):
yield identity
# If there is a next page, extract the querystring and get it
if identities.get('next') is not None:
qs = urlparse(identities['next']).query
identities = client.get_identities(params=qs)
else:
break
def run(self, **kwargs):
l = self.get_logger(**kwargs)
l.info('Starting location import')
imported_count = 0
client = IdentityStoreApiClient(
settings.IDENTITY_STORE_TOKEN, settings.IDENTITY_STORE_URL)
for identity in self.get_identities(client):
parish = identity.get('details', {}).get('parish')
if parish is not None:
_, created = Parish.objects.get_or_create(name=parish.title())
if created:
imported_count += 1
l.info('Imported {} locations'.format(imported_count))
return imported_count
sync_locations = SyncLocations()
|
Add comment to explain pagination handling
|
Add comment to explain pagination handling
|
Python
|
bsd-3-clause
|
praekelt/familyconnect-registration,praekelt/familyconnect-registration
|
e9fc291faca8af35398b958d046e951aa8471cbf
|
apps/core/tests/test_factories.py
|
apps/core/tests/test_factories.py
|
from .. import factories
from . import CoreFixturesTestCase
class AnalysisFactoryTestCase(CoreFixturesTestCase):
def test_new_factory_with_Experiments(self):
experiments = factories.ExperimentFactory.create_batch(3)
# build
analysis = factories.AnalysisFactory.build(experiments=experiments)
self.assertEqual(analysis.experiments.count(), 0)
# create
analysis = factories.AnalysisFactory(experiments=experiments)
experiments_ids = list(
analysis.experiments.values_list('id', flat=True)
)
expected_experiments_ids = [e.id for e in experiments]
self.assertEqual(experiments_ids, expected_experiments_ids)
|
from .. import factories, models
from . import CoreFixturesTestCase
class AnalysisFactoryTestCase(CoreFixturesTestCase):
def test_new_factory_with_Experiments(self):
experiments = factories.ExperimentFactory.create_batch(3)
# build
analysis = factories.AnalysisFactory.build(experiments=experiments)
self.assertEqual(analysis.experiments.count(), 0)
# create
analysis = factories.AnalysisFactory(experiments=experiments)
experiments_ids = analysis.experiments.values_list(
'id', flat=True
)
expected_experiments_ids = models.Experiment.objects.values_list(
'id', flat=True
)
self.assertEqual(
list(experiments_ids),
list(expected_experiments_ids)
)
|
Fix broken test since models new default ordering
|
Fix broken test since models new default ordering
|
Python
|
bsd-3-clause
|
Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel
|
f4e36132448a4a55bff5660b3f5a669e0095ecc5
|
awx/main/models/activity_stream.py
|
awx/main/models/activity_stream.py
|
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
OPERATION_CHOICES = [
('create', _('Entity Created')),
('update', _("Entity Updated")),
('delete', _("Entity Deleted")),
('associate', _("Entity Associated with another Entity")),
('disaassociate', _("Entity was Disassociated with another Entity"))
]
user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL)
operation = models.CharField(max_length=9, choices=OPERATION_CHOICES)
timestamp = models.DateTimeField(auto_now_add=True)
changes = models.TextField(blank=True)
object1_id = models.PositiveIntegerField(db_index=True)
object1_type = models.TextField()
object2_id = models.PositiveIntegerField(db_index=True)
object2_type = models.TextField()
object_relationship_type = models.TextField()
|
# Copyright (c) 2013 AnsibleWorks, Inc.
# All Rights Reserved.
from django.db import models
from django.utils.translation import ugettext_lazy as _
class ActivityStream(models.Model):
'''
Model used to describe activity stream (audit) events
'''
class Meta:
app_label = 'main'
OPERATION_CHOICES = [
('create', _('Entity Created')),
('update', _("Entity Updated")),
('delete', _("Entity Deleted")),
('associate', _("Entity Associated with another Entity")),
('disaassociate', _("Entity was Disassociated with another Entity"))
]
user = models.ForeignKey('auth.User', null=True, on_delete=models.SET_NULL, related_name='activity_stream')
operation = models.CharField(max_length=9, choices=OPERATION_CHOICES)
timestamp = models.DateTimeField(auto_now_add=True)
changes = models.TextField(blank=True)
object1_id = models.PositiveIntegerField(db_index=True)
object1_type = models.TextField()
object2_id = models.PositiveIntegerField(db_index=True, null=True)
object2_type = models.TextField(null=True, blank=True)
object_relationship_type = models.TextField(blank=True)
|
Fix up some issues with supporting schema migration
|
Fix up some issues with supporting schema migration
|
Python
|
apache-2.0
|
wwitzel3/awx,wwitzel3/awx,snahelou/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx
|
29eb3661ace0f3dd62d210621ebd24ef95261162
|
src/listen.py
|
src/listen.py
|
import redis
import re
from common import get_db
from datetime import datetime
MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'
def listen(args):
global MSGPATTERN
rserver = redis.Redis('localhost')
pubsub = rserver.pubsub()
pubsub.subscribe(CHANNEL)
db = get_db(args.mongohost)
for packet in pubsub.listen():
try:
if packet['type'] != 'message': continue
match = MSGPATTERN.match(packet['data'])
component = match.group(1)
level = int(match.group(2))
message = match.group(3)
db.insert(dict(
tstamp=datetime.now(),comp=component,lvl=level,msg=message))
except Exception, e:
print e, packet
|
import redis
import re
from common import get_db
from datetime import datetime
MSGPATTERN = re.compile('^(\w+)\|(\d)\|([\s\S]*)$')
CHANNEL = 'logfire'
def listen(args):
global MSGPATTERN
rserver = redis.Redis('localhost')
pubsub = rserver.pubsub()
pubsub.subscribe(CHANNEL)
db = get_db(args.mongohost)
for packet in pubsub.listen():
try:
if packet['type'] != 'message': continue
match = MSGPATTERN.match(packet['data'])
component = match.group(1)
level = int(match.group(2))
message = match.group(3)
db.insert(dict(
tstamp=datetime.utcnow(),comp=component,lvl=level,msg=message))
except Exception, e:
print e, packet
|
Make sure timestamp of log message is UTC when it goes into DB
|
Make sure timestamp of log message is UTC when it goes into DB
|
Python
|
mit
|
jay3sh/logfire,jay3sh/logfire
|
941ab0315d71fbea552b0ab12d75e4d8968adfce
|
cube2sphere/blender_init.py
|
cube2sphere/blender_init.py
|
__author__ = 'Xyene'
import bpy
import sys
import math
bpy.context.scene.cycles.resolution_x = int(sys.argv[-5])
bpy.context.scene.cycles.resolution_y = int(sys.argv[-4])
for i, name in enumerate(['bottom', 'top', 'left', 'right', 'back', 'front']):
bpy.data.images[name].filepath = "%s" % sys.argv[-6 - i]
camera = bpy.data.objects["Camera"]
camera.rotation_mode = 'XYZ'
camera.rotation_euler = (math.pi / 2 + float(sys.argv[-3]), float(sys.argv[-2]), float(sys.argv[-1]))
bpy.ops.render.render(animation=True)
|
__author__ = 'Xyene'
import bpy
import sys
import math
for scene in bpy.data.scenes:
scene.render.resolution_x = int(sys.argv[-5])
scene.render.resolution_y = int(sys.argv[-4])
scene.render.resolution_percentage = 100
scene.render.use_border = False
for i, name in enumerate(['bottom', 'top', 'left', 'right', 'back', 'front']):
bpy.data.images[name].filepath = "%s" % sys.argv[-6 - i]
camera = bpy.data.objects["Camera"]
camera.rotation_mode = 'XYZ'
camera.rotation_euler = (math.pi / 2 + float(sys.argv[-3]), float(sys.argv[-2]), float(sys.argv[-1]))
bpy.ops.render.render(animation=True)
|
Change the way we pass resolution to blender
|
Change the way we pass resolution to blender
|
Python
|
agpl-3.0
|
Xyene/cube2sphere
|
ad8d69e4c5447297db535f8ca9d1ac00e85f01e8
|
httpbin/runner.py
|
httpbin/runner.py
|
# -*- coding: utf-8 -*-
"""
httpbin.runner
~~~~~~~~~~~~~~
This module serves as a command-line runner for httpbin, powered by
gunicorn.
"""
import sys
from gevent.wsgi import WSGIServer
from httpbin import app
def main():
try:
port = int(sys.argv[1])
except (KeyError, ValueError, IndexError):
port = 5000
print 'Starting httpbin on port {0}'.format(port)
http_server = WSGIServer(('', port), app)
http_server.serve_forever()
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""
httpbin.runner
~~~~~~~~~~~~~~
This module serves as a command-line runner for httpbin, powered by
gunicorn.
"""
import sys
from gevent.pywsgi import WSGIServer
from httpbin import app
def main():
try:
port = int(sys.argv[1])
except (KeyError, ValueError, IndexError):
port = 5000
print 'Starting httpbin on port {0}'.format(port)
http_server = WSGIServer(('', port), app)
http_server.serve_forever()
if __name__ == '__main__':
main()
|
Use pywsgi.py instead of wsgi (better chunked handling)
|
Use pywsgi.py instead of wsgi (better chunked handling)
|
Python
|
isc
|
ewdurbin/httpbin,luhkevin/httpbin,Jaccorot/httpbin,yemingm/httpbin,shaunstanislaus/httpbin,mozillazg/bustard-httpbin,postmanlabs/httpbin,logonmy/httpbin,admin-zhx/httpbin,vscarpenter/httpbin,Lukasa/httpbin,Lukasa/httpbin,ashcoding/httpbin,yangruiyou85/httpbin,pestanko/httpbin,luosam1123/httpbin,mansilladev/httpbin,mojaray2k/httpbin,habibmasuro/httpbin,bradparks/httpbin__http_echo_service_for_testing_http_requests,phouse512/httpbin,OndrejPontes/httpbin,luhkevin/httpbin,paranoiasystem/httpbin,kennethreitz/httpbin,mansilladev/httpbin,gvangool/httpbin,Runscope/httpbin,habibmasuro/httpbin,krissman/httpbin,SunGuo/httpbin,nkhuyu/httpbin,vscarpenter/httpbin,yemingm/httpbin,Stackato-Apps/httpbin,gvangool/httpbin,SunGuo/httpbin,scottydelta/httpbin,hnq90/httpbin,lioonline/httpbin,bradparks/httpbin__http_echo_service_for_testing_http_requests,admin-zhx/httpbin,krissman/httpbin,pskrz/httpbin,luosam1123/httpbin,Jaccorot/httpbin,logonmy/httpbin,ewdurbin/httpbin,mozillazg/bustard-httpbin,shaunstanislaus/httpbin,yangruiyou85/httpbin,tatsuhiro-t/httpbin,nkhuyu/httpbin,ashcoding/httpbin,marinehero/httpbin,postmanlabs/httpbin,marinehero/httpbin,fangdingjun/httpbin,kennethreitz/httpbin,sigmavirus24/httpbin,paranoiasystem/httpbin,fangdingjun/httpbin,Stackato-Apps/httpbin,pskrz/httpbin,scottydelta/httpbin,mojaray2k/httpbin,phouse512/httpbin,pestanko/httpbin,OndrejPontes/httpbin,Runscope/httpbin,lioonline/httpbin,sigmavirus24/httpbin,hnq90/httpbin
|
8ddbd0b39687f46637041848ab7190bcefd57b68
|
pyramid_mongodb/__init__.py
|
pyramid_mongodb/__init__.py
|
"""
simplified mongodb integration
1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db )
import python_mongodb
def main(global_config, **settings):
## ...
# Initialize mongodb , which is a subscriber
python_mongodb.initialize_mongo_db( config , settings )
## ...
return config.make_wsgi_app()
2. in each of your envinronment.ini files, have:
mongodb.use = true
mongodb.uri = mongodb://localhost
mongodb.name = myapp
if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to )
"""
import pymongo
from gridfs import GridFS
def initialize_mongo_db( config, settings ):
if ( 'mongodb.use' in settings ) and ( settings['mongodb.use'] == 'true' ):
conn = pymongo.Connection( settings['mongodb.uri'] )
config.registry.settings['!mongodb.conn'] = conn
config.add_subscriber(add_mongo_db, 'pyramid.events.NewRequest')
def add_mongo_db(event):
settings = event.request.registry.settings
db = settings['!mongodb.conn'][settings['mongodb.name']]
event.request.mongodb = db
event.request.gridfs = GridFS(db)
|
"""
simplified mongodb integration
1. Add two lines to app/__init__.py ( the import and the call to initialize_mongo_db )
import python_mongodb
def main(global_config, **settings):
## ...
# Initialize mongodb , which is a subscriber
python_mongodb.initialize_mongo_db( config , settings )
## ...
return config.make_wsgi_app()
2. in each of your envinronment.ini files, have:
mongodb.use = true
mongodb.uri = mongodb://localhost
mongodb.name = myapp
if "mongodb.use" is not "true", then it won't be configured -- so you can do your local development / tests / etc without having mongodb running ( should you want to )
"""
import pymongo
from gridfs import GridFS
def initialize_mongo_db(config, settings):
if ('mongodb.use' in settings) and (settings['mongodb.use'] == 'true'):
conn = pymongo.Connection(settings['mongodb.uri'])
config.registry.settings['!mongodb.conn'] = conn
config.set_request_property(add_mongo_db, 'mongodb', reify=True)
def add_mongo_db(request):
settings = request.registry.settings
db = settings['!mongodb.conn'][settings['mongodb.name']]
request.mongodb = db
request.gridfs = GridFS(db)
|
Use set_request_property instead of subscriber to improve performance
|
Use set_request_property instead of subscriber to improve performance
|
Python
|
mit
|
niallo/pyramid_mongodb
|
92c024c2112573e4c4b2d1288b1ec3c7a40bc670
|
test/test_uploader.py
|
test/test_uploader.py
|
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
|
import boto3
from os import path
from lambda_uploader import uploader, config
from moto import mock_s3
EX_CONFIG = path.normpath(path.join(path.dirname(__file__),
'../test/configs'))
@mock_s3
def test_s3_upload():
mock_bucket = 'mybucket'
conn = boto3.resource('s3')
conn.create_bucket(Bucket=mock_bucket)
conf = config.Config(path.dirname(__file__),
config_file=path.join(EX_CONFIG, 'lambda.json'))
conf.set_s3(mock_bucket)
upldr = uploader.PackageUploader(conf, None)
upldr._upload_s3(path.join(path.dirname(__file__), 'dummyfile'))
# fetch the contents back out, be sure we truly uploaded the dummyfile
retrieved_bucket = conn.Object(
mock_bucket,
conf.s3_package_name()
).get()['Body']
found_contents = str(retrieved_bucket.read()).rstrip()
assert found_contents == 'dummy data'
|
Add additional assertion that the file we uploaded is correct
|
Add additional assertion that the file we uploaded is correct
We should pull back down the S3 bucket file and be sure it's the same, proving we used the boto3 API correctly. We should probably, at some point, also upload a _real_ zip file and not just a plaintext file.
|
Python
|
apache-2.0
|
rackerlabs/lambda-uploader,dsouzajude/lambda-uploader
|
cc4b68c7eccf05ca32802022b2abfd31b51bce32
|
chef/exceptions.py
|
chef/exceptions.py
|
# Exception hierarchy for chef
# Copyright (c) 2010 Noah Kantrowitz <[email protected]>
class ChefError(Exception):
"""Top-level Chef error."""
class ChefServerError(ChefError):
"""An error from a Chef server. May include a HTTP response code."""
def __init__(self, message, code=None):
ChefError.__init__(self, message)
self.code = code
|
# Exception hierarchy for chef
# Copyright (c) 2010 Noah Kantrowitz <[email protected]>
class ChefError(Exception):
"""Top-level Chef error."""
class ChefServerError(ChefError):
"""An error from a Chef server. May include a HTTP response code."""
def __init__(self, message, code=None):
super(ChefError, self).__init__(message)
self.code = code
|
Use super() for great justice.
|
Use super() for great justice.
|
Python
|
apache-2.0
|
Scalr/pychef,Scalr/pychef,cread/pychef,dipakvwarade/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,coderanger/pychef,jarosser06/pychef,jarosser06/pychef
|
f11d7232486a92bf5e9dba28432ee2ed97e02da4
|
print_web_django/api/views.py
|
print_web_django/api/views.py
|
from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all()
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
|
from rest_framework import viewsets
from . import serializers, models
class PrintJobViewSet(viewsets.ModelViewSet):
serializer_class = serializers.PrintJobSerializer
def get_queryset(self):
return self.request.user.printjobs.all().order_by('-created')
def perform_create(self, serializer):
# need to also pass the requests user on a create
serializer.save(user=self.request.user)
|
Sort by descending date created (new first)
|
Sort by descending date created (new first)
|
Python
|
mit
|
aabmass/print-web,aabmass/print-web,aabmass/print-web
|
97d6f5e7b346944ac6757fd4570bfbc7dcf52425
|
survey/admin.py
|
survey/admin.py
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from survey.models import Answer, Category, Question, Response, Survey
from .actions import make_published
class QuestionInline(admin.TabularInline):
model = Question
ordering = ("order", "category")
extra = 1
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
class SurveyAdmin(admin.ModelAdmin):
list_display = ("name", "is_published", "need_logged_user", "template")
list_filter = ("is_published", "need_logged_user")
inlines = [CategoryInline, QuestionInline]
actions = [make_published]
class AnswerBaseInline(admin.StackedInline):
fields = ("question", "body")
readonly_fields = ("question",)
extra = 0
model = Answer
class ResponseAdmin(admin.ModelAdmin):
list_display = ("interview_uuid", "survey", "created", "user")
list_filter = ("survey", "created")
date_hierarchy = "created"
inlines = [AnswerBaseInline]
# specifies the order as well as which fields to act on
readonly_fields = ("survey", "created", "updated", "interview_uuid", "user")
# admin.site.register(Question, QuestionInline)
# admin.site.register(Category, CategoryInline)
admin.site.register(Survey, SurveyAdmin)
admin.site.register(Response, ResponseAdmin)
|
# -*- coding: utf-8 -*-
from django.contrib import admin
from survey.actions import make_published
from survey.models import Answer, Category, Question, Response, Survey
class QuestionInline(admin.TabularInline):
model = Question
ordering = ("order", "category")
extra = 1
class CategoryInline(admin.TabularInline):
model = Category
extra = 0
class SurveyAdmin(admin.ModelAdmin):
list_display = ("name", "is_published", "need_logged_user", "template")
list_filter = ("is_published", "need_logged_user")
inlines = [CategoryInline, QuestionInline]
actions = [make_published]
class AnswerBaseInline(admin.StackedInline):
fields = ("question", "body")
readonly_fields = ("question",)
extra = 0
model = Answer
class ResponseAdmin(admin.ModelAdmin):
list_display = ("interview_uuid", "survey", "created", "user")
list_filter = ("survey", "created")
date_hierarchy = "created"
inlines = [AnswerBaseInline]
# specifies the order as well as which fields to act on
readonly_fields = ("survey", "created", "updated", "interview_uuid", "user")
# admin.site.register(Question, QuestionInline)
# admin.site.register(Category, CategoryInline)
admin.site.register(Survey, SurveyAdmin)
admin.site.register(Response, ResponseAdmin)
|
Fix Attempted relative import beyond top-level package
|
Fix Attempted relative import beyond top-level package
|
Python
|
agpl-3.0
|
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
|
a03eb91088943a4b3ed0ae5fc87b104562a4a645
|
location_field/urls.py
|
location_field/urls.py
|
try:
from django.conf.urls import patterns # Django>=1.6
except ImportError:
from django.conf.urls.defaults import patterns # Django<1.6
import os
app_dir = os.path.dirname(__file__)
urlpatterns = patterns(
'',
(r'^media/(.*)$', 'django.views.static.serve', {
'document_root': '%s/media' % app_dir}),
)
|
from django.conf.urls import patterns
import os
app_dir = os.path.dirname(__file__)
urlpatterns = patterns(
'',
(r'^media/(.*)$', 'django.views.static.serve', {
'document_root': '%s/media' % app_dir}),
)
|
Drop support for Django 1.6
|
Drop support for Django 1.6
|
Python
|
mit
|
Mixser/django-location-field,recklessromeo/django-location-field,Mixser/django-location-field,voodmania/django-location-field,recklessromeo/django-location-field,undernewmanagement/django-location-field,voodmania/django-location-field,caioariede/django-location-field,caioariede/django-location-field,undernewmanagement/django-location-field,Mixser/django-location-field,undernewmanagement/django-location-field,caioariede/django-location-field,recklessromeo/django-location-field,voodmania/django-location-field
|
f292cfa783bcc30c2625b340ad763db2723ce056
|
test/test_db.py
|
test/test_db.py
|
from piper.db import DbCLI
import mock
class DbCLIBase(object):
def setup_method(self, method):
self.cli = DbCLI(mock.Mock())
self.ns = mock.Mock()
self.config = mock.Mock()
class TestDbCLIRun(DbCLIBase):
def test_plain_run(self):
self.cli.cls.init = mock.Mock()
ret = self.cli.run(self.ns, self.config)
assert ret == 0
self.cli.cls.init.assert_called_once_with(self.ns, self.config)
|
from piper.db import DbCLI
from piper.db import DatabaseBase
import mock
import pytest
class DbCLIBase(object):
def setup_method(self, method):
self.cli = DbCLI(mock.Mock())
self.ns = mock.Mock()
self.config = mock.Mock()
class TestDbCLIRun(DbCLIBase):
def test_plain_run(self):
self.cli.cls.init = mock.Mock()
ret = self.cli.run(self.ns, self.config)
assert ret == 0
self.cli.cls.init.assert_called_once_with(self.ns, self.config)
class TestDatabaseBaseInit(object):
def setup_method(self, method):
self.db = DatabaseBase()
self.ns = mock.Mock()
self.config = mock.Mock()
def test_raises_not_implemented_error(self):
with pytest.raises(NotImplementedError):
self.db.init(self.ns, self.config)
|
Add tests for DatabaseBase abstraction
|
Add tests for DatabaseBase abstraction
|
Python
|
mit
|
thiderman/piper
|
1fbb79762c7e8342e840f0c1bc95c99fd981b81d
|
dariah_contributions/urls.py
|
dariah_contributions/urls.py
|
from django.conf.urls import patterns, url
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .models import Contribution
from .views import ContributionCreate, ContributionDelete, ContributionUpdate, ContributionRDF
urlpatterns = patterns('',
url(r'^(all)?/$', ListView.as_view(model=Contribution, queryset=Contribution.published.all()), name='list'),
# example: /contribution/
# example: /contribution/all/
url(r'^add/$', ContributionCreate.as_view(), name='add'),
# example: /contribution/add/
url(r'^(?P<pk>\d+)/update/$', ContributionUpdate.as_view(), name='update'),
# example: /contribution/5/update/
url(r'^(?P<pk>\d+)/delete/$', ContributionDelete.as_view(), name='delete'),
# example: /contribution/5/delete/
url(r'^(?P<pk>\d+)\.xml$', ContributionRDF.as_view(), name='detail_rdf'),
# example: /contribution/detail_rdf/5/
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Contribution, queryset=Contribution.published.all()), name='detail'),
# example: /contribution/5/
)
|
from django.conf.urls import patterns, url
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from .models import Contribution
from .views import ContributionCreate, ContributionDelete, ContributionUpdate, ContributionRDF
urlpatterns = patterns('',
url(r'^(all/)?$', ListView.as_view(model=Contribution, queryset=Contribution.published.all()), name='list'),
# example: /contribution/
# example: /contribution/all/
url(r'^add/$', ContributionCreate.as_view(), name='add'),
# example: /contribution/add/
url(r'^(?P<pk>\d+)/update/$', ContributionUpdate.as_view(), name='update'),
# example: /contribution/5/update/
url(r'^(?P<pk>\d+)/delete/$', ContributionDelete.as_view(), name='delete'),
# example: /contribution/5/delete/
url(r'^(?P<pk>\d+)\.xml$', ContributionRDF.as_view(), name='detail_rdf'),
# example: /contribution/detail_rdf/5/
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Contribution, queryset=Contribution.published.all()), name='detail'),
# example: /contribution/5/
)
|
Fix the 'contribution/all' or 'contribution/' URL.
|
Fix the 'contribution/all' or 'contribution/' URL.
|
Python
|
apache-2.0
|
DANS-KNAW/dariah-contribute,DANS-KNAW/dariah-contribute
|
63c2cc935d3c97ecb8b297ae387bfdf719cf1350
|
apps/admin/forms.py
|
apps/admin/forms.py
|
from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class LoginForm(forms.ModelForm):
"""docstring for LoginForm"""
class Meta:
model = User
fields = ['username', 'password']
class CategoryForm(forms.ModelForm):
"""docstring for CategoryForm"""
class Meta:
model = Category
fields = '__all__'
class BookForm(forms.ModelForm):
"""docstring for BookForm"""
class Meta:
model = Book
fields = ('title', 'description', 'slug', 'categories',
'pages', 'author', 'publish_date', 'cover', 'price')
widgets = {
'categories': forms.widgets.SelectMultiple(
attrs={'class': 'form-control select2',
'style': 'width: 100%;',
'multiple': "multiple"}),
}
|
from django.contrib.auth.models import User
from django import forms
from apps.categories.models import *
from apps.books.models import *
class CategoryForm(forms.ModelForm):
"""docstring for CategoryForm"""
class Meta:
model = Category
fields = '__all__'
class BookForm(forms.ModelForm):
"""docstring for BookForm"""
class Meta:
model = Book
fields = ('title', 'description', 'slug', 'categories',
'pages', 'author', 'publish_date', 'cover', 'price')
widgets = {
'categories': forms.widgets.SelectMultiple(
attrs={'class': 'form-control select2',
'style': 'width: 100%;',
'multiple': "multiple"}),
}
|
Remove unused FormLogin in admin app
|
[REMOVE] Remove unused FormLogin in admin app
|
Python
|
mit
|
vuonghv/brs,vuonghv/brs,vuonghv/brs,vuonghv/brs
|
0d33acf31254714b3a9f76d3fe97c77e7270c110
|
tests/_utils.py
|
tests/_utils.py
|
"""Utilities for tests.
"""
import codecs
import codecs
import os
import re
def strip_ansi(string):
"""Strip ANSI encoding from given string.
Parameters
----------
string : str
String from which encoding needs to be removed
Returns
-------
str
Encoding free string
"""
pattern = r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]'
return re.sub(pattern, '', string, flags=re.I)
def remove_file(filename):
"""Removes file silently.
Parameters
----------
filename : str
File name to be removed
Raises
------
Exception
If given file is not deletable
"""
try:
os.remove(filename)
except OSError as e:
if e.errno != errno.ENOENT:
raise Exception(e)
def decode_utf_8_text(text):
"""Decodes the text from utf-8 format.
Parameters
----------
text : str
Text to be decoded
Returns
-------
str
Decoded text
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
def encode_utf_8_text(text):
"""Encodes the text to utf-8 format
Parameters
----------
text : str
Text to be encoded
Returns
-------
str
Encoded text
"""
try:
return codecs.encode(text, 'utf-8')
except:
return text
|
"""Utilities for tests.
"""
import errno
import codecs
import os
import re
def strip_ansi(string):
"""Strip ANSI encoding from given string.
Parameters
----------
string : str
String from which encoding needs to be removed
Returns
-------
str
Encoding free string
"""
pattern = r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]'
return re.sub(pattern, '', string, flags=re.I)
def remove_file(filename):
"""Removes file silently.
Parameters
----------
filename : str
File name to be removed
Raises
------
Exception
If given file is not deletable
"""
try:
os.remove(filename)
except OSError as e:
if e.errno != errno.ENOENT:
raise Exception(e)
def decode_utf_8_text(text):
"""Decodes the text from utf-8 format.
Parameters
----------
text : str
Text to be decoded
Returns
-------
str
Decoded text
"""
try:
return codecs.decode(text, 'utf-8')
except:
return text
def encode_utf_8_text(text):
"""Encodes the text to utf-8 format
Parameters
----------
text : str
Text to be encoded
Returns
-------
str
Encoded text
"""
try:
return codecs.encode(text, 'utf-8')
except:
return text
|
Test Utils: Cleans up the code
|
Test Utils: Cleans up the code
|
Python
|
mit
|
manrajgrover/halo,ManrajGrover/halo
|
6f464e422befe22e56bb759a7ac7ff52a353c6d9
|
accountant/functional_tests/test_layout_and_styling.py
|
accountant/functional_tests/test_layout_and_styling.py
|
# -*- coding: utf-8 -*-
import unittest
from .base import FunctionalTestCase
from .pages import game
class StylesheetTests(FunctionalTestCase):
def test_color_css_loaded(self):
self.story('Create a game')
self.browser.get(self.live_server_url)
page = game.Homepage(self.browser)
page.start_button.click()
self.assertTrue(any('css/color.css' in s.get_attribute('href')
for s in page.stylesheets))
def test_main_stylesheet_loaded(self):
self.story('Load the start page')
self.browser.get(self.live_server_url)
page = game.Homepage(self.browser)
self.assertTrue(any('css/main.css' in s.get_attribute('href')
for s in page.stylesheets))
|
# -*- coding: utf-8 -*-
import unittest
from .base import FunctionalTestCase
from .pages import game
class StylesheetTests(FunctionalTestCase):
def test_color_css_loaded(self):
self.story('Create a game')
self.browser.get(self.live_server_url)
page = game.Homepage(self.browser)
page.start_button.click()
self.assertTrue(any('css/color.css' in s.get_attribute('href')
for s in page.stylesheets))
def test_main_stylesheet_loaded(self):
self.story('Load the start page')
self.browser.get(self.live_server_url)
page = game.Homepage(self.browser)
self.assertTrue(any('css/main.css' in s.get_attribute('href')
for s in page.stylesheets))
# Test constant to see if css actually gets loaded
self.assertEqual('rgb(55, 71, 79)',
page.bank_cash.value_of_css_property('border-color'))
|
Test is loaded CSS is applied
|
Test is loaded CSS is applied
|
Python
|
mit
|
XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant
|
517f53dc91164f4249de9dbaf31be65df02ffde7
|
numpy/fft/setup.py
|
numpy/fft/setup.py
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fft', parent_package, top_path)
config.add_data_dir('tests')
# Configure pocketfft_internal
config.add_extension('_pocketfft_internal',
sources=['_pocketfft.c']
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
import sys
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fft', parent_package, top_path)
config.add_data_dir('tests')
# AIX needs to be told to use large file support - at all times
defs = [('_LARGE_FILES', None)] if sys.platform[:3] == "aix" else []
# Configure pocketfft_internal
config.add_extension('_pocketfft_internal',
sources=['_pocketfft.c'],
define_macros=defs,
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)
|
Add _LARGE_FILES to def_macros[] when platform is AIX (gh-15938)
|
BUG: Add _LARGE_FILES to def_macros[] when platform is AIX (gh-15938)
AIX needs to be told to use large file support at all times. Fixes parts of gh-15801.
|
Python
|
bsd-3-clause
|
mhvk/numpy,pbrod/numpy,mattip/numpy,anntzer/numpy,numpy/numpy,numpy/numpy,pbrod/numpy,rgommers/numpy,numpy/numpy,endolith/numpy,abalkin/numpy,pdebuyl/numpy,grlee77/numpy,mattip/numpy,grlee77/numpy,pdebuyl/numpy,charris/numpy,charris/numpy,seberg/numpy,pbrod/numpy,grlee77/numpy,anntzer/numpy,jakirkham/numpy,seberg/numpy,rgommers/numpy,simongibbons/numpy,pdebuyl/numpy,madphysicist/numpy,endolith/numpy,abalkin/numpy,anntzer/numpy,mhvk/numpy,mhvk/numpy,jakirkham/numpy,simongibbons/numpy,mattip/numpy,simongibbons/numpy,grlee77/numpy,numpy/numpy,madphysicist/numpy,seberg/numpy,pbrod/numpy,charris/numpy,charris/numpy,endolith/numpy,madphysicist/numpy,mhvk/numpy,endolith/numpy,jakirkham/numpy,simongibbons/numpy,abalkin/numpy,madphysicist/numpy,mhvk/numpy,simongibbons/numpy,rgommers/numpy,seberg/numpy,mattip/numpy,grlee77/numpy,anntzer/numpy,jakirkham/numpy,madphysicist/numpy,pbrod/numpy,pdebuyl/numpy,rgommers/numpy,jakirkham/numpy
|
8a522bc92bbf5bee8bc32a0cc332dc77fa86fcd6
|
drcontroller/http_server.py
|
drcontroller/http_server.py
|
import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
|
import eventlet
import os
import commands
from eventlet import wsgi
from paste.deploy import loadapp
# Monkey patch socket, time, select, threads
eventlet.patcher.monkey_patch(all=False, socket=True, time=True,
select=True, thread=True, os=True)
def main():
conf = "conf/api-paste.ini"
appname = "main"
commands.getoutput('mkdir -p ../logs')
app = loadapp("config:%s" % os.path.abspath(conf), appname)
wsgi.server(eventlet.listen(('', 80)), app)
if __name__ == '__main__':
main()
|
Update http server to un-blocking
|
Update http server to un-blocking
|
Python
|
apache-2.0
|
fs714/drcontroller
|
9bc9b2ea4a53e27b4d9f5f55e2c36fe483ab2de5
|
pylancard/trainer.py
|
pylancard/trainer.py
|
import logging
import random
DIRECT = 'direct'
REVERSE = 'reverse'
LOG = logging.getLogger(__name__)
class Trainer:
def __init__(self, store, kind=DIRECT):
self.store = store
if kind == DIRECT:
self._words = list(store.direct_index.items())
self._plugin = store.meaning_plugin
elif kind == REVERSE:
self._words = list(store.reverse_index.items())
self._plugin = store.original_plugin
else:
raise ValueError("Expected kind, got %r", kind)
self.challenge = self.answer = None
def check(self, answer):
converted = self._plugin.convert_word(answer.strip())
if converted != self.answer:
LOG.info("'%(converted)s' (converted from '%(answer)s') "
"is incorrect",
locals())
return False
else:
LOG.debug("%s is accepted", converted)
return True
def next(self):
self.challenge, self.answer = random.choice(self._words)
LOG.debug("Next challenge is '%s'", self.challenge)
return self.challenge
|
import logging
import random
DIRECT = 'direct'
REVERSE = 'reverse'
LOG = logging.getLogger(__name__)
class Trainer:
def __init__(self, store, kind=DIRECT):
self.store = store
if kind == DIRECT:
self._words = list(store.direct_index.items())
self._plugin = store.meaning_plugin
elif kind == REVERSE:
self._words = list(store.reverse_index.items())
self._plugin = store.original_plugin
else:
raise ValueError("Expected kind, got %r", kind)
self.challenge = self.answer = None
self._init()
def check(self, answer):
converted = self._plugin.convert_word(answer.strip())
if converted != self.answer:
LOG.info("'%(converted)s' (converted from '%(answer)s') "
"is incorrect",
locals())
return False
else:
LOG.debug("%s is accepted", converted)
return True
def next(self):
assert len(self._words) != 0
try:
self.challenge, self.answer = self._words[self._ptr]
except IndexError:
LOG.info("All words finished, starting from the beginning")
self._init()
return self.next()
else:
self._ptr += 1
LOG.debug("Next challenge is '%s'", self.challenge)
return self.challenge
def _init(self):
self._ptr = 0
random.shuffle(self._words)
|
Initialize random sequence of words when starting training, so that words do not repeat
|
Initialize random sequence of words when starting training, so that words do not repeat
|
Python
|
bsd-2-clause
|
dtantsur/pylancard
|
620bf504292583b2547cf7489eeeaaa582ddad77
|
indra/tests/test_ctd.py
|
indra/tests/test_ctd.py
|
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 4, cp.statements
|
import os
from indra.statements import *
from indra.sources import ctd
from indra.sources.ctd.processor import CTDChemicalGeneProcessor
HERE = os.path.dirname(os.path.abspath(__file__))
def test_statement_type_mapping():
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^phosphorylation', 'X',
'X decreases the phosphorylation of Y')
assert set(st.values()) == {Dephosphorylation}, st
st = CTDChemicalGeneProcessor.get_statement_types(
'decreases^reaction|increases^phosphorylation', 'X',
'X decreases the reaction [Z increases the phosphorylation of Y]')
assert set(st.values()) == {Dephosphorylation}, st
def test_chemical_gene():
fname = os.path.join(HERE, 'ctd_chem_gene_20522546.tsv')
cp = ctd.process_tsv(fname, 'chemical_gene')
assert len(cp.statements) == 3, cp.statements
assert isinstance(cp.statements[0], Dephosphorylation)
assert cp.statements[0].enz.name == 'wortmannin'
assert isinstance(cp.statements[1], Dephosphorylation)
assert cp.statements[1].enz.name == 'YM-254890'
assert isinstance(cp.statements[2], Phosphorylation)
assert cp.statements[2].enz.name == 'zinc atom'
|
Fix and extend test conditions
|
Fix and extend test conditions
|
Python
|
bsd-2-clause
|
sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,sorgerlab/belpy
|
0e2270415b287cb643cff5023dcaacbcb2d5e3fc
|
translators/google.py
|
translators/google.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
def save_google_translation(queue, source_text, client_id, client_secret, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
translate_from=translate_from,
translate_to=translate_to)
end = time.time()
print("Google", end - begin)
except Exception as e:
print("Google failed!", e)
queue.put({'translation_google': translation})
return None
def google_translation(text, translate_from='et', translate_to='en'):
response = requests.get(url)
translation = response['data']['translations'][0]['translatedText']
print("Test", translation)
return translation
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import requests
import json
def save_google_translation(queue, source_text, translate_from='et', translate_to='en'):
translation = ''
try:
begin = time.time()
translation = google_translation(source_text,
translate_from=translate_from,
translate_to=translate_to)
end = time.time()
print("Google", end - begin)
except Exception as e:
print("Google failed!", e)
queue.put({'translation_google': translation})
return None
def google_translation(text, translate_from='et', translate_to='en'):
response = requests.get(url)
json_response = json.loads(response.text)
translation = json_response['data']['translations'][0]['translatedText']
return translation
|
Fix Google Translator request & processing
|
Fix Google Translator request & processing
|
Python
|
mit
|
ChameleonTartu/neurotolge,ChameleonTartu/neurotolge,ChameleonTartu/neurotolge
|
0f018ec9bfd0c93d980b232af325be453c065632
|
qsimcirq/_version.py
|
qsimcirq/_version.py
|
"""The version number defined here is read automatically in setup.py."""
__version__ = "0.14.0"
|
"""The version number defined here is read automatically in setup.py."""
__version__ = "0.14.1.dev20220804"
|
Update to dev version 0.14.1+dev20220804
|
Update to dev version 0.14.1+dev20220804
|
Python
|
apache-2.0
|
quantumlib/qsim,quantumlib/qsim,quantumlib/qsim,quantumlib/qsim
|
0a2dc53cd388f73064bb66e794e3af5f3e48a92f
|
bot/setup.py
|
bot/setup.py
|
from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
author_email="[email protected]",
packages=find_packages(),
entry_points={
'reviewbot.tools': [
'pep8 = reviewbot.tools.pep8:pep8Tool',
]
},
install_requires=[
'celery>=2.5',
'pep8>=0.7.0',
],
)
|
from setuptools import setup, find_packages
PACKAGE_NAME = "ReviewBot"
VERSION = "0.1"
setup(name=PACKAGE_NAME,
version=VERSION,
description="ReviewBot, the automated code reviewer",
author="Steven MacLeod",
author_email="[email protected]",
packages=find_packages(),
entry_points={
'reviewbot.tools': [
'pep8 = reviewbot.tools.pep8:pep8Tool',
]
},
install_requires=[
'celery>=3.0',
'pep8>=0.7.0',
],
)
|
Update the required version of Celery
|
Update the required version of Celery
|
Python
|
mit
|
reviewboard/ReviewBot,reviewboard/ReviewBot,reviewboard/ReviewBot,reviewboard/ReviewBot
|
1c86e9164d9df9cbb75b520b9700a5621a1116f9
|
bqx/_func.py
|
bqx/_func.py
|
from .parts import Column
def BETWEEN(expr1, expr2, expr3):
return Column('%s BETWEEN %s AND %s' % (_actual_n(expr1), _actual_n(expr2), _actual_n(expr3)))
def CAST(type1, type2):
return Column('CAST(%s AS %s)' % (type1, type2))
def CONCAT(*args):
arg = [_actual_n(a) for a in args]
arg = ', '.join(arg)
return Column('CONCAT(%s)' % arg)
def CONTAINS(exp, search_str):
return Column('%s CONTAINS %s' % (_actual_n(exp), _actual_n(search_str)))
def IN(search_expr, *expr):
return Column('%s IN(%s)' % (_actual_n(search_expr), ', '.join(_actual_n(x) for x in expr)))
def IS_NULL(expr):
return Column('%s IS NULL' % _actual_n(expr))
def _fn_factory(name):
def _fn(*col):
return Column('{0}({1})'.format(name, ','.join(_actual_n(x) for x in col)))
return _fn
def _actual_n(col):
if isinstance(col, str):
return "'%s'" % col
elif isinstance(col, Column):
return col.real_name
else:
return str(col)
|
from .parts import Column
def BETWEEN(expr1, expr2, expr3):
return Column('%s BETWEEN %s AND %s' % (_actual_n(expr1), _actual_n(expr2), _actual_n(expr3)))
def CAST(type1, type2):
return Column('CAST(%s AS %s)' % (type1, type2))
def CONCAT(*args):
arg = [_actual_n(a) for a in args]
arg = ', '.join(arg)
return Column('CONCAT(%s)' % arg)
def CONTAINS(exp, search_str):
return Column('%s CONTAINS %s' % (_actual_n(exp), _actual_n(search_str)))
def IN(search_expr, *expr):
return Column('%s IN(%s)' % (_actual_n(search_expr), ', '.join(_actual_n(x) for x in expr)))
def IS_NULL(expr):
return Column('%s IS NULL' % _actual_n(expr))
def _fn_factory(name):
def _fn(*col):
return Column('{0}({1})'.format(name, ','.join(_actual_n(x) for x in col)))
return _fn
def _actual_n(col):
if isinstance(col, str):
return "'%s'" % col
elif isinstance(col, Column):
return str(col.real_name)
else:
return str(col)
|
Fix columns not to be converted into str
|
Fix columns not to be converted into str
|
Python
|
bsd-3-clause
|
fuller-inc/bqx
|
4e8dc0ca41ee1e21a75a3e803c3b2b223d9f14cb
|
users/managers.py
|
users/managers.py
|
from django.utils import timezone
from django.contrib.auth.models import BaseUserManager
from model_utils.managers import InheritanceQuerySet
from .conf import settings
class UserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
users_auto_activate = not settings.USERS_VERIFY_EMAIL
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
is_active = extra_fields.pop('is_active', users_auto_activate)
user = self.model(email=email, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
is_staff = extra_fields.pop('is_staff', False)
return self._create_user(email, password, is_staff, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
**extra_fields)
class UserInheritanceManager(UserManager):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
|
from django.utils import timezone
from django.contrib.auth.models import BaseUserManager
from model_utils.managers import InheritanceQuerySet
from .conf import settings
class UserManager(BaseUserManager):
def _create_user(self, email, password,
is_staff, is_superuser, **extra_fields):
users_auto_activate = not settings.USERS_VERIFY_EMAIL
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
is_active = extra_fields.pop('is_active', users_auto_activate)
user = self.model(email=email, is_staff=is_staff, is_active=is_active,
is_superuser=is_superuser, last_login=now,
date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
is_staff = extra_fields.pop('is_staff', False)
return self._create_user(email, password, is_staff, False,
**extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True,
is_active=True, **extra_fields)
class UserInheritanceManager(UserManager):
def get_queryset(self):
return InheritanceQuerySet(self.model).select_subclasses()
|
Fix issue with create_superuser method on UserManager
|
Fix issue with create_superuser method on UserManager
|
Python
|
bsd-3-clause
|
mishbahr/django-users2,mishbahr/django-users2
|
818e15028c4dd158fa93fe4bcd351255585c2f4f
|
src/model/predict_rf_model.py
|
src/model/predict_rf_model.py
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
X_test = test.ix[:,1:]
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
|
import numpy as np
import pandas as pd
import sys
import os
from sklearn.externals import joblib
from sklearn.ensemble import RandomForestClassifier
scriptpath = os.path.dirname(os.path.realpath(sys.argv[0])) + '/../'
sys.path.append(os.path.abspath(scriptpath))
import utils
parameter_str = '_'.join(['top', str(utils.k), 'cw', str(utils.click_weight), 'year', utils.train_year])
cforest = joblib.load(utils.model_path + 'rf_all_without_time_' + parameter_str +'.pkl')
test = joblib.load(utils.processed_data_path + 'test_all_' + parameter_str +'.pkl')
#X_test = test.ix[:,1:]
X_test = test.ix[:9,1:]
X_test.fillna(-1, inplace=True)
print "predict RandomForest Classifier..."
probs = cforest.predict_proba(X_test)
sorted_index = np.argsort(-np.array(probs))[:,:5]
result = pd.DataFrame(columns = {'hotel_cluster'})
result['hotel_cluster'] = np.array([np.array_str(sorted_index[i])[1:-1] for i in range(sorted_index.shape[0])])
result.hotel_cluster.to_csv(utils.model_path +
'results/submission_rf_all_without_time_' + parameter_str + '.csv', header=True, index_label='id')
|
Handle missing value in predit rf
|
Handle missing value in predit rf
|
Python
|
bsd-3-clause
|
parkerzf/kaggle-expedia,parkerzf/kaggle-expedia,parkerzf/kaggle-expedia
|
a9fb1bb437e27f0bcd5a382e82f100722d9f0688
|
data_structures/circular_buffer.py
|
data_structures/circular_buffer.py
|
from .transition import Transition
class CircularBuffer(object):
def __init__(self, capacity=100000):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(Transition(*args))
else:
self.memory[self.position] = Transition(*args)
self.position = self.position % self.capacity
def get_batch(self):
return self.memory[:self.position]
def reset(self):
self.memory.clear()
self.position = 0
def __len__(self):
return len(self.memory)
|
from .transition import Transition
class CircularBuffer(object):
def __init__(self, capacity=100000):
self.capacity = capacity
self.memory = []
self.position = 0
def push(self, *args):
if len(self.memory) < self.capacity:
self.memory.append(Transition(*args))
else:
self.memory[self.position] = Transition(*args)
self.position = (self.position + 1) % self.capacity
def get_batch(self):
return self.memory[:self.position]
def reset(self):
self.memory.clear()
self.position = 0
def __len__(self):
return len(self.memory)
|
Fix index. Caught by Tudor.
|
Fix index. Caught by Tudor.
|
Python
|
mit
|
floringogianu/categorical-dqn
|
7cda2fe25dd65b3120f177d331088ce7733d1c6c
|
server.py
|
server.py
|
from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
docs = article_service.all()
return req.Response(text=docs.to_json())
def keywords(req):
"""
Retrieve articles by keywords
"""
words = req.match_dict['keywords']
docs = article_service.keywords(words)
headers = {'Content-Type': 'application/json'}
body = docs.to_json().encode()
return req.Response(body=body, headers=headers)
app = Application()
app.router.add_route('/', index)
app.router.add_route('/articles', articles)
app.router.add_route('/articles/keywords/{keywords}', keywords)
#Some bugs require us to dial to MongoDB just before server is listening
host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news'
connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False)
app.run(debug=True)
|
from japronto import Application
from services.articles import ArticleService
from mongoengine import *
article_service = ArticleService()
def index(req):
"""
The main index
"""
return req.Response(text='You reached the index!')
def articles(req):
"""
Get alll articles
"""
docs = article_service.all()
return req.Response(text=docs.to_json())
def keywords(req):
"""
Retrieve articles by keywords
"""
#AsyncIO buffer problem
req.transport.set_write_buffer_limits=4096
words = req.match_dict['keywords']
docs = article_service.keywords(words)
headers = {'Content-Type': 'application/json'}
body = docs.to_json().encode()
return req.Response(body=body, headers=headers)
app = Application()
app.router.add_route('/', index)
app.router.add_route('/articles', articles)
app.router.add_route('/articles/keywords/{keywords}', keywords)
#Some bugs require us to dial to MongoDB just before server is listening
host = 'mongodb://aws-ap-southeast-1-portal.0.dblayer.com/news'
connect(db='news',host=host, port=15501, username='azzuwan', password='Reddoor74', alias='default', connect=False)
app.run(debug=True)
|
Increase request buffer as workaround for stackoverflow in asyncio
|
Increase request buffer as workaround for stackoverflow in asyncio
|
Python
|
mit
|
azzuwan/PyApiServerExample
|
8cc8f9a1535a2361c27e9411f9163ecd2a9958d5
|
utils/__init__.py
|
utils/__init__.py
|
import pymongo
connection = pymongo.MongoClient("mongodb://localhost")
db = connection.vcf_explorer
import database
import parse_vcf
import filter_vcf
import query
|
import pymongo
import config #config.py
connection = pymongo.MongoClient(host=config.MONGODB_HOST, port=config.MONGODB_PORT)
db = connection[config.MONGODB_NAME]
import database
import parse_vcf
import filter_vcf
import query
|
Set mongodb settings using config.py
|
Set mongodb settings using config.py
|
Python
|
mit
|
CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer,CuppenResearch/vcf-explorer
|
2206681a89346970b71ca8d0ed1ff60a861b2ff9
|
doc/examples/plot_pyramid.py
|
doc/examples/plot_pyramid.py
|
"""
====================
Build image pyramids
====================
This example shows how to build image pyramids.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import img_as_float
from skimage.transform import build_gaussian_pyramid
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(build_gaussian_pyramid(image, downscale=2))
display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
display[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
display[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(display)
plt.show()
|
"""
====================
Build image pyramids
====================
The `build_gauassian_pyramid` function takes an image and yields successive
images shrunk by a constant scale factor. Image pyramids are often used, e.g.,
to implement algorithms for denoising, texture discrimination, and scale-
invariant detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import img_as_float
from skimage.transform import build_gaussian_pyramid
image = data.lena()
rows, cols, dim = image.shape
pyramid = tuple(build_gaussian_pyramid(image, downscale=2))
display = np.zeros((rows, cols + cols / 2, 3), dtype=np.double)
display[:rows, :cols, :] = pyramid[0]
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
display[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
plt.imshow(display)
plt.show()
|
Update pyramid example with longer description
|
Update pyramid example with longer description
|
Python
|
bsd-3-clause
|
chintak/scikit-image,paalge/scikit-image,keflavich/scikit-image,SamHames/scikit-image,jwiggins/scikit-image,bsipocz/scikit-image,keflavich/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,SamHames/scikit-image,youprofit/scikit-image,chintak/scikit-image,dpshelio/scikit-image,Midafi/scikit-image,WarrenWeckesser/scikits-image,ofgulban/scikit-image,bennlich/scikit-image,ajaybhat/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-image,newville/scikit-image,warmspringwinds/scikit-image,ofgulban/scikit-image,GaZ3ll3/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,ClinicalGraphics/scikit-image,almarklein/scikit-image,emon10005/scikit-image,oew1v07/scikit-image,jwiggins/scikit-image,chriscrosscutler/scikit-image,Britefury/scikit-image,vighneshbirodkar/scikit-image,Midafi/scikit-image,chintak/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,paalge/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,almarklein/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,newville/scikit-image,pratapvardhan/scikit-image,SamHames/scikit-image,michaelpacer/scikit-image,chriscrosscutler/scikit-image,juliusbierk/scikit-image,almarklein/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,ClinicalGraphics/scikit-image,SamHames/scikit-image,juliusbierk/scikit-image,dpshelio/scikit-image,blink1073/scikit-image,vighneshbirodkar/scikit-image,michaelpacer/scikit-image,rjeli/scikit-image,emon10005/scikit-image,Hiyorimi/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,Britefury/scikit-image,paalge/scikit-image,ajaybhat/scikit-image,oew1v07/scikit-image,robintw/scikit-image,michaelaye/scikit-image,robintw/scikit-image
|
1454b42049e94db896aab99e2dd1b286ca2d04e3
|
convert-bookmarks.py
|
convert-bookmarks.py
|
#!/usr/bin/env python
#
# Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json
#
from argparse import ArgumentParser
from bs4 import BeautifulSoup
from datetime import datetime, timezone
import json
parser = ArgumentParser(description='Convert Netscape bookmarks to JSON')
parser.add_argument(dest='filenames', metavar='filename', nargs='*')
parser.add_argument('-t', '--tag', metavar='tag', dest='tags',
action='append', help='add tags to bookmarks')
args = parser.parse_args()
bookmarks = []
for filename in args.filenames:
soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib")
for link in soup.find_all('a'):
bookmark = {}
bookmark['url'] = link.get('href')
bookmark['title'] = link.string.strip()
secs = link.get('add_date')
date = datetime.fromtimestamp(int(secs), tz=timezone.utc)
bookmark['add_date'] = { '$date': date.isoformat() }
bookmark['tags'] = link.get('tags').split(',')
sibling = link.parent.next_sibling
if sibling and sibling.name == 'dd':
bookmark['comment'] = sibling.string.strip()
print(json.dumps(bookmark, sort_keys=False, indent=4))
|
#!/usr/bin/env python
#
# Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json
#
from argparse import ArgumentParser
from bs4 import BeautifulSoup
from datetime import datetime, timezone
import json
parser = ArgumentParser(description='Convert Netscape bookmarks to JSON')
parser.add_argument(dest='filenames', metavar='filename', nargs='*')
parser.add_argument('-t', '--tag', metavar='tag', dest='tags',
action='append', help='add tag to bookmarks, repeat \
for multiple tags')
parser.add_argument('-m', '--mongodb', action='store_true', dest='mongo',
help='output in mongodb import format')
args = parser.parse_args()
for filename in args.filenames:
soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib")
for link in soup.find_all('a'):
bookmark = {}
bookmark['url'] = link.get('href')
bookmark['title'] = link.string.strip()
secs = link.get('add_date')
date = datetime.fromtimestamp(int(secs), tz=timezone.utc)
bookmark['add_date'] = {'$date': date.isoformat()} if args.mongo \
else date.isoformat()
bookmark['tags'] = link.get('tags').split(',')
if args.tags:
bookmark['tags'] += args.tags
sibling = link.parent.next_sibling
if sibling and sibling.name == 'dd':
bookmark['comment'] = sibling.string.strip()
print(json.dumps(bookmark, sort_keys=False, indent=4))
|
Add options for add date and tags.
|
Add options for add date and tags.
|
Python
|
mit
|
jhh/netscape-bookmark-converter
|
82daed35cb328590e710800672fc3524c226d166
|
feder/letters/tests/base.py
|
feder/letters/tests/base.py
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='[email protected]')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise new Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
import email
from os.path import dirname, join
from django.utils import six
from django_mailbox.models import Mailbox
from feder.letters.signals import MessageParser
class MessageMixin(object):
def setUp(self):
self.mailbox = Mailbox.objects.create(from_email='[email protected]')
super(MessageMixin, self).setUp()
@staticmethod
def _get_email_path(filename):
return join(dirname(__file__), 'messages', filename)
@staticmethod
def _get_email_object(filename): # See coddingtonbear/django-mailbox#89
path = MessageMixin._get_email_path(filename)
for line in open('git-lfs.github.com', 'r'):
if 'git-lfs' in line:
raise Exception("File '{}' not downloaded. Only Git-LFS reference available. Perform 'git lfs pull'.".format(filename))
if six.PY3:
return email.message_from_file(open(path, 'r'))
else: # Deprecated. Back-ward compatible for PY2.7<
return email.message_from_file(open(path, 'rb'))
def get_message(self, filename):
message = self._get_email_object(filename)
msg = self.mailbox._process_message(message)
msg.save()
return msg
def load_letter(self, name):
message = self.get_message(name)
return MessageParser(message).insert()
|
Fix detect Git-LFS in tests
|
Fix detect Git-LFS in tests
|
Python
|
mit
|
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
|
dabb6e7b3855d93df74d690607432e27b5d9c82f
|
ipython/profile/00_import_sciqnd.py
|
ipython/profile/00_import_sciqnd.py
|
import cPickle as pickle
import glob
import json
import math
import os
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy as sp
import scipy.io
import scipy.stats
import skimage
import skimage.transform
import skimage.io
import cv2
# The following lines call magic commands
get_ipython().run_line_magic(u"pdb", u"")
# Insert breakpoints as breakpoint()() instead of Tracer()()
from IPython.core.debugger import Tracer as breakpoint
|
import cPickle as pickle
import glob
import json
import math
import os
import sys
import cv2
import h5py
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy as sp
import scipy.io
import scipy.stats
import skimage
import skimage.transform
import skimage.io
# The following lines call magic commands
get_ipython().run_line_magic(u"pdb", u"")
# Insert breakpoints as breakpoint()() instead of Tracer()()
from IPython.core.debugger import Tracer as breakpoint
|
Add h5py on sciqnd ipython profile
|
Add h5py on sciqnd ipython profile
|
Python
|
mit
|
escorciav/linux-utils,escorciav/linux-utils
|
6cd7e79fc32ebf75776ab0bcf367854d76dd5e03
|
src/redditsubscraper/items.py
|
src/redditsubscraper/items.py
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
|
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
import scrapy
class Post(scrapy.Item):
"""
A model representing a single Reddit post.
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
class Comment(scrapy.Item):
"""
A model representing a single Reddit comment
"""
"""An id encoded in base-36 without any prefixes."""
id = scrapy.Field()
parent_id = scrapy.Field()
class RedditItemPipeline(object):
pass
|
Add comments to item fields.
|
Add comments to item fields.
|
Python
|
mit
|
rfkrocktk/subreddit-scraper
|
b590ddd735131faa3fd1bdc91b1866e1bd7b0738
|
us_ignite/snippets/management/commands/snippets_load_fixtures.py
|
us_ignite/snippets/management/commands/snippets_load_fixtures.py
|
from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'Up next:',
'body': '',
'url_text': 'Get involved',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
|
from django.core.management.base import BaseCommand
from us_ignite.snippets.models import Snippet
FIXTURES = [
{
'slug': 'home-box',
'name': 'UP NEXT: LOREM IPSUM',
'body': '',
'url_text': 'GET INVOLVED',
'url': '',
},
{
'slug': 'featured',
'name': 'FEATURED CONTENT',
'body': '',
'url_text': 'FEATURED',
'url': '',
},
]
class Command(BaseCommand):
def handle(self, *args, **options):
for data in FIXTURES:
try:
# Ignore existing snippets:
Snippet.objects.get(slug=data['slug'])
continue
except Snippet.DoesNotExist:
pass
data.update({
'status': Snippet.PUBLISHED,
})
Snippet.objects.create(**data)
print u'Importing %s' % data['slug']
print "Done!"
|
Add featured homepage initial fixture.
|
Add featured homepage initial fixture.
|
Python
|
bsd-3-clause
|
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
|
d37f91f50dd6c0c3202258daca95ee6ee111688f
|
pyjswidgets/pyjamas/ui/Focus.oldmoz.py
|
pyjswidgets/pyjamas/ui/Focus.oldmoz.py
|
def ensureFocusHandler():
JS("""
return (focusHandler !== null) ? focusHandler : (focusHandler =
@{{createFocusHandler}}());
""")
def createFocusHandler():
JS("""
return function(evt) {
// This function is called directly as an event handler, so 'this' is
// set up by the browser to be the input on which the event is fired. We
// call focus() in a timeout or the element may be blurred when this event
// ends.
var div = this['parentNode'];
if (div['onfocus']) {
$wnd['setTimeout'](function() {
div['focus']();
}, 0);
}
};
""")
def createFocusable0(focusHandler):
JS("""
var div = $doc['createElement']('div');
div['tabIndex'] = 0;
var input = $doc['createElement']('input');
input['type'] = 'text';
input['style']['opacity'] = 0;
input['tabIndex'] = -1;
input['style']['zIndex'] = -1;
input['style']['width'] = '1px';
input['style']['height'] = '1px';
input['style']['overflow'] = 'hidden';
input['style']['position'] = 'absolute';
input['addEventListener']( 'focus', focusHandler, false);
div['appendChild'](input);
return div;
""")
def createFocusable():
ensureFocusHandler()
return createFocusable0()
|
def ensureFocusHandler():
JS("""
return (focusHandler !== null) ? focusHandler : (focusHandler =
@{{createFocusHandler}}());
""")
def createFocusHandler():
JS("""
return function(evt) {
// This function is called directly as an event handler, so 'this' is
// set up by the browser to be the input on which the event is fired. We
// call focus() in a timeout or the element may be blurred when this event
// ends.
var div = this['parentNode'];
if (div['onfocus']) {
$wnd['setTimeout'](function() {
div['focus']();
}, 0);
}
};
""")
def createFocusable0(focusHandler):
JS("""
var div = $doc['createElement']('div');
div['tabIndex'] = 0;
var input = $doc['createElement']('input');
input['type'] = 'text';
input['style']['opacity'] = 0;
input['tabIndex'] = -1;
input['style']['zIndex'] = -1;
input['style']['width'] = '1px';
input['style']['height'] = '1px';
input['style']['overflow'] = 'hidden';
input['style']['position'] = 'absolute';
input['addEventListener']( 'focus', focusHandler, false);
div['appendChild'](input);
return div;
""")
def createFocusable():
return createFocusable0(ensureFocusHandler())
|
Fix for IE 11 (Focus)
|
Fix for IE 11 (Focus)
IE presents itself as mozilla, so it trips on the bug.
|
Python
|
apache-2.0
|
gpitel/pyjs,spaceone/pyjs,lancezlin/pyjs,spaceone/pyjs,lancezlin/pyjs,pombredanne/pyjs,pyjs/pyjs,Hasimir/pyjs,gpitel/pyjs,pyjs/pyjs,spaceone/pyjs,pyjs/pyjs,Hasimir/pyjs,lancezlin/pyjs,pyjs/pyjs,pombredanne/pyjs,gpitel/pyjs,Hasimir/pyjs,gpitel/pyjs,spaceone/pyjs,pombredanne/pyjs,lancezlin/pyjs,pombredanne/pyjs,Hasimir/pyjs
|
f7373a4c2adc74fc2ff18a7c441a978b6982df89
|
pip/utils/packaging.py
|
pip/utils/packaging.py
|
from __future__ import absolute_import
import logging
import sys
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers
from pip._vendor.packaging import version
logger = logging.getLogger(__name__)
def get_metadata(dist):
if (isinstance(dist, pkg_resources.DistInfoDistribution) and
dist.has_metadata('METADATA')):
return dist.get_metadata('METADATA')
elif dist.has_metadata('PKG-INFO'):
return dist.get_metadata('PKG-INFO')
def check_requires_python(requires_python):
if requires_python is None:
# The package provides no information
return True
try:
requires_python_specifier = specifiers.SpecifierSet(requires_python)
except specifiers.InvalidSpecifier as e:
logger.debug(
"Package %s has an invalid Requires-Python entry - %s" % (
requires_python, e))
return ValueError('Wrong Specifier')
# We only use major.minor.micro
python_version = version.parse('.'.join(map(str, sys.version_info[:3])))
if python_version not in requires_python_specifier:
return False
|
from __future__ import absolute_import
import logging
import sys
from pip._vendor import pkg_resources
from pip._vendor.packaging import specifiers
from pip._vendor.packaging import version
logger = logging.getLogger(__name__)
def get_metadata(dist):
if (isinstance(dist, pkg_resources.DistInfoDistribution) and
dist.has_metadata('METADATA')):
return dist.get_metadata('METADATA')
elif dist.has_metadata('PKG-INFO'):
return dist.get_metadata('PKG-INFO')
def check_requires_python(requires_python):
"""
Check if the python version in used match the `requires_python` specifier passed.
Return `True` if the version of python in use matches the requirement.
Return `False` if the version of python in use does not matches the requirement.
Raises an InvalidSpecifier if `requires_python` have an invalid format.
"""
if requires_python is None:
# The package provides no information
return True
try:
requires_python_specifier = specifiers.SpecifierSet(requires_python)
except specifiers.InvalidSpecifier as e:
logger.debug(
"Package %s has an invalid Requires-Python entry - %s" % (
requires_python, e))
raise specifiers.InvalidSpecifier(*e.args)
# We only use major.minor.micro
python_version = version.parse('.'.join(map(str, sys.version_info[:3])))
return python_version in requires_python_specifier
|
Update check_requires_python and describe behavior in docstring
|
Update check_requires_python and describe behavior in docstring
|
Python
|
mit
|
pradyunsg/pip,fiber-space/pip,atdaemon/pip,RonnyPfannschmidt/pip,techtonik/pip,rouge8/pip,xavfernandez/pip,fiber-space/pip,rouge8/pip,pradyunsg/pip,zvezdan/pip,techtonik/pip,pypa/pip,sigmavirus24/pip,sigmavirus24/pip,RonnyPfannschmidt/pip,zvezdan/pip,benesch/pip,rouge8/pip,atdaemon/pip,pfmoore/pip,pypa/pip,sbidoul/pip,fiber-space/pip,xavfernandez/pip,sbidoul/pip,benesch/pip,pfmoore/pip,xavfernandez/pip,techtonik/pip,zvezdan/pip,atdaemon/pip,RonnyPfannschmidt/pip,benesch/pip,sigmavirus24/pip
|
3d5fd3233ecaf2bae5fbd5a1ae349c55d2f4cdc7
|
scistack/scistack.py
|
scistack/scistack.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SciStack: the web app to build docker containers for reproducable science
"""
import os
import flask
app = flask.Flask(__name__)
@app.route("/")
def hello():
return "Choose a domain!"
if __name__ == "__main__":
app.run()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
SciStack: the web app to build docker containers for reproducable science
"""
import os
import flask
import inspect
app = flask.Flask(__name__, static_url_path='')
# Home of any pre-build docker files
docker_file_path = os.path.join(os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()))), "..", "dockerfiles")
@app.route("/")
def hello():
return "Choose a domain!"
@app.route("/dfview/<path:fname>")
def send_dockerfile(fname):
with open(os.path.join(docker_file_path, fname)) as dfile:
return_value = dfile.read()
return return_value
if __name__ == "__main__":
app.run()
|
Return pre-built dockerfile to user
|
Return pre-built dockerfile to user
|
Python
|
mit
|
callaghanmt/research-stacks,callaghanmt/research-stacks,callaghanmt/research-stacks
|
834d02d65b0d71bd044b18b0be031751a8c1a7de
|
script/lib/config.py
|
script/lib/config.py
|
#!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '607907aed2c1dcdd3b5968a756a990ba3f47bca7'
|
#!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '276722e68bb643e3ae3b468b701c276aeb884838'
|
Upgrade libchromiumcontent: Add support for acceptsFirstMouse.
|
Upgrade libchromiumcontent: Add support for acceptsFirstMouse.
|
Python
|
mit
|
bbondy/electron,greyhwndz/electron,Neron-X5/electron,jacksondc/electron,baiwyc119/electron,brave/electron,tinydew4/electron,trigrass2/electron,pirafrank/electron,arturts/electron,RobertJGabriel/electron,takashi/electron,wan-qy/electron,hokein/atom-shell,digideskio/electron,tincan24/electron,jonatasfreitasv/electron,beni55/electron,tinydew4/electron,mhkeller/electron,aaron-goshine/electron,michaelchiche/electron,systembugtj/electron,leolujuyi/electron,bwiggs/electron,chrisswk/electron,twolfson/electron,tylergibson/electron,yan-foto/electron,MaxWhere/electron,vipulroxx/electron,matiasinsaurralde/electron,roadev/electron,Faiz7412/electron,arturts/electron,IonicaBizauKitchen/electron,felixrieseberg/electron,fomojola/electron,aichingm/electron,MaxWhere/electron,Andrey-Pavlov/electron,timruffles/electron,tinydew4/electron,John-Lin/electron,adamjgray/electron,aichingm/electron,IonicaBizauKitchen/electron,bruce/electron,preco21/electron,etiktin/electron,howmuchcomputer/electron,voidbridge/electron,DivyaKMenon/electron,leethomas/electron,edulan/electron,eric-seekas/electron,medixdev/electron,vHanda/electron,thomsonreuters/electron,leethomas/electron,michaelchiche/electron,rprichard/electron,evgenyzinoviev/electron,robinvandernoord/electron,tincan24/electron,rhencke/electron,greyhwndz/electron,jtburke/electron,carsonmcdonald/electron,beni55/electron,ankitaggarwal011/electron,jlord/electron,howmuchcomputer/electron,brave/electron,aecca/electron,digideskio/electron,posix4e/electron,fffej/electron,iftekeriba/electron,pombredanne/electron,shennushi/electron,meowlab/electron,bruce/electron,Jacobichou/electron,d-salas/electron,fomojola/electron,gabrielPeart/electron,davazp/electron,etiktin/electron,takashi/electron,christian-bromann/electron,digideskio/electron,kenmozi/electron,farmisen/electron,wan-qy/electron,gamedevsam/electron,RIAEvangelist/electron,stevemao/electron,setzer777/electron,aliib/electron,davazp/electron,chriskdon/electron,cqqccqc/electron,maxogden/atom-shell,vipulroxx/electron,gamedevsam/electron,bpasero/electron,jaanus/electron,oiledCode/electron,Rokt33r/electron,meowlab/electron,aichingm/electron,fireball-x/atom-shell,xiruibing/electron,trigrass2/electron,evgenyzinoviev/electron,aichingm/electron,shaundunne/electron,rajatsingla28/electron,thingsinjars/electron,jaanus/electron,rhencke/electron,thompsonemerson/electron,chriskdon/electron,stevemao/electron,destan/electron,rajatsingla28/electron,GoooIce/electron,dongjoon-hyun/electron,arusakov/electron,timruffles/electron,vaginessa/electron,trigrass2/electron,sircharleswatson/electron,neutrous/electron,pombredanne/electron,vipulroxx/electron,coderhaoxin/electron,brave/muon,sky7sea/electron,jlord/electron,anko/electron,JesselJohn/electron,sircharleswatson/electron,baiwyc119/electron,rreimann/electron,zhakui/electron,shiftkey/electron,egoist/electron,tomashanacek/electron,gstack/infinium-shell,GoooIce/electron,kazupon/electron,ervinb/electron,nekuz0r/electron,egoist/electron,xfstudio/electron,adcentury/electron,tincan24/electron,systembugtj/electron,mhkeller/electron,gerhardberger/electron,BionicClick/electron,vaginessa/electron,jsutcodes/electron,felixrieseberg/electron,gamedevsam/electron,iftekeriba/electron,BionicClick/electron,wolfflow/electron,aecca/electron,chrisswk/electron,anko/electron,jsutcodes/electron,nicobot/electron,ankitaggarwal011/electron,arusakov/electron,stevekinney/electron,aaron-goshine/electron,jacksondc/electron,lrlna/electron,zhakui/electron,wan-qy/electron,trigrass2/electron,shennushi/electron,natgolov/electron,kokdemo/electron,neutrous/electron,miniak/electron,mattdesl/electron,iftekeriba/electron,nicholasess/electron,thompsonemerson/electron,Rokt33r/electron,RobertJGabriel/electron,setzer777/electron,jlord/electron,saronwei/electron,Gerhut/electron,thingsinjars/electron,Gerhut/electron,DivyaKMenon/electron,zhakui/electron,lzpfmh/electron,gbn972/electron,lzpfmh/electron,matiasinsaurralde/electron,noikiy/electron,the-ress/electron,fabien-d/electron,gabriel/electron,davazp/electron,astoilkov/electron,jiaz/electron,JussMee15/electron,nekuz0r/electron,jjz/electron,leftstick/electron,rsvip/electron,jiaz/electron,DivyaKMenon/electron,gabrielPeart/electron,stevemao/electron,Evercoder/electron,Rokt33r/electron,maxogden/atom-shell,bbondy/electron,Zagorakiss/electron,aliib/electron,mjaniszew/electron,twolfson/electron,biblerule/UMCTelnetHub,bobwol/electron,rsvip/electron,dongjoon-hyun/electron,abhishekgahlot/electron,nicholasess/electron,subblue/electron,zhakui/electron,felixrieseberg/electron,eriser/electron,carsonmcdonald/electron,digideskio/electron,dahal/electron,tonyganch/electron,RIAEvangelist/electron,yan-foto/electron,anko/electron,arusakov/electron,d-salas/electron,minggo/electron,evgenyzinoviev/electron,rhencke/electron,digideskio/electron,xiruibing/electron,jcblw/electron,electron/electron,posix4e/electron,mrwizard82d1/electron,Jacobichou/electron,adcentury/electron,bright-sparks/electron,timruffles/electron,smczk/electron,aaron-goshine/electron,micalan/electron,arturts/electron,gamedevsam/electron,Evercoder/electron,beni55/electron,sircharleswatson/electron,aaron-goshine/electron,darwin/electron,Neron-X5/electron,medixdev/electron,gabrielPeart/electron,hokein/atom-shell,tinydew4/electron,egoist/electron,twolfson/electron,shennushi/electron,nicobot/electron,jacksondc/electron,SufianHassan/electron,GoooIce/electron,stevekinney/electron,thingsinjars/electron,shaundunne/electron,kostia/electron,adcentury/electron,seanchas116/electron,Floato/electron,jhen0409/electron,minggo/electron,seanchas116/electron,howmuchcomputer/electron,the-ress/electron,rhencke/electron,jaanus/electron,lrlna/electron,bitemyapp/electron,takashi/electron,Ivshti/electron,eriser/electron,natgolov/electron,smczk/electron,maxogden/atom-shell,mubassirhayat/electron,dongjoon-hyun/electron,renaesop/electron,faizalpribadi/electron,farmisen/electron,Jacobichou/electron,leftstick/electron,joneit/electron,stevekinney/electron,mattotodd/electron,vHanda/electron,egoist/electron,matiasinsaurralde/electron,carsonmcdonald/electron,brenca/electron,gabriel/electron,xiruibing/electron,cos2004/electron,jlhbaseball15/electron,seanchas116/electron,JesselJohn/electron,minggo/electron,joaomoreno/atom-shell,micalan/electron,systembugtj/electron,egoist/electron,benweissmann/electron,pirafrank/electron,howmuchcomputer/electron,eriser/electron,felixrieseberg/electron,abhishekgahlot/electron,MaxGraey/electron,nagyistoce/electron-atom-shell,miniak/electron,dongjoon-hyun/electron,leolujuyi/electron,lzpfmh/electron,wolfflow/electron,RobertJGabriel/electron,soulteary/electron,takashi/electron,jcblw/electron,SufianHassan/electron,edulan/electron,bobwol/electron,gabriel/electron,shaundunne/electron,jjz/electron,pandoraui/electron,Andrey-Pavlov/electron,greyhwndz/electron,thingsinjars/electron,jhen0409/electron,shockone/electron,vHanda/electron,jjz/electron,jcblw/electron,micalan/electron,Rokt33r/electron,soulteary/electron,gabriel/electron,davazp/electron,nicholasess/electron,bpasero/electron,Jacobichou/electron,BionicClick/electron,deed02392/electron,thompsonemerson/electron,renaesop/electron,astoilkov/electron,egoist/electron,kokdemo/electron,nekuz0r/electron,shiftkey/electron,icattlecoder/electron,micalan/electron,jonatasfreitasv/electron,kikong/electron,mattdesl/electron,joneit/electron,mrwizard82d1/electron,fritx/electron,brave/electron,jiaz/electron,Jonekee/electron,tylergibson/electron,leethomas/electron,renaesop/electron,chriskdon/electron,eric-seekas/electron,farmisen/electron,yan-foto/electron,leftstick/electron,voidbridge/electron,RIAEvangelist/electron,chrisswk/electron,ianscrivener/electron,IonicaBizauKitchen/electron,RIAEvangelist/electron,smczk/electron,matiasinsaurralde/electron,jhen0409/electron,kenmozi/electron,soulteary/electron,sshiting/electron,JesselJohn/electron,d-salas/electron,rsvip/electron,kostia/electron,twolfson/electron,RobertJGabriel/electron,setzer777/electron,sircharleswatson/electron,stevemao/electron,ianscrivener/electron,joneit/electron,eriser/electron,robinvandernoord/electron,icattlecoder/electron,trankmichael/electron,renaesop/electron,gstack/infinium-shell,kenmozi/electron,noikiy/electron,twolfson/electron,fireball-x/atom-shell,soulteary/electron,shockone/electron,Gerhut/electron,carsonmcdonald/electron,jiaz/electron,aichingm/electron,miniak/electron,voidbridge/electron,bpasero/electron,jsutcodes/electron,gbn972/electron,deepak1556/atom-shell,gbn972/electron,tonyganch/electron,adamjgray/electron,stevekinney/electron,yan-foto/electron,hokein/atom-shell,mirrh/electron,anko/electron,jannishuebl/electron,trankmichael/electron,tomashanacek/electron,ankitaggarwal011/electron,robinvandernoord/electron,maxogden/atom-shell,robinvandernoord/electron,shockone/electron,joneit/electron,baiwyc119/electron,davazp/electron,ervinb/electron,cqqccqc/electron,preco21/electron,micalan/electron,LadyNaggaga/electron,gabrielPeart/electron,howmuchcomputer/electron,fabien-d/electron,preco21/electron,tincan24/electron,gabrielPeart/electron,gstack/infinium-shell,JesselJohn/electron,mrwizard82d1/electron,Floato/electron,oiledCode/electron,shennushi/electron,jacksondc/electron,brave/electron,SufianHassan/electron,soulteary/electron,arturts/electron,bruce/electron,rajatsingla28/electron,fomojola/electron,jaanus/electron,medixdev/electron,bwiggs/electron,bitemyapp/electron,aecca/electron,saronwei/electron,felixrieseberg/electron,tylergibson/electron,eric-seekas/electron,beni55/electron,aliib/electron,tylergibson/electron,Faiz7412/electron,michaelchiche/electron,edulan/electron,yalexx/electron,synaptek/electron,icattlecoder/electron,gabriel/electron,yalexx/electron,kokdemo/electron,digideskio/electron,jsutcodes/electron,setzer777/electron,evgenyzinoviev/electron,ervinb/electron,benweissmann/electron,webmechanicx/electron,jjz/electron,noikiy/electron,noikiy/electron,seanchas116/electron,miniak/electron,bobwol/electron,MaxGraey/electron,christian-bromann/electron,coderhaoxin/electron,icattlecoder/electron,d-salas/electron,rreimann/electron,pombredanne/electron,voidbridge/electron,ianscrivener/electron,sky7sea/electron,ervinb/electron,the-ress/electron,astoilkov/electron,mrwizard82d1/electron,joaomoreno/atom-shell,aliib/electron,chrisswk/electron,rsvip/electron,Zagorakiss/electron,jonatasfreitasv/electron,abhishekgahlot/electron,rajatsingla28/electron,subblue/electron,yan-foto/electron,fritx/electron,John-Lin/electron,kenmozi/electron,evgenyzinoviev/electron,vipulroxx/electron,setzer777/electron,shennushi/electron,thompsonemerson/electron,SufianHassan/electron,cqqccqc/electron,fffej/electron,destan/electron,Evercoder/electron,etiktin/electron,astoilkov/electron,jtburke/electron,arturts/electron,mhkeller/electron,mattotodd/electron,mattdesl/electron,smczk/electron,jcblw/electron,cos2004/electron,Andrey-Pavlov/electron,chriskdon/electron,destan/electron,jlhbaseball15/electron,anko/electron,leftstick/electron,carsonmcdonald/electron,rprichard/electron,kikong/electron,adcentury/electron,posix4e/electron,chrisswk/electron,michaelchiche/electron,rreimann/electron,eric-seekas/electron,roadev/electron,synaptek/electron,MaxWhere/electron,bbondy/electron,rajatsingla28/electron,takashi/electron,Andrey-Pavlov/electron,leolujuyi/electron,brave/muon,eriser/electron,BionicClick/electron,jlord/electron,bitemyapp/electron,wan-qy/electron,mattotodd/electron,electron/electron,Rokt33r/electron,IonicaBizauKitchen/electron,jannishuebl/electron,webmechanicx/electron,roadev/electron,deepak1556/atom-shell,tonyganch/electron,Floato/electron,Jonekee/electron,davazp/electron,chriskdon/electron,mhkeller/electron,thomsonreuters/electron,jhen0409/electron,pandoraui/electron,Ivshti/electron,kostia/electron,Gerhut/electron,kcrt/electron,edulan/electron,matiasinsaurralde/electron,arusakov/electron,minggo/electron,jlhbaseball15/electron,mirrh/electron,neutrous/electron,leolujuyi/electron,RIAEvangelist/electron,bruce/electron,biblerule/UMCTelnetHub,ervinb/electron,dahal/electron,brenca/electron,meowlab/electron,medixdev/electron,webmechanicx/electron,gerhardberger/electron,fireball-x/atom-shell,tomashanacek/electron,joaomoreno/atom-shell,dahal/electron,oiledCode/electron,John-Lin/electron,sircharleswatson/electron,systembugtj/electron,etiktin/electron,iftekeriba/electron,tinydew4/electron,meowlab/electron,xiruibing/electron,roadev/electron,Jonekee/electron,bright-sparks/electron,adamjgray/electron,felixrieseberg/electron,jsutcodes/electron,arusakov/electron,nicobot/electron,sky7sea/electron,trigrass2/electron,jlhbaseball15/electron,vaginessa/electron,kcrt/electron,mubassirhayat/electron,bpasero/electron,shockone/electron,wolfflow/electron,bright-sparks/electron,Andrey-Pavlov/electron,astoilkov/electron,pandoraui/electron,sshiting/electron,electron/electron,leolujuyi/electron,christian-bromann/electron,deed02392/electron,kazupon/electron,DivyaKMenon/electron,brave/electron,posix4e/electron,bbondy/electron,wolfflow/electron,simonfork/electron,robinvandernoord/electron,wan-qy/electron,astoilkov/electron,fffej/electron,deepak1556/atom-shell,kokdemo/electron,joaomoreno/atom-shell,joaomoreno/atom-shell,yalexx/electron,bright-sparks/electron,Gerhut/electron,preco21/electron,pirafrank/electron,fomojola/electron,nicobot/electron,medixdev/electron,bitemyapp/electron,jonatasfreitasv/electron,mirrh/electron,webmechanicx/electron,mhkeller/electron,sshiting/electron,bright-sparks/electron,natgolov/electron,deepak1556/atom-shell,mjaniszew/electron,darwin/electron,saronwei/electron,Zagorakiss/electron,leethomas/electron,cos2004/electron,greyhwndz/electron,pandoraui/electron,MaxWhere/electron,gerhardberger/electron,minggo/electron,abhishekgahlot/electron,DivyaKMenon/electron,faizalpribadi/electron,vHanda/electron,bruce/electron,Andrey-Pavlov/electron,jcblw/electron,rreimann/electron,coderhaoxin/electron,joneit/electron,arturts/electron,gerhardberger/electron,mattdesl/electron,pirafrank/electron,darwin/electron,Faiz7412/electron,nicholasess/electron,coderhaoxin/electron,LadyNaggaga/electron,trankmichael/electron,takashi/electron,bitemyapp/electron,leolujuyi/electron,pandoraui/electron,xiruibing/electron,Zagorakiss/electron,gstack/infinium-shell,leftstick/electron,simongregory/electron,roadev/electron,voidbridge/electron,michaelchiche/electron,meowlab/electron,Jonekee/electron,mjaniszew/electron,natgolov/electron,kostia/electron,benweissmann/electron,seanchas116/electron,fritx/electron,jiaz/electron,mjaniszew/electron,aecca/electron,RobertJGabriel/electron,aliib/electron,jaanus/electron,rprichard/electron,yalexx/electron,wan-qy/electron,the-ress/electron,mattotodd/electron,kenmozi/electron,Neron-X5/electron,JussMee15/electron,eric-seekas/electron,kokdemo/electron,jtburke/electron,rajatsingla28/electron,mattotodd/electron,mattdesl/electron,LadyNaggaga/electron,LadyNaggaga/electron,zhakui/electron,stevemao/electron,jacksondc/electron,farmisen/electron,carsonmcdonald/electron,nicholasess/electron,shockone/electron,bitemyapp/electron,timruffles/electron,synaptek/electron,aliib/electron,brave/muon,simonfork/electron,ervinb/electron,darwin/electron,the-ress/electron,farmisen/electron,vipulroxx/electron,bbondy/electron,oiledCode/electron,Ivshti/electron,cqqccqc/electron,fireball-x/atom-shell,faizalpribadi/electron,simongregory/electron,Evercoder/electron,Jonekee/electron,joneit/electron,jtburke/electron,preco21/electron,ianscrivener/electron,nagyistoce/electron-atom-shell,kostia/electron,leethomas/electron,simonfork/electron,kikong/electron,brenca/electron,BionicClick/electron,RIAEvangelist/electron,jacksondc/electron,subblue/electron,tonyganch/electron,beni55/electron,MaxGraey/electron,timruffles/electron,nagyistoce/electron-atom-shell,posix4e/electron,Gerhut/electron,BionicClick/electron,kcrt/electron,benweissmann/electron,jlord/electron,jannishuebl/electron,leethomas/electron,miniak/electron,mirrh/electron,Jonekee/electron,faizalpribadi/electron,rprichard/electron,kcrt/electron,gerhardberger/electron,tylergibson/electron,MaxWhere/electron,dkfiresky/electron,Zagorakiss/electron,nagyistoce/electron-atom-shell,saronwei/electron,John-Lin/electron,thompsonemerson/electron,robinvandernoord/electron,stevemao/electron,JussMee15/electron,bbondy/electron,howmuchcomputer/electron,vHanda/electron,simonfork/electron,gbn972/electron,GoooIce/electron,aecca/electron,evgenyzinoviev/electron,kikong/electron,bpasero/electron,cos2004/electron,GoooIce/electron,LadyNaggaga/electron,electron/electron,jonatasfreitasv/electron,Neron-X5/electron,renaesop/electron,Floato/electron,biblerule/UMCTelnetHub,mubassirhayat/electron,dkfiresky/electron,dahal/electron,GoooIce/electron,jannishuebl/electron,John-Lin/electron,shaundunne/electron,simongregory/electron,mattdesl/electron,cos2004/electron,benweissmann/electron,edulan/electron,xfstudio/electron,nicobot/electron,preco21/electron,xiruibing/electron,deed02392/electron,MaxGraey/electron,ankitaggarwal011/electron,jaanus/electron,bobwol/electron,trankmichael/electron,fffej/electron,anko/electron,trigrass2/electron,jlhbaseball15/electron,tinydew4/electron,pombredanne/electron,sshiting/electron,natgolov/electron,farmisen/electron,neutrous/electron,wolfflow/electron,tincan24/electron,faizalpribadi/electron,thingsinjars/electron,subblue/electron,cqqccqc/electron,etiktin/electron,pirafrank/electron,subblue/electron,natgolov/electron,fomojola/electron,vaginessa/electron,seanchas116/electron,mhkeller/electron,electron/electron,MaxWhere/electron,maxogden/atom-shell,pombredanne/electron,eric-seekas/electron,mubassirhayat/electron,MaxGraey/electron,soulteary/electron,Neron-X5/electron,vaginessa/electron,jjz/electron,biblerule/UMCTelnetHub,gerhardberger/electron,nicholasess/electron,aecca/electron,eriser/electron,RobertJGabriel/electron,arusakov/electron,gerhardberger/electron,nagyistoce/electron-atom-shell,michaelchiche/electron,miniak/electron,twolfson/electron,DivyaKMenon/electron,aaron-goshine/electron,minggo/electron,benweissmann/electron,kazupon/electron,saronwei/electron,dkfiresky/electron,shiftkey/electron,kcrt/electron,mrwizard82d1/electron,destan/electron,noikiy/electron,dkfiresky/electron,simonfork/electron,brave/muon,destan/electron,oiledCode/electron,systembugtj/electron,JussMee15/electron,rreimann/electron,jannishuebl/electron,lrlna/electron,adcentury/electron,wolfflow/electron,Faiz7412/electron,shaundunne/electron,destan/electron,simongregory/electron,ankitaggarwal011/electron,meowlab/electron,gamedevsam/electron,jlhbaseball15/electron,baiwyc119/electron,fabien-d/electron,abhishekgahlot/electron,kcrt/electron,fomojola/electron,Neron-X5/electron,adamjgray/electron,cos2004/electron,bruce/electron,bobwol/electron,jtburke/electron,bwiggs/electron,brenca/electron,shiftkey/electron,joaomoreno/atom-shell,noikiy/electron,stevekinney/electron,leftstick/electron,electron/electron,thomsonreuters/electron,trankmichael/electron,lzpfmh/electron,jsutcodes/electron,the-ress/electron,edulan/electron,kenmozi/electron,greyhwndz/electron,gbn972/electron,synaptek/electron,mirrh/electron,electron/electron,SufianHassan/electron,shockone/electron,shiftkey/electron,Evercoder/electron,nekuz0r/electron,cqqccqc/electron,jhen0409/electron,trankmichael/electron,sky7sea/electron,setzer777/electron,thompsonemerson/electron,aichingm/electron,jhen0409/electron,sky7sea/electron,mjaniszew/electron,brenca/electron,Ivshti/electron,d-salas/electron,posix4e/electron,kazupon/electron,fabien-d/electron,simonfork/electron,shaundunne/electron,kikong/electron,deed02392/electron,Floato/electron,fffej/electron,tonyganch/electron,jcblw/electron,dahal/electron,mirrh/electron,matiasinsaurralde/electron,dahal/electron,d-salas/electron,brave/muon,jonatasfreitasv/electron,Rokt33r/electron,pirafrank/electron,the-ress/electron,rhencke/electron,kazupon/electron,adcentury/electron,tomashanacek/electron,micalan/electron,shiftkey/electron,thomsonreuters/electron,christian-bromann/electron,rsvip/electron,greyhwndz/electron,lrlna/electron,vaginessa/electron,iftekeriba/electron,fffej/electron,thingsinjars/electron,icattlecoder/electron,stevekinney/electron,JussMee15/electron,fireball-x/atom-shell,dongjoon-hyun/electron,dkfiresky/electron,tomashanacek/electron,dkfiresky/electron,gabriel/electron,lrlna/electron,sircharleswatson/electron,LadyNaggaga/electron,gbn972/electron,vHanda/electron,simongregory/electron,tomashanacek/electron,IonicaBizauKitchen/electron,lrlna/electron,abhishekgahlot/electron,nicobot/electron,pandoraui/electron,zhakui/electron,deepak1556/atom-shell,xfstudio/electron,bwiggs/electron,synaptek/electron,lzpfmh/electron,faizalpribadi/electron,oiledCode/electron,xfstudio/electron,darwin/electron,sshiting/electron,xfstudio/electron,baiwyc119/electron,jannishuebl/electron,bwiggs/electron,SufianHassan/electron,tylergibson/electron,bwiggs/electron,rreimann/electron,Zagorakiss/electron,shennushi/electron,JesselJohn/electron,christian-bromann/electron,simongregory/electron,bobwol/electron,aaron-goshine/electron,nekuz0r/electron,vipulroxx/electron,synaptek/electron,ianscrivener/electron,biblerule/UMCTelnetHub,sky7sea/electron,brenca/electron,gabrielPeart/electron,systembugtj/electron,hokein/atom-shell,saronwei/electron,JesselJohn/electron,adamjgray/electron,chriskdon/electron,icattlecoder/electron,deed02392/electron,mrwizard82d1/electron,fritx/electron,hokein/atom-shell,webmechanicx/electron,subblue/electron,renaesop/electron,gamedevsam/electron,bpasero/electron,bpasero/electron,Jacobichou/electron,smczk/electron,neutrous/electron,etiktin/electron,christian-bromann/electron,brave/electron,JussMee15/electron,tonyganch/electron,mubassirhayat/electron,John-Lin/electron,kazupon/electron,mjaniszew/electron,xfstudio/electron,rhencke/electron,jiaz/electron,brave/muon,Evercoder/electron,roadev/electron,IonicaBizauKitchen/electron,iftekeriba/electron,ankitaggarwal011/electron,yalexx/electron,nekuz0r/electron,beni55/electron,adamjgray/electron,coderhaoxin/electron,fabien-d/electron,neutrous/electron,yalexx/electron,tincan24/electron,jjz/electron,kokdemo/electron,medixdev/electron,voidbridge/electron,Jacobichou/electron,gstack/infinium-shell,Ivshti/electron,smczk/electron,sshiting/electron,fritx/electron,thomsonreuters/electron,dongjoon-hyun/electron,Faiz7412/electron,yan-foto/electron,deed02392/electron,baiwyc119/electron,pombredanne/electron,thomsonreuters/electron,Floato/electron,kostia/electron,bright-sparks/electron,lzpfmh/electron,ianscrivener/electron,mattotodd/electron,jtburke/electron,coderhaoxin/electron,webmechanicx/electron,fritx/electron,biblerule/UMCTelnetHub
|
099eb53d3c7a4be19fd79f11c9ccf52faff300d4
|
script/lib/config.py
|
script/lib/config.py
|
#!/usr/bin/env python
import platform
import sys
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'e4b283c22236560fd289fe59c03e50adf39e7c4b'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
|
#!/usr/bin/env python
import platform
import sys
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'aa87035cc012ce0d533bb56b947bca81a6e71b82'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[0],
'win32': '32bit',
}[sys.platform]
DIST_ARCH = {
'32bit': 'ia32',
'64bit': 'x64',
}[ARCH]
TARGET_PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
verbose_mode = False
def enable_verbose_mode():
print 'Running in verbose mode'
global verbose_mode
verbose_mode = True
def is_verbose_mode():
return verbose_mode
|
Upgrade libchromiumcontent to fix generating node.lib
|
Upgrade libchromiumcontent to fix generating node.lib
|
Python
|
mit
|
setzer777/electron,dkfiresky/electron,carsonmcdonald/electron,davazp/electron,michaelchiche/electron,gerhardberger/electron,systembugtj/electron,renaesop/electron,mirrh/electron,bbondy/electron,subblue/electron,Andrey-Pavlov/electron,joaomoreno/atom-shell,bpasero/electron,hokein/atom-shell,bpasero/electron,benweissmann/electron,iftekeriba/electron,neutrous/electron,gamedevsam/electron,Zagorakiss/electron,seanchas116/electron,jcblw/electron,arusakov/electron,aaron-goshine/electron,aecca/electron,tinydew4/electron,aecca/electron,gabriel/electron,benweissmann/electron,shockone/electron,lrlna/electron,shockone/electron,subblue/electron,dahal/electron,brave/electron,xfstudio/electron,matiasinsaurralde/electron,vaginessa/electron,wan-qy/electron,robinvandernoord/electron,smczk/electron,farmisen/electron,natgolov/electron,tonyganch/electron,cos2004/electron,pirafrank/electron,iftekeriba/electron,thompsonemerson/electron,bobwol/electron,ianscrivener/electron,ervinb/electron,digideskio/electron,noikiy/electron,lzpfmh/electron,dkfiresky/electron,aliib/electron,tomashanacek/electron,wolfflow/electron,joaomoreno/atom-shell,mjaniszew/electron,aichingm/electron,neutrous/electron,rsvip/electron,ervinb/electron,leolujuyi/electron,jsutcodes/electron,Faiz7412/electron,bobwol/electron,kokdemo/electron,sshiting/electron,oiledCode/electron,RobertJGabriel/electron,abhishekgahlot/electron,rhencke/electron,aichingm/electron,coderhaoxin/electron,baiwyc119/electron,Jonekee/electron,bright-sparks/electron,jhen0409/electron,eric-seekas/electron,rsvip/electron,beni55/electron,posix4e/electron,synaptek/electron,matiasinsaurralde/electron,minggo/electron,medixdev/electron,vHanda/electron,renaesop/electron,chriskdon/electron,neutrous/electron,brave/electron,chrisswk/electron,fritx/electron,christian-bromann/electron,tylergibson/electron,adcentury/electron,brenca/electron,DivyaKMenon/electron,aaron-goshine/electron,kenmozi/electron,rajatsingla28/electron,electron/electron,deepak1556/atom-shell,mattdesl/electron,leolujuyi/electron,zhakui/electron,mirrh/electron,kazupon/electron,tincan24/electron,Floato/electron,miniak/electron,deed02392/electron,bwiggs/electron,destan/electron,mjaniszew/electron,rajatsingla28/electron,edulan/electron,jsutcodes/electron,egoist/electron,ianscrivener/electron,electron/electron,shiftkey/electron,timruffles/electron,jacksondc/electron,michaelchiche/electron,gabriel/electron,webmechanicx/electron,thingsinjars/electron,davazp/electron,nekuz0r/electron,jtburke/electron,kenmozi/electron,leolujuyi/electron,stevemao/electron,LadyNaggaga/electron,kcrt/electron,cos2004/electron,simongregory/electron,anko/electron,synaptek/electron,adcentury/electron,jlord/electron,MaxWhere/electron,bruce/electron,bpasero/electron,MaxWhere/electron,greyhwndz/electron,JussMee15/electron,stevemao/electron,kcrt/electron,chriskdon/electron,rsvip/electron,arturts/electron,leethomas/electron,voidbridge/electron,wolfflow/electron,Faiz7412/electron,joaomoreno/atom-shell,cqqccqc/electron,stevekinney/electron,roadev/electron,jiaz/electron,shaundunne/electron,jcblw/electron,gerhardberger/electron,jtburke/electron,yalexx/electron,Jacobichou/electron,baiwyc119/electron,Rokt33r/electron,roadev/electron,arusakov/electron,Rokt33r/electron,kazupon/electron,yalexx/electron,gabrielPeart/electron,eric-seekas/electron,oiledCode/electron,jtburke/electron,vaginessa/electron,Rokt33r/electron,jannishuebl/electron,rreimann/electron,greyhwndz/electron,saronwei/electron,arusakov/electron,trigrass2/electron,aecca/electron,ankitaggarwal011/electron,benweissmann/electron,dkfiresky/electron,gabrielPeart/electron,jannishuebl/electron,Faiz7412/electron,Gerhut/electron,simonfork/electron,tonyganch/electron,aichingm/electron,cqqccqc/electron,carsonmcdonald/electron,LadyNaggaga/electron,trankmichael/electron,anko/electron,micalan/electron,the-ress/electron,coderhaoxin/electron,dahal/electron,wolfflow/electron,bitemyapp/electron,michaelchiche/electron,simongregory/electron,shockone/electron,gabrielPeart/electron,rajatsingla28/electron,farmisen/electron,d-salas/electron,joaomoreno/atom-shell,jonatasfreitasv/electron,jhen0409/electron,aichingm/electron,mhkeller/electron,wan-qy/electron,subblue/electron,lzpfmh/electron,stevekinney/electron,gamedevsam/electron,arturts/electron,SufianHassan/electron,eriser/electron,setzer777/electron,smczk/electron,mattdesl/electron,wolfflow/electron,egoist/electron,simongregory/electron,tylergibson/electron,nicobot/electron,tinydew4/electron,kcrt/electron,deed02392/electron,chrisswk/electron,takashi/electron,GoooIce/electron,kazupon/electron,natgolov/electron,trigrass2/electron,renaesop/electron,SufianHassan/electron,darwin/electron,twolfson/electron,tylergibson/electron,egoist/electron,fffej/electron,jjz/electron,jaanus/electron,jjz/electron,nicobot/electron,jacksondc/electron,tincan24/electron,Evercoder/electron,simonfork/electron,rsvip/electron,adamjgray/electron,Ivshti/electron,posix4e/electron,thomsonreuters/electron,felixrieseberg/electron,simongregory/electron,d-salas/electron,brave/muon,ervinb/electron,aliib/electron,mubassirhayat/electron,trigrass2/electron,coderhaoxin/electron,kenmozi/electron,webmechanicx/electron,aaron-goshine/electron,smczk/electron,trankmichael/electron,lrlna/electron,kcrt/electron,sircharleswatson/electron,felixrieseberg/electron,xiruibing/electron,sircharleswatson/electron,stevemao/electron,minggo/electron,brenca/electron,tinydew4/electron,kikong/electron,joaomoreno/atom-shell,nekuz0r/electron,RobertJGabriel/electron,beni55/electron,gamedevsam/electron,nicholasess/electron,tinydew4/electron,yan-foto/electron,shaundunne/electron,tomashanacek/electron,tincan24/electron,nicholasess/electron,christian-bromann/electron,jcblw/electron,natgolov/electron,eric-seekas/electron,DivyaKMenon/electron,Rokt33r/electron,biblerule/UMCTelnetHub,miniak/electron,matiasinsaurralde/electron,rajatsingla28/electron,gabrielPeart/electron,bbondy/electron,yalexx/electron,deepak1556/atom-shell,digideskio/electron,takashi/electron,shaundunne/electron,digideskio/electron,trigrass2/electron,mubassirhayat/electron,egoist/electron,bobwol/electron,kostia/electron,bitemyapp/electron,pirafrank/electron,jaanus/electron,medixdev/electron,IonicaBizauKitchen/electron,fomojola/electron,IonicaBizauKitchen/electron,lrlna/electron,deed02392/electron,electron/electron,pombredanne/electron,mhkeller/electron,fritx/electron,chriskdon/electron,Neron-X5/electron,darwin/electron,xfstudio/electron,MaxWhere/electron,RIAEvangelist/electron,fffej/electron,Floato/electron,takashi/electron,thingsinjars/electron,mattdesl/electron,joneit/electron,rreimann/electron,noikiy/electron,matiasinsaurralde/electron,brave/muon,baiwyc119/electron,icattlecoder/electron,bruce/electron,mrwizard82d1/electron,medixdev/electron,greyhwndz/electron,evgenyzinoviev/electron,MaxGraey/electron,nekuz0r/electron,iftekeriba/electron,minggo/electron,John-Lin/electron,edulan/electron,d-salas/electron,Ivshti/electron,trankmichael/electron,deepak1556/atom-shell,leftstick/electron,abhishekgahlot/electron,evgenyzinoviev/electron,the-ress/electron,timruffles/electron,thomsonreuters/electron,icattlecoder/electron,kenmozi/electron,kostia/electron,robinvandernoord/electron,Ivshti/electron,brave/muon,etiktin/electron,BionicClick/electron,RobertJGabriel/electron,leethomas/electron,icattlecoder/electron,gabriel/electron,pandoraui/electron,kenmozi/electron,maxogden/atom-shell,voidbridge/electron,RobertJGabriel/electron,xiruibing/electron,IonicaBizauKitchen/electron,subblue/electron,gstack/infinium-shell,chrisswk/electron,noikiy/electron,vHanda/electron,webmechanicx/electron,saronwei/electron,brave/electron,noikiy/electron,brenca/electron,arusakov/electron,yan-foto/electron,kostia/electron,Zagorakiss/electron,John-Lin/electron,yalexx/electron,biblerule/UMCTelnetHub,Neron-X5/electron,jhen0409/electron,carsonmcdonald/electron,bpasero/electron,tylergibson/electron,miniak/electron,stevemao/electron,xiruibing/electron,dongjoon-hyun/electron,zhakui/electron,aichingm/electron,chriskdon/electron,noikiy/electron,thingsinjars/electron,christian-bromann/electron,ankitaggarwal011/electron,preco21/electron,darwin/electron,fomojola/electron,shockone/electron,jlhbaseball15/electron,beni55/electron,oiledCode/electron,mjaniszew/electron,baiwyc119/electron,micalan/electron,simonfork/electron,leftstick/electron,greyhwndz/electron,fffej/electron,tonyganch/electron,soulteary/electron,howmuchcomputer/electron,darwin/electron,DivyaKMenon/electron,mjaniszew/electron,leethomas/electron,etiktin/electron,leethomas/electron,mrwizard82d1/electron,adamjgray/electron,roadev/electron,neutrous/electron,thompsonemerson/electron,GoooIce/electron,jannishuebl/electron,mubassirhayat/electron,robinvandernoord/electron,Andrey-Pavlov/electron,bwiggs/electron,medixdev/electron,synaptek/electron,yan-foto/electron,neutrous/electron,howmuchcomputer/electron,nagyistoce/electron-atom-shell,vaginessa/electron,fffej/electron,saronwei/electron,christian-bromann/electron,miniak/electron,tinydew4/electron,BionicClick/electron,iftekeriba/electron,astoilkov/electron,bright-sparks/electron,preco21/electron,RIAEvangelist/electron,vHanda/electron,bright-sparks/electron,the-ress/electron,lzpfmh/electron,synaptek/electron,kikong/electron,pandoraui/electron,yalexx/electron,sky7sea/electron,jsutcodes/electron,rhencke/electron,jlhbaseball15/electron,stevekinney/electron,Neron-X5/electron,RIAEvangelist/electron,Neron-X5/electron,adcentury/electron,preco21/electron,IonicaBizauKitchen/electron,rajatsingla28/electron,vHanda/electron,xfstudio/electron,wan-qy/electron,pirafrank/electron,wan-qy/electron,vipulroxx/electron,John-Lin/electron,egoist/electron,abhishekgahlot/electron,Andrey-Pavlov/electron,DivyaKMenon/electron,nicholasess/electron,maxogden/atom-shell,adamjgray/electron,coderhaoxin/electron,gstack/infinium-shell,simonfork/electron,brave/muon,setzer777/electron,edulan/electron,thomsonreuters/electron,jaanus/electron,astoilkov/electron,pandoraui/electron,gerhardberger/electron,thompsonemerson/electron,electron/electron,meowlab/electron,tonyganch/electron,LadyNaggaga/electron,howmuchcomputer/electron,leolujuyi/electron,gbn972/electron,nekuz0r/electron,posix4e/electron,Jonekee/electron,gbn972/electron,jhen0409/electron,arturts/electron,anko/electron,IonicaBizauKitchen/electron,benweissmann/electron,synaptek/electron,nicobot/electron,Floato/electron,mattotodd/electron,fomojola/electron,dongjoon-hyun/electron,gstack/infinium-shell,minggo/electron,bright-sparks/electron,meowlab/electron,roadev/electron,jiaz/electron,MaxGraey/electron,systembugtj/electron,wan-qy/electron,soulteary/electron,Floato/electron,RIAEvangelist/electron,benweissmann/electron,bbondy/electron,miniak/electron,destan/electron,coderhaoxin/electron,gbn972/electron,bruce/electron,nekuz0r/electron,aichingm/electron,renaesop/electron,gabriel/electron,jaanus/electron,trigrass2/electron,meowlab/electron,thomsonreuters/electron,michaelchiche/electron,rsvip/electron,sircharleswatson/electron,saronwei/electron,gamedevsam/electron,Gerhut/electron,nagyistoce/electron-atom-shell,tincan24/electron,meowlab/electron,jonatasfreitasv/electron,jlord/electron,renaesop/electron,hokein/atom-shell,preco21/electron,jiaz/electron,carsonmcdonald/electron,bitemyapp/electron,wolfflow/electron,adamjgray/electron,fomojola/electron,mirrh/electron,jtburke/electron,trankmichael/electron,shennushi/electron,jhen0409/electron,sircharleswatson/electron,sky7sea/electron,evgenyzinoviev/electron,jacksondc/electron,simongregory/electron,adamjgray/electron,twolfson/electron,bobwol/electron,tinydew4/electron,biblerule/UMCTelnetHub,eric-seekas/electron,micalan/electron,ankitaggarwal011/electron,farmisen/electron,dongjoon-hyun/electron,hokein/atom-shell,jonatasfreitasv/electron,destan/electron,Andrey-Pavlov/electron,xfstudio/electron,aliib/electron,kikong/electron,Zagorakiss/electron,ervinb/electron,astoilkov/electron,LadyNaggaga/electron,stevemao/electron,John-Lin/electron,thomsonreuters/electron,fomojola/electron,mirrh/electron,howmuchcomputer/electron,maxogden/atom-shell,faizalpribadi/electron,shaundunne/electron,vipulroxx/electron,baiwyc119/electron,meowlab/electron,takashi/electron,davazp/electron,SufianHassan/electron,Gerhut/electron,cos2004/electron,joneit/electron,vaginessa/electron,kazupon/electron,thompsonemerson/electron,mrwizard82d1/electron,robinvandernoord/electron,bbondy/electron,jsutcodes/electron,etiktin/electron,vHanda/electron,fomojola/electron,natgolov/electron,fabien-d/electron,aecca/electron,timruffles/electron,jtburke/electron,gabrielPeart/electron,shiftkey/electron,jiaz/electron,oiledCode/electron,astoilkov/electron,Rokt33r/electron,lzpfmh/electron,fireball-x/atom-shell,Evercoder/electron,shockone/electron,arturts/electron,greyhwndz/electron,LadyNaggaga/electron,Neron-X5/electron,sircharleswatson/electron,deepak1556/atom-shell,beni55/electron,preco21/electron,evgenyzinoviev/electron,Jacobichou/electron,eriser/electron,digideskio/electron,jlhbaseball15/electron,mattotodd/electron,dongjoon-hyun/electron,jhen0409/electron,stevekinney/electron,mubassirhayat/electron,anko/electron,arusakov/electron,gbn972/electron,shockone/electron,kazupon/electron,webmechanicx/electron,bwiggs/electron,chrisswk/electron,beni55/electron,electron/electron,sircharleswatson/electron,tomashanacek/electron,kcrt/electron,bitemyapp/electron,biblerule/UMCTelnetHub,nagyistoce/electron-atom-shell,nagyistoce/electron-atom-shell,tomashanacek/electron,sky7sea/electron,kokdemo/electron,thompsonemerson/electron,twolfson/electron,soulteary/electron,rreimann/electron,joneit/electron,astoilkov/electron,Faiz7412/electron,hokein/atom-shell,vipulroxx/electron,jlord/electron,jlhbaseball15/electron,egoist/electron,kcrt/electron,coderhaoxin/electron,sshiting/electron,gabriel/electron,christian-bromann/electron,rhencke/electron,mjaniszew/electron,adcentury/electron,nicholasess/electron,pirafrank/electron,SufianHassan/electron,jjz/electron,mhkeller/electron,arturts/electron,gbn972/electron,mhkeller/electron,meowlab/electron,JussMee15/electron,seanchas116/electron,micalan/electron,LadyNaggaga/electron,tincan24/electron,voidbridge/electron,sky7sea/electron,fabien-d/electron,MaxWhere/electron,JesselJohn/electron,gbn972/electron,smczk/electron,abhishekgahlot/electron,kostia/electron,shaundunne/electron,Evercoder/electron,etiktin/electron,iftekeriba/electron,voidbridge/electron,oiledCode/electron,brenca/electron,miniak/electron,JesselJohn/electron,vipulroxx/electron,lrlna/electron,destan/electron,mattotodd/electron,bruce/electron,systembugtj/electron,howmuchcomputer/electron,biblerule/UMCTelnetHub,deed02392/electron,felixrieseberg/electron,Evercoder/electron,aecca/electron,Gerhut/electron,jsutcodes/electron,brenca/electron,lrlna/electron,eric-seekas/electron,RobertJGabriel/electron,ervinb/electron,BionicClick/electron,bbondy/electron,shennushi/electron,vaginessa/electron,evgenyzinoviev/electron,MaxGraey/electron,vaginessa/electron,felixrieseberg/electron,brave/electron,soulteary/electron,d-salas/electron,rhencke/electron,bitemyapp/electron,ianscrivener/electron,nagyistoce/electron-atom-shell,brave/muon,kokdemo/electron,systembugtj/electron,farmisen/electron,jaanus/electron,kikong/electron,shiftkey/electron,roadev/electron,hokein/atom-shell,mattdesl/electron,leethomas/electron,MaxGraey/electron,felixrieseberg/electron,dongjoon-hyun/electron,cqqccqc/electron,bobwol/electron,the-ress/electron,Andrey-Pavlov/electron,bwiggs/electron,takashi/electron,electron/electron,systembugtj/electron,thingsinjars/electron,jsutcodes/electron,JussMee15/electron,brave/electron,chriskdon/electron,Evercoder/electron,robinvandernoord/electron,simonfork/electron,gerhardberger/electron,webmechanicx/electron,jannishuebl/electron,destan/electron,jlhbaseball15/electron,ianscrivener/electron,mirrh/electron,pombredanne/electron,faizalpribadi/electron,tomashanacek/electron,beni55/electron,xfstudio/electron,Gerhut/electron,Gerhut/electron,nicholasess/electron,vipulroxx/electron,Jonekee/electron,timruffles/electron,bbondy/electron,edulan/electron,rreimann/electron,synaptek/electron,fabien-d/electron,tincan24/electron,medixdev/electron,farmisen/electron,neutrous/electron,JesselJohn/electron,joneit/electron,chriskdon/electron,gabrielPeart/electron,Jonekee/electron,shiftkey/electron,faizalpribadi/electron,jjz/electron,digideskio/electron,the-ress/electron,dongjoon-hyun/electron,ankitaggarwal011/electron,gerhardberger/electron,deed02392/electron,christian-bromann/electron,lzpfmh/electron,pombredanne/electron,faizalpribadi/electron,davazp/electron,shennushi/electron,electron/electron,jcblw/electron,jacksondc/electron,nicobot/electron,John-Lin/electron,timruffles/electron,jannishuebl/electron,medixdev/electron,deed02392/electron,smczk/electron,destan/electron,posix4e/electron,aaron-goshine/electron,yan-foto/electron,bwiggs/electron,Zagorakiss/electron,vHanda/electron,Faiz7412/electron,noikiy/electron,darwin/electron,bitemyapp/electron,jjz/electron,ankitaggarwal011/electron,icattlecoder/electron,oiledCode/electron,shennushi/electron,pombredanne/electron,mhkeller/electron,ankitaggarwal011/electron,IonicaBizauKitchen/electron,webmechanicx/electron,JesselJohn/electron,gstack/infinium-shell,Rokt33r/electron,bpasero/electron,brave/muon,seanchas116/electron,dahal/electron,JussMee15/electron,adamjgray/electron,RIAEvangelist/electron,rhencke/electron,shennushi/electron,fabien-d/electron,sshiting/electron,baiwyc119/electron,pandoraui/electron,xiruibing/electron,kostia/electron,d-salas/electron,posix4e/electron,carsonmcdonald/electron,dahal/electron,soulteary/electron,JussMee15/electron,nicobot/electron,pombredanne/electron,maxogden/atom-shell,jonatasfreitasv/electron,leftstick/electron,cqqccqc/electron,kokdemo/electron,Neron-X5/electron,rajatsingla28/electron,vipulroxx/electron,systembugtj/electron,leolujuyi/electron,jlhbaseball15/electron,thomsonreuters/electron,bruce/electron,lzpfmh/electron,Ivshti/electron,fffej/electron,jlord/electron,SufianHassan/electron,shaundunne/electron,BionicClick/electron,davazp/electron,mattotodd/electron,setzer777/electron,trigrass2/electron,fritx/electron,gamedevsam/electron,SufianHassan/electron,mrwizard82d1/electron,simongregory/electron,xiruibing/electron,thingsinjars/electron,Jacobichou/electron,Jonekee/electron,dahal/electron,abhishekgahlot/electron,aliib/electron,fireball-x/atom-shell,seanchas116/electron,fritx/electron,cos2004/electron,howmuchcomputer/electron,biblerule/UMCTelnetHub,setzer777/electron,fritx/electron,Zagorakiss/electron,davazp/electron,bruce/electron,leethomas/electron,minggo/electron,jiaz/electron,jlord/electron,nicholasess/electron,subblue/electron,wan-qy/electron,rhencke/electron,jacksondc/electron,sshiting/electron,ervinb/electron,digideskio/electron,mattotodd/electron,jiaz/electron,arturts/electron,Jacobichou/electron,tonyganch/electron,trankmichael/electron,renaesop/electron,leolujuyi/electron,bpasero/electron,gabriel/electron,xiruibing/electron,evgenyzinoviev/electron,kokdemo/electron,rreimann/electron,bobwol/electron,twolfson/electron,bright-sparks/electron,ianscrivener/electron,jcblw/electron,benweissmann/electron,DivyaKMenon/electron,etiktin/electron,fabien-d/electron,mirrh/electron,GoooIce/electron,aliib/electron,yalexx/electron,pandoraui/electron,wolfflow/electron,fireball-x/atom-shell,kikong/electron,brave/electron,BionicClick/electron,thompsonemerson/electron,mattotodd/electron,Floato/electron,dkfiresky/electron,farmisen/electron,dahal/electron,seanchas116/electron,fffej/electron,anko/electron,cqqccqc/electron,joneit/electron,robinvandernoord/electron,BionicClick/electron,tonyganch/electron,anko/electron,Zagorakiss/electron,stevekinney/electron,lrlna/electron,matiasinsaurralde/electron,jonatasfreitasv/electron,faizalpribadi/electron,aaron-goshine/electron,deepak1556/atom-shell,stevemao/electron,zhakui/electron,sky7sea/electron,Jonekee/electron,greyhwndz/electron,Andrey-Pavlov/electron,leftstick/electron,yan-foto/electron,roadev/electron,chrisswk/electron,stevekinney/electron,MaxWhere/electron,eriser/electron,gerhardberger/electron,cos2004/electron,natgolov/electron,kokdemo/electron,bright-sparks/electron,fireball-x/atom-shell,fireball-x/atom-shell,GoooIce/electron,carsonmcdonald/electron,icattlecoder/electron,DivyaKMenon/electron,faizalpribadi/electron,maxogden/atom-shell,the-ress/electron,pirafrank/electron,adcentury/electron,bwiggs/electron,aaron-goshine/electron,fritx/electron,micalan/electron,abhishekgahlot/electron,edulan/electron,gamedevsam/electron,shiftkey/electron,eriser/electron,Jacobichou/electron,jannishuebl/electron,matiasinsaurralde/electron,astoilkov/electron,trankmichael/electron,kazupon/electron,joaomoreno/atom-shell,sshiting/electron,nekuz0r/electron,sky7sea/electron,ianscrivener/electron,pirafrank/electron,michaelchiche/electron,leftstick/electron,michaelchiche/electron,mattdesl/electron,yan-foto/electron,shiftkey/electron,shennushi/electron,dkfiresky/electron,minggo/electron,voidbridge/electron,jjz/electron,takashi/electron,mrwizard82d1/electron,Ivshti/electron,voidbridge/electron,tomashanacek/electron,mhkeller/electron,etiktin/electron,d-salas/electron,eric-seekas/electron,dkfiresky/electron,nicobot/electron,arusakov/electron,posix4e/electron,cqqccqc/electron,zhakui/electron,rreimann/electron,JesselJohn/electron,saronwei/electron,adcentury/electron,aecca/electron,gstack/infinium-shell,eriser/electron,simonfork/electron,tylergibson/electron,iftekeriba/electron,twolfson/electron,mrwizard82d1/electron,RobertJGabriel/electron,tylergibson/electron,John-Lin/electron,seanchas116/electron,subblue/electron,xfstudio/electron,JesselJohn/electron,brenca/electron,Evercoder/electron,preco21/electron,felixrieseberg/electron,twolfson/electron,sshiting/electron,natgolov/electron,bpasero/electron,mattdesl/electron,JussMee15/electron,GoooIce/electron,aliib/electron,icattlecoder/electron,kostia/electron,MaxWhere/electron,zhakui/electron,edulan/electron,Jacobichou/electron,joneit/electron,pandoraui/electron,jaanus/electron,jonatasfreitasv/electron,gerhardberger/electron,cos2004/electron,thingsinjars/electron,the-ress/electron,jcblw/electron,kenmozi/electron,mubassirhayat/electron,eriser/electron,micalan/electron,jacksondc/electron,setzer777/electron,GoooIce/electron,smczk/electron,leftstick/electron,RIAEvangelist/electron,Floato/electron,soulteary/electron,mjaniszew/electron,jtburke/electron,pombredanne/electron,MaxGraey/electron,saronwei/electron,zhakui/electron
|
f2071eb5781f4dfa4cacbcd9f0d1c71412ba80b1
|
constants.py
|
constants.py
|
# Store various constants here
# Maximum file upload size (in bytes).
MAX_CONTENT_LENGTH = 1 * 1024 * 1024 * 1024
# Authentication constants
PWD_HASH_ALGORITHM = 'pbkdf2_sha256'
SALT_SIZE = 24
MIN_PASSWORD_LENGTH = 8
MAX_PASSWORD_LENGTH = 1024
HASH_ROUNDS = 50000
PWD_RESET_KEY_LENGTH = 32
# Length of time before recovery key expires, in minutes.
PWD_RESET_KEY_EXPIRATION = 1440
class Permissions:
'''
Enumerates administrator permissions. These values are independent of
each other, but must be unique. Permissions should be stored in the session
'''
# Access to the admin page
Admin = 0
# Website admins.
SiteAdmin = 1
# Allowed to add and manage users.
UserAdmin = 2
# Allowed to run the room hassle.
HassleAdmin = 3
|
# Store various constants here
# Maximum file upload size (in bytes).
MAX_CONTENT_LENGTH = 1 * 1024 * 1024 * 1024
# Authentication constants
PWD_HASH_ALGORITHM = 'pbkdf2_sha256'
SALT_SIZE = 24
MIN_PASSWORD_LENGTH = 8
MAX_PASSWORD_LENGTH = 1024
HASH_ROUNDS = 100000
PWD_RESET_KEY_LENGTH = 32
# Length of time before recovery key expires, in minutes.
PWD_RESET_KEY_EXPIRATION = 1440
class Permissions:
'''
Enumerates administrator permissions. These values are independent of
each other, but must be unique. Permissions should be stored in the session
'''
# Access to the admin page
Admin = 0
# Website admins.
SiteAdmin = 1
# Allowed to add and manage users.
UserAdmin = 2
# Allowed to run the room hassle.
HassleAdmin = 3
|
Set hash rounds back to 100000
|
Set hash rounds back to 100000
- Installed python-m2crypto package which speeds up pbkdf2 enough that
100K rounds is fine again.
|
Python
|
mit
|
RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite,RuddockHouse/RuddockWebsite
|
3a78496f350c904ce64d30f422dfae8b6bc879c3
|
flask_api/tests/runtests.py
|
flask_api/tests/runtests.py
|
import unittest
import sys
import subprocess
if __name__ == '__main__':
if len(sys.argv) > 1:
unittest.main(module='flask_api.tests')
else:
subprocess.call([sys.executable, '-m', 'unittest', 'discover'])
|
import unittest
if __name__ == '__main__':
unittest.main(module='flask_api.tests')
|
Simplify test execution to restore coverage measurement
|
Simplify test execution to restore coverage measurement
|
Python
|
bsd-2-clause
|
theskumar-archive/flask-api,theskumar-archive/flask-api,theskumar-archive/flask-api,theskumar-archive/flask-api
|
dcb8add6685dfb7dff626742b17ce03e013e72a1
|
src/enrich/kucera_francis_enricher.py
|
src/enrich/kucera_francis_enricher.py
|
__author__ = 's7a'
# All imports
from extras import KuceraFrancis
from resource import Resource
from os import path
# The Kucera Francis enrichment class
class KuceraFrancisEnricher:
# Constructor for the Kucera Francis Enricher
def __init__(self):
self.kf = KuceraFrancis(path.join('data', 'kucera_francis.csv'))
# Enrich the word
def enrich_word(self, word):
if self.kf.frequency(word) == 0:
return Resource.link(word)
return word
|
__author__ = 's7a'
# All imports
from extras import StemmedKuceraFrancis
from resource import Resource
from os import path
# The Kucera Francis enrichment class
class KuceraFrancisEnricher:
# Constructor for the Kucera Francis Enricher
def __init__(self):
self.kf = StemmedKuceraFrancis(path.join('data', 'kucera_francis.csv'))
# Enrich the word
def enrich_word(self, word):
if self.kf.frequency(word) == 0:
return Resource.link(word)
return word
|
Use stemmed Kucera Francis for Enrichment
|
Use stemmed Kucera Francis for Enrichment
|
Python
|
mit
|
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
|
d57844d1d6b2172fe196db4945517a5b3a68d343
|
satchless/process/__init__.py
|
satchless/process/__init__.py
|
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return not self.get_next_step()
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
class InvalidData(Exception):
"""
Raised for by step validation process
"""
pass
class Step(object):
"""
A single step in a multistep process
"""
def validate(self):
raise NotImplementedError() # pragma: no cover
class ProcessManager(object):
"""
A multistep process handler
"""
def validate_step(self, step):
try:
step.validate()
except InvalidData:
return False
return True
def get_next_step(self):
for step in self:
if not self.validate_step(step):
return step
def get_errors(self):
errors = {}
for step in self:
try:
step.validate()
except InvalidData as error:
errors[str(step)] = error
return errors
def is_complete(self):
return self.get_next_step() is None
def __getitem__(self, step_id):
for step in self:
if str(step) == step_id:
return step
raise KeyError('%r is not a valid step' % (step_id,))
|
Check explicit that next step is None
|
Check explicit that next step is None
|
Python
|
bsd-3-clause
|
taedori81/satchless
|
221a84d52e5165013a5c7eb0b00c3ebcae294c8a
|
dashboard_app/extension.py
|
dashboard_app/extension.py
|
from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bundle_stream_list"
@property
def description(self):
return "Validation Dashboard"
@property
def version(self):
import versiontools
import dashboard_app
return versiontools.format_version(dashboard_app.__version__)
def contribute_to_settings(self, settings):
super(DashboardExtension, self).contribute_to_settings(settings)
settings['INSTALLED_APPS'].extend([
"linaro_django_pagination",
"south",
])
settings['MIDDLEWARE_CLASSES'].append(
'linaro_django_pagination.middleware.PaginationMiddleware')
settings['RESTRUCTUREDTEXT_FILTER_SETTINGS'] = {
"initial_header_level": 4}
# TODO: Add dataview database support
|
from lava_server.extension import LavaServerExtension
class DashboardExtension(LavaServerExtension):
@property
def app_name(self):
return "dashboard_app"
@property
def name(self):
return "Dashboard"
@property
def main_view_name(self):
return "dashboard_app.views.bundle_stream_list"
@property
def description(self):
return "Validation Dashboard"
@property
def version(self):
import versiontools
import dashboard_app
return versiontools.format_version(dashboard_app.__version__)
def contribute_to_settings(self, settings):
super(DashboardExtension, self).contribute_to_settings(settings)
settings['INSTALLED_APPS'].extend([
"linaro_django_pagination",
"south",
])
settings['MIDDLEWARE_CLASSES'].append(
'linaro_django_pagination.middleware.PaginationMiddleware')
settings['RESTRUCTUREDTEXT_FILTER_SETTINGS'] = {
"initial_header_level": 4}
def contribute_to_settings_ex(self, settings_module, settings_object):
settings_module['DATAVIEW_DIRS'] = settings_object._settings.get(
"DATAVIEW_DIRS", [])
settings_module['DATAREPORT_DIRS'] = settings_object._settings.get(
"DATAREPORT_DIRS", [])
|
Add support for configuring data views and reports
|
Add support for configuring data views and reports
|
Python
|
agpl-3.0
|
Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server
|
0003ee31f78d7861713a2bb7daacb9701b26a1b9
|
cinder/wsgi/wsgi.py
|
cinder/wsgi/wsgi.py
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cinder OS API WSGI application."""
import sys
import warnings
from cinder import objects
warnings.simplefilter('once', DeprecationWarning)
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import wsgi
from cinder import i18n
i18n.enable_lazy()
# Need to register global_opts
from cinder.common import config
from cinder import rpc
from cinder import version
CONF = cfg.CONF
def initialize_application():
objects.register_all()
CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup(CONF, "cinder")
config.set_middleware_defaults()
rpc.init(CONF)
return wsgi.Loader(CONF).load_app(name='osapi_volume')
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Cinder OS API WSGI application."""
import sys
import warnings
from cinder import objects
warnings.simplefilter('once', DeprecationWarning)
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import wsgi
from cinder import i18n
i18n.enable_lazy()
# Need to register global_opts
from cinder.common import config
from cinder.common import constants
from cinder import rpc
from cinder import service
from cinder import version
CONF = cfg.CONF
def initialize_application():
objects.register_all()
CONF(sys.argv[1:], project='cinder',
version=version.version_string())
logging.setup(CONF, "cinder")
config.set_middleware_defaults()
rpc.init(CONF)
service.setup_profiler(constants.API_BINARY, CONF.host)
return wsgi.Loader(CONF).load_app(name='osapi_volume')
|
Initialize osprofiler in WSGI application
|
Initialize osprofiler in WSGI application
This patch adds missing initialization of OSProfiler
when Cinder API is running as WSGI application.
Change-Id: Ifaffa2d58eeadf5d47fafbdde5538d26bcd346a6
|
Python
|
apache-2.0
|
Datera/cinder,phenoxim/cinder,mahak/cinder,openstack/cinder,j-griffith/cinder,Datera/cinder,j-griffith/cinder,mahak/cinder,openstack/cinder,phenoxim/cinder
|
ef50e82c3c1f49d63d013ac538d932d40c430a46
|
pyradiator/endpoint.py
|
pyradiator/endpoint.py
|
import queue
import threading
class Producer(object):
def __init__(self, period_in_seconds, queue, function):
self._period_in_seconds = period_in_seconds
self._queue = queue
self._function = function
self._event = threading.Event()
self._thread = threading.Thread(target=self._loop)
def start(self):
self._thread.start()
def stop(self):
self._event.set()
self._thread.join()
def _loop(self):
while not self._event.wait(self._period_in_seconds):
self.__put_item_into_the_queue()
def __put_item_into_the_queue(self):
try:
self._queue.put(self._function)
except queue.Full:
pass
class Consumer(object):
STOP_SENTINEL = "STOP"
def __init__(self, queue, function):
self._queue = queue
self._function = function
self._thread = threading.Thread(target=self._loop)
self.no_date_from_the_queue = True
def start(self):
self._thread.start()
def stop(self):
self._queue.put(self.STOP_SENTINEL)
self._thread.join()
def _loop(self):
for result in iter(self._queue.get, self.STOP_SENTINEL):
self.no_date_from_the_queue = result is None
if result:
self._function(result)
|
try:
import queue
except ImportError:
import Queue
import threading
class Producer(object):
def __init__(self, period_in_seconds, queue, function):
self._period_in_seconds = period_in_seconds
self._queue = queue
self._function = function
self._event = threading.Event()
self._thread = threading.Thread(target=self._loop)
def start(self):
self._thread.start()
def stop(self):
self._event.set()
self._thread.join()
def _loop(self):
while not self._event.wait(self._period_in_seconds):
self.__put_item_into_the_queue()
def __put_item_into_the_queue(self):
try:
self._queue.put(self._function)
except queue.Full:
pass
class Consumer(object):
STOP_SENTINEL = "STOP"
def __init__(self, queue, function):
self._queue = queue
self._function = function
self._thread = threading.Thread(target=self._loop)
self.no_date_from_the_queue = True
def start(self):
self._thread.start()
def stop(self):
self._queue.put(self.STOP_SENTINEL)
self._thread.join()
def _loop(self):
for result in iter(self._queue.get, self.STOP_SENTINEL):
self.no_date_from_the_queue = result is None
if result:
self._function(result)
|
Handle import error on older python versions
|
Handle import error on older python versions
|
Python
|
mit
|
crashmaster/pyradiator
|
91556f15e64f2407d77ab6ea35d74abccc9f1984
|
pystitch/dmc_colors.py
|
pystitch/dmc_colors.py
|
import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
print row
number = int(row[0])
name = row[1]
hex_color = row[5]
red, green, blue = color.RGBColorFromHexString(hex_color)
return DMCColor(number, name, red, green, blue)
class DMCColor(color.RGBColor):
def __init__(self, number, name, red, green, blue):
self.number = number
self.name = name
super(DMCColor, self).__init__(red, green, blue)
def main():
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = list()
for row in reader:
dmc_colors.append(_CreateDmcColorFromRow(row))
print dmc_colors
main()
|
import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int(row[0])
name = row[1]
hex_color = row[5]
red, green, blue = color.RGBTupleFromHexString(hex_color)
return DMCColor(number, name, red, green, blue)
# DMC Colors singleton
_dmc_colors = None
def _CreateDMCColors():
global _dmc_colors
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = set()
for row in reader:
dmc_colors.add(_CreateDmcColorFromRow(row))
return dmc_colors
def GetDMCColors():
global _dmc_colors
if not _dmc_colors:
_dmc_colors = frozenset(_CreateDMCColors())
return _dmc_colors
class DMCColor(color.RGBColor):
def __init__(self, number, name, red, green, blue):
self.number = number
self.name = name
super(DMCColor, self).__init__(red, green, blue)
# Simple executable functionality for debugging.
def main():
for color in GetDMCColors():
print color
if __name__ == '__main__':
main()
|
Add functionality to build the DMCColors set.
|
Add functionality to build the DMCColors set.
|
Python
|
apache-2.0
|
nanaze/pystitch,nanaze/pystitch
|
511a133599b86deae83d9ad8a3f7a7c5c45e07bf
|
core/views.py
|
core/views.py
|
from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
|
from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
form = ContactForm()
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
|
Clear the contact form after it has been successfully posted.
|
Clear the contact form after it has been successfully posted.
|
Python
|
bsd-3-clause
|
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
|
7cb68f6a749a38fef9820004a857e301c12a3044
|
morenines/util.py
|
morenines/util.py
|
import os
import hashlib
from fnmatch import fnmatchcase
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
|
import os
import hashlib
def get_files(index):
paths = []
for dirpath, dirnames, filenames in os.walk(index.headers['root_path']):
# Remove ignored directories
dirnames[:] = [d for d in dirnames if not index.ignores.match(d)]
for filename in (f for f in filenames if not index.ignores.match(f)):
# We want the path of the file, not its name
path = os.path.join(dirpath, filename)
# That path must be relative to the root, not absolute
path = os.path.relpath(path, index.headers['root_path'])
paths.append(path)
return paths
def get_ignores(ignores_path):
with open(ignores_path, 'r') as ignores_file:
ignores = [line.strip() for line in ignores_file]
return ignores
def get_hash(path):
h = hashlib.sha1()
with open(path, 'rb') as f:
h.update(f.read())
return h.hexdigest()
def get_new_and_missing(index):
current_files = get_files(index)
new_files = [path for path in current_files if path not in index.files]
missing_files = [path for path in index.files.iterkeys() if path not in current_files]
return new_files, missing_files
|
Fix in-place os.walk() dirs modification
|
Fix in-place os.walk() dirs modification
|
Python
|
mit
|
mcgid/morenines,mcgid/morenines
|
c157ddeae7131e4141bca43857730103617b42c4
|
froide/upload/serializers.py
|
froide/upload/serializers.py
|
from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
|
from rest_framework import serializers
from .models import Upload
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = Upload
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['guid'].required = True
|
Make guid required in upload API
|
Make guid required in upload API
|
Python
|
mit
|
stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide
|
1d32debc1ea2ce8d11c8bc1abad048d6e4937520
|
froide_campaign/listeners.py
|
froide_campaign/listeners.py
|
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .consumers import PRESENCE_ROOM
from .models import Campaign
def connect_info_object(sender, **kwargs):
reference = kwargs.get('reference')
if not reference:
return
if not reference.startswith('campaign:'):
return
namespace, campaign_value = reference.split(':', 1)
try:
campaign, ident = campaign_value.split('@', 1)
except (ValueError, IndexError):
return
if not ident:
return
try:
campaign_pk = int(campaign)
except ValueError:
return
try:
campaign = Campaign.objects.get(pk=campaign_pk)
except Campaign.DoesNotExist:
return
provider = campaign.get_provider()
iobj = provider.connect_request(ident, sender)
broadcast_request_made(provider, iobj)
def broadcast_request_made(provider, iobj):
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
PRESENCE_ROOM.format(provider.campaign.id), {
"type": "request_made",
"data": provider.get_detail_data(iobj)
}
)
|
Fix non-iobj campaign request connection
|
Fix non-iobj campaign request connection
|
Python
|
mit
|
okfde/froide-campaign,okfde/froide-campaign,okfde/froide-campaign
|
83bc5fbaff357b43c49f948ec685e7ab067b8f78
|
core/urls.py
|
core/urls.py
|
from django.conf.urls.defaults import *
urlpatterns = patterns("core.views",
url("^airport_list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/",
"airports_for_boundary", name="airports_for_boundary"),
)
|
from django.conf.urls.defaults import *
urlpatterns = patterns("core.views",
url("^airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/",
"airports_for_boundary", name="airports_for_boundary"),
)
|
Change URL pattern for airport list.
|
Change URL pattern for airport list.
|
Python
|
bsd-2-clause
|
stephenmcd/ratemyflight,stephenmcd/ratemyflight
|
de1ff8a480cc6d6e86bb179e6820ab9f21145679
|
byceps/services/user/event_service.py
|
byceps/services/user/event_service.py
|
"""
byceps.services.user.event_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from typing import Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData
) -> UserEvent:
"""Assemble, but not persist, a user event."""
now = datetime.utcnow()
return UserEvent(now, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
|
"""
byceps.services.user.event_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from typing import Optional, Sequence
from ...database import db
from ...typing import UserID
from .models.event import UserEvent, UserEventData
def create_event(event_type: str, user_id: UserID, data: UserEventData) -> None:
"""Create a user event."""
event = _build_event(event_type, user_id, data)
db.session.add(event)
db.session.commit()
def _build_event(event_type: str, user_id: UserID, data: UserEventData,
occurred_at: Optional[datetime]=None) -> UserEvent:
"""Assemble, but not persist, a user event."""
if occurred_at is None:
occurred_at = datetime.utcnow()
return UserEvent(occurred_at, event_type, user_id, data)
def get_events_for_user(user_id: UserID) -> Sequence[UserEvent]:
"""Return the events for that user."""
return UserEvent.query \
.filter_by(user_id=user_id) \
.order_by(UserEvent.occurred_at) \
.all()
|
Allow to provide a custom `occurred_at` value when building a user event
|
Allow to provide a custom `occurred_at` value when building a user event
|
Python
|
bsd-3-clause
|
homeworkprod/byceps,m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps
|
e4b2d60af93fd84407eb7107497b2b500d79f9d7
|
calexicon/dates/tests/test_distant.py
|
calexicon/dates/tests/test_distant.py
|
import unittest
from datetime import date as vanilla_date, timedelta
from calexicon.dates import DistantDate
class TestDistantDate(unittest.TestCase):
def test_subtraction(self):
dd = DistantDate(10000, 1, 1)
self.assertIsInstance(dd - vanilla_date(9999, 1, 1), timedelta)
self.assertIsInstance(dd - timedelta(0), DistantDate)
def test_subtract_correct_result(self):
dd = DistantDate(10000, 1, 2)
dd2 = DistantDate(10000, 1, 1)
self.assertEqual(dd - dd2, timedelta(days=1))
def test_subtract_vanilla_date_from_distant_date(self):
dd = DistantDate(10000, 1, 2)
d = vanilla_date(9984, 2, 29)
x = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 15 * 365 + 3 + 2
self.assertEqual(dd - d, timedelta(days=x))
|
import unittest
from datetime import date as vanilla_date, timedelta
from calexicon.calendars import ProlepticJulianCalendar
from calexicon.dates import DateWithCalendar, DistantDate
class TestDistantDate(unittest.TestCase):
def test_subtraction(self):
dd = DistantDate(10000, 1, 1)
self.assertIsInstance(dd - vanilla_date(9999, 1, 1), timedelta)
self.assertIsInstance(dd - timedelta(0), DistantDate)
def test_subtract_correct_result(self):
dd = DistantDate(10000, 1, 2)
dd2 = DistantDate(10000, 1, 1)
self.assertEqual(dd - dd2, timedelta(days=1))
def test_subtract_vanilla_date_from_distant_date(self):
dd = DistantDate(10000, 1, 2)
d = vanilla_date(9984, 2, 29)
x = 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 + 15 * 365 + 3 + 2
self.assertEqual(dd - d, timedelta(days=x))
def test_equality(self):
dd = DistantDate(2010, 8, 1)
ProlepticJulianCalendar().bless(dd)
dwc = DateWithCalendar(ProlepticJulianCalendar, DistantDate(2010, 8, 1))
self.assertTrue(dwc == dd)
|
Add a passing test for equality.
|
Add a passing test for equality.
Narrow down problems with constructing a date far in the future.
|
Python
|
apache-2.0
|
jwg4/qual,jwg4/calexicon
|
1f2d8fadd114106cefbc23060f742163be415376
|
cherrypy/process/__init__.py
|
cherrypy/process/__init__.py
|
"""Site container for an HTTP server.
A Web Site Process Bus object is used to connect applications, servers,
and frameworks with site-wide services such as daemonization, process
reload, signal handling, drop privileges, PID file management, logging
for all of these, and many more.
The 'plugins' module defines a few abstract and concrete services for
use with the bus. Some use tool-specific channels; see the documentation
for each class.
"""
from cherrypy.process.wspbus import bus # noqa
from cherrypy.process import plugins, servers # noqa
|
"""Site container for an HTTP server.
A Web Site Process Bus object is used to connect applications, servers,
and frameworks with site-wide services such as daemonization, process
reload, signal handling, drop privileges, PID file management, logging
for all of these, and many more.
The 'plugins' module defines a few abstract and concrete services for
use with the bus. Some use tool-specific channels; see the documentation
for each class.
"""
from .wspbus import bus
from . import plugins, servers
__all__ = ('bus', 'plugins', 'servers')
|
Use __all__ to avoid linter errors
|
Use __all__ to avoid linter errors
|
Python
|
bsd-3-clause
|
Safihre/cherrypy,Safihre/cherrypy,cherrypy/cherrypy,cherrypy/cherrypy
|
9deef39639bd42d6a6c91f6aafdf8e92a73a605d
|
fortdepend/preprocessor.py
|
fortdepend/preprocessor.py
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(pcpp.Preprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
import io
import pcpp
class FortranPreprocessor(pcpp.Preprocessor):
def __init__(self):
super(FortranPreprocessor, self).__init__()
def parse_to_string_lines(self, text):
with io.StringIO() as f:
self.parse(text)
self.write(f)
f.seek(0)
result = f.readlines()
return result
|
Fix super() call (properly) for py2.7
|
Fix super() call (properly) for py2.7
|
Python
|
mit
|
ZedThree/fort_depend.py,ZedThree/fort_depend.py
|
0a234829ecdde1483273d0f6fb249cc9fc0425d5
|
ffmpeg_process.py
|
ffmpeg_process.py
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if self._cmdline is None:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.paused:
self.unpause()
if self.running:
logging.debug('stopping ffmpeg process')
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
# coding: utf-8
import logging
import psutil
from subprocess import PIPE
class FfmpegProcess(object):
def __init__(self):
self._cmdline = None
self._process = None
self._paused = False
def run(self):
if self._cmdline is None:
logging.debug('cmdline is not yet defined')
return
if not self.running:
logging.debug('starting ffmpeg with command-line:\n`%s`',
self.cmdline)
# stdin pipe is required to shutdown ffmpeg gracefully (see below)
self._process = psutil.Popen(self._cmdline, stdin=PIPE)
def stop(self):
if self.paused:
self.unpause()
if self.running:
logging.debug('stopping ffmpeg process')
# emulate 'q' keyboard press to shutdown ffmpeg
self._process.communicate(input='q')
self._process.wait()
@property
def running(self):
return self._process is not None and self._process.is_running()
def pause(self):
if self.running:
if not self._paused:
logging.debug('suspending ffmpeg process')
self._process.suspend()
self._paused = True
def unpause(self):
if self.running:
if self._paused:
logging.debug('resuming ffmpeg process')
self._process.resume()
self._paused = False
@property
def paused(self):
return self._paused and self.running
@property
def cmdline(self):
return self._cmdline
@cmdline.setter
def cmdline(self, value):
self._cmdline = value
|
Implement pause property more accurately
|
Implement pause property more accurately
|
Python
|
mit
|
dkrikun/ffmpeg-rcd
|
2649e2e6a2d79febad14e0728c65b1429beb8858
|
spotpy/unittests/test_fast.py
|
spotpy/unittests/test_fast.py
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 800 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(800,len(results))
if __name__ == '__main__':
unittest.main()
|
import unittest
try:
import spotpy
except ImportError:
import sys
sys.path.append(".")
import spotpy
from spotpy.examples.spot_setup_hymod_python import spot_setup
class TestFast(unittest.TestCase):
def setUp(self):
self.spot_setup = spot_setup()
self.rep = 200 # REP must be a multiply of amount of parameters which are in 7 if using hymod
self.timeout = 10 # Given in Seconds
def test_fast(self):
sampler = spotpy.algorithms.fast(self.spot_setup, parallel="seq", dbname='test_FAST', dbformat="ram",
sim_timeout=self.timeout)
results = []
sampler.sample(self.rep)
results = sampler.getdata()
self.assertEqual(200,len(results))
if __name__ == '__main__':
unittest.main()
|
Reduce amounts of runs for fast test analysis
|
Reduce amounts of runs for fast test analysis
|
Python
|
mit
|
thouska/spotpy,bees4ever/spotpy,thouska/spotpy,bees4ever/spotpy,bees4ever/spotpy,thouska/spotpy
|
6dc4314f1c5510a6e5f857d739956654909d97b2
|
pronto/__init__.py
|
pronto/__init__.py
|
# coding: utf-8
"""a Python frontend to ontologies
"""
from __future__ import absolute_import
from __future__ import unicode_literals
__version__ = 'dev'
__author__ = 'Martin Larralde'
__author_email__ = '[email protected]'
__license__ = "MIT"
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .synonym import Synonym, SynonymType
# Dynamically get the version of the installed module
try:
import pkg_resources
__version__ = pkg_resources.get_distribution(__name__).version
except Exception:
pkg_resources = None
finally:
del pkg_resources
|
# coding: utf-8
"""a Python frontend to ontologies
"""
from __future__ import absolute_import
from __future__ import unicode_literals
__version__ = 'dev'
__author__ = 'Martin Larralde'
__author_email__ = '[email protected]'
__license__ = "MIT"
from .ontology import Ontology
from .term import Term, TermList
from .relationship import Relationship
from .synonym import Synonym, SynonymType
from .description import Description
# Dynamically get the version of the installed module
try:
import pkg_resources
__version__ = pkg_resources.get_distribution(__name__).version
except Exception:
pkg_resources = None
finally:
del pkg_resources
|
Add `Description` to top-level imports
|
Add `Description` to top-level imports
|
Python
|
mit
|
althonos/pronto
|
1e47f79647baffd62d2a434710fe98b3c2247f28
|
tests/pgcomplex_app/models.py
|
tests/pgcomplex_app/models.py
|
# -*- coding: utf-8 -*-
from django.db import models
from django_orm.postgresql.fields.arrays import ArrayField
from django_orm.postgresql.fields.interval import IntervalField
from django_orm.postgresql.fields.bytea import ByteaField
from django_orm.postgresql.manager import PgManager
class IntModel(models.Model):
lista = ArrayField(dbtype='int')
objects = PgManager()
class TextModel(models.Model):
lista = ArrayField(dbtype='text')
objects = PgManager()
class DoubleModel(models.Model):
lista = ArrayField(dbtype='double precision')
objects = PgManager()
class VarcharModel(models.Model):
lista = ArrayField(dbtype='varchar(40)')
objects = PgManager()
class IntervalModel(models.Model):
iv = IntervalField()
objects = PgManager()
class ByteaModel(models.Model):
bb = ByteaField()
objects = PgManager()
from django_orm.postgresql.geometric.fields import PointField, CircleField
from django_orm.postgresql.geometric.fields import LsegField, BoxField
from django_orm.postgresql.geometric.fields import PathField, PolygonField
class GeomModel(models.Model):
pt = PointField()
pl = PolygonField()
ln = LsegField()
bx = BoxField()
cr = CircleField()
ph = PathField()
objects = PgManager()
|
# -*- coding: utf-8 -*-
from django.db import models
from django_orm.postgresql.fields.arrays import ArrayField
from django_orm.postgresql.fields.interval import IntervalField
from django_orm.postgresql.fields.bytea import ByteaField
from django_orm.manager import Manager
class IntModel(models.Model):
lista = ArrayField(dbtype='int')
objects = Manager()
class TextModel(models.Model):
lista = ArrayField(dbtype='text')
objects = Manager()
class DoubleModel(models.Model):
lista = ArrayField(dbtype='double precision')
objects = Manager()
class VarcharModel(models.Model):
lista = ArrayField(dbtype='varchar(40)')
objects = Manager()
class IntervalModel(models.Model):
iv = IntervalField()
objects = Manager()
class ByteaModel(models.Model):
bb = ByteaField()
objects = Manager()
from django_orm.postgresql.geometric.fields import PointField, CircleField
from django_orm.postgresql.geometric.fields import LsegField, BoxField
from django_orm.postgresql.geometric.fields import PathField, PolygonField
class GeomModel(models.Model):
pt = PointField()
pl = PolygonField()
ln = LsegField()
bx = BoxField()
cr = CircleField()
ph = PathField()
objects = Manager()
|
Fix tests with last changes on api.
|
Fix tests with last changes on api.
|
Python
|
bsd-3-clause
|
EnTeQuAk/django-orm,EnTeQuAk/django-orm
|
035d871399a5e9a60786332b2a8c42fbea98397f
|
docker/settings.py
|
docker/settings.py
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 100
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
from .base_settings import *
import os
INSTALLED_APPS += [
'data_aggregator.apps.DataAggregatorConfig',
'webpack_loader',
]
if os.getenv('ENV') == 'localdev':
DEBUG = True
DATA_AGGREGATOR_ACCESS_GROUP = 'u_test_group'
DATA_AGGREGATOR_THREADING_ENABLED = False
RESTCLIENTS_DAO_CACHE_CLASS = None
DATA_AGGREGATOR_THREADING_ENABLED = False
else:
DATA_AGGREGATOR_ACCESS_GROUP = os.getenv('ACCESS_GROUP', '')
DATA_AGGREGATOR_THREADING_ENABLED = True
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'data_aggregator/bundles/',
'STATS_FILE': os.path.join(BASE_DIR, 'data_aggregator', 'static', 'webpack-stats.json'),
}
}
RESTCLIENTS_CANVAS_POOL_SIZE = 50
ACADEMIC_CANVAS_ACCOUNT_ID = '84378'
|
Revert "Increase rest client pool size to 100"
|
Revert "Increase rest client pool size to 100"
|
Python
|
apache-2.0
|
uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics,uw-it-aca/canvas-analytics
|
7665e2b0af042948dfc7a1814275cd3309f5f6cf
|
pages/tests/__init__.py
|
pages/tests/__init__.py
|
"""Django page CMS test suite module"""
from djangox.test.depth import alltests
def suite():
return alltests(__file__, __name__)
|
"""Django page CMS test suite module"""
import unittest
def suite():
suite = unittest.TestSuite()
from pages.tests.test_functionnal import FunctionnalTestCase
from pages.tests.test_unit import UnitTestCase
from pages.tests.test_regression import RegressionTestCase
from pages.tests.test_pages_link import LinkTestCase
from pages.tests.test_auto_render import AutoRenderTestCase
suite.addTest(unittest.makeSuite(FunctionnalTestCase))
suite.addTest(unittest.makeSuite(UnitTestCase))
suite.addTest(unittest.makeSuite(RegressionTestCase))
suite.addTest(unittest.makeSuite(LinkTestCase))
suite.addTest(unittest.makeSuite(AutoRenderTestCase))
return suite
|
Remove the dependency to django-unittest-depth
|
Remove the dependency to django-unittest-depth
|
Python
|
bsd-3-clause
|
remik/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,batiste/django-page-cms,akaihola/django-page-cms,oliciv/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,akaihola/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,oliciv/django-page-cms
|
8dccce77f6c08a7c20f38b9f1bacc27b71ab56a1
|
examples/web/wiki/macros/utils.py
|
examples/web/wiki/macros/utils.py
|
"""Utils macros
Utility macros
"""
def macros(macro, environ, *args, **kwargs):
"""Return a list of available macros"""
s = "\n".join(["* %s" % k for k in environ["macros"].keys()])
return environ["parser"].generate(s, environ=environ)
|
"""Utils macros
Utility macros
"""
from inspect import getdoc
def macros(macro, environ, *args, **kwargs):
"""Return a list of available macros"""
macros = environ["macros"].items()
s = "\n".join(["== %s ==\n%s\n" % (k, getdoc(v)) for k, v in macros])
return environ["parser"].generate(s, environ=environ)
|
Change the output of <<macros>>
|
examples/web/wiki: Change the output of <<macros>>
|
Python
|
mit
|
treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,treemo/circuits,eriol/circuits
|
38833f68daabe845650250e3edf9cb4b3cc9cb62
|
events/templatetags/humantime.py
|
events/templatetags/humantime.py
|
# -*- encoding:utf-8 -*-
# Template tag
from django.template.defaultfilters import stringfilter
from datetime import datetime, timedelta
from django import template
register = template.Library()
@register.filter
def event_time(start, end):
today = datetime.today ()
result = ""
if start == today:
result += "aujourd'hui "
else:
result += "le %s " % start.strftime ("%A %d %B %Y")
if start.day == end.day and start.month == end.month and start.year == end.year:
result += "de %s " % start.strftime ("%H:%M")
result += "à %s " % end.strftime ("%H:%M")
else:
result += "à %s" % start.strftime ("%H:%M")
result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M")
return result
|
# -*- encoding:utf-8 -*-
# Template tag
from django.template.defaultfilters import stringfilter
from datetime import datetime, timedelta
from django import template
import locale
register = template.Library()
@register.filter
def event_time(start, end):
today = datetime.today ()
result = ""
# Hack! get the correct user local from the request
loc = locale.getlocale()
locale.setlocale(locale.LC_ALL, 'fr_CA.UTF8')
if start == today:
result += "Aujourd'hui "
else:
result += "Le %s " % start.strftime ("%A %d %B %Y")
if start.day == end.day and start.month == end.month and start.year == end.year:
result += "de %s " % start.strftime ("%H:%M")
result += "à %s " % end.strftime ("%H:%M")
else:
result += "à %s" % start.strftime ("%H:%M")
result += "jusqu'au %s" % end.strftime ("%A %d %B %Y à %H:%M")
locale.setlocale(locale.LC_ALL, loc)
return result
|
Print date in fr_CA locale
|
hack: Print date in fr_CA locale
|
Python
|
agpl-3.0
|
mlhamel/agendadulibre,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,mlhamel/agendadulibre,vcorreze/agendaEteAccoord,vcorreze/agendaEteAccoord
|
e715dd65d3adf74624bc2102afd6a6d8f8706da6
|
dlm/models/components/linear.py
|
dlm/models/components/linear.py
|
import numpy
import theano
import theano.tensor as T
class Linear():
def __init__(self, rng, input, n_in, n_out, W=None, b=None):
self.input = input
if W is None:
W_values = numpy.asarray(
rng.uniform(
low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)),
high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)
),
dtype=theano.config.floatX
)
W = theano.shared(value=W_values, name='W', borrow=True)
if b is None:
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
b = theano.shared(value=b_values, name='b', borrow=True)
self.W = W
self.b = b
self.output = T.dot(input, self.W) + self.b
# parameters of the model
self.params = [self.W, self.b]
|
import numpy
import theano
import theano.tensor as T
class Linear():
def __init__(self, rng, input, n_in, n_out, W_values=None, b_values=None):
self.input = input
if W_values is None:
W_values = numpy.asarray(
rng.uniform(
low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)),
high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)),
size=(n_in, n_out)
),
dtype=theano.config.floatX
)
W = theano.shared(value=W_values, name='W', borrow=True)
if b_values is None:
b_values = numpy.zeros((n_out,), dtype=theano.config.floatX)
# b_values = numpy.asarray(
# rng.uniform(
# low = -0.01, #low=-numpy.sqrt(6. / (n_in + n_out)),
# high = 0.01, #high=numpy.sqrt(6. / (n_in + n_out)),
# size=(n_out,)
# ),
# dtype=theano.config.floatX
)
b = theano.shared(value=b_values, name='b', borrow=True)
self.W = W
self.b = b
self.output = T.dot(input, self.W) + self.b
# parameters of the model
self.params = [self.W, self.b]
|
Initialize from argument or using a uniform distribution
|
Initialize from argument or using a uniform distribution
|
Python
|
mit
|
nusnlp/corelm
|
e0091310ffdb39127f7138966026445b0bac53fc
|
salt/states/rdp.py
|
salt/states/rdp.py
|
# -*- coding: utf-8 -*-
'''
Manage RDP Service on Windows servers
'''
def __virtual__():
'''
Load only if network_win is loaded
'''
return 'rdp' if 'rdp.enable' in __salt__ else False
def enabled(name):
'''
Enable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
ret['changes'] = {'enabled rdp': True}
if __opts__['test']:
ret['result'] = None
return ret
ret['result'] = __salt__['rdp.enable']()
return ret
def disabled(name):
'''
Disable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
ret['changes'] = {'disable rdp': True}
if __opts__['test']:
return ret
ret['result'] = __salt__['rdp.disable']()
return ret
|
# -*- coding: utf-8 -*-
'''
Manage RDP Service on Windows servers
'''
def __virtual__():
'''
Load only if network_win is loaded
'''
return 'rdp' if 'rdp.enable' in __salt__ else False
def enabled(name):
'''
Enable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
ret['changes'] = {'enabled rdp': True}
if __opts__['test']:
ret['result'] = stat
return ret
ret['result'] = __salt__['rdp.enable']()
return ret
def disabled(name):
'''
Disable RDP the service on the server
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if stat:
ret['changes'] = {'disable rdp': True}
if __opts__['test']:
ret['result'] = stat
return ret
ret['result'] = __salt__['rdp.disable']()
return ret
|
Return proper results for 'test=True'
|
Return proper results for 'test=True'
|
Python
|
apache-2.0
|
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
|
1a3c251abe2e8ebf3020a21a3449abae6b04c2b1
|
perf/tests/test_system.py
|
perf/tests/test_system.py
|
import os.path
import sys
from perf.tests import get_output
from perf.tests import unittest
class SystemTests(unittest.TestCase):
def test_show(self):
args = [sys.executable, '-m', 'perf', 'system', 'show']
proc = get_output(args)
regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks'
'|OK! System ready for benchmarking'
'|WARNING: no operation available for your platform)'
% os.path.basename(sys.executable))
self.assertRegex(proc.stdout, regex, msg=proc)
self.assertEqual(proc.returncode, 2, msg=proc)
if __name__ == "__main__":
unittest.main()
|
import os.path
import sys
from perf.tests import get_output
from perf.tests import unittest
class SystemTests(unittest.TestCase):
def test_show(self):
args = [sys.executable, '-m', 'perf', 'system', 'show']
proc = get_output(args)
regex = ('(Run "%s -m perf system tune" to tune the system configuration to run benchmarks'
'|OK! System ready for benchmarking'
'|WARNING: no operation available for your platform)'
% os.path.basename(sys.executable))
self.assertRegex(proc.stdout, regex, msg=proc)
# The return code is either 0 if the system is tuned or 2 if the
# system isn't
self.assertIn(proc.returncode, (0, 2), msg=proc)
if __name__ == "__main__":
unittest.main()
|
Fix test_show test to support tuned systems
|
Fix test_show test to support tuned systems
|
Python
|
mit
|
vstinner/pyperf,haypo/perf
|
141eb2a647490142adf017d3a755d03ab89ed687
|
jrnl/plugins/tag_exporter.py
|
jrnl/plugins/tag_exporter.py
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can convert entries and journals into json."""
names = ["tags"]
extension = "tags"
@classmethod
def export_entry(cls, entry):
"""Returns a markdown representation of a single entry."""
return ", ".join(entry.tags)
@classmethod
def export_journal(cls, journal):
"""Returns a json representation of an entire journal."""
tag_counts = get_tags_count(journal)
result = ""
if not tag_counts:
return '[No tags found in journal.]'
elif min(tag_counts)[0] == 0:
tag_counts = filter(lambda x: x[0] > 1, tag_counts)
result += '[Removed tags that appear only once.]\n'
result += "\n".join("{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=True))
return result
|
#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, unicode_literals
from .text_exporter import TextExporter
from .util import get_tags_count
class TagExporter(TextExporter):
"""This Exporter can lists the tags for entries and journals, exported as a plain text file."""
names = ["tags"]
extension = "tags"
@classmethod
def export_entry(cls, entry):
"""Returns a list of tags for a single entry."""
return ", ".join(entry.tags)
@classmethod
def export_journal(cls, journal):
"""Returns a list of tags and their frequency for an entire journal."""
tag_counts = get_tags_count(journal)
result = ""
if not tag_counts:
return '[No tags found in journal.]'
elif min(tag_counts)[0] == 0:
tag_counts = filter(lambda x: x[0] > 1, tag_counts)
result += '[Removed tags that appear only once.]\n'
result += "\n".join("{0:20} : {1}".format(tag, n) for n, tag in sorted(tag_counts, reverse=True))
return result
|
Update `Tag` exporter code documentation.
|
Update `Tag` exporter code documentation.
|
Python
|
mit
|
maebert/jrnl,notbalanced/jrnl,philipsd6/jrnl,MinchinWeb/jrnl
|
093c9065de9e0e08f248bbb84696bf30309bd536
|
examples/parallel/timer.py
|
examples/parallel/timer.py
|
import rx
import concurrent.futures
import time
seconds = [5, 1, 2, 4, 3]
def sleep(t):
time.sleep(t)
return t
def output(result):
print '%d seconds' % result
with concurrent.futures.ProcessPoolExecutor(5) as executor:
rx.Observable.from_(seconds).flat_map(
lambda s: executor.submit(sleep, s)
).subscribe(output)
# 1 seconds
# 2 seconds
# 3 seconds
# 4 seconds
# 5 seconds
|
from __future__ import print_function
import rx
import concurrent.futures
import time
seconds = [5, 1, 2, 4, 3]
def sleep(t):
time.sleep(t)
return t
def output(result):
print('%d seconds' % result)
with concurrent.futures.ProcessPoolExecutor(5) as executor:
rx.Observable.from_(seconds).flat_map(
lambda s: executor.submit(sleep, s)
).subscribe(output)
# 1 seconds
# 2 seconds
# 3 seconds
# 4 seconds
# 5 seconds
|
Fix parallel example for Python 3
|
Fix parallel example for Python 3
|
Python
|
mit
|
dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY
|
efeb8bbf351f8c2c25be15b5ca32d5f76ebdd4ef
|
launch_control/models/hw_device.py
|
launch_control/models/hw_device.py
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU,
... u"800MHz OMAP3 Processor")
>>> cpu.attributes[u'machine'] = u'arm'
>>> cpu.attributes[u'mhz'] = '800'
>>> cpu.attributes[u'vendor'] = u'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'desc', 'attributes')
def __init__(self, device_type, description, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
"""
Module with the HardwareDevice model.
"""
from launch_control.utils.json import PlainOldData
class HardwareDevice(PlainOldData):
"""
Model representing any HardwareDevice
A device is just a "device_type" attribute with a bag of properties
and a human readable description. Individual device types can be
freely added. For simplicity some common types of devices are
provided as class properties DEVICE_xxx.
Instances will come from a variety of factory classes, each capable
of enumerating devices that it understands. The upside of having a
common class like this is that it's easier to store it in the
database _and_ not have to agree on a common set of properties for,
say, all CPUs.
If you want you can create instances manually, like this:
>>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU,
... u"800MHz OMAP3 Processor")
>>> cpu.attributes[u'machine'] = u'arm'
>>> cpu.attributes[u'mhz'] = '800'
>>> cpu.attributes[u'vendor'] = u'Texas Instruments'
"""
DEVICE_CPU = "device.cpu"
DEVICE_MEM = "device.mem"
DEVICE_USB = "device.usb"
DEVICE_PCI = "device.pci"
DEVICE_BOARD = "device.board"
__slots__ = ('device_type', 'description', 'attributes')
def __init__(self, device_type, description, attributes=None):
self.device_type = device_type
self.description = description
self.attributes = attributes or {}
|
Fix slot name in HardwareDevice
|
Fix slot name in HardwareDevice
|
Python
|
agpl-3.0
|
Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server
|
351dd3d0540b6169a58897f9cb2ec6b1c20d57a5
|
core/forms/games.py
|
core/forms/games.py
|
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Submit, Button, Fieldset
from django.forms import ModelForm, Textarea
from core.models import Game
class GameForm(ModelForm):
class Meta:
model = Game
exclude = ['owner', 'date_published']
widgets = {
'description': Textarea(attrs={'cols': 100, 'rows': 15})
}
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'{{ heading }}',
'name',
'description',
'link',
HTML("""{% if form.image.value %}<img class="img-responsive" src="{{ MEDIA_URL }}{{ form.image.value }}">
{% endif %}"""),
'image',
'tags',
'group',
'event_name',
'game_file'
),
FormActions(
Submit('save', 'Save'),
Button('cancel', 'Cancel', onclick='history.go(-1);', css_class="btn-default")
)
)
|
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, HTML, Submit, Button, Fieldset
from django.forms import ModelForm, Textarea
from core.models import Game
class GameForm(ModelForm):
class Meta:
model = Game
exclude = ['owner', 'date_published']
widgets = {
'description': Textarea(attrs={'cols': 100, 'rows': 15})
}
def __init__(self, *args, **kwargs):
super(GameForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
'{{ heading }}',
'name',
'description',
HTML("""{% if form.image.value %}<img class="img-responsive" src="{{ MEDIA_URL }}{{ form.image.value }}">
{% endif %}"""),
'image',
'tags',
'group',
'event_name',
'game_file'
),
FormActions(
Submit('save', 'Save'),
Button('cancel', 'Cancel', onclick='history.go(-1);', css_class="btn-default")
)
)
|
Remove unused field from game form
|
Remove unused field from game form
|
Python
|
mit
|
joshsamara/game-website,joshsamara/game-website,joshsamara/game-website
|
26b66a830fd9322dcc826fee2f1924670ea6c976
|
tests/functional/test_requests.py
|
tests/functional/test_requests.py
|
import pytest
from tests.lib import PipTestEnvironment
@pytest.mark.network
def test_timeout(script: PipTestEnvironment) -> None:
result = script.pip(
"--timeout",
"0.0001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
import pytest
from tests.lib import PipTestEnvironment
@pytest.mark.network
def test_timeout(script: PipTestEnvironment) -> None:
result = script.pip(
"--timeout",
"0.00001",
"install",
"-vvv",
"INITools",
expect_error=True,
)
assert (
"Could not fetch URL https://pypi.org/simple/initools/: "
"connection error: HTTPSConnectionPool(host='pypi.org', port=443): "
"Max retries exceeded with url: /simple/initools/ "
) in result.stdout
|
Decrease timeout to make test less flaky
|
Decrease timeout to make test less flaky
|
Python
|
mit
|
pypa/pip,pradyunsg/pip,sbidoul/pip,sbidoul/pip,pfmoore/pip,pradyunsg/pip,pypa/pip,pfmoore/pip
|
51f6272870e4e72d2364b2c2f660457b5c9286ef
|
doc/sample_code/search_forking_pro.py
|
doc/sample_code/search_forking_pro.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import pandas as pd
sys.path.append('./../../')
from pyogi.ki2converter import *
from pyogi.kifu import *
if __name__ == '__main__':
res_table = []
for n in range(0, 50000):
n1 = (n // 10000)
n2 = int(n < 10000)
relpath = '~/data/shogi/2chkifu/{0}000{1}/{2:0>5}.KI2'.format(n1, n2, n)
kifile = os.path.expanduser(relpath)
if not os.path.exists(kifile):
continue
ki2converter = Ki2converter()
ki2converter.from_path(kifile)
csa = ki2converter.to_csa()
if not csa:
continue
kifu = Kifu(csa)
res = kifu.get_forking(['OU', 'HI'])
if res[2] or res[3]:
print(kifu.players)
# Output
# 1. sente forked | gote forked
# 2. (sente won & sente forked) | (gote won & gote forked)
res_table.append(
[res[2] != [] or res[3] != [],
(kifu.sente_win and res[2]!=[]) or
((not kifu.sente_win) and res[3]!=[])])
df = pd.DataFrame(res_table, columns=['fork', 'fork&win'])
pd.crosstab(df.loc[:, 'fork'], df.loc[:, 'fork&win'])
|
Add sum up part using pd.crosstab
|
Add sum up part using pd.crosstab
|
Python
|
mit
|
tosh1ki/pyogi,tosh1ki/pyogi
|
4db93f27d6d4f9b05b33af96bff15108272df6ce
|
src/webapp/public.py
|
src/webapp/public.py
|
import json
from flask import Blueprint, render_template
import database as db
from database.model import Team
bp = Blueprint('public', __name__)
@bp.route("/map")
def map_page():
return render_template("public/map.html")
@bp.route("/map_teams")
def map_teams():
qry = db.session.query(Team).filter_by(confirmed=True).filter_by(deleted=False).filter_by(backup=False)
data = []
for item in qry:
if item.location is not None:
data.append({"lat": item.location.lat,
"lon": item.location.lon,
"name": item.name})
return json.dumps(data)
|
import json
from flask import Blueprint, render_template
import database as db
from database.model import Team
bp = Blueprint('public', __name__)
@bp.route("/map")
def map_page():
return render_template("public/map.html")
@bp.route("/map_teams")
def map_teams():
qry = db.session.query(Team).filter_by(confirmed=True).filter_by(deleted=False).filter_by(backup=False)
data_dict = {}
for item in qry:
if item.location is not None:
ident = "%s%s" % (item.location.lat, item.location.lon)
if ident not in data_dict:
data_dict[ident] = {
"lat": item.location.lat,
"lon": item.location.lon,
"name": item.name
}
else:
data_dict[ident]["name"] += "<br>" + item.name
data = [entry for entry in data_dict.itervalues()]
return json.dumps(data)
|
Add multi team output in markers
|
Add multi team output in markers
Signed-off-by: Dominik Pataky <[email protected]>
|
Python
|
bsd-3-clause
|
eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system
|
3885e8fd36f419976d0b002c391dc246588929c7
|
admin/metrics/views.py
|
admin/metrics/views.py
|
from django.views.generic import TemplateView
from admin.base.settings import KEEN_CREDENTIALS
from admin.base.utils import OSFAdmin
class MetricsView(OSFAdmin, TemplateView):
template_name = 'metrics/osf_metrics.html'
def get_context_data(self, **kwargs):
kwargs.update(KEEN_CREDENTIALS.copy())
return super(MetricsView, self).get_context_data(**kwargs)
|
from django.views.generic import TemplateView
from django.contrib.auth.mixins import PermissionRequiredMixin
from admin.base.settings import KEEN_CREDENTIALS
from admin.base.utils import OSFAdmin
class MetricsView(OSFAdmin, TemplateView, PermissionRequiredMixin):
template_name = 'metrics/osf_metrics.html'
permission_required = 'admin.view_metrics'
def get_context_data(self, **kwargs):
kwargs.update(KEEN_CREDENTIALS.copy())
return super(MetricsView, self).get_context_data(**kwargs)
|
Add view metrics permission to metrics view
|
Add view metrics permission to metrics view
|
Python
|
apache-2.0
|
sloria/osf.io,monikagrabowska/osf.io,brianjgeiger/osf.io,sloria/osf.io,erinspace/osf.io,TomBaxter/osf.io,mfraezz/osf.io,chrisseto/osf.io,crcresearch/osf.io,adlius/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,acshi/osf.io,crcresearch/osf.io,cwisecarver/osf.io,icereval/osf.io,cwisecarver/osf.io,aaxelb/osf.io,adlius/osf.io,acshi/osf.io,sloria/osf.io,HalcyonChimera/osf.io,icereval/osf.io,adlius/osf.io,erinspace/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,brianjgeiger/osf.io,erinspace/osf.io,binoculars/osf.io,binoculars/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,cslzchen/osf.io,icereval/osf.io,chrisseto/osf.io,laurenrevere/osf.io,hmoco/osf.io,aaxelb/osf.io,brianjgeiger/osf.io,Nesiehr/osf.io,cslzchen/osf.io,aaxelb/osf.io,crcresearch/osf.io,Nesiehr/osf.io,leb2dg/osf.io,pattisdr/osf.io,felliott/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,chennan47/osf.io,felliott/osf.io,caseyrollins/osf.io,chrisseto/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,leb2dg/osf.io,caneruguz/osf.io,chrisseto/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,monikagrabowska/osf.io,felliott/osf.io,hmoco/osf.io,aaxelb/osf.io,mfraezz/osf.io,mfraezz/osf.io,hmoco/osf.io,CenterForOpenScience/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,caneruguz/osf.io,saradbowman/osf.io,cwisecarver/osf.io,caneruguz/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,acshi/osf.io,acshi/osf.io,laurenrevere/osf.io,HalcyonChimera/osf.io,leb2dg/osf.io,binoculars/osf.io,HalcyonChimera/osf.io,felliott/osf.io,acshi/osf.io,pattisdr/osf.io,Nesiehr/osf.io,mattclark/osf.io,TomBaxter/osf.io,mattclark/osf.io,TomBaxter/osf.io,Johnetordoff/osf.io,chennan47/osf.io,baylee-d/osf.io,saradbowman/osf.io,chennan47/osf.io,baylee-d/osf.io,baylee-d/osf.io,mattclark/osf.io
|
d10720d1dd7997b5e1543cb27f2cd3e1088f30f5
|
server/fulltext.py
|
server/fulltext.py
|
#!/usr/bin/env python
# encoding: utf-8
"""
"""
from bottle import route, run, template, request
import urllib2
import urllib
import sys
import os
from whoosh.index import create_in, open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser, MultifieldParser
from whoosh.query import *
@route('/')
def index():
return template('search')
@route('/epsg',method="POST")
def index():
ix = open_dir("../index")
result = []
with ix.searcher(closereader=False) as searcher:
parser = MultifieldParser(["code","name","area","type"], ix.schema)
query = request.POST.get('fulltext').strip()
myquery = parser.parse(query)
results = searcher.search(myquery, limit = 600)
num_results = len(results)
for r in results:
result.append(r)
return template('results',result=result, query=query,num_results=num_results)
run(host='localhost', port=8080)
|
#!/usr/bin/env python
# encoding: utf-8
"""
"""
from bottle import route, run, template, request
import urllib2
import urllib
import sys
import os
from whoosh.index import create_in, open_dir
from whoosh.fields import *
from whoosh.qparser import QueryParser, MultifieldParser
from whoosh.query import *
@route('/')
def index():
return template('search')
@route('/epsg',method="POST")
def index():
ix = open_dir("../index")
result = []
with ix.searcher(closereader=False) as searcher:
parser = MultifieldParser(["code","name","area","type"], ix.schema)
query = request.POST.get('fulltext').strip()
select = request.POST.get('type').strip()
status = request.POST.get('invalid')
print status, "status"
if status == None:
status = u"Valid"
print status, "status2"
query = query + " type:" + select + " status:" + status # change status from id tu text
print query
myquery = parser.parse(query)
results = searcher.search(myquery, limit = 600)
num_results = len(results)
for r in results:
result.append(r)
return template('results',result=result, query=query,num_results=num_results)
run(host='localhost', port=8080)
|
Add advanced search by select type or status
|
Add advanced search by select type or status
|
Python
|
bsd-2-clause
|
klokantech/epsg.io,dudaerich/epsg.io,dudaerich/epsg.io,klokantech/epsg.io,klokantech/epsg.io,dudaerich/epsg.io,dudaerich/epsg.io,klokantech/epsg.io
|
a01a3f9c07e0e5d93fc664df118c6085668410c1
|
test/test_url_subcommand.py
|
test/test_url_subcommand.py
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_TableUrlLoader(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
|
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <[email protected]>
"""
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
from .dataset import complex_json
class Test_url_subcommand(object):
@responses.activate
def test_normal(self):
url = "https://example.com/complex_jeson.json"
responses.add(
responses.GET,
url,
body=complex_json,
content_type='text/plain; charset=utf-8',
status=200)
runner = CliRunner()
db_path = "test_complex_json.sqlite"
with runner.isolated_filesystem():
result = runner.invoke(cmd, ["url", url, "-o", db_path])
print_traceback(result)
assert result.exit_code == ExitCode.SUCCESS
con = simplesqlite.SimpleSQLite(db_path, "r")
expected = set([
'ratings', 'screenshots_4', 'screenshots_3', 'screenshots_5', 'screenshots_1',
'screenshots_2', 'tags', 'versions', 'root'])
assert set(con.get_table_name_list()) == expected
|
Fix a test class name
|
Fix a test class name
|
Python
|
mit
|
thombashi/sqlitebiter,thombashi/sqlitebiter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.