commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
4b340e0712956ea44eace7382dd743890958a0fd
widgets/card.py
widgets/card.py
# -*- coding: utf-8 -*- from flask import render_template from models.person import Person def card(person_or_id, detailed=False, small=False): if isinstance(person_or_id, Person): person = person_or_id else: person = Person.query.filter_by(id=person_or_id).first() return render_template('widgets/card.html', person=person, detailed=detailed, small=small)
# -*- coding: utf-8 -*- from flask import render_template from models.person import Person def card(person_or_id, **kwargs): if isinstance(person_or_id, Person): person = person_or_id else: person = Person.query.filter_by(id=person_or_id).first() return render_template('widgets/card.html', person=person, **kwargs)
Revert "Fix a bug in caching"
Revert "Fix a bug in caching" This reverts commit 2565df456ecb290f620ce4dadca19c76b0eeb1af. Conflicts: widgets/card.py
Python
apache-2.0
teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr
fa75cdb0114d86b626a77ea19897abd532fd4aeb
src/hack4lt/forms.py
src/hack4lt/forms.py
from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from hack4lt.models import Hacker class RegistrationForm(forms.ModelForm): class Meta: model = Hacker fields = ('username', 'first_name', 'last_name', 'email', 'repository', 'website', 'stackoverflow_user', 'description') class LoginForm(forms.Form): username = forms.CharField(label=_('Username'), max_length=100) password = forms.CharField(label=_('Password'), max_length=128, widget=forms.PasswordInput(render_value=False)) def clean(self): cleaned_data = super(LoginForm, self).clean() if self.errors: return cleaned_data user = authenticate(**cleaned_data) if not user: raise forms.ValidationError(_('Username or password is incorrect')) cleaned_data['user'] = user return cleaned_data
from django import forms from django.contrib.auth import authenticate from django.utils.translation import ugettext_lazy as _ from django.forms.util import ErrorList from hack4lt.models import Hacker class RegistrationForm(forms.ModelForm): password = forms.CharField(label=_('Password'), max_length=128, min_length=6, widget=forms.PasswordInput(render_value=False)) password_repeat = forms.CharField(label=_('Repeat Password'), min_length=6, max_length=128, widget=forms.PasswordInput(render_value=False)) class Meta: model = Hacker fields = ('username', 'password', 'password_repeat', 'first_name', 'last_name', 'email', 'repository', 'website', 'stackoverflow_user', 'description') def is_valid(self): valid = super(RegistrationForm, self).is_valid() if not valid: return valid first_password = self.cleaned_data.get('password') repeat_password = self.cleaned_data.get('password_repeat') if first_password == repeat_password: return True errors = self._errors.setdefault('password', ErrorList()) errors.append(u'Passwords do not match') return False class LoginForm(forms.Form): username = forms.CharField(label=_('Username'), max_length=100) password = forms.CharField(label=_('Password'), max_length=128, widget=forms.PasswordInput(render_value=False)) def clean(self): cleaned_data = super(LoginForm, self).clean() if self.errors: return cleaned_data user = authenticate(**cleaned_data) if not user: raise forms.ValidationError(_('Username or password is incorrect')) cleaned_data['user'] = user return cleaned_data
Add password and password_repeat fields to registration form.
Add password and password_repeat fields to registration form.
Python
bsd-3-clause
niekas/Hack4LT
467e8e4d8113a8f6473d7f82d86d5401053362b8
scripts/gen-release-notes.py
scripts/gen-release-notes.py
""" Generates the release notes for the latest release, in Markdown. Convert CHANGELOG.rst to Markdown, and extracts just the latest release. Writes to ``scripts/latest-release-notes.md``, which can be used with https://github.com/softprops/action-gh-release. """ from pathlib import Path import pypandoc this_dir = Path(__file__).parent rst_text = (this_dir.parent / "CHANGELOG.rst").read_text(encoding="UTF-8") md_text = pypandoc.convert_text( rst_text, "md", format="rst", extra_args=["--wrap=preserve"] ) output_lines = [] first_heading_found = False for line in md_text.splitlines(): if line.startswith("# "): if first_heading_found: break first_heading_found = True output_lines.append(line) output_fn = this_dir / "latest-release-notes.md" output_fn.write_text("\n".join(output_lines), encoding="UTF-8") print(output_fn, "generated.")
""" Generates the release notes for the latest release, in Markdown. Convert CHANGELOG.rst to Markdown, and extracts just the latest release. Writes to ``scripts/latest-release-notes.md``, which can be used with https://github.com/softprops/action-gh-release. """ from pathlib import Path import pypandoc this_dir = Path(__file__).parent rst_text = (this_dir.parent / "CHANGELOG.rst").read_text(encoding="UTF-8") md_text = pypandoc.convert_text( rst_text, "md", format="rst", extra_args=["--wrap=preserve"] ) output_lines = [] first_heading_found = False for line in md_text.splitlines(): if line.startswith("# "): if first_heading_found: break first_heading_found = True else: output_lines.append(line) output_fn = this_dir / "latest-release-notes.md" output_fn.write_text("\n".join(output_lines), encoding="UTF-8") print(output_fn, "generated.")
Remove release title from the GitHub release notes body
Remove release title from the GitHub release notes body
Python
mit
pytest-dev/pytest-mock
ac33c7fcee74053dae6edfdd4596bfe03098711d
waptpkg.py
waptpkg.py
# -*- coding: utf-8 -*- import os import waptpackage from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey def download(remote, path, pkg): """Downloads package""" if not pkg.package: return False res = remote.download_packages(pkg, path) if res['errors']: return False pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0] if not pkg_path: return False return pkg_path def check_signature(pkg): """Check package signature if /etc/ssl/certs exists""" if not os.path.exists('/etc/ssl/certs'): return True if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')): return False return True def overwrite_signature(pkg): """Overwrite imported package signature""" cert_file = os.environ.get('WAPT_CERT') key_file = os.environ.get('WAPT_KEY') password = os.environ.get('WAPT_PASSWD') if not (cert_file and key_file and password): return False crt = SSLCertificate(cert_file) key = SSLPrivateKey(key_file, password=password) return pkg.sign_package(crt, key) def hash(pkg): """Creates a hash based on package properties""" return "%s:%s" % (pkg.package, pkg.architecture)
# -*- coding: utf-8 -*- import os import waptpackage from waptcrypto import SSLCABundle,SSLCertificate,SSLPrivateKey def download(remote, path, pkg): """Downloads package""" if not pkg.package: return False res = remote.download_packages(pkg, path) if res['errors']: return False pkg_path = res['downloaded'] and res['downloaded'][0] or res['skipped'][0] if not pkg_path: return False return pkg_path def check_signature(pkg): """Check package signature if /etc/ssl/certs exists""" if not os.path.exists('/etc/ssl/certs'): return True if not waptpackage.PackageEntry(waptfile=pkg.localpath).check_control_signature(SSLCABundle('/etc/ssl/certs')): return False return True def overwrite_signature(pkg): """Overwrite imported package signature""" cert_file = os.environ.get('WAPT_CERT') key_file = os.environ.get('WAPT_KEY') password = os.environ.get('WAPT_PASSWD') if not (cert_file and key_file and password): return False crt = SSLCertificate(cert_file) key = SSLPrivateKey(key_file, password=password) return pkg.sign_package(crt, key) def hash(pkg): """Creates a hash based on package properties""" return "%s:%s:%s" % (pkg.package, pkg.architecture, pkg.locale)
Include locale in package hash
Include locale in package hash
Python
mit
jf-guillou/wapt-scripts
13ba6bf5c12c46aa43c0060d40458fe453df9c33
ydf/yaml_ext.py
ydf/yaml_ext.py
""" ydf/yaml_ext ~~~~~~~~~~~~ Contains extensions to existing YAML functionality. """ import collections from ruamel import yaml from ruamel.yaml import resolver class OrderedLoader(yaml.Loader): """ Extends the default YAML loader to use :class:`~collections.OrderedDict` for mapping types. """ def __init__(self, *args, **kwargs): super(OrderedLoader, self).__init__(*args, **kwargs) self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping) @staticmethod def construct_ordered_mapping(loader, node): loader.flatten_mapping(node) return collections.OrderedDict(loader.construct_pairs(node)) def load(stream): """ Load the given YAML string. """ return yaml.load(stream, OrderedLoader)
""" ydf/yaml_ext ~~~~~~~~~~~~ Contains extensions to existing YAML functionality. """ import collections from ruamel import yaml from ruamel.yaml import resolver class OrderedRoundTripLoader(yaml.RoundTripLoader): """ Extends the default round trip YAML loader to use :class:`~collections.OrderedDict` for mapping types. """ def __init__(self, *args, **kwargs): super(OrderedRoundTripLoader, self).__init__(*args, **kwargs) self.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, self.construct_ordered_mapping) @staticmethod def construct_ordered_mapping(loader, node): loader.flatten_mapping(node) return collections.OrderedDict(loader.construct_pairs(node)) def load_all(stream): """ Load all documents within the given YAML string. :param stream: A valid YAML stream. :return: Generator that yields each document found in the YAML stream. """ return yaml.load_all(stream, OrderedRoundTripLoader)
Switch to round trip loader to support multiple documents.
Switch to round trip loader to support multiple documents.
Python
apache-2.0
ahawker/ydf
9b586b953bfe3c94adb40d0a804de3d46fca1887
httpie/config.py
httpie/config.py
import os __author__ = 'jakub' CONFIG_DIR = os.path.expanduser('~/.httpie')
import os from requests.compat import is_windows __author__ = 'jakub' CONFIG_DIR = (os.path.expanduser('~/.httpie') if not is_windows else os.path.expandvars(r'%APPDATA%\\httpie'))
Use %APPDATA% for data on Windows.
Use %APPDATA% for data on Windows.
Python
bsd-3-clause
codingjoe/httpie,konopski/httpie,Bogon/httpie,fontenele/httpie,aredo/httpie,GrimDerp/httpie,vietlq/httpie,paran0ids0ul/httpie,gnagel/httpie,fontenele/httpie,lingtalfi/httpie,rschmidtz/httpie,alexeikabak/httpie,konopski/httpie,PKRoma/httpie,GrimDerp/httpie,PKRoma/httpie,bright-sparks/httpie,marklap/httpie,fritaly/httpie,rgordeev/httpie,kaushik94/httpie,paran0ids0ul/httpie,mblayman/httpie,saisai/httpie,vietlq/httpie,zerin108/httpie,ardydedase/httpie,keita1314/httpie,aredo/httpie,hoatle/httpie,meigrafd/httpie,jakubroztocil/httpie,alex-bretet/httpie,alfcrisci/httpie,sofianhw/httpie,codingjoe/httpie,JPWKU/httpie,gnagel/httpie,insionng/httpie,zerodark/httpie,bright-sparks/httpie,alexeikabak/httpie,Bogon/httpie,jkbrzt/httpie,avtoritet/httpie,lk1ngaa7/httpie,fritaly/httpie,bgarrels/httpie,HackerTool/httpie,rschmidtz/httpie,zerin108/httpie,marklap/httpie,HackerTool/httpie,danieldc/httpie,danieldc/httpie,guiquanz/httpie,chaos33/httpie,jcrumb/httpie,Batterfii/httpie,a-x-/httpie,bitcoinfees/two1-httpie,kevinlondon/httpie,rusheel/httpie,alex-bretet/httpie,insionng/httpie,kevinlondon/httpie,rgordeev/httpie,hoatle/httpie,Batterfii/httpie,bitcoinfees/two1-httpie,jakubroztocil/httpie,alfcrisci/httpie,MiteshShah/httpie,lingtalfi/httpie,ardydedase/httpie,normabuttz/httpie,lk1ngaa7/httpie,jakubroztocil/httpie,guiquanz/httpie,bgarrels/httpie,whitefoxx/httpie,jkbrzt/httpie,wandec/first,meigrafd/httpie,jkbrzt/httpie,mblayman/httpie,zerodark/httpie,sofianhw/httpie,avtoritet/httpie,jcrumb/httpie,tylertebbs20/Practice-httpie,normabuttz/httpie,a-x-/httpie,whitefoxx/httpie,tylertebbs20/Practice-httpie,saisai/httpie,rusheel/httpie,JPWKU/httpie,MiteshShah/httpie,keita1314/httpie
085edf28b2e70552789407e16ca83faf78313672
version.py
version.py
major = 0 minor=0 patch=0 branch="dev" timestamp=1376579871.17
major = 0 minor=0 patch=25 branch="master" timestamp=1376610207.69
Tag commit for v0.0.25-master generated by gitmake.py
Tag commit for v0.0.25-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
09d85cf39fd8196b26b357ee3f0b9fbb67770014
flask_jq.py
flask_jq.py
from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/_add_numbers') def add_numbers(): ''' Because numbers must be added server side ''' a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html')
from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/_add_numbers') def add_numbers(): ''' Because numbers must be added server side ''' a = request.args.get('a', 0, type=int) b = request.args.get('b', 0, type=int) return jsonify(result=a + b) @app.route('/') def index(): return render_template('index.html') if __name__ == '__main__': app.run('0.0.0.0',port=4000)
Add app run on main
Add app run on main
Python
mit
avidas/flask-jquery,avidas/flask-jquery,avidas/flask-jquery
c5ba874987b2e788ae905a1a84e7f2575ff9f991
conman/redirects/models.py
conman/redirects/models.py
from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import ugettext_lazy as _ from conman.routes.models import Route from . import views class RouteRedirect(Route): """ When `route` is browsed to, browser should be redirected to `target`. This model holds the data required to make that connection. """ target = models.ForeignKey('routes.Route', related_name='+') permanent = models.BooleanField(default=False, blank=True) view = views.RouteRedirectView.as_view() def clean(self): """Forbid setting target equal to self.""" if self.target_id == self.route_ptr_id: error = {'target': _('A RouteRedirect cannot redirect to itself.')} raise ValidationError(error) def save(self, *args, **kwargs): """Validate the Redirect before saving.""" self.clean() return super().save(*args, **kwargs) class URLRedirect(Route): """A `Route` that redirects to an arbitrary URL.""" target = models.URLField(max_length=2000) permanent = models.BooleanField(default=False, blank=True) view = views.URLRedirectView.as_view()
from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import ugettext_lazy as _ from conman.routes.models import Route from . import views class RouteRedirect(Route): """ When `route` is browsed to, browser should be redirected to `target`. This model holds the data required to make that connection. """ target = models.ForeignKey('routes.Route', related_name='+') permanent = models.BooleanField(default=False) view = views.RouteRedirectView.as_view() def clean(self): """Forbid setting target equal to self.""" if self.target_id == self.route_ptr_id: error = {'target': _('A RouteRedirect cannot redirect to itself.')} raise ValidationError(error) def save(self, *args, **kwargs): """Validate the Redirect before saving.""" self.clean() return super().save(*args, **kwargs) class URLRedirect(Route): """A `Route` that redirects to an arbitrary URL.""" target = models.URLField(max_length=2000) permanent = models.BooleanField(default=False) view = views.URLRedirectView.as_view()
Remove explicit default from BooleanField
Remove explicit default from BooleanField
Python
bsd-2-clause
Ian-Foote/django-conman,meshy/django-conman,meshy/django-conman
f5d56b0c54af414f02721a1a02a0eaf80dbba898
client/python/unrealcv/util.py
client/python/unrealcv/util.py
import numpy as np import PIL from io import BytesIO # StringIO module is removed in python3, use io module def read_png(res): import PIL.Image img = PIL.Image.open(BytesIO(res)) return np.asarray(img) def read_npy(res): # res is a binary buffer return np.load(BytesIO(res))
import numpy as np import PIL.Image from io import BytesIO # StringIO module is removed in python3, use io module def read_png(res): img = None try: PIL_img = PIL.Image.open(BytesIO(res)) img = np.asarray(PIL_img) except: print('Read png can not parse response %s' % str(res[:20])) return img def read_npy(res): # res is a binary buffer arr = None try: arr = np.load(BytesIO(res)) except: print('Read npy can not parse response %s' % str(res[:20])) return arr
Handle exceptions in read_png and read_npy.
Handle exceptions in read_png and read_npy.
Python
mit
unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv,unrealcv/unrealcv
95f0ae5e04df6e5ce454b15551133caacfd44536
services/netflix.py
services/netflix.py
import foauth.providers class Netflix(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.netflix.com/' docs_url = 'http://developer.netflix.com/docs' # URLs to interact with the API request_token_url = 'http://api.netflix.com/oauth/request_token' authorize_url = 'https://api-user.netflix.com/oauth/login' access_token_url = 'http://api.netflix.com/oauth/access_token' api_domains = ['api-public.netflix.com', 'api.netflix.com'] available_permissions = [ (None, 'read and manage your queue'), ]
import foauth.providers from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY class Netflix(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.netflix.com/' docs_url = 'http://developer.netflix.com/docs' # URLs to interact with the API request_token_url = 'http://api.netflix.com/oauth/request_token' authorize_url = 'https://api-user.netflix.com/oauth/login' access_token_url = 'http://api.netflix.com/oauth/access_token' api_domains = ['api-public.netflix.com', 'api.netflix.com'] available_permissions = [ (None, 'read and manage your queue'), ] https = False signature_type = SIGNATURE_TYPE_QUERY def get_authorize_params(self, redirect_uri): params = super(Netflix, self).get_authorize_params(redirect_uri) params['oauth_consumer_key'] = self.client_id return params
Fix token retrieval for Netflix
Fix token retrieval for Netflix
Python
bsd-3-clause
foauth/foauth.org,foauth/oauth-proxy,foauth/foauth.org,foauth/foauth.org
3093941ebed1f9c726a88776819ee181cdb0b869
piper/db/core.py
piper/db/core.py
import logbook # Let's name this DatabaseBase. 'tis a silly name. class DatabaseBase(object): """ Abstract class representing a persistance layer """ def __init__(self): self.log = logbook.Logger(self.__class__.__name__) def init(self, ns, config): raise NotImplementedError() class DbCLI(object): def __init__(self, cls): self.cls = cls self.log = logbook.Logger(self.__class__.__name__) def compose(self, parser): # pragma: nocover db = parser.add_parser('db', help='Perform database tasks') sub = db.add_subparsers(help='Database commands', dest="db_command") sub.add_parser('init', help='Do the initial setup of the database') return 'db', self.run def run(self, ns, config): self.cls.init(ns, config) return 0
import logbook class LazyDatabaseMixin(object): """ A mixin class that gives the subclass lazy access to the database layer The lazy attribute self.db is added, and the database class is gotten from self.config, and an instance is made and returned. """ _db = None @property def db(self): assert self.config is not None, \ 'Database accessed before self.config was set.' if self._db is None: self._db = self.config.get_database() self._db.setup() return self._db # Let's name this DatabaseBase. 'tis a silly name. class DatabaseBase(object): """ Abstract class representing a persistance layer """ def __init__(self): self.log = logbook.Logger(self.__class__.__name__) def init(self, ns, config): raise NotImplementedError() class DbCLI(object): def __init__(self, cls): self.cls = cls self.log = logbook.Logger(self.__class__.__name__) def compose(self, parser): # pragma: nocover db = parser.add_parser('db', help='Perform database tasks') sub = db.add_subparsers(help='Database commands', dest="db_command") sub.add_parser('init', help='Do the initial setup of the database') return 'db', self.run def run(self, ns, config): self.cls.init(ns, config) return 0
Add first iteration of LazyDatabaseMixin()
Add first iteration of LazyDatabaseMixin()
Python
mit
thiderman/piper
4de82c9a0737c079634a87d0ea358fba7840a419
sesame/test_settings.py
sesame/test_settings.py
from __future__ import unicode_literals AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "sesame.backends.ModelBackend", ] CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}} DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}} INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "sesame", "sesame.test_app", ] LOGGING_CONFIG = None MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", ] ROOT_URLCONF = "sesame.test_urls" SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously." SESSION_ENGINE = "django.contrib.sessions.backends.cache" TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
from __future__ import unicode_literals AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "sesame.backends.ModelBackend", ] CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}} DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3"}} INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "sesame", "sesame.test_app", ] LOGGING_CONFIG = None MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", ] PASSWORD_HASHERS = ["django.contrib.auth.hashers.SHA1PasswordHasher"] ROOT_URLCONF = "sesame.test_urls" SECRET_KEY = "Anyone who finds an URL will be able to log in. Seriously." SESSION_ENGINE = "django.contrib.sessions.backends.cache" TEMPLATES = [{"BACKEND": "django.template.backends.django.DjangoTemplates"}]
Use a fast password hasher for tests.
Use a fast password hasher for tests. Speed is obviously more important than security in tests.
Python
bsd-3-clause
aaugustin/django-sesame,aaugustin/django-sesame
cdae77dee9888d6d6094566747650bf80d631f03
station.py
station.py
"""Creates the station class""" #import ask_user from ask_user #import int_check from int_check #import reasonable_check from reasonable_check class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations total_station_pop: calculates total station population ask_user(prompt, lower_range, upper_range): function to get input, maybe it should live somewhere else? """ def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing): self.capacity = user.says("Enter the max capacity of the station between" lower "and" upper) self.escalators = user.says("Enter the number of escalators in the station between" lower "and" upper) self.train_wait = user.says("Enter the wait time between trains in seconds between" lower "and" upper) self.travelors_arriving = user.says("How many people just exited the train? between" lower "and" upper) self.travelors_departing = user.says("How many people are waiting for the train? between" lower "and" upper)
"""Creates the station class""" #import request_integer_in_range from request_integer_in_range class Station: """ Each train station is an instance of the Station class. Methods: __init__: creates a new stations request_integer_in_range : requests an integer in a range """ def __init__(self, capacity, escalators, train_wait, travelors_arriving, travelors_departing): self.capacity = request_integer_in_range("Enter the station capacity between 10 and 10000: ", 10, 10000) self.escalators = request_integer_in_range("Enter an odd number of escalators between 1 and 7: ", 1, 7) self.train_wait = request_integer_in_range("Enter the wait time between trains in seconds between 60 and 1800 ", 60, 1800) self.travelors_arriving = request_integer_in_range("Enter the number of people exiting the train between 1 and 500: ", 1, 500) self.travelors_departing = request_integer_in_range("Enter the number of people waiting for the train between 1 and 500: ", 1, 500)
Integrate integer test function into instantiation
Integrate integer test function into instantiation Ref #23
Python
mit
ForestPride/rail-problem
fff0b4af89e02ff834221ef056b7dcb979dc6cd7
webpay/webpay.py
webpay/webpay.py
from .api import Account, Charges, Customers import requests class WebPay: def __init__(self, key, api_base = 'https://api.webpay.jp/v1'): self.key = key self.api_base = api_base self.account = Account(self) self.charges = Charges(self) self.customers = Customers(self) def post(self, path, params): r = requests.post(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def get(self, path, params = {}): r = requests.get(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def delete(self, path, params = {}): r = requests.delete(self.api_base + path, auth = (self.key, ''), params = params) return r.json()
from .api import Account, Charges, Customers import requests import json class WebPay: def __init__(self, key, api_base = 'https://api.webpay.jp/v1'): self.key = key self.api_base = api_base self.account = Account(self) self.charges = Charges(self) self.customers = Customers(self) def post(self, path, params): r = requests.post(self.api_base + path, auth = (self.key, ''), data = json.dumps(params)) return r.json() def get(self, path, params = {}): r = requests.get(self.api_base + path, auth = (self.key, ''), params = params) return r.json() def delete(self, path, params = {}): r = requests.delete(self.api_base + path, auth = (self.key, ''), data = json.dumps(params)) return r.json()
Use JSON for other than GET request
Use JSON for other than GET request Because internal dict parameters is not handled as expected. >>> payload = {'key1': 'value1', 'key2': 'value2', 'set': {'a': 'x', 'b': 'y'}} >>> r = requests.post("http://httpbin.org/post", data=payload) >>> r.json() {... 'form': {'key2': 'value2', 'key1': 'value1', 'set': ['a', 'b']} ...}
Python
mit
yamaneko1212/webpay-python
b67617abe1e8530523da7231a9d74283935a1bb7
htext/ja/utils.py
htext/ja/utils.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import six BASIC_LATIN_RE = re.compile(r'[\u0021-\u007E]') WHITESPACE_RE = re.compile("[\s]+", re.UNICODE) def force_text(value): if isinstance(value, six.text_type): return value elif isinstance(value, six.string_types): return six.b(value).decode() else: value = str(value) return value if isinstance(value, six.text_type) else value.decode() def basic_latin_to_fullwidth(value): """ 基本ラテン文字を全角に変換する U+0021..U+007FはU+FF01..U+FF5Eに対応しているので コードポイントに差分の0xFEE0を足す """ _value = value.replace(' ', '\u3000') return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value) def aggregate_whitespace(value): return ' '.join(WHITESPACE_RE.split(value))
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import six BASIC_LATIN_RE = re.compile(r'[\u0021-\u007E]') WHITESPACE_RE = re.compile("[\s]+", re.UNICODE) def force_text(value): if isinstance(value, six.text_type): return value elif isinstance(value, six.string_types): return six.b(value).decode('utf-8') else: value = str(value) return value if isinstance(value, six.text_type) else value.decode('utf-8') def basic_latin_to_fullwidth(value): """ 基本ラテン文字を全角に変換する U+0021..U+007FはU+FF01..U+FF5Eに対応しているので コードポイントに差分の0xFEE0を足す """ _value = value.replace(' ', '\u3000') return BASIC_LATIN_RE.sub(lambda x: unichr(ord(x.group(0)) + 0xFEE0), _value) def aggregate_whitespace(value): return ' '.join(WHITESPACE_RE.split(value))
Fix UnicodeDecodeError on the environments where the default encoding is ascii
Fix UnicodeDecodeError on the environments where the default encoding is ascii
Python
mit
hunza/htext
68aefd4c1bc682dc04721f5572ab21b609e1818f
manage.py
manage.py
import os from app import create_app, db from app.models import User, Category from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
import os from app import create_app, db from app.models import User, Category from flask_script import Manager from flask_migrate import Migrate, MigrateCommand app = create_app(os.getenv('FLASK_CONFIG') or 'default') manager = Manager(app) migrate = Migrate(app, db) manager.add_command('db', MigrateCommand) #pylint: disable-msg=E1101 @manager.command def adduser(email, username, admin=False): """ Register a new user""" from getpass import getpass password = getpass() password2 = getpass(prompt='Confirm: ') if password != password2: import sys sys.exit("Error: Passwords do not match!") db.create_all() category = Category.get_by_name('Almenn frétt') if category is None: category = Category(name='Almenn frétt', name_en='General News', active=True) db.session.add(category) user = User(email=email, username=username, password=password, is_admin=admin) db.session.add(user) db.session.commit() print('User {0} was registered successfully!'.format(username)) if __name__ == '__main__': manager.run()
Add name_en field due to 'not null' constraint on the Category table
Add name_en field due to 'not null' constraint on the Category table
Python
mit
finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is,finnurtorfa/aflafrettir.is
c563c0deb99d3364df3650321c914164d99d32cf
been/source/markdowndirectory.py
been/source/markdowndirectory.py
from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) html = md.convert(event['content']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory)
from been.core import DirectorySource, source_registry from hashlib import sha1 import re import unicodedata import time import markdown # slugify from Django source (BSD license) def slugify(value): value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) return re.sub('[-\s]+', '-', value) class MarkdownDirectory(DirectorySource): kind = 'markdown' def process_event(self, event): md = markdown.Markdown(extensions=['meta']) html = md.convert(event['content']) event['title'] = ' '.join(md.Meta.get('title', [event['filename']])) event['slug'] = '-'.join(md.Meta.get('slug', [slugify(event['title'])])) event['summary'] = ' '.join(md.Meta.get('summary', [event['content'][:100]])) if md.Meta.get('published'): # Parse time, then convert struct_time (local) -> epoch (GMT) -> struct_time (GMT) event['timestamp'] = time.gmtime(time.mktime(time.strptime(' '.join(md.Meta.get('published')), '%Y-%m-%d %H:%M:%S'))) event['_id'] = sha1(event['full_path'].encode('utf-8')).hexdigest() if time.gmtime() < event['timestamp']: return None else: return event source_registry.add(MarkdownDirectory)
Add attribution to slugify function.
Add attribution to slugify function.
Python
bsd-3-clause
chromakode/been
8f41ff94ecfceedf14cea03e7f2ca08df380edb0
weight/models.py
weight/models.py
# -*- coding: utf-8 -*- # This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(_('Creation date')) weight = models.FloatField(_('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: # Order by creation_date, ascending (oldest last), better for diagram ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
# -*- coding: utf-8 -*- # This file is part of Workout Manager. # # Workout Manager is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Workout Manager is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Workout Manager. If not, see <http://www.gnu.org/licenses/>. from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ class WeightEntry(models.Model): """Model for a weight point """ creation_date = models.DateField(verbose_name = _('Date')) weight = models.FloatField(verbose_name = _('Weight')) user = models.ForeignKey(User, verbose_name = _('User')) # Metaclass to set some other properties class Meta: # Order by creation_date, ascending (oldest last), better for diagram ordering = ["creation_date", ] def __unicode__(self): """Return a more human-readable representation """ return "%s: %s kg" % (self.creation_date, self.weight)
Make the verbose name for weight entries more user friendly
Make the verbose name for weight entries more user friendly
Python
agpl-3.0
rolandgeider/wger,petervanderdoes/wger,DeveloperMal/wger,petervanderdoes/wger,kjagoo/wger_stark,rolandgeider/wger,wger-project/wger,petervanderdoes/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,kjagoo/wger_stark,wger-project/wger,wger-project/wger,rolandgeider/wger,DeveloperMal/wger,DeveloperMal/wger,kjagoo/wger_stark,petervanderdoes/wger,rolandgeider/wger
1b0a5388c246dba1707f768e9be08b3a63503a31
samples/python/topology/tweepy/app.py
samples/python/topology/tweepy/app.py
from streamsx.topology.topology import * import streamsx.topology.context import sys import tweets # # Continually stream tweets that contain # the terms passed on the command line. # # python3 app.py Food GlutenFree # def main(): terms = sys.argv[1:] topo = Topology("TweetsUsingTweepy") # Event based source stream # Each tuple is a dictionary containing # the full tweet (converted from JSON) ts = topo.source(tweets.tweets(terms)) # get the text of the tweet ts = ts.transform(tweets.text) # just print it ts.print() streamsx.topology.context.submit("DISTRIBUTED", topo.graph) if __name__ == '__main__': main()
from streamsx.topology.topology import * import streamsx.topology.context import sys import tweets # # Continually stream tweets that contain # the terms passed on the command line. # # python3 app.py Food GlutenFree # # # Requires tweepy to be installed # # pip3 install tweepy # # http://www.tweepy.org/ # # You must create Twitter application authentication tokens # and set them in the mykeys.py module. # Note this is only intended as a simple sample, # def main(): terms = sys.argv[1:] topo = Topology("TweetsUsingTweepy") # Event based source stream # Each tuple is a dictionary containing # the full tweet (converted from JSON) ts = topo.source(tweets.tweets(terms)) # get the text of the tweet ts = ts.transform(tweets.text) # just print it ts.print() streamsx.topology.context.submit("DISTRIBUTED", topo.graph) if __name__ == '__main__': main()
Add some info about tweepy
Add some info about tweepy
Python
apache-2.0
IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,IBMStreams/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,IBMStreams/streamsx.topology,ibmkendrick/streamsx.topology,wmarshall484/streamsx.topology,ibmkendrick/streamsx.topology,ibmkendrick/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,IBMStreams/streamsx.topology,ddebrunner/streamsx.topology,ddebrunner/streamsx.topology,wmarshall484/streamsx.topology,wmarshall484/streamsx.topology
14f2161efbd9c8377e6ff3675c48aba1ac0c47d5
API/chat/forms.py
API/chat/forms.py
import time from django import forms from .models import Message from .utils import timestamp_to_datetime, datetime_to_timestamp class MessageForm(forms.Form): text = forms.CharField(widget=forms.Textarea) typing = forms.BooleanField(required=False) class MessageCreationForm(MessageForm): username = forms.CharField(max_length=20) datetime_start = forms.IntegerField() def clean_datetime_start(self): now = int(round(time.time() * 1000)) timestamp = int(self.data['datetime_start']) if now < timestamp: timestamp = now self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp) def save(self): self.clean_datetime_start() message = Message.objects.create(channel=self.channel, **self.cleaned_data) if not message.typing: message.datetime_sent = message.datetime_start message.save() return message; class MessagePatchForm(MessageForm): datetime_sent = forms.IntegerField() def save(self, message): timestamp_start = datetime_to_timestamp(message.datetime_start) timestamp_sent = int(self.cleaned_data['datetime_sent']) if timestamp_sent < timestamp_start: timestamp_sent = timestamp_start message.datetime_sent = timestamp_to_datetime(timestamp_sent) message.text = self.cleaned_data['text'] message.typing = self.cleaned_data.get('typing', False) message.save()
import time from django import forms from .models import Message from .utils import timestamp_to_datetime, datetime_to_timestamp class MessageForm(forms.Form): text = forms.CharField(widget=forms.Textarea) typing = forms.BooleanField(required=False) message_type = forms.CharField(widget=forms.Textarea) class MessageCreationForm(MessageForm): username = forms.CharField(max_length=20) datetime_start = forms.IntegerField() def clean_datetime_start(self): now = int(round(time.time() * 1000)) timestamp = int(self.data['datetime_start']) if now < timestamp: timestamp = now self.cleaned_data['datetime_start'] = timestamp_to_datetime(timestamp) def save(self): self.clean_datetime_start() message = Message.objects.create(channel=self.channel, **self.cleaned_data) if not message.typing: message.datetime_sent = message.datetime_start message.save() return message; class MessagePatchForm(MessageForm): datetime_sent = forms.IntegerField() def save(self, message): timestamp_start = datetime_to_timestamp(message.datetime_start) timestamp_sent = int(self.cleaned_data['datetime_sent']) if timestamp_sent < timestamp_start: timestamp_sent = timestamp_start message.datetime_sent = timestamp_to_datetime(timestamp_sent) message.text = self.cleaned_data['text'] message.typing = self.cleaned_data.get('typing', False) message.save()
Add message_type as CharField in form
Add message_type as CharField in form
Python
mit
gtklocker/ting,gtklocker/ting,mbalamat/ting,mbalamat/ting,mbalamat/ting,gtklocker/ting,dionyziz/ting,gtklocker/ting,dionyziz/ting,dionyziz/ting,dionyziz/ting,mbalamat/ting
5733c800c10a7546228ec4562e40b2bd06c77c7e
models.py
models.py
from django.db import models # Create your models here.
from django.db import models from django.utils import timezone import datetime class Poll(models.Model): question = models.CharField(max_length=255) pub_date = models.DateTimeField('date published') def __unicode__(self): return self.question def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) was_published_recently.admin_order_field = 'pub_date' was_published_recently.boolean = True was_published_recently.short_description = 'Published recently?' class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=255) votes = models.IntegerField(default=0) def __unicode__(self): return self.choice_text
Improve database model and apperance for admin site
Improve database model and apperance for admin site
Python
mit
egel/polls
c0633bc60dda6b81e623795f2c65a1eb0ba5933d
blinkytape/blinkyplayer.py
blinkytape/blinkyplayer.py
import time class BlinkyPlayer(object): FOREVER = -1 def __init__(self, blinkytape): self._blinkytape = blinkytape def play(self, animation, num_cycles = FOREVER): finished = self._make_finished_predicate(animation, num_cycles) animation.begin() while not finished(): pixels = animation.next_frame() self._blinkytape.update(pixels) time.sleep(animation.frame_period_sec) animation.end() def _make_finished_predicate(self, animation, num_cycles): if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError if num_cycles == self.FOREVER: predicate = lambda: False else: self._num_frames = animation.frame_count * num_cycles def predicate(): finished = self._num_frames <= 0 self._num_frames = self._num_frames - 1 return finished return predicate
import time class BlinkyPlayer(object): FOREVER = -1 def __init__(self, blinkytape): self._blinkytape = blinkytape def play(self, animation, num_cycles = FOREVER): finished = self._finished_predicate(animation, num_cycles) animation.begin() while not finished(): pixels = animation.next_frame() self._blinkytape.update(pixels) time.sleep(animation.frame_period_sec) animation.end() def _finished_predicate(self, animation, num_cycles): if num_cycles < 0 and num_cycles != self.FOREVER: raise ValueError if num_cycles == self.FOREVER: predicate = self._forever_predicate() else: self._num_frames = animation.frame_count * num_cycles predicate = self._frame_count_predicate() return predicate def _forever_predicate(self): return lambda: False def _frame_count_predicate(self): def predicate(): finished = self._num_frames <= 0 self._num_frames = self._num_frames - 1 return finished return predicate
Clean up BlinkyPlayer a little
Clean up BlinkyPlayer a little
Python
mit
jonspeicher/blinkyfun
027e78f3e88a17e05881259d1f29d472b02d0d3a
doc/source/scripts/titles.py
doc/source/scripts/titles.py
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line) if '.. toctree::' in line: if z: handle.write(' :maxdepth: {}\n'.format(z)) else: z += 1
import shutil import os import re work = os.getcwd() found = [] regex = re.compile(r'pydarkstar\.(.*)\.rst') for root, dirs, files in os.walk(work): for f in files: m = regex.match(f) if m: found.append((root, f)) for root, f in found: path = os.path.join(root, f) with open(path, 'r') as handle: lines = handle.readlines() with open(path, 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) line = re.sub(r'\s+module$', '', line) line = re.sub(r'^pydarkstar\.', '', line) #print('{:2d} {}'.format(i, line.rstrip())) handle.write(line) #print('') # fix main file with open('pydarkstar.rst', 'r') as handle: lines = handle.readlines() z = 0 with open('pydarkstar.rst', 'w') as handle: for i, line in enumerate(lines): if i == 0: line = re.sub(r'\s+package$', '', line) if re.match(r'^\s\s\spydarkstar.*$', line): handle.write(' {}'.format(line.lstrip())) else: handle.write(line)
Change to 3 spaces in front of toctree elements
Change to 3 spaces in front of toctree elements
Python
mit
AdamGagorik/pydarkstar
72f28cfa2723faaa7f7ed2b165fd99b214bc67c9
MeetingMinutes.py
MeetingMinutes.py
import sublime, sublime_plugin import os import re from .mistune import markdown class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='strict') html_source = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' + markdown(md_source) + '</body></html>' file_name = self.view.file_name() html_file = self.change_extension(file_name, ".html") with open(html_file, 'w+') as file_: file_.write(html_source) print(file_name) print(html_file) def change_extension(self,file_name, new_ext): f, ext = os.path.splitext(file_name) f += new_ext return f
import sublime, sublime_plugin import os import re from .mistune import markdown HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' HTML_END = '</body></html>' class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_source = self.view.substr(region) md_source.encode(encoding='UTF-8',errors='strict') html_source = HTML_START + markdown(md_source) + HTML_END file_name = self.view.file_name() html_file = self.change_extension(file_name, ".html") with open(html_file, 'w+') as file_: file_.write(html_source) print(file_name) print(html_file) def change_extension(self,file_name, new_ext): f, ext = os.path.splitext(file_name) f += new_ext return f
Create variables for HTML start and end.
Create variables for HTML start and end.
Python
mit
Txarli/sublimetext-meeting-minutes,Txarli/sublimetext-meeting-minutes
5ede88c91f61b4aeb3a1e9b55e6b7836cf805255
django_filepicker/utils.py
django_filepicker/utils.py
import re import urllib from os.path import basename from django.core.files import File class FilepickerFile(object): filepicker_url_regex = re.compile( r'https?:\/\/www.filepicker.io\/api\/file\/.*') def __init__(self, url): if not self.filepicker_url_regex.match(url): raise ValueError('Not a filepicker.io URL: %s' % url) self.url = url def get_file(self): ''' Downloads the file from filepicker.io and returns a Django File wrapper object ''' filename, header = urllib.urlretrieve(self.url) name = basename(filename) disposition = header.get('Content-Disposition') if disposition: name = disposition.rpartition("filename=")[2].strip('" ') return File(open(filename, 'r'), name=name)
import re import urllib import os from django.core.files import File class FilepickerFile(object): filepicker_url_regex = re.compile( r'https?:\/\/www.filepicker.io\/api\/file\/.*') def __init__(self, url): if not self.filepicker_url_regex.match(url): raise ValueError('Not a filepicker.io URL: %s' % url) self.url = url def get_file(self): ''' Downloads the file from filepicker.io and returns a Django File wrapper object ''' # clean up any old downloads that are still hanging around self.cleanup() # The temporary file will be created in a directory set by the # environment (TEMP_DIR, TEMP or TMP) self.filename, header = urllib.urlretrieve(self.url) name = os.path.basename(self.filename) disposition = header.get('Content-Disposition') if disposition: name = disposition.rpartition("filename=")[2].strip('" ') self.tempfile = open(self.filename, 'r') return File(self.tempfile, name=name) def cleanup(self): ''' Removes any downloaded objects and closes open files. ''' if hasattr(self, 'tempfile'): self.tempfile.close() delattr(self, 'tempfile') if hasattr(self, 'filename'): # the file might have been moved in the meantime so # check first if os.path.exists(self.filename): os.remove(self.filename) delattr(self, 'filename') def __enter__(self): ''' Allow FilepickerFile to be used as a context manager as such: with FilepickerFile(url) as f: model.field.save(f.name, f.) ''' return self.get_file() def __exit__(self, *args): self.cleanup() def __del__(self): self.cleanup()
Add context manager and destructor for cleanup
Add context manager and destructor for cleanup When exiting the context or calling cleanup() explicitly, the temporary file created after downloading is removed and any open files closed.
Python
mit
FundedByMe/filepicker-django,FundedByMe/filepicker-django,filepicker/filepicker-django,filepicker/filepicker-django
13d0b4b50b2eaaf5c557576b7b45a378d901c49c
src/zeit/cms/testcontenttype/interfaces.py
src/zeit/cms/testcontenttype/interfaces.py
# Copyright (c) 2007-2011 gocept gmbh & co. kg # See also LICENSE.txt # $Id$ """Interface definitions for the test content type.""" import zope.interface class ITestContentType(zope.interface.Interface): """A type for testing.""" ITestContentType.setTaggedValue('zeit.cms.type', 'testcontenttype')
# Copyright (c) 2007-2011 gocept gmbh & co. kg # See also LICENSE.txt # $Id$ """Interface definitions for the test content type.""" import zope.interface class ITestContentType(zope.interface.Interface): """A type for testing."""
Remove superfluous type annotation, it's done by the TypeGrokker now
Remove superfluous type annotation, it's done by the TypeGrokker now
Python
bsd-3-clause
ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms,ZeitOnline/zeit.cms
8f993412a0110085fee10331daecfb3d36973518
__init__.py
__init__.py
### # Copyright (c) 2012, spline # All rights reserved. # # ### """ Add a description of the plugin (to be presented to the user inside the wizard) here. This should describe *what* the plugin does. """ import supybot import supybot.world as world # Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.unknown # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = {} # This is a url where the most recent plugin package can be downloaded. __url__ = '' # 'http://supybot.com/Members/yourname/Scores/download' import config import plugin reload(plugin) # In case we're being reloaded. # Add more reloads here if you add third-party modules and want them to be # reloaded when this plugin is reloaded. Don't forget to import them as well! if world.testing: import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
### # Copyright (c) 2012, spline # All rights reserved. # # ### """ Add a description of the plugin (to be presented to the user inside the wizard) here. This should describe *what* the plugin does. """ import supybot import supybot.world as world # Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.unknown # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = {} # This is a url where the most recent plugin package can be downloaded. __url__ = '' # 'http://supybot.com/Members/yourname/Scores/download' import config import plugin reload(config) reload(plugin) # In case we're being reloaded. # Add more reloads here if you add third-party modules and want them to be # reloaded when this plugin is reloaded. Don't forget to import them as well! if world.testing: import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
Add reload to init for config
Add reload to init for config
Python
mit
reticulatingspline/Scores,cottongin/Scores
f447e8fa50770d133d53e69477292b3925203c64
modular_blocks/models.py
modular_blocks/models.py
from django.db import models from .fields import ListTextField class TwoModularColumnsMixin(models.Model): sidebar_left = ListTextField() sidebar_right = ListTextField() class Meta: abstract = True
from django.db import models from .fields import ListTextField class TwoModularColumnsMixin(models.Model): sidebar_left = ListTextField( blank=True, null=True, ) sidebar_right = ListTextField( lank=True, null=True, ) class Meta: abstract = True
Add null and blank to sidebars
Add null and blank to sidebars
Python
agpl-3.0
rezometz/django-modular-blocks,rezometz/django-modular-blocks,rezometz/django-modular-blocks
b63b22678a005baa6195854b65cc1828061febba
vx/mode.py
vx/mode.py
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('return', 'for', 'while', 'break', 'continue', 'def') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
import vx import os.path def mode_from_filename(file): root, ext = os.path.splitext(file) ext = ext if ext else root mode = None if ext == '.c': return c_mode elif ext == '.py': return python_mode class mode: def __init__(self, window): self.breaks = ('_', ' ', '\n', '\t') self.keywords = () class python_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '{', '}', '.', ',', '#') self.keywords = ('class', 'return', 'for', 'while', 'break', 'continue', 'def', 'from', 'import') class c_mode(mode): def __init__(self, window): super().__init__(window) self.breaks = ('_', ' ', '\n', '\t', '(', ')', '<', '>', '.', ',', '#') self.keywords = ('#include', '#define', 'if', 'else', 'return', 'goto', 'break', 'continue', r'"(?:[^"\\]|\\.)*"')
Add .py extension handling and more python keywords
Add .py extension handling and more python keywords
Python
mit
philipdexter/vx,philipdexter/vx
f62980f99654b22930cac6716410b145b590221f
Lib/lib-tk/FixTk.py
Lib/lib-tk/FixTk.py
import sys, os v = os.path.join(sys.prefix, "tcl", "tcl8.3") if os.path.exists(os.path.join(v, "init.tcl")): os.environ["TCL_LIBRARY"] = v
import sys, os, _tkinter ver = str(_tkinter.TCL_VERSION) v = os.path.join(sys.prefix, "tcl", "tcl"+ver) if os.path.exists(os.path.join(v, "init.tcl")): os.environ["TCL_LIBRARY"] = v
Work the Tcl version number in the path we search for.
Work the Tcl version number in the path we search for.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
1c43affbd82f68ed8956cd407c494ff46dab9203
examples/IPLoM_example.py
examples/IPLoM_example.py
from pygraphc.misc.IPLoM import * from pygraphc.evaluation.ExternalEvaluation import * # set input path ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1/' + ip_address standard_file = standard_path + 'auth.log.anon.labeled' analyzed_file = 'auth.log.anon' prediction_file = 'iplom-result-' + ip_address + '.txt' OutputPath = './result' para = Para(path=standard_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # set cluster label to get evaluation metrics ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) homogeneity_completeness_vmeasure = ExternalEvaluation.get_homogeneity_completeness_vmeasure(standard_file, prediction_file) # print evaluation result print homogeneity_completeness_vmeasure print ('The running time of IPLoM is', time)
from pygraphc.misc.IPLoM import * from pygraphc.evaluation.ExternalEvaluation import * # set input path dataset_path = '/home/hudan/Git/labeled-authlog/dataset/Hofstede2014/dataset1_perday/' groundtruth_file = dataset_path + 'Dec 1.log.labeled' analyzed_file = 'Dec 1.log' OutputPath = '/home/hudan/Git/pygraphc/result/misc/' prediction_file = OutputPath + 'Dec 1.log.perline' para = Para(path=dataset_path, logname=analyzed_file, save_path=OutputPath) # call IPLoM and get clusters myparser = IPLoM(para) time = myparser.main_process() clusters = myparser.get_clusters() original_logs = myparser.logs # set cluster label to get evaluation metrics ExternalEvaluation.set_cluster_label_id(None, clusters, original_logs, prediction_file) # get evaluation of clustering performance ar = ExternalEvaluation.get_adjusted_rand(groundtruth_file, prediction_file) ami = ExternalEvaluation.get_adjusted_mutual_info(groundtruth_file, prediction_file) nmi = ExternalEvaluation.get_normalized_mutual_info(groundtruth_file, prediction_file) h = ExternalEvaluation.get_homogeneity(groundtruth_file, prediction_file) c = ExternalEvaluation.get_completeness(groundtruth_file, prediction_file) v = ExternalEvaluation.get_vmeasure(groundtruth_file, prediction_file) # print evaluation result print ar, ami, nmi, h, c, v print ('The running time of IPLoM is', time)
Edit path and external evaluation
Edit path and external evaluation
Python
mit
studiawan/pygraphc
6e1126fe9a8269ff4489ee338000afc852bce922
oidc_apis/id_token.py
oidc_apis/id_token.py
import inspect from .scopes import get_userinfo_by_scopes def process_id_token(payload, user, scope=None): if scope is None: # HACK: Steal the scope argument from the locals dictionary of # the caller, since it was not passed to us scope = inspect.stack()[1][0].f_locals.get('scope', []) payload.update(get_userinfo_by_scopes(user, scope)) return payload
import inspect from .scopes import get_userinfo_by_scopes def process_id_token(payload, user, scope=None): if scope is None: # HACK: Steal the scope argument from the locals dictionary of # the caller, since it was not passed to us scope = inspect.stack()[1][0].f_locals.get('scope', []) payload.update(get_userinfo_by_scopes(user, scope)) payload['preferred_username'] = user.username return payload
Add username to ID Token
Add username to ID Token
Python
mit
mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo
b47e3677120b9b2d64d38b48b0382dc7986a1b82
opps/core/__init__.py
opps/core/__init__.py
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ('opps.article', 'opps.image', 'opps.channel', 'opps.source', 'redactor', 'tagging',) settings.REDACTOR_OPTIONS = {'lang': 'en'} settings.REDACTOR_UPLOAD = 'uploads/'
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ trans_app_label = _('Opps')
Remove installed app on init opps core
Remove installed app on init opps core
Python
mit
YACOWS/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,YACOWS/opps
52d15d09ed079d1b8598f314524066b56273af3d
addie/_version.py
addie/_version.py
# This file was generated by 'versioneer.py' (0.15) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json import sys version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
# This file was generated by 'versioneer.py' (0.15) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' { "dirty": false, "error": null, "full-revisionid": "aaeac9708788e1b02d6a763b86333eff9bad7122", "version": "5.0.4" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
Remove sys import in versioneer file
Remove sys import in versioneer file
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
25a97de30fcc9cddd7f58cd25584fd726f0cc8e4
guild/commands/packages_list.py
guild/commands/packages_list.py
# Copyright 2017-2020 TensorHub, 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 __future__ import absolute_import from __future__ import division import click from guild import click_util @click.command("list, ls") @click.argument("terms", metavar="[TERM]...", nargs=-1) @click.option("-a", "--all", help="Show all packages.", is_flag=True) @click_util.use_args def list_packages(args): """List installed packages. Specify one or more `TERM` arguments to show packages matching any of the specified values. """ from . import packages_impl packages_impl.list_packages(args)
# Copyright 2017-2020 TensorHub, 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 __future__ import absolute_import from __future__ import division import click from guild import click_util @click.command("list, ls") @click.argument("terms", metavar="[TERM]...", nargs=-1) @click.option("-a", "--all", help="Show all installed Python packages.", is_flag=True) @click_util.use_args def list_packages(args): """List installed packages. Specify one or more `TERM` arguments to show packages matching any of the specified values. """ from . import packages_impl packages_impl.list_packages(args)
Clarify meaning of --all option for packages command
Clarify meaning of --all option for packages command
Python
apache-2.0
guildai/guild,guildai/guild,guildai/guild,guildai/guild
ccdeb23eb54191913a97b48907e0738f6969ce58
tests/factories/config.py
tests/factories/config.py
# -*- coding: utf-8 -*- # Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from factory import SubFactory from pycroft.model.config import Config from .base import BaseFactory from .finance import AccountFactory, BankAccountFactory from .property import PropertyGroupFactory, MemberPropertyGroupFactory class ConfigFactory(BaseFactory): """This is a dummy Config factory, Referencing PropertyGroups with no a-priori property relationships and arbitrary Accounts. """ class Meta: model = Config id = 1 # `PropertyGroup`s member_group = SubFactory(MemberPropertyGroupFactory) network_access_group = SubFactory(PropertyGroupFactory) violation_group = SubFactory(PropertyGroupFactory) cache_group = SubFactory(PropertyGroupFactory) traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory) external_group = SubFactory(PropertyGroupFactory) payment_in_default_group = SubFactory(PropertyGroupFactory) blocked_group = SubFactory(PropertyGroupFactory) caretaker_group = SubFactory(PropertyGroupFactory) treasurer_group = SubFactory(PropertyGroupFactory) # `Account`s membership_fee_account = SubFactory(AccountFactory) membership_fee_bank_account = SubFactory(BankAccountFactory)
# -*- coding: utf-8 -*- # Copyright (c) 2018 The Pycroft Authors. See the AUTHORS file. # This file is part of the Pycroft project and licensed under the terms of # the Apache License, Version 2.0. See the LICENSE file for details. from factory import SubFactory from pycroft.model.config import Config from .base import BaseFactory from .finance import AccountFactory, BankAccountFactory from .property import PropertyGroupFactory, MemberPropertyGroupFactory class ConfigFactory(BaseFactory): """This is a dummy Config factory, Referencing PropertyGroups with no a-priori property relationships and arbitrary Accounts. """ class Meta: model = Config id = 1 # `PropertyGroup`s member_group = SubFactory(MemberPropertyGroupFactory) network_access_group = SubFactory(PropertyGroupFactory) violation_group = SubFactory(PropertyGroupFactory) cache_group = SubFactory(PropertyGroupFactory) traffic_limit_exceeded_group = SubFactory(PropertyGroupFactory) external_group = SubFactory(PropertyGroupFactory) payment_in_default_group = SubFactory(PropertyGroupFactory, granted=frozenset(("payment_in_default",)), denied=frozenset(("network_access", "userwww", "userdb"))) blocked_group = SubFactory(PropertyGroupFactory) caretaker_group = SubFactory(PropertyGroupFactory) treasurer_group = SubFactory(PropertyGroupFactory) # `Account`s membership_fee_account = SubFactory(AccountFactory) membership_fee_bank_account = SubFactory(BankAccountFactory)
Add correct properties for payment_in_default test group
Add correct properties for payment_in_default test group
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
fb9c56381d259de7d1765ca0e058f82d61e4e975
examples/ellipses_FreeCAD.py
examples/ellipses_FreeCAD.py
from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) + ".\.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print area, " ", area/500/70 part = Part.makeCompound(shapes)
from __future__ import division import numpy as np import FreeCAD as FC import Part import Draft import os doc = FC.newDocument("ellipses") folder = os.path.dirname(__file__) #+ "/.." fname = folder + "/vor_ellipses.txt" data = np.loadtxt(fname) shapes = [] area = 0 radii = [] for ellipse in data: cx, cy, b, a, ang = ellipse ang = ang*np.pi/180 place = FC.Placement() place.Rotation = (0, 0, np.sin(ang/2), np.cos(ang/2)) place.Base = FC.Vector(100*cx, 100*cy, 0) ellipse = Draft.makeEllipse(100*a, 100*b, placement=place) radii.append([100*a, 100*b]) shapes.append(ellipse) area = area + np.pi*a*b*100*100 print "area: %g " % (area/500/70) print "radius: %g +/- %g" % (np.mean(radii), np.std(radii)) part = Part.makeCompound(shapes)
Add radii mean and standard deviation
Add radii mean and standard deviation
Python
mit
nicoguaro/ellipse_packing
08de3f0bf326e8625462d9dbdb7297d8749bc416
examples/joystick_example.py
examples/joystick_example.py
#!/usr/bin/env python3 """This example shows how to use the Joystick Click wrapper of the LetMeCreate. It continuously reads the position of the joystick, prints it in the terminal and displays a pattern on the LED's based on the x coordinate. The Joystick Click must be inserted in Mikrobus 1 before running this program. """ from letmecreate.core import i2c from letmecreate.core import led from letmecreate.click import joystick OFFSET = 98 MAXIMUM = OFFSET2 def get_led_mask(perc): div = int((1. - perc)led.LED_CNT) if div > led.LED_CNT: div = led.LED_CNT mask = 0 for i in range(div): mask |= (1 << i) return mask i2c.init() led.init() while True: pos = joystick.get_position() print('{} {}'.format(pos[0], pos[1])) mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM)) led.switch_on(mask) led.switch_off(~mask) i2c.release() led.release()
#!/usr/bin/env python3 """This example shows how to use the Joystick Click wrapper of the LetMeCreate. It continuously reads the position of the joystick, prints it in the terminal and displays a pattern on the LED's based on the x coordinate. The Joystick Click must be inserted in Mikrobus 1 before running this program. """ from letmecreate.core import i2c from letmecreate.core import led from letmecreate.click import joystick OFFSET = 98 MAXIMUM = OFFSET2 def get_led_mask(perc): div = int((1. - perc)led.LED_CNT) if div > led.LED_CNT: div = led.LED_CNT mask = 0 for i in range(div): mask |= (1 << i) return mask i2c.init() led.init() while True: pos = joystick.get_position() print('{} {}'.format(pos[0], pos[1])) mask = get_led_mask(float(pos[0] + OFFSET)/float(MAXIMUM)) led.switch_on(mask) led.switch_off(~mask) i2c.release() led.release()
Replace tabs by space in example
joystick: Replace tabs by space in example Signed-off-by: Francois Berder <59eaf4bb0211c66c3d7532da6d77ecf42a779d82@outlook.fr>
Python
bsd-3-clause
francois-berder/PyLetMeCreate
98a4cd76ce9ecb81675ebaa29b249a8d80347e0d
zc-list.py
zc-list.py
#!/usr/bin/env python import client_wrap KEY_LONG = "key1" DATA_LONG = 1024 KEY_DOUBLE = "key2" DATA_DOUBLE = 100.53 KEY_STRING = "key3" DATA_STRING = "test data" def init_data(client): client.WriteLong(KEY_LONG, DATA_LONG) client.WriteDouble(KEY_DOUBLE, DATA_DOUBLE) client.WriteString(KEY_STRING, DATA_STRING) def check_data(client): assert DATA_LONG == client.ReadLong(KEY_LONG) assert DATA_DOUBLE == client.ReadDouble(KEY_DOUBLE) assert DATA_STRING == client.ReadString(KEY_STRING) def main(): client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0) init_data(client) check_data(client) if __name__ == "__main__": main()
#!/usr/bin/env python import client_wrap def main(): client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0) key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: return print keys if __name__ == "__main__": main()
Implement displaying of the current key list
Implement displaying of the current key list
Python
agpl-3.0
ellysh/zero-cache-utils,ellysh/zero-cache-utils
2049be18b864fe2dab61ca6258b2295b3270d5c2
setup.py
setup.py
import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '0.0' distutils.core.setup( name='kxg', version=version, author='Kale Kundert and Alex Mitchell', url='https://github.com/kxgames/GameEngine', download_url='https://github.com/kxgames/GameEngine/tarball/'+version, license='LICENSE.txt', description="A multiplayer game engine.", long_description=open('README.rst').read(), keywords=['game', 'network', 'gui', 'pyglet'], packages=['kxg'], requires=[ 'pyglet', 'nonstdlib', 'linersock', 'vecrec', 'glooey', ], )
import distutils.core # Uploading to PyPI # ================= # $ python setup.py register -r pypi # $ python setup.py sdist upload -r pypi version = '0.0' distutils.core.setup( name='kxg', version=version, author='Kale Kundert and Alex Mitchell', url='https://github.com/kxgames/GameEngine', download_url='https://github.com/kxgames/GameEngine/tarball/'+version, license='LICENSE.txt', description="A multiplayer game engine.", long_description=open('README.rst').read(), keywords=['game', 'network', 'gui', 'pyglet'], packages=['kxg'], requires=[ 'pyglet', 'nonstdlib', 'linersock', 'vecrec', 'glooey', 'pytest', ], )
Add pytest as a dependency
Add pytest as a dependency
Python
mit
kxgames/kxg
a61386cbbcbe3e68bcdf0a98c23547117a496fec
zerver/views/webhooks/github_dispatcher.py
zerver/views/webhooks/github_dispatcher.py
from __future__ import absolute_import from django.http import HttpRequest, HttpResponse from .github_webhook import api_github_webhook from .github import api_github_landing def api_github_webhook_dispatch(request): # type: (HttpRequest) -> HttpResponse if request.META.get('HTTP_X_GITHUB_EVENT'): return api_github_webhook(request) else: return api_github_landing(request)
from __future__ import absolute_import from django.http import HttpRequest, HttpResponse from django.views.decorators.csrf import csrf_exempt from .github_webhook import api_github_webhook from .github import api_github_landing # Since this dispatcher is an API-style endpoint, it needs to be # explicitly marked as CSRF-exempt @csrf_exempt def api_github_webhook_dispatch(request): # type: (HttpRequest) -> HttpResponse if request.META.get('HTTP_X_GITHUB_EVENT'): return api_github_webhook(request) else: return api_github_landing(request)
Fix GitHub integration CSRF issue.
github: Fix GitHub integration CSRF issue. The new GitHub dispatcher integration was apparently totally broken, because we hadn't tagged the new dispatcher endpoint as exempt from CSRF checking. I'm not sure why the test suite didn't catch this.
Python
apache-2.0
AZtheAsian/zulip,dhcrzf/zulip,JPJPJPOPOP/zulip,christi3k/zulip,hackerkid/zulip,verma-varsha/zulip,j831/zulip,Diptanshu8/zulip,dhcrzf/zulip,ryanbackman/zulip,shubhamdhama/zulip,Galexrt/zulip,hackerkid/zulip,andersk/zulip,amyliu345/zulip,j831/zulip,mahim97/zulip,brainwane/zulip,SmartPeople/zulip,ryanbackman/zulip,Galexrt/zulip,dawran6/zulip,JPJPJPOPOP/zulip,rht/zulip,niftynei/zulip,vaidap/zulip,amanharitsh123/zulip,AZtheAsian/zulip,shubhamdhama/zulip,rht/zulip,kou/zulip,jphilipsen05/zulip,mahim97/zulip,verma-varsha/zulip,isht3/zulip,cosmicAsymmetry/zulip,vabs22/zulip,vabs22/zulip,eeshangarg/zulip,showell/zulip,PhilSk/zulip,timabbott/zulip,rishig/zulip,jrowan/zulip,sharmaeklavya2/zulip,aakash-cr7/zulip,tommyip/zulip,JPJPJPOPOP/zulip,zulip/zulip,ryanbackman/zulip,jackrzhang/zulip,jackrzhang/zulip,rht/zulip,cosmicAsymmetry/zulip,brainwane/zulip,brockwhittaker/zulip,timabbott/zulip,andersk/zulip,christi3k/zulip,rishig/zulip,isht3/zulip,blaze225/zulip,punchagan/zulip,kou/zulip,susansls/zulip,brainwane/zulip,eeshangarg/zulip,jainayush975/zulip,brainwane/zulip,susansls/zulip,vabs22/zulip,vabs22/zulip,verma-varsha/zulip,Diptanshu8/zulip,rht/zulip,punchagan/zulip,jrowan/zulip,sonali0901/zulip,dawran6/zulip,eeshangarg/zulip,showell/zulip,eeshangarg/zulip,tommyip/zulip,JPJPJPOPOP/zulip,shubhamdhama/zulip,showell/zulip,shubhamdhama/zulip,christi3k/zulip,sonali0901/zulip,eeshangarg/zulip,dhcrzf/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,Diptanshu8/zulip,kou/zulip,souravbadami/zulip,hackerkid/zulip,tommyip/zulip,souravbadami/zulip,samatdav/zulip,amyliu345/zulip,brockwhittaker/zulip,amanharitsh123/zulip,ryanbackman/zulip,j831/zulip,SmartPeople/zulip,synicalsyntax/zulip,samatdav/zulip,dawran6/zulip,kou/zulip,andersk/zulip,PhilSk/zulip,vaidap/zulip,AZtheAsian/zulip,jrowan/zulip,zulip/zulip,aakash-cr7/zulip,christi3k/zulip,rishig/zulip,souravbadami/zulip,sharmaeklavya2/zulip,zulip/zulip,Diptanshu8/zulip,dawran6/zulip,jackrzhang/zulip,blaze225/zulip,isht3/zulip,brainwane/zulip,synicalsyntax/zulip,punchagan/zulip,synicalsyntax/zulip,amyliu345/zulip,dhcrzf/zulip,sonali0901/zulip,zulip/zulip,rishig/zulip,synicalsyntax/zulip,hackerkid/zulip,samatdav/zulip,susansls/zulip,hackerkid/zulip,susansls/zulip,brockwhittaker/zulip,susansls/zulip,timabbott/zulip,aakash-cr7/zulip,sharmaeklavya2/zulip,rht/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,jainayush975/zulip,aakash-cr7/zulip,zulip/zulip,shubhamdhama/zulip,brockwhittaker/zulip,andersk/zulip,jackrzhang/zulip,dattatreya303/zulip,Galexrt/zulip,rht/zulip,zulip/zulip,amanharitsh123/zulip,jackrzhang/zulip,j831/zulip,tommyip/zulip,JPJPJPOPOP/zulip,punchagan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,tommyip/zulip,jphilipsen05/zulip,timabbott/zulip,PhilSk/zulip,niftynei/zulip,samatdav/zulip,dattatreya303/zulip,SmartPeople/zulip,kou/zulip,shubhamdhama/zulip,amanharitsh123/zulip,brainwane/zulip,verma-varsha/zulip,blaze225/zulip,j831/zulip,AZtheAsian/zulip,eeshangarg/zulip,Galexrt/zulip,blaze225/zulip,amyliu345/zulip,verma-varsha/zulip,tommyip/zulip,synicalsyntax/zulip,dawran6/zulip,vaidap/zulip,dhcrzf/zulip,showell/zulip,jphilipsen05/zulip,ryanbackman/zulip,sonali0901/zulip,sonali0901/zulip,aakash-cr7/zulip,brainwane/zulip,andersk/zulip,christi3k/zulip,jainayush975/zulip,AZtheAsian/zulip,j831/zulip,rht/zulip,AZtheAsian/zulip,ryanbackman/zulip,vabs22/zulip,zulip/zulip,shubhamdhama/zulip,kou/zulip,rishig/zulip,mahim97/zulip,hackerkid/zulip,timabbott/zulip,mahim97/zulip,niftynei/zulip,jrowan/zulip,sharmaeklavya2/zulip,souravbadami/zulip,jphilipsen05/zulip,verma-varsha/zulip,jackrzhang/zulip,jackrzhang/zulip,dattatreya303/zulip,rishig/zulip,punchagan/zulip,tommyip/zulip,andersk/zulip,jainayush975/zulip,jphilipsen05/zulip,blaze225/zulip,PhilSk/zulip,Diptanshu8/zulip,Diptanshu8/zulip,amyliu345/zulip,timabbott/zulip,dhcrzf/zulip,cosmicAsymmetry/zulip,amanharitsh123/zulip,cosmicAsymmetry/zulip,rishig/zulip,niftynei/zulip,showell/zulip,isht3/zulip,SmartPeople/zulip,vaidap/zulip,vaidap/zulip,PhilSk/zulip,andersk/zulip,sonali0901/zulip,aakash-cr7/zulip,Galexrt/zulip,jrowan/zulip,susansls/zulip,christi3k/zulip,jainayush975/zulip,niftynei/zulip,amyliu345/zulip,PhilSk/zulip,brockwhittaker/zulip,eeshangarg/zulip,synicalsyntax/zulip,hackerkid/zulip,showell/zulip,dattatreya303/zulip,dawran6/zulip,jainayush975/zulip,mahim97/zulip,cosmicAsymmetry/zulip,punchagan/zulip,synicalsyntax/zulip,souravbadami/zulip,cosmicAsymmetry/zulip,timabbott/zulip,dhcrzf/zulip,dattatreya303/zulip,vabs22/zulip,jrowan/zulip,niftynei/zulip,brockwhittaker/zulip,JPJPJPOPOP/zulip,blaze225/zulip,punchagan/zulip,amanharitsh123/zulip,samatdav/zulip,jphilipsen05/zulip,sharmaeklavya2/zulip,samatdav/zulip,Galexrt/zulip,Galexrt/zulip,mahim97/zulip,dattatreya303/zulip,kou/zulip
a7c49480e1eb530aa4df494709ec1f7edd875e1a
devito/ir/clusters/analysis.py
devito/ir/clusters/analysis.py
from devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR, TILABLE, WRAPPABLE) __all__ = ['analyze'] def analyze(clusters): return clusters
from collections import OrderedDict from devito.ir.clusters.queue import Queue from devito.ir.support import (SEQUENTIAL, PARALLEL, PARALLEL_IF_ATOMIC, VECTOR, TILABLE, WRAPPABLE) from devito.tools import timed_pass __all__ = ['analyze'] class State(object): def __init__(self): self.properties = OrderedDict() self.scopes = OrderedDict() class Detector(Queue): def __init__(self, state): super(Detector, self).__init__() self.state = state def callback(self, clusters, prefix): self._callback(clusters, prefix) return clusters class Parallelism(Detector): def _callback(self, clusters, prefix): properties = OrderedDict() def analyze(clusters): state = State() clusters = Parallelism(state).process(clusters) return clusters
Add machinery to detect Cluster properties
ir: Add machinery to detect Cluster properties
Python
mit
opesci/devito,opesci/devito
b362e6060abe631f25e5227664df4e1670f4d630
registration/admin.py
registration/admin.py
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
from django.contrib import admin from registration.models import RegistrationProfile class RegistrationAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'activation_key_expired') raw_id_fields = ['user'] search_fields = ('user__username', 'user__first_name') admin.site.register(RegistrationProfile, RegistrationAdmin)
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Use raw_id_fields for the relation from RegistrationProfile to User, for sites which have huge numbers of users.
Python
bsd-3-clause
arpitremarkable/django-registration,sergafts/django-registration,wy123123/django-registration,wda-hb/test,furious-luke/django-registration,imgmix/django-registration,matejkloska/django-registration,PetrDlouhy/django-registration,pando85/django-registration,yorkedork/django-registration,pando85/django-registration,percipient/django-registration,tanjunyen/django-registration,torchingloom/django-registration,wy123123/django-registration,kazitanvirahsan/django-registration,maitho/django-registration,kinsights/django-registration,rulz/django-registration,mick-t/django-registration,ei-grad/django-registration,nikolas/django-registration,percipient/django-registration,timgraham/django-registration,ei-grad/django-registration,mick-t/django-registration,PetrDlouhy/django-registration,arpitremarkable/django-registration,tanjunyen/django-registration,kinsights/django-registration,stillmatic/django-registration,torchingloom/django-registration,matejkloska/django-registration,imgmix/django-registration,kazitanvirahsan/django-registration,yorkedork/django-registration,memnonila/django-registration,timgraham/django-registration,Geffersonvivan/django-registration,alawnchen/django-registration,alawnchen/django-registration,erinspace/django-registration,furious-luke/django-registration,rulz/django-registration,wda-hb/test,PSU-OIT-ARC/django-registration,Geffersonvivan/django-registration,sergafts/django-registration,nikolas/django-registration,erinspace/django-registration,PSU-OIT-ARC/django-registration,allo-/django-registration,allo-/django-registration,maitho/django-registration,stillmatic/django-registration,memnonila/django-registration
d60b0ee8c212728721f47cc57303ae24888cc387
models.py
models.py
import datetime import math from flask import Markup from peewee import Model, TextField, DateTimeField from app import db class Quote(Model): content = TextField() timestamp = DateTimeField(default=datetime.datetime.now) class Meta: database = db def html(self): return Markup(self.content) @classmethod def paged(cls, page, page_size): quotes = Quote.select().order_by(Quote.timestamp.desc()) page_count = math.ceil(quotes.count() / page_size) return quotes.offset(page * page_size).limit(page_size), page_count
import datetime import math from flask import Markup from peewee import Model, TextField, DateTimeField from app import db class Quote(Model): content = TextField() timestamp = DateTimeField(default=datetime.datetime.now) class Meta: database = db def html(self): return Markup(self.content.replace('\n', '<br>')) @classmethod def paged(cls, page, page_size): quotes = Quote.select().order_by(Quote.timestamp.desc()) page_count = math.ceil(quotes.count() / page_size) return quotes.offset(page * page_size).limit(page_size), page_count
Add support for carriage returns
Add support for carriage returns
Python
apache-2.0
agateau/tmc2,agateau/tmc2
37333506e6866e7d0859c5068f115a3e1b9dec3a
test/test_coordinate.py
test/test_coordinate.py
import unittest from src import coordinate class TestRules(unittest.TestCase): """ Tests for the coordinate module """ def test_get_x_board(self): board_location = coordinate.Coordinate(4, 6) expected_result = 4 actual_result = board_location.get_x_board() self.assertEqual(actual_result, expected_result) def test_get_y_board(self): board_location = coordinate.Coordinate(4, 6) expected_result = 6 actual_result = board_location.get_y_board() self.assertEqual(actual_result, expected_result) def test_get_x_array(self): board_location = coordinate.Coordinate(4, 6) expected_result = 3 actual_result = board_location.get_x_array() self.assertEqual(actual_result, expected_result) def test_get_y_array(self): board_location = coordinate.Coordinate(4, 6) expected_result = 5 actual_result = board_location.get_y_array() self.assertEqual(actual_result, expected_result)
import unittest from src import coordinate class TestRules(unittest.TestCase): """ Tests for the coordinate module """ def test_get_x_board(self): board_location = coordinate.Coordinate(4, 6) expected_result = 4 actual_result = board_location.get_x_board() self.assertEqual(actual_result, expected_result) def test_get_y_board(self): board_location = coordinate.Coordinate(4, 6) expected_result = 6 actual_result = board_location.get_y_board() self.assertEqual(actual_result, expected_result) def test_get_x_array(self): board_location = coordinate.Coordinate(4, 6) expected_result = 3 actual_result = board_location.get_x_array() self.assertEqual(actual_result, expected_result) def test_get_y_array(self): board_location = coordinate.Coordinate(4, 6) expected_result = 5 actual_result = board_location.get_y_array() self.assertEqual(actual_result, expected_result) def test_coordinate_bad_x(self): self.assertRaises(TypeError, coordinate.Coordinate, "4", 6) def test_coordinate_bad_y(self): self.assertRaises(TypeError, coordinate.Coordinate, 4, "6") def test_coordinate_bad_location(self): self.assertRaises(ValueError, coordinate.Coordinate, 50, 100)
Add unit tests for fail fast logic in convertCharToInt()
Add unit tests for fail fast logic in convertCharToInt()
Python
mit
blairck/jaeger
4622c1d2623468503b5d51683f953b82ca611b35
vumi/demos/tests/test_static_reply.py
vumi/demos/tests/test_static_reply.py
from twisted.internet.defer import inlineCallbacks from vumi.application.tests.utils import ApplicationTestCase from vumi.demos.static_reply import StaticReplyApplication class TestStaticReplyApplication(ApplicationTestCase): application_class = StaticReplyApplication @inlineCallbacks def test_receive_message(self): yield self.get_application(config={ 'reply_text': 'Your message is important to us.', }) yield self.dispatch(self.mkmsg_in()) [reply] = yield self.get_dispatched_messages() self.assertEqual('Your message is important to us.', reply['content']) self.assertEqual(u'close', reply['session_event']) @inlineCallbacks def test_receive_message_no_reply(self): yield self.get_application(config={}) yield self.dispatch(self.mkmsg_in()) self.assertEqual([], (yield self.get_dispatched_messages()))
from twisted.internet.defer import inlineCallbacks from vumi.application.tests.helpers import ApplicationHelper from vumi.demos.static_reply import StaticReplyApplication from vumi.tests.helpers import VumiTestCase class TestStaticReplyApplication(VumiTestCase): def setUp(self): self.app_helper = ApplicationHelper(StaticReplyApplication) self.add_cleanup(self.app_helper.cleanup) @inlineCallbacks def test_receive_message(self): yield self.app_helper.get_application({ 'reply_text': 'Your message is important to us.', }) yield self.app_helper.make_dispatch_inbound("Hello") [reply] = self.app_helper.get_dispatched_outbound() self.assertEqual('Your message is important to us.', reply['content']) self.assertEqual(u'close', reply['session_event']) @inlineCallbacks def test_receive_message_no_reply(self): yield self.app_helper.get_application({}) yield self.app_helper.make_dispatch_inbound("Hello") self.assertEqual([], self.app_helper.get_dispatched_outbound())
Switch static_reply tests to new helpers.
Switch static_reply tests to new helpers.
Python
bsd-3-clause
vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,harrissoerja/vumi,harrissoerja/vumi,harrissoerja/vumi
bb04512cdf264a3ef87f3d0093db9fe10723a668
core/wsgi.py
core/wsgi.py
""" WSGI config for core project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") application = get_wsgi_application()
""" WSGI config for core project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ """ import os, sys, site site.addsitedir('/usr/local/share/virtualenvs/guhema/lib/python3.4/site-packages') sys.path.append('/var/www/vhosts/guhema.com/httpdocs/django') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dpb.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
Add pathts for apache deployment
Add pathts for apache deployment
Python
mit
n2o/guhema,n2o/guhema
1c1f2cab677ead5f3cf3aa59c5094a741378e5bc
dame/dame.py
dame/dame.py
__author__ = "Richard Lindsley" import sys import sip sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QString', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) sip.setapi('QVariant', 2) from PyQt4 import Qt def main(): qt_app = Qt.QApplication(sys.argv) label = Qt.QLabel("Hello, world") label.show() qt_app.exec_() if __name__ == "__main__": main()
__author__ = "Richard Lindsley" import sys #import sip #sip.setapi('QDate', 2) #sip.setapi('QDateTime', 2) #sip.setapi('QString', 2) #sip.setapi('QTextStream', 2) #sip.setapi('QTime', 2) #sip.setapi('QUrl', 2) #sip.setapi('QVariant', 2) #from PyQt4 import Qt from PySide.QtCore import * from PySide.QtGui import * def main(): qt_app = QApplication(sys.argv) label = QLabel("Hello, world") label.show() qt_app.exec_() if __name__ == "__main__": main()
Use pyside instead of pyqt4
Use pyside instead of pyqt4
Python
mit
richli/dame
06542afc4becb4cf3cf96dd15ab240ab4353bf2b
ca/views.py
ca/views.py
from flask import request, render_template from ca import app, db from ca.forms import RequestForm from ca.models import Request @app.route('/', methods=['GET']) def index(): return render_template('index.html') @app.route('/', methods=['POST']) def post_request(): form = RequestForm(request.form) if form.validate(): req = Request(form.id.data, form.email.data) db.session.add(req) db.session.commit() return render_template('thanks.html') else: return render_template('index.html', form=form)
from flask import request, render_template from ca import app, db from ca.forms import RequestForm from ca.models import Request @app.route('/', methods=['GET']) def index(): form = RequestForm() return render_template('index.html', form=form) @app.route('/', methods=['POST']) def post_request(): form = RequestForm(request.form) if form.validate(): req = Request(form.id.data, form.email.data) db.session.add(req) db.session.commit() return render_template('thanks.html') else: return render_template('index.html', form=form)
Create form on index view
Create form on index view - Need to always pass a form to the view - make sure to create on for the `GET` view - Fixes #33
Python
mit
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net
a621a7803d177e4851d229973586d9b114b0f84c
__init__.py
__init__.py
# -*- coding: utf-8 -*- from flask import Flask from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB'] = config['MongoDB']['db_name'] app.config['MONGODB_HOST'] = config['MongoDB']['host'] app.config['MONGODB_PORT'] = int(config['MongoDB']['port']) app.config['MONGODB_USERNAME'] = config['MongoDB']['username'] app.config['MONGODB_PASSWORD'] = config['MongoDB']['password'] db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) register_blueprints(app) if __name__ == '__main__': app.run()
# -*- coding: utf-8 -*- from flask import Flask, render_template from flask.ext.mongoengine import MongoEngine, MongoEngineSessionInterface import configparser app = Flask(__name__) # Security WTF_CSRF_ENABLED = True app.config['SECRET_KEY'] = '2bN9UUaBpcjrxR' # App Config config = configparser.ConfigParser() config.read('config/config.ini') app.config['MONGODB_DB'] = config['MongoDB']['db_name'] app.config['MONGODB_HOST'] = config['MongoDB']['host'] app.config['MONGODB_PORT'] = int(config['MongoDB']['port']) app.config['MONGODB_USERNAME'] = config['MongoDB']['username'] app.config['MONGODB_PASSWORD'] = config['MongoDB']['password'] db = MongoEngine(app) def register_blueprints(app): # Prevents circular imports from weighttracker.views.measurement_views import measurements app.register_blueprint(measurements) from weighttracker.views.inspiration_views import inspirations app.register_blueprint(inspirations) register_blueprints(app) @app.route('/', defaults={'path': ''}) @app.route('/<path:path>') def catch_all(path): return render_template('index.html') if __name__ == '__main__': app.run()
Create a catch-all route and route to the homepage.
Create a catch-all route and route to the homepage. Signed-off-by: Robert Dempsey <715b5a941e732be1613fdd9d94dfd8e50c02b187@gmail.com>
Python
mit
rdempsey/weight-tracker,rdempsey/weight-tracker,rdempsey/weight-tracker
01b511b1f337f00eb72530692eec202611599c5a
tilequeue/queue/file.py
tilequeue/queue/file.py
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = ''.join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): coord = self.fp.readline() if coord: coords.append(CoordMessage(deserialize_coord(coord), None)) else: break return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: self.clear() self.fp.write(self.fp.read()) self.fp.close()
Fix a bug in OutputFileQueue.close().
Fix a bug in OutputFileQueue.close(). tilequeue/queue/file.py -01a8fcb made `OutputFileQueue.read()` use `readline()` instead of `next()`, but didn't update `OutputFileQueue.close()`, which uses a list comprehension to grab the rest of the file. Since `.read()` no longer uses the iteration protocol, `.close()` will start iterating from the beginning of the file. Use `.read()` instead of a list comprehension to only grab everything after what `.readline()` already picked up.
Python
mit
mapzen/tilequeue,tilezen/tilequeue
8d02d9cf5e07951a80bf424334ba59af92cfd6cc
test/suite/out/long_lines.py
test/suite/out/long_lines.py
if True: if True: if True: self.__heap.sort( ) # pylint: builtin sort probably faster than O(n)-time heapify if True: foo = '( ' + \ array[0] + ' '
if True: if True: if True: self.__heap.sort( ) # pylint: builtin sort probably faster than O(n)-time heapify if True: foo = '( ' + array[0] + ' '
Update due to logical line changes
Update due to logical line changes
Python
mit
vauxoo-dev/autopep8,SG345/autopep8,MeteorAdminz/autopep8,Vauxoo/autopep8,SG345/autopep8,hhatto/autopep8,Vauxoo/autopep8,MeteorAdminz/autopep8,hhatto/autopep8,vauxoo-dev/autopep8
45c7e910f13a43427359801782eef7ce537d6f5f
delayed_assert/__init__.py
delayed_assert/__init__.py
from delayed_assert.delayed_assert import expect, assert_expectations
import sys if sys.version_info > (3, 0): # Python 3 and above from delayed_assert.delayed_assert import expect, assert_expectations else: # for Python 2 from delayed_assert import expect, assert_expectations
Support for python 2 and 3
Support for python 2 and 3
Python
unlicense
pr4bh4sh/python-delayed-assert
8154b206160cde249c474f5905a60b9a8086c910
conftest.py
conftest.py
# Copyright (c) 2016,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Configure pytest for metpy.""" import os import matplotlib import matplotlib.pyplot import numpy import pandas import pytest import scipy import xarray import metpy.calc # Need to disable fallback before importing pint os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0' import pint # noqa: I100, E402 def pytest_report_header(config, startdir): """Add dependency information to pytest output.""" return ('Dependencies: Matplotlib ({}), NumPy ({}), Pandas ({}), ' 'Pint ({}), SciPy ({}), Xarray ({})'.format(matplotlib.__version__, numpy.__version__, pandas.__version__, pint.__version__, scipy.__version__, xarray.__version__)) @pytest.fixture(autouse=True) def doctest_available_modules(doctest_namespace): """Make modules available automatically to doctests.""" doctest_namespace['metpy'] = metpy doctest_namespace['metpy.calc'] = metpy.calc doctest_namespace['plt'] = matplotlib.pyplot
# Copyright (c) 2016,2019 MetPy Developers. # Distributed under the terms of the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause """Configure pytest for metpy.""" import os import matplotlib import matplotlib.pyplot import numpy import pandas import pooch import pytest import scipy import traitlets import xarray import metpy.calc # Need to disable fallback before importing pint os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0' import pint # noqa: I100, E402 def pytest_report_header(config, startdir): """Add dependency information to pytest output.""" return (f'Dep Versions: Matplotlib {matplotlib.__version__}, ' f'NumPy {numpy.__version__}, SciPy {scipy.__version__}, ' f'Xarray {xarray.__version__}, Pint {pint.__version__}, ' f'Pandas {pandas.__version__}, Traitlets {traitlets.__version__}, ' f'Pooch {pooch.version.full_version}') @pytest.fixture(autouse=True) def doctest_available_modules(doctest_namespace): """Make modules available automatically to doctests.""" doctest_namespace['metpy'] = metpy doctest_namespace['metpy.calc'] = metpy.calc doctest_namespace['plt'] = matplotlib.pyplot
Print out all dependency versions at the start of pytest
TST: Print out all dependency versions at the start of pytest
Python
bsd-3-clause
Unidata/MetPy,dopplershift/MetPy,Unidata/MetPy,dopplershift/MetPy
f7fa8b72b8d8d1b7bfcd6c738520fc87cd20e320
ixdjango/tests/__init__.py
ixdjango/tests/__init__.py
""" Hook into the test runner """ import subprocess from django.test.simple import DjangoTestSuiteRunner from django.utils import unittest from ixdjango.test_suite.utils import (CoreUtilsTests) class TestRunner(DjangoTestSuiteRunner): """ Place where we hook into DjangoTestSuiteRunner """ def setup_test_environment(self, *args, **kwargs): """ Hook to set up the test environment """ from django.conf import settings print "Running hooks from %s" % __name__ username = settings.DATABASES['default']['USER'] print " - Ensure %s can create a test DB" % username subprocess.call(['sudo', 'su', 'postgres', '-c', "psql -c 'alter user %s with createdb;'" % username]) return super(TestRunner, self).setup_test_environment(*args, **kwargs) def suite(): """ Put together a suite of tests to run for the application """ loader = unittest.TestLoader() all_tests = unittest.TestSuite([ # # Utilities test cases # loader.loadTestsFromTestCase(CoreUtilsTests) ]) return all_tests
""" Hook into the test runner """ import subprocess try: from django.test.runner import DiscoverRunner as BaseTestRunner except ImportError: from django.test.simple import DjangoTestSuiteRunner as BaseTestRunner from django.utils import unittest from ixdjango.test_suite.utils import (CoreUtilsTests) class TestRunner(BaseTestRunner): """ Place where we hook into DjangoTestSuiteRunner """ def setup_test_environment(self, *args, **kwargs): """ Hook to set up the test environment """ from django.conf import settings print "Running hooks from %s" % __name__ username = settings.DATABASES['default']['USER'] print " - Ensure %s can create a test DB" % username subprocess.call(['sudo', 'su', 'postgres', '-c', "psql -c 'alter user %s with createdb;'" % username]) return super(TestRunner, self).setup_test_environment(*args, **kwargs) def suite(): """ Put together a suite of tests to run for the application """ loader = unittest.TestLoader() all_tests = unittest.TestSuite([ # # Utilities test cases # loader.loadTestsFromTestCase(CoreUtilsTests) ]) return all_tests
Use DiscoverRunner from Django 1.6 if available
Use DiscoverRunner from Django 1.6 if available
Python
mit
infoxchange/ixdjango
ee03f3ae0d0501568cec87d8d4d7114441c19776
conftest.py
conftest.py
collect_ignore = ["setup.py"]
import tempfile import shutil import jedi collect_ignore = ["setup.py"] # The following hooks (pytest_configure, pytest_unconfigure) are used # to modify `jedi.settings.cache_directory` because `clean_jedi_cache` # has no effect during doctests. Without these hooks, doctests uses # user's cache (e.g., ~/.cache/jedi/). We should remove this # workaround once the problem is fixed in py.test. # # See: # - https://github.com/davidhalter/jedi/pull/168 # - https://bitbucket.org/hpk42/pytest/issue/275/ jedi_cache_directory_orig = None jedi_cache_directory_temp = None def pytest_configure(config): global jedi_cache_directory_orig, jedi_cache_directory_temp jedi_cache_directory_orig = jedi.settings.cache_directory jedi_cache_directory_temp = tempfile.mkdtemp(prefix='jedi-test-') jedi.settings.cache_directory = jedi_cache_directory_temp def pytest_unconfigure(config): global jedi_cache_directory_orig, jedi_cache_directory_temp jedi.settings.cache_directory = jedi_cache_directory_orig shutil.rmtree(jedi_cache_directory_temp)
Use pytest_(un)configure to setup cache_directory
Use pytest_(un)configure to setup cache_directory
Python
mit
jonashaag/jedi,jonashaag/jedi,flurischt/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,mfussenegger/jedi,tjwei/jedi,dwillmer/jedi,WoLpH/jedi,flurischt/jedi,dwillmer/jedi
62ad2eb82c037350f25d3e575e59f16740365159
pies/ast.py
pies/ast.py
from __future__ import absolute_import from ast import * from .version_info import PY2 if PY2: Try = TryExcept def argument_names(node): return [isinstance(arg, Name) and arg.id or None for arg in node.args.args] def kw_only_argument_names(node): return [] def kw_only_default_count(node): return 0 else: TryFinally = () def argument_names(node): return [arg.arg for arg in node.args.args] def kw_only_argument_names(node): return [arg.arg for arg in node.args.kwonlyargs] def kw_only_default_count(node): return sum(1 for n in node.args.kw_defaults if n is not None)
from __future__ import absolute_import import sys from ast import * from .version_info import PY2 if PY2 or sys.version_info[1] <= 2: Try = TryExcept else: TryFinally = () if PY2: def argument_names(node): return [isinstance(arg, Name) and arg.id or None for arg in node.args.args] def kw_only_argument_names(node): return [] def kw_only_default_count(node): return 0 else: def argument_names(node): return [arg.arg for arg in node.args.args] def kw_only_argument_names(node): return [arg.arg for arg in node.args.kwonlyargs] def kw_only_default_count(node): return sum(1 for n in node.args.kw_defaults if n is not None)
Fix small incompatibility with Python 3.2
Fix small incompatibility with Python 3.2
Python
mit
lisongmin/pies,AbsoluteMSTR/pies,timothycrosley/pies,AbsoluteMSTR/pies,timothycrosley/pies,lisongmin/pies
99bcbd8795f3e2b1a10ac8fa81dd69d1cad7c022
yunity/api/serializers.py
yunity/api/serializers.py
def user(model): if not model.is_authenticated(): return {} return { 'id': model.id, 'display_name': model.display_name, 'first_name': model.first_name, 'last_name': model.last_name, } def category(model): return { 'id': model.id, 'name': model.name, 'parent': model.parent_id, } def conversation(model): participants = [_['id'] for _ in model.participants.order_by('id').values('id')] newest_message = model.messages.order_by('-created_at').first() return { 'id': model.id, 'name': model.name, 'participants': participants, 'message': conversation_message(newest_message), } def conversation_message(model): return { 'id': model.id, 'sender': model.sent_by_id, 'created_at': model.created_at.isoformat(), 'content': model.content, }
def user(model): if not model.is_authenticated(): return {} return { 'id': model.id, 'display_name': model.display_name, 'first_name': model.first_name, 'last_name': model.last_name, } def category(model): return { 'id': model.id, 'name': model.name, 'parent': model.parent_id, } def conversation(model): participants = [_['id'] for _ in model.participants.order_by('id').values('id')] newest_message = model.messages.order_by('-created_at').first() return { 'id': model.id, 'name': model.name, 'participants': participants, 'message': conversation_message(newest_message), } def conversation_message(model): if model: return { 'id': model.id, 'sender': model.sent_by_id, 'created_at': model.created_at.isoformat(), 'content': model.content, } else: return None
Allow empty conversations to be serialized
Allow empty conversations to be serialized A conversation may exist without any content. The serializer then returns an empty message value.
Python
agpl-3.0
yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend,yunity/yunity-core
d6f2b132844d1923932447c0ce67c581f723f433
wagtail/wagtailadmin/menu.py
wagtail/wagtailadmin/menu.py
from __future__ import unicode_literals from six import text_type from django.utils.text import slugify from django.utils.html import format_html class MenuItem(object): def __init__(self, label, url, name=None, classnames='', order=1000): self.label = label self.url = url self.classnames = classnames self.name = (name or slugify(text_type(label))) self.order = order def render_html(self): return format_html( """<li class="menu-{0}"><a href="{1}" class="{2}">{3}</a></li>""", self.name, self.url, self.classnames, self.label)
from __future__ import unicode_literals from six import text_type try: # renamed util -> utils in Django 1.7; try the new name first from django.forms.utils import flatatt except ImportError: from django.forms.util import flatatt from django.utils.text import slugify from django.utils.html import format_html class MenuItem(object): def __init__(self, label, url, name=None, classnames='', attrs=None, order=1000): self.label = label self.url = url self.classnames = classnames self.name = (name or slugify(text_type(label))) self.order = order if attrs: self.attr_string = flatatt(attrs) else: self.attr_string = "" def render_html(self): return format_html( """<li class="menu-{0}"><a href="{1}" class="{2}"{3}>{4}</a></li>""", self.name, self.url, self.classnames, self.attr_string, self.label)
Support passing html attributes into MenuItem
Support passing html attributes into MenuItem
Python
bsd-3-clause
JoshBarr/wagtail,m-sanders/wagtail,hamsterbacke23/wagtail,benemery/wagtail,jordij/wagtail,nutztherookie/wagtail,mixxorz/wagtail,nutztherookie/wagtail,dresiu/wagtail,serzans/wagtail,mixxorz/wagtail,bjesus/wagtail,nrsimha/wagtail,nilnvoid/wagtail,inonit/wagtail,torchbox/wagtail,wagtail/wagtail,dresiu/wagtail,davecranwell/wagtail,timorieber/wagtail,kurtrwall/wagtail,Pennebaker/wagtail,kaedroho/wagtail,kurtrwall/wagtail,thenewguy/wagtail,jnns/wagtail,nealtodd/wagtail,rsalmaso/wagtail,taedori81/wagtail,mephizzle/wagtail,stevenewey/wagtail,quru/wagtail,marctc/wagtail,tangentlabs/wagtail,Klaudit/wagtail,quru/wagtail,gogobook/wagtail,kurtrwall/wagtail,takeshineshiro/wagtail,rsalmaso/wagtail,quru/wagtail,wagtail/wagtail,thenewguy/wagtail,benjaoming/wagtail,mixxorz/wagtail,taedori81/wagtail,nrsimha/wagtail,taedori81/wagtail,nilnvoid/wagtail,zerolab/wagtail,mephizzle/wagtail,rjsproxy/wagtail,darith27/wagtail,benjaoming/wagtail,iho/wagtail,jnns/wagtail,rv816/wagtail,nealtodd/wagtail,torchbox/wagtail,serzans/wagtail,mephizzle/wagtail,WQuanfeng/wagtail,takeflight/wagtail,mjec/wagtail,thenewguy/wagtail,torchbox/wagtail,rjsproxy/wagtail,jorge-marques/wagtail,m-sanders/wagtail,iho/wagtail,benemery/wagtail,serzans/wagtail,stevenewey/wagtail,janusnic/wagtail,JoshBarr/wagtail,chimeno/wagtail,Tivix/wagtail,chimeno/wagtail,nilnvoid/wagtail,Klaudit/wagtail,chrxr/wagtail,marctc/wagtail,KimGlazebrook/wagtail-experiment,gogobook/wagtail,zerolab/wagtail,dresiu/wagtail,takeflight/wagtail,nimasmi/wagtail,nimasmi/wagtail,JoshBarr/wagtail,Pennebaker/wagtail,hanpama/wagtail,davecranwell/wagtail,iansprice/wagtail,kaedroho/wagtail,inonit/wagtail,mixxorz/wagtail,rv816/wagtail,KimGlazebrook/wagtail-experiment,stevenewey/wagtail,inonit/wagtail,jordij/wagtail,kurtw/wagtail,bjesus/wagtail,mephizzle/wagtail,jorge-marques/wagtail,torchbox/wagtail,nilnvoid/wagtail,chimeno/wagtail,gasman/wagtail,mjec/wagtail,dresiu/wagtail,hanpama/wagtail,hamsterbacke23/wagtail,rv816/wagtail,KimGlazebrook/wagtail-experiment,tangentlabs/wagtail,mayapurmedia/wagtail,willcodefortea/wagtail,FlipperPA/wagtail,FlipperPA/wagtail,gogobook/wagtail,timorieber/wagtail,jnns/wagtail,m-sanders/wagtail,nutztherookie/wagtail,nimasmi/wagtail,hamsterbacke23/wagtail,mjec/wagtail,thenewguy/wagtail,wagtail/wagtail,kaedroho/wagtail,willcodefortea/wagtail,willcodefortea/wagtail,bjesus/wagtail,gasman/wagtail,chrxr/wagtail,gogobook/wagtail,zerolab/wagtail,rjsproxy/wagtail,wagtail/wagtail,nrsimha/wagtail,Klaudit/wagtail,iho/wagtail,mjec/wagtail,chrxr/wagtail,timorieber/wagtail,FlipperPA/wagtail,benemery/wagtail,mikedingjan/wagtail,mikedingjan/wagtail,gasman/wagtail,janusnic/wagtail,Toshakins/wagtail,WQuanfeng/wagtail,rv816/wagtail,takeflight/wagtail,WQuanfeng/wagtail,janusnic/wagtail,rjsproxy/wagtail,nutztherookie/wagtail,janusnic/wagtail,iansprice/wagtail,JoshBarr/wagtail,jnns/wagtail,takeshineshiro/wagtail,kaedroho/wagtail,willcodefortea/wagtail,taedori81/wagtail,bjesus/wagtail,jorge-marques/wagtail,Tivix/wagtail,darith27/wagtail,marctc/wagtail,mayapurmedia/wagtail,gasman/wagtail,mayapurmedia/wagtail,tangentlabs/wagtail,dresiu/wagtail,iansprice/wagtail,kaedroho/wagtail,kurtw/wagtail,inonit/wagtail,benjaoming/wagtail,Tivix/wagtail,zerolab/wagtail,stevenewey/wagtail,mayapurmedia/wagtail,davecranwell/wagtail,jorge-marques/wagtail,darith27/wagtail,chimeno/wagtail,Toshakins/wagtail,rsalmaso/wagtail,nrsimha/wagtail,gasman/wagtail,Tivix/wagtail,nealtodd/wagtail,Pennebaker/wagtail,rsalmaso/wagtail,jordij/wagtail,jorge-marques/wagtail,benemery/wagtail,iho/wagtail,hamsterbacke23/wagtail,FlipperPA/wagtail,hanpama/wagtail,takeshineshiro/wagtail,kurtw/wagtail,nimasmi/wagtail,iansprice/wagtail,kurtrwall/wagtail,nealtodd/wagtail,davecranwell/wagtail,rsalmaso/wagtail,timorieber/wagtail,Pennebaker/wagtail,Klaudit/wagtail,serzans/wagtail,m-sanders/wagtail,marctc/wagtail,taedori81/wagtail,darith27/wagtail,thenewguy/wagtail,chimeno/wagtail,zerolab/wagtail,takeflight/wagtail,chrxr/wagtail,mikedingjan/wagtail,Toshakins/wagtail,mikedingjan/wagtail,KimGlazebrook/wagtail-experiment,quru/wagtail,Toshakins/wagtail,tangentlabs/wagtail,WQuanfeng/wagtail,kurtw/wagtail,mixxorz/wagtail,hanpama/wagtail,takeshineshiro/wagtail,benjaoming/wagtail,jordij/wagtail,wagtail/wagtail
a056c630a197a070e55cce9f76124d56ba781e52
app/views/main.py
app/views/main.py
from flask import Blueprint, render_template from flask_login import login_required main = Blueprint("main", __name__) @main.route("/") @main.route("/index") @login_required def index(): return "Logged in" @main.route("/login") def login(): return render_template("login.html")
from flask import Blueprint, render_template, g, redirect, url_for from flask_login import login_required, current_user, logout_user main = Blueprint("main", __name__) @main.route("/") @main.route("/index") @login_required def index(): return "Logged in" @main.route("/login") def login(): if g.user.is_authenticated: return redirect(url_for("main.index")) return render_template("login.html") @main.route("/logout") def logout(): logout_user() return redirect(url_for("main.login")) @main.before_request def before_request(): g.user = current_user
Add logout and auth checks
Add logout and auth checks
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
9c07f8fdb9c955f49cf6ff92a25b1c0629157811
assembler6502.py
assembler6502.py
#! /usr/bin/env python import sys import assembler6502_tokenizer as tokenizer import assembler6502_parser as parser def output_byte(hexcode): sys.stdout.write(hexcode) #sys.stdout.write(chr(int(hexcode, 16))) def main(): code = """ ; sample code beginning: sty $44,X """ for line in code.split("\n"): hexcodes = parser.parse_line(line) for hexcode in hexcodes: output_byte(hexcode) print if __name__ == "__main__": main()
#! /usr/bin/env python import sys import assembler6502_tokenizer as tokenizer import assembler6502_parser as parser def output_byte(hexcode): sys.stdout.write(hexcode + "\n") #sys.stdout.write(chr(int(hexcode, 16))) def main(): code = sys.stdin.read() for line in code.split("\n"): hexcodes = parser.parse_line(line) for hexcode in hexcodes: output_byte(hexcode) if __name__ == "__main__": main()
Use stdin for assembler input
Use stdin for assembler input
Python
mit
technetia/project-tdm,technetia/project-tdm,technetia/project-tdm
391ff28186e40bee9ba7966b739090d67d61b2a6
APITaxi/models/security.py
APITaxi/models/security.py
# -*- coding: utf8 -*- from flask.ext.security import UserMixin, RoleMixin from ..models import db roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) apikey = db.Column(db.String(36), nullable=False) def get_user_from_api_key(self, apikey): user = self.user_model.query.filter_by(apikey=apikey) return user.get() or None
# -*- coding: utf8 -*- from flask.ext.security import UserMixin, RoleMixin from ..models import db from uuid import uuid4 roles_users = db.Table('roles_users', db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) class Role(db.Model, RoleMixin): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) roles = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic')) apikey = db.Column(db.String(36), nullable=False) def __init__(self, *args, **kwargs): kwargs['apikey'] = str(uuid4()) super(self.__class__, self).__init__(**kwargs) def get_user_from_api_key(self, apikey): user = self.user_model.query.filter_by(apikey=apikey) return user.get() or None
Add apikey when creating a user
Add apikey when creating a user
Python
agpl-3.0
odtvince/APITaxi,l-vincent-l/APITaxi,l-vincent-l/APITaxi,openmaraude/APITaxi,odtvince/APITaxi,odtvince/APITaxi,odtvince/APITaxi,openmaraude/APITaxi
8090fa9c072656497ff383e9b76d49af2955e420
examples/hopv/hopv_graph_conv.py
examples/hopv/hopv_graph_conv.py
""" Script that trains graph-conv models on HOPV dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from models import GraphConvTensorGraph np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from deepchem.molnet import load_hopv # Load HOPV dataset hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = hopv_datasets # Fit models metric = [ dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"), dc.metrics.Metric( dc.metrics.mean_absolute_error, np.mean, mode="regression") ] # Number of features on conv-mols n_feat = 75 # Batch size of models batch_size = 50 model = GraphConvTensorGraph( len(hopv_tasks), batch_size=batch_size, mode='regression') # Fit trained model model.fit(train_dataset, nb_epoch=25) print("Evaluating model") train_scores = model.evaluate(train_dataset, metric, transformers) valid_scores = model.evaluate(valid_dataset, metric, transformers) print("Train scores") print(train_scores) print("Validation scores") print(valid_scores)
""" Script that trains graph-conv models on HOPV dataset. """ from __future__ import print_function from __future__ import division from __future__ import unicode_literals import numpy as np from models import GraphConvModel np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from deepchem.molnet import load_hopv # Load HOPV dataset hopv_tasks, hopv_datasets, transformers = load_hopv(featurizer='GraphConv') train_dataset, valid_dataset, test_dataset = hopv_datasets # Fit models metric = [ dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean, mode="regression"), dc.metrics.Metric( dc.metrics.mean_absolute_error, np.mean, mode="regression") ] # Number of features on conv-mols n_feat = 75 # Batch size of models batch_size = 50 model = GraphConvModel( len(hopv_tasks), batch_size=batch_size, mode='regression') # Fit trained model model.fit(train_dataset, nb_epoch=25) print("Evaluating model") train_scores = model.evaluate(train_dataset, metric, transformers) valid_scores = model.evaluate(valid_dataset, metric, transformers) print("Train scores") print(train_scores) print("Validation scores") print(valid_scores)
Fix GraphConvTensorGraph to GraphConvModel in hopv example
Fix GraphConvTensorGraph to GraphConvModel in hopv example
Python
mit
Agent007/deepchem,lilleswing/deepchem,lilleswing/deepchem,Agent007/deepchem,peastman/deepchem,miaecle/deepchem,peastman/deepchem,ktaneishi/deepchem,miaecle/deepchem,Agent007/deepchem,deepchem/deepchem,ktaneishi/deepchem,deepchem/deepchem,ktaneishi/deepchem,miaecle/deepchem,lilleswing/deepchem
66f06164a5654f2925fb16a1ce28638fd57e3a9e
issue_tracker/accounts/urls.py
issue_tracker/accounts/urls.py
from django.conf.urls.defaults import * from django.contrib.auth.views import logout_then_login, login from django.contrib.auth.forms import AuthenticationForm urlpatterns = patterns('', (r'^login/$', login, {}, 'login' ), (r'^logout/$', logout_then_login, {}, 'logout'), )
from django.conf.urls.defaults import * from django.contrib.auth.views import logout_then_login, login from accounts.views import register from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import AuthenticationForm urlpatterns = patterns('', (r'^register/$', register, {}, 'register' ), (r'^login/$', login, {}, 'login' ), (r'^logout/$', logout_then_login, {}, 'logout'), )
Add url mapping to register.
Add url mapping to register.
Python
mit
hfrequency/django-issue-tracker
fb1422c22e570da21279edee0ea79605e74f7a92
crispy/__init__.py
crispy/__init__.py
import logging logging.basicConfig(level=logging.WARNING)
import logging # These are required to activate the cx_Freeze hooks import matplotlib import matplotlib.backends.backend_qt5agg import PyQt5.QtPrintSupport logging.basicConfig(level=logging.WARNING)
Add imports imports to trigger cx_Freeze hooks
Add imports imports to trigger cx_Freeze hooks
Python
mit
mretegan/crispy,mretegan/crispy
d6a03fad6c9280981ae3beee24de89bd6361bcc9
dumbrepl.py
dumbrepl.py
if __name__ == "__main__": import pycket.test.testhelper as th th.dumb_repl()
if __name__ == "__main__": import pycket.values import pycket.config from pycket.env import w_global_config #w_global_config.set_linklet_mode_off() import pycket.test.testhelper as th th.dumb_repl()
Make sure things are loaded right.
Make sure things are loaded right.
Python
mit
samth/pycket,pycket/pycket,pycket/pycket,samth/pycket,samth/pycket,pycket/pycket
bd69ad0bf57876cef01cc8f7cdce49a301eb2444
bin/remotePush.py
bin/remotePush.py
import json,httplib config_data = json.load(open('conf/net/ext_service/parse.json')) silent_push_msg = { "where": { "deviceType": "ios" }, "data": { # "alert": "The Mets scored! The game is now tied 1-1.", "content-available": 1, "sound": "", } } parse_headers = { "X-Parse-Application-Id": config_data["emission_id"], "X-Parse-REST-API-Key": config_data["emission_key"], "Content-Type": "application/json" } connection = httplib.HTTPSConnection('api.parse.com', 443) connection.connect() connection.request('POST', '/1/push', json.dumps(silent_push_msg), parse_headers) result = json.loads(connection.getresponse().read()) print result
import json,httplib import sys config_data = json.load(open('conf/net/ext_service/parse.json')) interval = sys.argv[1] print "pushing for interval %s" % interval silent_push_msg = { "where": { "deviceType": "ios" }, "channels": [ interval ], "data": { # "alert": "The Mets scored! The game is now tied 1-1.", "content-available": 1, "sound": "", } } parse_headers = { "X-Parse-Application-Id": config_data["emission_id"], "X-Parse-REST-API-Key": config_data["emission_key"], "Content-Type": "application/json" } connection = httplib.HTTPSConnection('api.parse.com', 443) connection.connect() connection.request('POST', '/1/push', json.dumps(silent_push_msg), parse_headers) result = json.loads(connection.getresponse().read()) print result
Make the remote push script take in the interval as an argument
Make the remote push script take in the interval as an argument We will use the interval as the channel
Python
bsd-3-clause
shankari/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,yw374cornell/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server
3794fe611e5fbbe55506a7d2e59b2f3f872d8733
backend/controllers/file_controller.py
backend/controllers/file_controller.py
import os from werkzeug.utils import secure_filename import config from flask_restful import Resource from flask import request, abort def allowed_file(filename): return ('.' in filename and filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS) class File(Resource): def post(self): if 'uploaded_data' not in request.files: abort(500) file = request.files['uploaded_data'] if file.filename == '': abort(500) if allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File uploaded successfully'} def delete(self): filename = request.args.get('filename') os.remove(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File deleted successfully'}
import os from werkzeug.utils import secure_filename import config from flask_restful import Resource from flask import request, abort def allowed_file(filename): return ('.' in filename and filename.rsplit('.', 1)[1].lower() in config.ALLOWED_EXTENSIONS) class File(Resource): def post(self): if 'uploaded_data' not in request.files: abort(400, 'Uploaded_data is required for the request') file = request.files['uploaded_data'] if file.filename == '': abort(400, 'Filename cannot be empty') if allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File uploaded successfully'} else: abort(415, 'File type is not supported') def delete(self): filename = secure_filename(request.args.get('filename')) os.remove(os.path.join(config.UPLOAD_FOLDER, filename)) return {'response': 'File deleted successfully'}
Change status codes and messages
Change status codes and messages
Python
apache-2.0
googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer,googleinterns/inventory-visualizer
123875153e81253a44d0e8b2d8de5abee195362a
backend/shmitter/tweets/serializers.py
backend/shmitter/tweets/serializers.py
from rest_framework import serializers from shmitter.likes import services as likes_services from .models import Tweet from . import services as tweets_services class TweetSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') is_fan = serializers.SerializerMethodField() is_retweeted = serializers.SerializerMethodField() class Meta: model = Tweet fields = ( 'id', 'owner', 'body', 'is_fan', 'is_retweeted', 'total_likes', 'created', ) def get_is_fan(self, obj) -> bool: """ Check if a `request.user` has liked this tweet (`obj`). """ user = self.context.get('request').user return likes_services.is_fan(obj, user) def get_is_retweeted(self, obj) -> bool: """ Check if a `request.user` has retweeted this tweet (`obj`). """ user = self.context.get('request').user return tweets_services.is_retweeted(obj, user)
from rest_framework import serializers from shmitter.likes import services as likes_services from .models import Tweet from . import services as tweets_services class TweetSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') is_fan = serializers.SerializerMethodField() is_retweeted = serializers.SerializerMethodField() class Meta: model = Tweet fields = ( 'id', 'owner', 'body', 'is_fan', 'is_retweeted', 'total_likes', 'total_retweets', 'created', ) def get_is_fan(self, obj) -> bool: """ Check if a `request.user` has liked this tweet (`obj`). """ user = self.context.get('request').user return likes_services.is_fan(obj, user) def get_is_retweeted(self, obj) -> bool: """ Check if a `request.user` has retweeted this tweet (`obj`). """ user = self.context.get('request').user return tweets_services.is_retweeted(obj, user)
Add total retweets to the serializer
Add total retweets to the serializer
Python
mit
apirobot/shmitter,apirobot/shmitter,apirobot/shmitter
28a4f4ab9d6b7c3ea14d48c002273acfe05d7246
bumblebee/util.py
bumblebee/util.py
import shlex import exceptions import subprocess def bytefmt(num): for unit in [ "", "Ki", "Mi", "Gi" ]: if num < 1024.0: return "{:.2f}{}B".format(num, unit) num /= 1024.0 return "{:05.2f%}{}GiB".format(num) def durationfmt(duration): minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) res = "{:02d}:{:02d}".format(minutes, seconds) if hours > 0: res = "{:02d}:{}".format(hours, res) return res def execute(cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate() if p.returncode != 0: raise exceptions.RuntimeError("{} exited with {}".format(cmd, p.returncode))
import shlex import subprocess try: from exceptions import RuntimeError except ImportError: # Python3 doesn't require this anymore pass def bytefmt(num): for unit in [ "", "Ki", "Mi", "Gi" ]: if num < 1024.0: return "{:.2f}{}B".format(num, unit) num /= 1024.0 return "{:05.2f%}{}GiB".format(num) def durationfmt(duration): minutes, seconds = divmod(duration, 60) hours, minutes = divmod(minutes, 60) res = "{:02d}:{:02d}".format(minutes, seconds) if hours > 0: res = "{:02d}:{}".format(hours, res) return res def execute(cmd): args = shlex.split(cmd) p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = p.communicate() if p.returncode != 0: raise RuntimeError("{} exited with {}".format(cmd, p.returncode))
Fix import error for Python3
[core] Fix import error for Python3 Import exceptions module only for Python2. fixes #22
Python
mit
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
81b7089633b9d43b05566a1e23f93fb59678fe1e
plugins/unicode_plugin.py
plugins/unicode_plugin.py
import string import textwrap import binascii from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class DecodeHexPlugin(BasePlugin): short_description = 'Decode hex string to encodings:' default = True description = textwrap.dedent(''' This plugin tries to decode the given hexstring with some common encodings, then print it '''.strip()) def sentinel(self): return all(not len(x) % 2 for x in self.args['STRING']) def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) binary = binascii.unhexlify(s) result += self._decode('UTF8', 'utf8', binary) result += self._decode('iso-8859-1 (Cyrillic)', 'iso-8859-1', binary) return result @staticmethod def _decode(name, encoding, binary): try: s = binary.decode(encoding) except UnicodeDecodeError: s = '<invalid>' return '{0}: "{1}"\n'.format(name, s)
import string import textwrap import binascii import unicodedata from veryprettytable import VeryPrettyTable from plugins import BasePlugin __author__ = 'peter' class DecodeHexPlugin(BasePlugin): short_description = 'Decode hex string to encodings:' default = True description = textwrap.dedent(''' This plugin tries to decode the given hexstring with some common encodings, then print it. It tries to remove control characters from the string after decoding to prevent terminal breakage. '''.strip()) def sentinel(self): return all(not len(x) % 2 for x in self.args['STRING']) def handle(self): result = '' for s in self.args['STRING']: if len(self.args['STRING']) > 1: result += '{0}:\n'.format(s) binary = binascii.unhexlify(s) result += self._decode('UTF8', 'utf8', binary) result += self._decode('iso-8859-1 (Cyrillic)', 'iso-8859-1', binary) return result def _decode(self, name, encoding, binary): try: s = self._clean(binary.decode(encoding)) except UnicodeDecodeError: s = '<invalid>' return '{0}: "{1}"\n'.format(name, s) @staticmethod def _clean(s): return "".join(ch for ch in s if unicodedata.category(ch)[0] != "C")
Remove control characters from printed string to prevent terminal breakage
Remove control characters from printed string to prevent terminal breakage
Python
mit
Sakartu/stringinfo
c0596310d9281fc07d4db6e6fd2ed8433335edb9
examples/build_examples.py
examples/build_examples.py
#!/usr/bin/env python import glob import os import platform import subprocess import sys cx_path = sys.argv[1] if len(sys.argv) > 1 else "cx" os.chdir(os.path.dirname(__file__)) for file in glob.glob("*.cx"): if platform.system() == "Windows" and file == "tree.cx": continue extension = ".out" if platform.system() != "Windows" else ".exe" output = os.path.splitext(file)[0] + extension exit_status = subprocess.call([cx_path, file, "-o", output]) if exit_status != 0: sys.exit(1) print("All examples built successfully.")
#!/usr/bin/env python import glob import os import platform import subprocess import sys cx_path = sys.argv[1] if len(sys.argv) > 1 else "cx" os.chdir(os.path.dirname(__file__)) for file in glob.glob("*.cx"): if platform.system() == "Windows" and file == "tree.cx": continue extension = ".out" if platform.system() != "Windows" else ".exe" output = os.path.splitext(file)[0] + extension exit_status = subprocess.call([cx_path, file, "-o", output, "-Werror"]) if exit_status != 0: sys.exit(1) print("All examples built successfully.")
Use -Werror for code examples
Use -Werror for code examples
Python
mit
delta-lang/delta,delta-lang/delta,delta-lang/delta,delta-lang/delta
19326b0b96e053c4b4fab402a379a03c39fbe46d
apps/homepage/templatetags/homepage_tags.py
apps/homepage/templatetags/homepage_tags.py
from django import template from homepage.models import Tab register = template.Library() @register.tag(name="get_tabs") def get_tabs(parser, token): return GetElementNode() class GetElementNode(template.Node): def __init__(self): pass def render(self, context): context['tabs'] = Tab.objects.all() return ''
from django import template from homepage.models import Tab register = template.Library() @register.tag(name="get_tabs") def get_tabs(parser, token): return GetElementNode() class GetElementNode(template.Node): def __init__(self): pass def render(self, context): context['tabs'] = Tab.objects.all().select_related('grid') return ''
Reduce queries on all pages by using select_related in the get_tabs template tag.
Reduce queries on all pages by using select_related in the get_tabs template tag.
Python
mit
cartwheelweb/packaginator,nanuxbe/djangopackages,miketheman/opencomparison,audreyr/opencomparison,audreyr/opencomparison,cartwheelweb/packaginator,QLGu/djangopackages,pydanny/djangopackages,cartwheelweb/packaginator,benracine/opencomparison,nanuxbe/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,miketheman/opencomparison,benracine/opencomparison,QLGu/djangopackages
5aff8defb8baf83176ea861b03de04a9d6ac8a31
bundles/views.py
bundles/views.py
from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer permission_classes = [permissions.IsAuthenticated] def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
from django.views.generic import DetailView, ListView from rest_framework import filters, generics, permissions from rest_framework.response import Response from . import models, serializers class BundleList(ListView): model = models.Bundle context_object_name = 'bundles' paginate_by = 25 class BundleDetail(DetailView): model = models.Bundle context_object_name = 'bundle' class BundleView(generics.RetrieveAPIView): serializer_class = serializers.BundleSerializer def get(self, request, slug): try: bundle = models.Bundle.objects.get(slug=slug) except models.Bundle.DoesNotExist: return Response(status=404) serializer = serializers.BundleSerializer(bundle) return Response(serializer.data)
Make bundle view accessible to anyone
Make bundle view accessible to anyone
Python
agpl-3.0
lutris/website,lutris/website,lutris/website,lutris/website
b3391187cb87ae33d4b8dd6e55f5edfdb695ea53
mapbox_vector_tile/__init__.py
mapbox_vector_tile/__init__.py
from . import encoder from . import decoder def decode(tile, y_coord_down=False): vector_tile = decoder.TileData() message = vector_tile.getMessage(tile, y_coord_down) return message def encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096, on_invalid_geometry=None, round_fn=None, check_winding_order=True): vector_tile = encoder.VectorTile(extents, on_invalid_geometry, round_fn=round_fn, check_winding_order=check_winding_order) if (isinstance(layers, list)): for layer in layers: vector_tile.addFeatures(layer['features'], layer['name'], quantize_bounds, y_coord_down) else: vector_tile.addFeatures(layers['features'], layers['name'], quantize_bounds, y_coord_down) return vector_tile.tile.SerializeToString()
from . import encoder from . import decoder # Enable Shapely "speedups" if available # http://toblerity.org/shapely/manual.html#performance from shapely import speedups if speedups.available: speedups.enable() def decode(tile, y_coord_down=False): vector_tile = decoder.TileData() message = vector_tile.getMessage(tile, y_coord_down) return message def encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096, on_invalid_geometry=None, round_fn=None, check_winding_order=True): vector_tile = encoder.VectorTile(extents, on_invalid_geometry, round_fn=round_fn, check_winding_order=check_winding_order) if (isinstance(layers, list)): for layer in layers: vector_tile.addFeatures(layer['features'], layer['name'], quantize_bounds, y_coord_down) else: vector_tile.addFeatures(layers['features'], layers['name'], quantize_bounds, y_coord_down) return vector_tile.tile.SerializeToString()
Enable Shapely speedups when available.
Enable Shapely speedups when available. http://toblerity.org/shapely/manual.html#performance
Python
mit
mapzen/mapbox-vector-tile
e53e214b97a9a4c7ad2dbca88b01798dcc614b6a
auth0/v2/authentication/social.py
auth0/v2/authentication/social.py
from .base import AuthenticationBase class Social(AuthenticationBase): def __init__(self, domain): self.domain = domain def login(self, client_id, access_token, connection): """Login using a social provider's access token Given the social provider's access_token and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token. Currently, this endpoint only works for Facebook, Google, Twitter and Weibo. Args: client_id (str): client name. access_token (str): social provider's access_token. connection (str): connection type (e.g: 'facebook') Returns: A dict with 'access_token' and 'id_token' keys. """ return self.post( 'https://%s/oauth/access_token' % self.domain, data={ 'client_id': client_id, 'access_token': access_token, 'connection': connection, 'scope': 'openid', }, headers={'Content-Type': 'application/json'} )
from .base import AuthenticationBase class Social(AuthenticationBase): """Social provider's endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def login(self, client_id, access_token, connection): """Login using a social provider's access token Given the social provider's access_token and the connection specified, it will do the authentication on the provider and return a dict with the access_token and id_token. Currently, this endpoint only works for Facebook, Google, Twitter and Weibo. Args: client_id (str): client name. access_token (str): social provider's access_token. connection (str): connection type (e.g: 'facebook') Returns: A dict with 'access_token' and 'id_token' keys. """ return self.post( 'https://%s/oauth/access_token' % self.domain, data={ 'client_id': client_id, 'access_token': access_token, 'connection': connection, 'scope': 'openid', }, headers={'Content-Type': 'application/json'} )
Add class docstring to Social
Add class docstring to Social
Python
mit
auth0/auth0-python,auth0/auth0-python
1608134ea633c0fe8cd4636b11dc5a931d02e024
intercom.py
intercom.py
import configparser import time import RPIO as GPIO from client import MumbleClient class InterCom: def __init__(self): config = configparser.ConfigParser() config.read('intercom.ini') self.mumble_client = MumbleClient(config['mumbleclient']) self.exit = False self.send_input = False if config['general']['gpiotype'] == 'BCM': GPIO.setmode(GPIO.BCM) self.button = int(config['general']['button']) GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def run(self): while not self.exit: if GPIO.input(self.button): self.mumble_client.send_input_audio() if __name__ == '__main__': InterCom().run()
import configparser import time import RPi.GPIO as GPIO from client import MumbleClient class InterCom: def __init__(self): config = configparser.ConfigParser() config.read('intercom.ini') self.mumble_client = MumbleClient(config['mumbleclient']) self.exit = False self.send_input = False if config['general']['gpiotype'] == 'BCM': GPIO.setmode(GPIO.BCM) self.button = int(config['general']['button']) GPIO.setup(self.button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) def run(self): while not self.exit: if GPIO.input(self.button): self.mumble_client.send_input_audio() if __name__ == '__main__': try: InterCom().run() except Exception as e: raise e finally: GPIO.cleanup()
Change to rpio and add clean
Change to rpio and add clean
Python
mit
pkronstrom/intercom
05e568571c2f6891ed7be6198b8cf5e4e540d674
dev_tools/run_tests.py
dev_tools/run_tests.py
#!/usr/bin/env python3 """Run tests under a consistent environment... Whether run from the terminal, in CI or from the editor this file makes sure the tests are run in a consistent environment. """ #------------------------------------------------------------------------------ # Py2C - A Python to C++ compiler # Copyright (C) 2014 Pradyun S. Gedam #------------------------------------------------------------------------------ import sys from os.path import join, realpath, dirname # Local modules import cleanup cleanup.REMOVE_GENERATED_AST = False cleanup.PRINT_OUTPUT = False cleanup.main() # Third Party modules import nose import coverage base_dir = realpath(dirname(__file__)) root_dir = join(dirname(base_dir), "py2c") REPORT = True if "--dont-report" in sys.argv: sys.argv.remove("--dont-report") REPORT = False cov = coverage.coverage(config_file=join(base_dir, ".coveragerc")) cov.start() success = nose.run( env={ "NOSE_INCLUDE_EXE": "True", "NOSE_WITH_HTML_REPORT": "True", "NOSE_WITH_SPECPLUGIN": "True" }, defaultTest=root_dir, ) cov.stop() cov.save() if success and REPORT: cov.html_report() cov.report() sys.exit(0 if success else 1)
#!/usr/bin/env python3 """Run tests under a consistent environment... Whether run from the terminal, in CI or from the editor this file makes sure the tests are run in a consistent environment. """ #------------------------------------------------------------------------------ # Py2C - A Python to C++ compiler # Copyright (C) 2014 Pradyun S. Gedam #------------------------------------------------------------------------------ # Local modules import cleanup # Standard library import sys from os.path import join, realpath, dirname # Third Party modules import nose import coverage cleanup.REMOVE_GENERATED_AST = False cleanup.main() base_dir = realpath(dirname(__file__)) root_dir = join(dirname(base_dir), "py2c") REPORT = True if "--dont-report" in sys.argv: sys.argv.remove("--dont-report") REPORT = False cov = coverage.coverage(config_file=join(base_dir, ".coveragerc")) cov.start() success = nose.run( env={ "NOSE_INCLUDE_EXE": "True", "NOSE_WITH_HTML_REPORT": "True", "NOSE_WITH_SPECPLUGIN": "True" }, defaultTest=root_dir, ) cov.stop() cov.save() if success and REPORT: cov.html_report() cov.report() sys.exit(0 if success else 1)
Move all imports to top-of-module, don't hide cleanup output.
[RUN_TESTS] Move all imports to top-of-module, don't hide cleanup output.
Python
bsd-3-clause
pradyunsg/Py2C,pradyunsg/Py2C
0fe30bb04e9b3d981cd1f6264485d98ca56a2fb8
events/migrations/0035_add_n_events_to_keyword.py
events/migrations/0035_add_n_events_to_keyword.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-12-02 15:46 from __future__ import unicode_literals from django.db import migrations, models def forward(apps, schema_editor): Keyword = apps.get_model('events', 'Keyword') for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None): n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count() if n_events != keyword.n_events: keyword.n_events = n_events keyword.save(update_fields=("n_events",)) class Migration(migrations.Migration): dependencies = [ ('events', '0034_add_keyword_deprecated'), ] operations = [ migrations.AddField( model_name='keyword', name='n_events', field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'), ), migrations.AlterField( model_name='event', name='audience', field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'), ), migrations.AlterField( model_name='event', name='keywords', field=models.ManyToManyField(related_name='events', to='events.Keyword'), ), migrations.RunPython(forward, migrations.RunPython.noop) ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.11 on 2016-12-02 15:46 from __future__ import unicode_literals from django.db import migrations, models def forward(apps, schema_editor): Keyword = apps.get_model('events', 'Keyword') for keyword in Keyword.objects.exclude(events=None) | Keyword.objects.exclude(audience_events=None): n_events = (keyword.events.all() | keyword.audience_events.all()).distinct().count() if n_events != keyword.n_events: print("Updating event number for " + str(keyword.name)) keyword.n_events = n_events keyword.save(update_fields=("n_events",)) class Migration(migrations.Migration): dependencies = [ ('events', '0034_add_keyword_deprecated'), ] operations = [ migrations.AddField( model_name='keyword', name='n_events', field=models.IntegerField(db_index=True, default=0, editable=False, help_text='number of events with this keyword', verbose_name='event count'), ), migrations.AlterField( model_name='event', name='audience', field=models.ManyToManyField(blank=True, related_name='audience_events', to='events.Keyword'), ), migrations.AlterField( model_name='event', name='keywords', field=models.ManyToManyField(related_name='events', to='events.Keyword'), ), migrations.RunPython(forward, migrations.RunPython.noop) ]
Add logging to keyword data migration
Add logging to keyword data migration
Python
mit
City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents
887597d31dec7fe1f49402e44691c1e745d22968
cellcounter/wsgi.py
cellcounter/wsgi.py
""" WSGI config for cellcounter project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cellcounter.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for cellcounter project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os import site from distutils.sysconfig import get_python_lib #ensure the venv is being loaded correctly site.addsitedir(get_python_lib()) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cellcounter.settings") #import the DATABASE_URL from an Apache environment variable #this allows per-vhost database configuration to be passed in import django.core.handlers.wsgi _application = django.core.handlers.wsgi.WSGIHandler() def application(environ, start_response): os.environ['DATABASE_URL'] = environ['DATABASE_URL'] return _application(environ, start_response) # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Improve WSGI file for apache deployment/database configuration management
Improve WSGI file for apache deployment/database configuration management
Python
mit
cellcounter/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,oghm2/hackdayoxford,oghm2/hackdayoxford,haematologic/cellcounter,haematologic/cellcounter,haematologic/cellcounter,cellcounter/cellcounter
25712b9c94062f41c50a8611c5b7069bde7e1c8f
ibmcnx/cnx/VersionStamp.py
ibmcnx/cnx/VersionStamp.py
###### # Set the Version Stamp to actual time and date # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # print "\nSet Version Stamp in LotusConnections-config.xml to actual Date and Time\n" path = raw_input( "Path and Folder where config is temporarily stored: " ) execfile("connectionsConfig.py") LCConfigService.checkOutConfig(path,AdminControl.getCell()) LCConfigService.updateConfig("versionStamp","") LCConfigService.checkInConfig(path,AdminControl.getCell()) synchAllNodes()
###### # Set the Version Stamp to actual time and date # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # import ibmcnx.functions print "\nSet Version Stamp in LotusConnections-config.xml to actual Date and Time\n" # Check properties if temppath is defined if ( ibmcnx.functions.tempPath() == '' ): path = raw_input( "Path and Folder where config is temporarily stored: " ) else: path = ibmcnx.functions.tempPath() execfile("connectionsConfig.py") LCConfigService.checkOutConfig(path,AdminControl.getCell()) LCConfigService.updateConfig("versionStamp","") LCConfigService.checkInConfig(path,AdminControl.getCell()) synchAllNodes()
Add option to get temppath from properties file
Add option to get temppath from properties file
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
e5656674eab83f7005c70d901187fd89027efeba
allaccess/management/commands/migrate_social_providers.py
allaccess/management/commands/migrate_social_providers.py
from __future__ import unicode_literals from django.core.management.base import NoArgsCommand, CommandError from allaccess.models import Provider class Command(NoArgsCommand): "Convert existing providers from django-social-auth to django-all-access." def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) try: from social_auth.backends import get_backends, BaseOAuth except ImportError: # pragma: no cover raise CommandError("django-social-auth is not installed.") for name, backend in get_backends(force_load=True).items(): if issubclass(backend, BaseOAuth) and backend.enabled(): # Create providers if they don't already exist key, secret = backend.get_key_and_secret() defaults = { 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''), 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''), 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''), 'profile_url': '', 'key': key or None, 'secret': secret or None, } provider, created = Provider.objects.get_or_create(name=name, defaults=defaults) if created and verbosity > 0: self.stdout.write('New provider created from "%s" backend.\n' % name)
from __future__ import unicode_literals from django.core.management.base import NoArgsCommand, CommandError from allaccess.models import Provider class Command(NoArgsCommand): "Convert existing providers from django-social-auth to django-all-access." def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) try: from social_auth.backends import get_backends, BaseOAuth except ImportError: # pragma: no cover raise CommandError("django-social-auth is not installed.") for name, backend in get_backends().items(): if issubclass(backend, BaseOAuth) and backend.enabled(): # Create providers if they don't already exist key, secret = backend.get_key_and_secret() defaults = { 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', ''), 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', ''), 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', ''), 'profile_url': '', 'key': key or None, 'secret': secret or None, } provider, created = Provider.objects.get_or_create(name=name, defaults=defaults) if created and verbosity > 0: self.stdout.write('New provider created from "%s" backend.\n' % name)
Remove force_load which was added in later versions.
Remove force_load which was added in later versions.
Python
bsd-2-clause
iXioN/django-all-access,vyscond/django-all-access,dpoirier/django-all-access,dpoirier/django-all-access,mlavin/django-all-access,iXioN/django-all-access,vyscond/django-all-access,mlavin/django-all-access
3faf3a9debc0fad175ca032f3eb0880defbd0cdb
akaudit/clidriver.py
akaudit/clidriver.py
#!/usr/bin/env python import sys import argparse from akaudit.audit import Auditer def main(argv = sys.argv, log = sys.stderr): parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-l', '--log', default='info', help='Log level') args = parser.parse_args() auditer = Auditer() auditer.run_audit(args) if __name__ == "__main__": main(sys.argv[1:])
#!/usr/bin/env python import sys import argparse from akaudit.audit import Auditer def main(argv = sys.argv, log = sys.stderr): parser = argparse.ArgumentParser(description='Audit who has access to your homes.', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-l', '--log', default='info', help='Log level') parser.add_argument('-i', '--interactive', help='Interactive mode (prompts asking if to delete each key)', action="store_true") args = parser.parse_args() auditer = Auditer() auditer.run_audit(args) if __name__ == "__main__": main(sys.argv[1:])
Add argument option for --interactive.
Add argument option for --interactive.
Python
apache-2.0
flaccid/akaudit
572a84ae4fe7ce464fe66b6462a80b09b20f8f1c
fireplace/cards/gvg/neutral_epic.py
fireplace/cards/gvg/neutral_epic.py
from ..utils import * ## # Minions # Hobgoblin class GVG_104: def OWN_CARD_PLAYED(self, card): if card.type == CardType.MINION and card.atk == 1: return [Buff(card, "GVG_104a")]
from ..utils import * ## # Minions # Hobgoblin class GVG_104: def OWN_CARD_PLAYED(self, card): if card.type == CardType.MINION and card.atk == 1: return [Buff(card, "GVG_104a")] # Piloted Sky Golem class GVG_105: def deathrattle(self): return [Summon(CONTROLLER, randomCollectible(type=CardType.MINION, cost=4))] # Junkbot class GVG_106: def OWN_MINION_DESTROY(self, minion): if minion.race == Race.MECHANICAL: return [Buff(SELF, "GVG_106e")] # Enhance-o Mechano class GVG_107: def action(self): for target in self.controller.field: tag = random.choice((GameTag.WINDFURY, GameTag.TAUNT, GameTag.DIVINE_SHIELD)) yield SetTag(target, {tag: True})
Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano
Implement Piloted Sky Golem, Junkbot and Enhance-o Mechano
Python
agpl-3.0
NightKev/fireplace,Ragowit/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace,amw2104/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,oftc-ftw/fireplace,butozerca/fireplace,Meerkov/fireplace,jleclanche/fireplace,amw2104/fireplace,butozerca/fireplace,Ragowit/fireplace,liujimj/fireplace
1d6984d31aaa87b5ed781e188b8b42221602cd3f
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- pytest_plugins = 'pytester'
# -*- coding: utf-8 -*- import os import warnings import pytest pytest_plugins = 'pytester' @pytest.fixture(scope='session', autouse=True) def verify_target_path(): import pytest_testdox current_path_root = os.path.dirname( os.path.dirname(os.path.realpath(__file__)) ) if current_path_root not in pytest_testdox.__file__: warnings.warn( 'pytest-testdox was not imported from your repository. ' 'You might be testing the wrong code ' '-- More: https://github.com/renanivo/pytest-testdox/issues/13', UserWarning )
Add warning on running repository's tests with pytest-testdox installed
Add warning on running repository's tests with pytest-testdox installed Fix #13
Python
mit
renanivo/pytest-testdox
dc1cedc1720886dcc3c3bd3da02c7aff58e5eb90
tests/runTests.py
tests/runTests.py
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"] os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
Make test runner work with blank mysql password
Make test runner work with blank mysql password
Python
mit
HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II
a69e8d0d179f12fd42eadd85eca8e0c968d67c91
tests/runTests.py
tests/runTests.py
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") os.system("mysql -u "+parser["database"]["username"]+" -p"+parser["database"]["password"]+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
import os import os.path import configparser import shutil import subprocess # Setup print("Setting up...") if os.path.isfile("../halite.ini"): shutil.copyfile("../halite.ini", "temp.ini") shutil.copyfile("tests.ini", "../halite.ini") parser = configparser.ConfigParser() parser.read("../halite.ini") # Website tests print("Beginning website backend tests") passwordField = "" if parser["database"]["password"] == "" else "-p"+parser["database"]["password"] os.system("mysql -u "+parser["database"]["username"]+" "+passwordField+" < ../website/sql/Database.sql") subprocess.call(["phpunit", "--stderr", "website/"]) # Environment tests. print(subprocess.Popen('cd environment; python3 testenv.py', stdout=subprocess.PIPE, shell = True).stdout.read().decode('utf-8')) # Tear down print("Almost done...") if os.path.isfile("../temp.ini"): shutil.copyfile("temp.ini", "../halite.ini")
Make test runner work with blank mysql password
Make test runner work with blank mysql password
Python
mit
HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,HaliteChallenge/Halite,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,yangle/HaliteIO,lanyudhy/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite,lanyudhy/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,yangle/HaliteIO,yangle/HaliteIO,yangle/HaliteIO,lanyudhy/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,yangle/HaliteIO,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite,HaliteChallenge/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite,lanyudhy/Halite-II,lanyudhy/Halite-II,HaliteChallenge/Halite-II
7172962abf0d5d5aad02c632944ed8cb33ca9bae
django/books/admin.py
django/books/admin.py
from django.contrib import admin from .models import Author, Book, Note, Tag, Section @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['name', 'goodreads_id'] prepopulated_fields = {'slug': ('name',), } @admin.register(Section) class SectionAdmin(admin.ModelAdmin): list_display = ['title', 'subtitle', 'get_page_display', 'book'] list_filter = ['book'] @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'slug'] @admin.register(Note) class NoteAdmin(admin.ModelAdmin): list_display = ['subject', 'section', 'book', 'get_page_display'] search_fields = ['subject', 'quote', 'comment'] @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ['slug', 'description', 'colour']
from django.contrib import admin from .models import Author, Book, Note, Tag, Section @admin.register(Author) class AuthorAdmin(admin.ModelAdmin): list_display = ['name', 'goodreads_id'] prepopulated_fields = {'slug': ('name',), } search_fields = ['name'] @admin.register(Section) class SectionAdmin(admin.ModelAdmin): list_display = ['title', 'subtitle', 'get_page_display', 'book'] list_filter = ['book'] @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title', 'slug'] @admin.register(Note) class NoteAdmin(admin.ModelAdmin): list_display = ['subject', 'section', 'book', 'get_page_display'] search_fields = ['subject', 'quote', 'comment'] @admin.register(Tag) class TagAdmin(admin.ModelAdmin): list_display = ['slug', 'description', 'colour']
Allow searching by name in AuthorAdmin
Allow searching by name in AuthorAdmin
Python
mit
dellsystem/bookmarker,dellsystem/bookmarker,dellsystem/bookmarker
23f404b61f2c9b89bb631ad0e60edf4416500f28
django_split/utils.py
django_split/utils.py
def overlapping(interval_a, interval_b): al, ah = interval_a bl, bh = interval_b if al > ah: raise ValueError("Interval A bounds are inverted") if bl > bh: raise ValueError("Interval B bounds are inverted") return ah >= bl and bh >= al
from __future__ import division import scipy import scipy.stats def overlapping(interval_a, interval_b): al, ah = interval_a bl, bh = interval_b if al > ah: raise ValueError("Interval A bounds are inverted") if bl > bh: raise ValueError("Interval B bounds are inverted") return ah >= bl and bh >= al def compute_normal_ppf(data_points): mean, var = scipy.mean(data_points), scipy.var(data_points) return scipy.stats.norm(mean, var).ppf def compute_binomial_rate_ppf(hits, total): if total == 0: return lambda p: 0 distribution = scipy.binom((hits / total), total) return lambda p: distribution.ppf(p) / total def compute_poisson_daily_rate_ppf(start_date, end_date, hits): days = (end_date - start_date).days return scipy.poisson(hits / days).ppf
Add utilities for computing metrics
Add utilities for computing metrics
Python
mit
prophile/django_split
dd269cea5623450c3c608d10b8ddce1ae6c9e84a
project_one/project_one.py
project_one/project_one.py
# System imports first import sys # Module (local) imports from import_data import import_data from process import process_data, normalize, rotate_data from output import plot_data def main(argv=None): """ Main function, executed when running 'project_one'. """ # Read the data data = import_data('data.txt') data = process_data(data) # data = normalize(data) # data = rotate_data(data) plot_data(data) # If we're being run with `python project_one.py`, execute main() and exit # afterwards with the return value of main(). if __name__ == "__main__": sys.exit(main())
# System imports first import sys import argparse # Module (local) imports from import_data import import_data from process import process_data, normalize, rotate_data from output import plot_data def main(argv=None): """ Main function, executed when running 'project_one'. """ # Parse command-line arguments, this allows the input to be # configured from the command line. parser = argparse.ArgumentParser( description='Import, process and plot test data.' ) parser.add_argument('data_file', type=str) args = parser.parse_args(argv) # Read the data data = import_data(args.data_file) data = process_data(data) # data = normalize(data) # data = rotate_data(data) plot_data(data) # If we're being run with `python project_one.py`, execute main() and exit # afterwards with the return value of main(). if __name__ == "__main__": sys.exit(main())
Use command-line argument to specify data.
Use command-line argument to specify data.
Python
bsd-3-clause
dokterbob/slf-project-one
2c05dba69c838cfd3808d8e03dbea3cc56d4f6d2
pyinfra_kubernetes/__init__.py
pyinfra_kubernetes/__init__.py
from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes def deploy_kubernetes_master(etcd_nodes): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') def deploy_kubernetes_node(master_address): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
from pyinfra.api import deploy from .configure import configure_kubeconfig, configure_kubernetes_component from .install import install_kubernetes @deploy('Deploy Kubernetes master') def deploy_kubernetes_master( state, host, etcd_nodes, ): # Install server components install_kubernetes(components=( 'kube-apiserver', 'kube-scheduler', 'kube-controller-manager', )) # Configure the API server, passing in our etcd nodes configure_kubernetes_component('kube-apiserver', etcd_nodes=etcd_nodes) configure_kubernetes_component('kube-scheduler') configure_kubernetes_component('kube-controller-manager') @deploy('Deploy Kubernetes node') def deploy_kubernetes_node( state, host, master_address, ): # Install node components install_kubernetes(components=( 'kubelet', 'kube-proxy', )) # Setup the kubeconfig for kubelet & kube-proxy to use configure_kubeconfig(master_address) configure_kubernetes_component('kubelet') configure_kubernetes_component('kube-proxy')
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
Make helper functions full `@deploy`s so they support global pyinfra kwargs.
Python
mit
EDITD/pyinfra-kubernetes,EDITD/pyinfra-kubernetes
de3f84934d86e48bf89822828df3eb9c3bd8e1e1
test/test_examples.py
test/test_examples.py
import glob from libmproxy import utils, script from libmproxy.proxy import config import tservers def test_load_scripts(): example_dir = utils.Data("libmproxy").path("../examples") scripts = glob.glob("%s/*.py" % example_dir) tmaster = tservers.TestMaster(config.ProxyConfig()) for f in scripts: if "har_extractor" in f: f += " -" if "iframe_injector" in f: f += " foo" # one argument required if "modify_response_body" in f: f += " foo bar" # two arguments required s = script.Script(f, tmaster) # Loads the script file. s.unload()
import glob from libmproxy import utils, script from libmproxy.proxy import config import tservers def test_load_scripts(): example_dir = utils.Data("libmproxy").path("../examples") scripts = glob.glob("%s/*.py" % example_dir) tmaster = tservers.TestMaster(config.ProxyConfig()) for f in scripts: if "har_extractor" in f: f += " -" if "iframe_injector" in f: f += " foo" # one argument required if "modify_response_body" in f: f += " foo bar" # two arguments required try: s = script.Script(f, tmaster) # Loads the script file. except Exception, v: if not "ImportError" in str(v): raise else: s.unload()
Test suite should pass even if example dependencies are not present
Test suite should pass even if example dependencies are not present
Python
mit
ryoqun/mitmproxy,ryoqun/mitmproxy,xaxa89/mitmproxy,guiquanz/mitmproxy,ccccccccccc/mitmproxy,ADemonisis/mitmproxy,jpic/mitmproxy,pombredanne/mitmproxy,noikiy/mitmproxy,xaxa89/mitmproxy,fimad/mitmproxy,onlywade/mitmproxy,dxq-git/mitmproxy,inscriptionweb/mitmproxy,sethp-jive/mitmproxy,ParthGanatra/mitmproxy,cortesi/mitmproxy,byt3bl33d3r/mitmproxy,dufferzafar/mitmproxy,mhils/mitmproxy,owers19856/mitmproxy,zlorb/mitmproxy,fimad/mitmproxy,claimsmall/mitmproxy,sethp-jive/mitmproxy,tekii/mitmproxy,xaxa89/mitmproxy,ParthGanatra/mitmproxy,0xwindows/InfoLeak,ujjwal96/mitmproxy,vhaupert/mitmproxy,rauburtin/mitmproxy,Kriechi/mitmproxy,MatthewShao/mitmproxy,zlorb/mitmproxy,ccccccccccc/mitmproxy,elitest/mitmproxy,zbuc/mitmproxy,jpic/mitmproxy,StevenVanAcker/mitmproxy,rauburtin/mitmproxy,jvillacorta/mitmproxy,tdickers/mitmproxy,macmantrl/mitmproxy,ryoqun/mitmproxy,meizhoubao/mitmproxy,mosajjal/mitmproxy,pombredanne/mitmproxy,dufferzafar/mitmproxy,owers19856/mitmproxy,onlywade/mitmproxy,mitmproxy/mitmproxy,Fuzion24/mitmproxy,mitmproxy/mitmproxy,dweinstein/mitmproxy,vhaupert/mitmproxy,MatthewShao/mitmproxy,inscriptionweb/mitmproxy,dufferzafar/mitmproxy,devasia1000/mitmproxy,liorvh/mitmproxy,syjzwjj/mitmproxy,macmantrl/mitmproxy,0xwindows/InfoLeak,noikiy/mitmproxy,dweinstein/mitmproxy,ZeYt/mitmproxy,devasia1000/mitmproxy,dxq-git/mitmproxy,StevenVanAcker/mitmproxy,mitmproxy/mitmproxy,Kriechi/mitmproxy,inscriptionweb/mitmproxy,tekii/mitmproxy,laurmurclar/mitmproxy,ryoqun/mitmproxy,Endika/mitmproxy,cortesi/mitmproxy,vhaupert/mitmproxy,ikoz/mitmproxy,zbuc/mitmproxy,scriptmediala/mitmproxy,tfeagle/mitmproxy,guiquanz/mitmproxy,zbuc/mitmproxy,dwfreed/mitmproxy,guiquanz/mitmproxy,azureplus/mitmproxy,fimad/mitmproxy,azureplus/mitmproxy,mosajjal/mitmproxy,mosajjal/mitmproxy,onlywade/mitmproxy,meizhoubao/mitmproxy,claimsmall/mitmproxy,scriptmediala/mitmproxy,noikiy/mitmproxy,xbzbing/mitmproxy,Fuzion24/mitmproxy,zlorb/mitmproxy,dxq-git/mitmproxy,ikoz/mitmproxy,Endika/mitmproxy,MatthewShao/mitmproxy,zbuc/mitmproxy,liorvh/mitmproxy,Kriechi/mitmproxy,fimad/mitmproxy,bazzinotti/mitmproxy,meizhoubao/mitmproxy,ikoz/mitmproxy,tdickers/mitmproxy,tfeagle/mitmproxy,syjzwjj/mitmproxy,gzzhanghao/mitmproxy,scriptmediala/mitmproxy,gzzhanghao/mitmproxy,bazzinotti/mitmproxy,tfeagle/mitmproxy,ddworken/mitmproxy,dweinstein/mitmproxy,mhils/mitmproxy,mitmproxy/mitmproxy,byt3bl33d3r/mitmproxy,Fuzion24/mitmproxy,Kriechi/mitmproxy,dxq-git/mitmproxy,dwfreed/mitmproxy,owers19856/mitmproxy,legendtang/mitmproxy,tdickers/mitmproxy,liorvh/mitmproxy,byt3bl33d3r/mitmproxy,macmantrl/mitmproxy,ujjwal96/mitmproxy,pombredanne/mitmproxy,mhils/mitmproxy,onlywade/mitmproxy,mosajjal/mitmproxy,ddworken/mitmproxy,ADemonisis/mitmproxy,legendtang/mitmproxy,dwfreed/mitmproxy,ccccccccccc/mitmproxy,meizhoubao/mitmproxy,ccccccccccc/mitmproxy,ADemonisis/mitmproxy,syjzwjj/mitmproxy,sethp-jive/mitmproxy,tekii/mitmproxy,Endika/mitmproxy,xbzbing/mitmproxy,byt3bl33d3r/mitmproxy,liorvh/mitmproxy,devasia1000/mitmproxy,gzzhanghao/mitmproxy,jvillacorta/mitmproxy,syjzwjj/mitmproxy,xaxa89/mitmproxy,scriptmediala/mitmproxy,sethp-jive/mitmproxy,bazzinotti/mitmproxy,legendtang/mitmproxy,dweinstein/mitmproxy,xbzbing/mitmproxy,bazzinotti/mitmproxy,0xwindows/InfoLeak,jpic/mitmproxy,ikoz/mitmproxy,mhils/mitmproxy,xbzbing/mitmproxy,gzzhanghao/mitmproxy,Fuzion24/mitmproxy,rauburtin/mitmproxy,noikiy/mitmproxy,elitest/mitmproxy,claimsmall/mitmproxy,jvillacorta/mitmproxy,ujjwal96/mitmproxy,elitest/mitmproxy,ujjwal96/mitmproxy,StevenVanAcker/mitmproxy,pombredanne/mitmproxy,tdickers/mitmproxy,jpic/mitmproxy,laurmurclar/mitmproxy,0xwindows/InfoLeak,tfeagle/mitmproxy,owers19856/mitmproxy,laurmurclar/mitmproxy,mitmproxy/mitmproxy,macmantrl/mitmproxy,tekii/mitmproxy,mhils/mitmproxy,ZeYt/mitmproxy,StevenVanAcker/mitmproxy,ParthGanatra/mitmproxy,azureplus/mitmproxy,Endika/mitmproxy,ZeYt/mitmproxy,MatthewShao/mitmproxy,ZeYt/mitmproxy,rauburtin/mitmproxy,laurmurclar/mitmproxy,ddworken/mitmproxy,claimsmall/mitmproxy,ParthGanatra/mitmproxy,vhaupert/mitmproxy,devasia1000/mitmproxy,ddworken/mitmproxy,cortesi/mitmproxy,dufferzafar/mitmproxy,ADemonisis/mitmproxy,legendtang/mitmproxy,dwfreed/mitmproxy,zlorb/mitmproxy,jvillacorta/mitmproxy,inscriptionweb/mitmproxy,azureplus/mitmproxy,cortesi/mitmproxy,elitest/mitmproxy,guiquanz/mitmproxy
c55243d591793a9213d27126a3c240bb47c5f82b
cartoframes/core/cartodataframe.py
cartoframes/core/cartodataframe.py
from geopandas import GeoDataFrame from ..utils.geom_utils import generate_index, generate_geometry class CartoDataFrame(GeoDataFrame): def __init__(self, *args, **kwargs): super(CartoDataFrame, self).__init__(*args, **kwargs) @staticmethod def from_carto(*args, **kwargs): from ..io.carto import read_carto return read_carto(*args, **kwargs) @classmethod def from_file(cls, filename, **kwargs): gdf = GeoDataFrame.from_file(filename, **kwargs) return cls(gdf) @classmethod def from_features(cls, features, **kwargs): gdf = GeoDataFrame.from_features(features, **kwargs) return cls(gdf) def to_carto(self, *args, **kwargs): from ..io.carto import to_carto return to_carto(self, *args, **kwargs) def convert(self, index_column=None, geom_column=None, lnglat_columns=None, drop_index=True, drop_geom=True, drop_lnglat=True): # Magic function generate_index(self, index_column, drop_index) generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat) return self def visualize(self, *args, **kwargs): from ..viz import Map, Layer return Map(Layer(self, *args, **kwargs)) viz = visualize
from geopandas import GeoDataFrame from ..utils.geom_utils import generate_index, generate_geometry class CartoDataFrame(GeoDataFrame): def __init__(self, *args, **kwargs): super(CartoDataFrame, self).__init__(*args, **kwargs) @staticmethod def from_carto(*args, **kwargs): from ..io.carto import read_carto return read_carto(*args, **kwargs) @classmethod def from_file(cls, filename, **kwargs): gdf = GeoDataFrame.from_file(filename, **kwargs) return cls(gdf) @classmethod def from_features(cls, features, **kwargs): gdf = GeoDataFrame.from_features(features, **kwargs) return cls(gdf) def to_carto(self, *args, **kwargs): from ..io.carto import to_carto return to_carto(self, *args, **kwargs) def convert(self, index_column=None, geom_column=None, lnglat_columns=None, drop_index=True, drop_geom=True, drop_lnglat=True): # Magic function generate_index(self, index_column, drop_index) generate_geometry(self, geom_column, lnglat_columns, drop_geom, drop_lnglat) return self def viz(self, *args, **kwargs): from ..viz import Map, Layer return Map(Layer(self, *args, **kwargs))
Rename visualize to viz in CDF
Rename visualize to viz in CDF
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
fc5ae93998045f340e44e267f409a7bdf534c756
website_slides/__init__.py
website_slides/__init__.py
# -*- coding: utf-8 -*- # ############################################################################## # # Odoo, Open Source Management Solution # Copyright (C) 2014-TODAY Odoo SA (<https://www.odoo.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import controllers import models
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import controllers import models
Use global LICENSE/COPYRIGHT files, remove boilerplate text
[LEGAL] Use global LICENSE/COPYRIGHT files, remove boilerplate text - Preserved explicit 3rd-party copyright notices - Explicit boilerplate should not be necessary - copyright law applies automatically in all countries thanks to Berne Convention + WTO rules, and a reference to the applicable license is clear enough.
Python
agpl-3.0
Endika/website,Yajo/website,kaerdsar/website,brain-tec/website,kaerdsar/website,gfcapalbo/website,pedrobaeza/website,Antiun/website,open-synergy/website,LasLabs/website,open-synergy/website,brain-tec/website,nuobit/website,acsone/website,nuobit/website,xpansa/website,acsone/website,Antiun/website,Antiun/website,pedrobaeza/website,LasLabs/website,brain-tec/website,gfcapalbo/website,Endika/website,Endika/website,pedrobaeza/website,pedrobaeza/website,gfcapalbo/website,Yajo/website,nuobit/website,brain-tec/website,Endika/website,open-synergy/website,acsone/website,xpansa/website,kaerdsar/website,xpansa/website,Antiun/website,nuobit/website,xpansa/website,Yajo/website,LasLabs/website,acsone/website,open-synergy/website,gfcapalbo/website,LasLabs/website,Yajo/website
ee6f71ba0e548fdb08a3f1b065cd081b2431caa6
lc0222_count_complete_tree_nodes.py
lc0222_count_complete_tree_nodes.py
"""Leetcode 222. Count Complete Tree Nodes Medium URL: https://leetcode.com/problems/count-complete-tree-nodes/ Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example: Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class Solution(object): def countNodes(self, root): """ :type root: TreeNode :rtype: int """ pass def main(): pass if __name__ == '__main__': main()
"""Leetcode 222. Count Complete Tree Nodes Medium URL: https://leetcode.com/problems/count-complete-tree-nodes/ Given a complete binary tree, count the number of nodes. Note: Definition of a complete binary tree from Wikipedia: In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h. Example: Input: 1 / \ 2 3 / \ / 4 5 6 Output: 6 """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None class SolutionPreorderRecur(object): def _preorder(self, root): if not root: return None self.n_nodes += 1 self._preorder(root.left) self._preorder(root.right) def countNodes(self, root): """ :type root: TreeNode :rtype: int Time complexity: O(n). Space complexity: O(1). """ self.n_nodes = 0 self._preorder(root) return self.n_nodes def main(): # Input: # 1 # / \ # 2 3 # / \ / # 4 5 6 # Output: 6 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.left = TreeNode(6) print SolutionPreorderRecur().countNodes(root) if __name__ == '__main__': main()
Complete preorder recur sol w/ time/space complexity
Complete preorder recur sol w/ time/space complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
8c819a1cb9df54c00b7246a07e2ba832b763876d
stream_django/templatetags/activity_tags.py
stream_django/templatetags/activity_tags.py
from django import template from django.template import Context, loader from stream_django.exceptions import MissingDataException import logging logger = logging.getLogger(__name__) register = template.Library() LOG = 'warn' IGNORE = 'ignore' FAIL = 'fail' missing_data_policies = [LOG, IGNORE, FAIL] def handle_not_enriched_data(activity, policy): message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id')) if policy == IGNORE: pass elif policy == FAIL: raise MissingDataException(message) elif policy == LOG: logger.warn(message) else: raise TypeError('%s is not a valid missing_data_policy' % policy) def render_activity(context, activity, template_prefix='', missing_data_policy=LOG): if hasattr(activity, 'enriched') and not activity.enriched: handle_not_enriched_data(activity, missing_data_policy) return '' if template_prefix != '': template_prefix = '%s_' % template_prefix if 'activities' in activity: template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb']) else: template_name = "activity/%s%s.html" % (template_prefix, activity['verb']) tmpl = loader.get_template(template_name) context['activity'] = activity context = Context(context) return tmpl.render(context) register.simple_tag(takes_context=True)(render_activity)
from django import template from django.template import loader from stream_django.exceptions import MissingDataException import logging logger = logging.getLogger(__name__) register = template.Library() LOG = 'warn' IGNORE = 'ignore' FAIL = 'fail' missing_data_policies = [LOG, IGNORE, FAIL] def handle_not_enriched_data(activity, policy): message = 'could not enrich field(s) %r for activity #%s' % (activity.not_enriched_data, activity.get('id')) if policy == IGNORE: pass elif policy == FAIL: raise MissingDataException(message) elif policy == LOG: logger.warn(message) else: raise TypeError('%s is not a valid missing_data_policy' % policy) def render_activity(context, activity, template_prefix='', missing_data_policy=LOG): if hasattr(activity, 'enriched') and not activity.enriched: handle_not_enriched_data(activity, missing_data_policy) return '' if template_prefix != '': template_prefix = '%s_' % template_prefix if 'activities' in activity: template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb']) else: template_name = "activity/%s%s.html" % (template_prefix, activity['verb']) tmpl = loader.get_template(template_name) context['activity'] = activity return tmpl.render(context) register.simple_tag(takes_context=True)(render_activity)
Use dict as a context object for Django 1.11 compatibility
Use dict as a context object for Django 1.11 compatibility Django’s template rendering in 1.11 needs a dictionary as the context instead of the object Context, otherwise the following error is raised: context must be a dict rather than Context.
Python
bsd-3-clause
GetStream/stream-django,GetStream/stream-django
6727bb98c91f1185042d08f3ff2a4c5ef625cae4
mjstat/languages/__init__.py
mjstat/languages/__init__.py
# -*- coding: utf-8 -*- """__init__.py: Language-dependent features. """ module_cache = {} def get_language(lang_code): """Return module with language localizations. This is a poor copy of the language framework of Docutils. """ if lang_code in module_cache: return module_cache[lang_code] for i in (1, 0): try: module = __import__(lang_code, globals(), locals(), level=i) break except ImportError: continue else: module = __import__('en', globals(), locals(), level=1) module_cache[lang_code] = module return module
# -*- coding: utf-8 -*- """__init__.py: Language-dependent features. """ from importlib import import_module module_cache = {} def get_language(lang_code): """Return module with language localizations. This is a revamped version of function docutils.languages.get_language. """ if lang_code in module_cache: return module_cache[lang_code] try: module = import_module('.' + lang_code, __name__) except ImportError: from . import en module = en module_cache[lang_code] = module return module
Use importlib.import_module instead of built-in __import__.
Use importlib.import_module instead of built-in __import__.
Python
mit
showa-yojyo/bin,showa-yojyo/bin
030d425bb2b9b552516957277aebb22806bfc699
bills/redis_queue.py
bills/redis_queue.py
# -*- coding: utf-8 -*- import redis class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self, name, namespace='queue', **redis_kwargs): """The default connection parameters are: host='localhost', port=6379, db=0""" self.db = redis.Redis(**redis_kwargs) self.key = '%s:%s' %(namespace, name) def qsize(self): """Return the approximate size of the queue.""" return self.db.llen(self.key) def empty(self): """Return True if the queue is empty, False otherwise.""" return self.qsize() == 0 def put(self, item): """Put item into the queue.""" self.db.rpush(self.key, item) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.""" if block: item = self.db.blpop(self.key, timeout=timeout) else: item = self.db.lpop(self.key) if item: item = item[1] return item def get_nowait(self): """Equivalent to get(False).""" return self.get(False) def __iter__(self): return self def next(self): item = self.get(False) if item is None: raise StopIteration return item
# -*- coding: utf-8 -*- import redis class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self, name, namespace='queue', **redis_kwargs): """The default connection parameters are: host='localhost', port=6379, db=0""" self.db = redis.Redis(**redis_kwargs) self.key = '%s:%s' %(namespace, name) def qsize(self): """Return the approximate size of the queue.""" return self.db.llen(self.key) def empty(self): """Return True if the queue is empty, False otherwise.""" return self.qsize() == 0 def put(self, item): """Put item into the queue.""" self.db.rpush(self.key, item) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.""" if block: item = self.db.blpop(self.key, timeout=timeout) if item: item = item[1] else: item = self.db.lpop(self.key) return item def get_nowait(self): """Equivalent to get(False).""" return self.get(False) def __iter__(self): return self def next(self): item = self.get(False) if item is None: raise StopIteration return item
Fix a bug in redis queue
Fix a bug in redis queue
Python
agpl-3.0
teampopong/crawlers,majorika/crawlers,majorika/crawlers,lexifdev/crawlers,lexifdev/crawlers,teampopong/crawlers
6a1d9a327ebf64acba9bd02330bfa047e8137337
bmi_live/__init__.py
bmi_live/__init__.py
"""BMI Live clinic""" import os pkg_directory = os.path.dirname(__file__) data_directory = os.path.join(pkg_directory, 'data')
"""BMI Live clinic""" import os from .diffusion import Diffusion from .bmi_diffusion import BmiDiffusion __all__ = ['Diffusion', 'BmiDiffusion'] pkg_directory = os.path.dirname(__file__) data_directory = os.path.join(pkg_directory, 'data')
Include classes in package definition
Include classes in package definition
Python
mit
csdms/bmi-live,csdms/bmi-live