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
e21260b57873ed70bd6b1690b62a754af58020fc
otp_twilio/migrations/0002_last_t.py
otp_twilio/migrations/0002_last_t.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('otp_twilio_encrypted', '0001_initial'), ] operations = [ migrations.AddField( model_name='twiliosmsdevice', ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('otp_twilio', '0001_initial'), ] operations = [ migrations.AddField( model_name='twiliosmsdevice', na...
Undo dependency name change in last migration
Undo dependency name change in last migration
Python
bsd-2-clause
prototypsthlm/otp_twilio_encrypted,gustavrannestig/otp_twilio_encrypted
7a0243728ae5079b2409c9ccbf500d05f69886f3
examples/simple/schemas.py
examples/simple/schemas.py
from aiohttp_json_api.schema import BaseSchema, fields, relationships from .models import Article, Comment, People class SchemaWithStorage(BaseSchema): @property def storage(self): return self.app['storage'][self.resource_class.__name__] async def query_collection(self, context, **kwargs): ...
from aiohttp_json_api.schema import BaseSchema, fields, relationships from .models import Article, Comment, People class SchemaWithStorage(BaseSchema): @property def storage(self): return self.app['storage'][self.resource_class.__name__] async def fetch_resource(self, resource_id, context, **kwa...
Add support for query relatives in simple example
Add support for query relatives in simple example
Python
mit
vovanbo/aiohttp_json_api
19d366141ffedbabc93de487d140333de30e4b7a
rcamp/lib/pam_backend.py
rcamp/lib/pam_backend.py
from django.conf import settings from accounts.models import ( RcLdapUser, User ) import pam import logging logger = logging.getLogger('accounts') class PamBackend(): def authenticate(self, request, username=None, password=None): rc_user = RcLdapUser.objects.get_user_from_suffixed_username(usernam...
from django.conf import settings from accounts.models import ( RcLdapUser, User ) import pam import logging logger = logging.getLogger('accounts') class PamBackend(): def authenticate(self, request, username=None, password=None): rc_user = RcLdapUser.objects.get_user_from_suffixed_username(usernam...
Add logging to debug hanging auth
Add logging to debug hanging auth
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
ea24974502e0e293905b493d0993ab2fc1812192
op_robot_tests/tests_files/brokers/openprocurement_client_helper.py
op_robot_tests/tests_files/brokers/openprocurement_client_helper.py
from openprocurement_client.client import Client import sys def prepare_api_wrapper(key='', host_url="https://api-sandbox.openprocurement.org", api_version='0.8'): return Client(key, host_url, api_version) def get_tenders(client, offset=None): params = {'opt_fields': 'tenderID', 'descending': 1} if offs...
from openprocurement_client.client import Client def prepare_api_wrapper(key='', host_url='https://api-sandbox.openprocurement.org', api_version='0.8'): return Client(key, host_url, api_version) def get_tenders(client, offset=None): params = {'opt_fields': 'te...
Remove unused import; split a long line of code
Remove unused import; split a long line of code
Python
apache-2.0
Rzaporozhets/robot_tests,mykhaly/robot_tests,bubanoid/robot_tests,VadimShurhal/robot_tests.broker.aps,SlaOne/robot_tests,selurvedu/robot_tests,Leits/robot_tests,cleardevice/robot_tests,openprocurement/robot_tests,kosaniak/robot_tests
d9a8d30ba12f4fb61fdffe353d225c2ffcd074fa
fabfile.py
fabfile.py
from fabric.api import cd, run, sudo, env, execute from datetime import datetime env.hosts = ['andrewlorente.com'] apps = { 'bloge': ['bloge@andrewlorente.com'], 'andrewlorente': ['andrewlorente@andrewlorente.com'], } def deploy(app): if app not in apps.keys(): raise Exception("Unknown deploy targ...
from fabric.api import cd, run, sudo, env, execute, task from datetime import datetime env.hosts = ['andrewlorente.com'] apps = { 'bloge': ['bloge@andrewlorente.com'], 'andrewlorente': ['andrewlorente@andrewlorente.com'], } @task def deploy(app): if app not in apps.keys(): raise Exception("Unknown...
Hide support functions from the public interface
Hide support functions from the public interface
Python
mit
ErinCall/andrewlorente
38c831d1ca49c209b315761f5b58793ff3639759
tests/test_months.py
tests/test_months.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_months ---------------------------------- Tests for `months` module. """ import unittest from months import months class TestMonths(unittest.TestCase): def setUp(self): pass def test_something(self): pass def tearDown(self): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_months ---------------------------------- Tests for `months` module. """ import os import sys import datetime import unittest sys.path.append(os.path.join('.', 'months')) sys.path.append(os.path.join('..', 'months')) from months import Month class TestMonths...
Add tests for Month functionality
Add tests for Month functionality
Python
mit
kstark/months
784b165d67550cd159b05aabfd2872ebc746a9e2
pants/views.py
pants/views.py
from cornice import Service from tokenlib.errors import Error as TokenError callurl = Service(name='callurl', path='/call-url') call = Service(name='call', path='/call/{token}') def is_authenticated(request): """Validates that an user is authenticated and extracts its userid""" request.validated['userid'] = ...
from pyramid.security import Allow, Authenticated, authenticated_userid from cornice import Service from tokenlib.errors import Error as TokenError callurl = Service(name='callurl', path='/call-url') call = Service(name='call', path='/call/{token}') def acl(request): return [(Allow, Authenticated, 'create-callu...
Implement ACL for call url creation
Implement ACL for call url creation
Python
mpl-2.0
ametaireau/pants-server,almet/pants-server
0a907442eee18d0b30ca4ad2c6a5ef1fabb90684
pelicanconf.py
pelicanconf.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Lex Toumbourou' SITENAME = u'LexToumbourou.com' SITEURL = 'http://lextoumbourou.com' TIMEZONE = 'Australia/Melbourne' DEFAULT_LANG = u'en' ARTICLE_URL = 'blog/posts/{slug}/' ARTICLE_SAVE_AS = 'blog/posts/{slug}/index....
#!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = u'Lex Toumbourou' SITENAME = u'LexToumbourou.com' SITEURL = 'http://lextoumbourou.com' TIMEZONE = 'Australia/Melbourne' DEFAULT_LANG = u'en' ARTICLE_URL = 'blog/posts/{slug}/' ARTICLE_SAVE_AS = 'blog/posts/{slug}/index....
Support static files via new Pelican API
Support static files via new Pelican API
Python
mit
lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io
d986f68c2490d276bec7f9511c567e591c70d2d3
corehq/ex-submodules/pillow_retry/management/commands/send_pillow_retry_queue_through_pillows.py
corehq/ex-submodules/pillow_retry/management/commands/send_pillow_retry_queue_through_pillows.py
from __future__ import absolute_import from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pillow') def handle(self, pi...
from __future__ import absolute_import from datetime import datetime from django.core.management.base import BaseCommand from pillow_retry.models import PillowError from corehq.apps.change_feed.producer import producer class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('pi...
Add some print statements for debugging.
Add some print statements for debugging.
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
c1a5c5394ff9838e01b32ff448e309893c5bdf7f
cmsplugin_iframe/migrations/0001_initial.py
cmsplugin_iframe/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ] operations = [ migrations.CreateModel( name='IframePlugin', fields=[ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('cms', '0001_initial'), ] operations = [ migrations.CreateModel( name='IframePlugin', fields=[ ...
Add in on_delete clause to work with more modern versions of Django
Add in on_delete clause to work with more modern versions of Django
Python
mit
satyrius/cmsplugin-iframe,satyrius/cmsplugin-iframe
6325b0eebbe5c14284df4fa5398ffc678c3e0eca
posts/tests.py
posts/tests.py
from test_plus.test import TestCase from posts.factories import PostFactory class PostsTest(TestCase): def test_get_list(self): post = PostFactory() post_list_url = self.reverse('post:list') self.get_check_200(post_list_url) self.assertResponseContains(post.title, html=False) ...
from test_plus.test import TestCase from posts.factories import PostFactory class PostsTest(TestCase): def test_get_list(self): # given post = PostFactory() post_list_url = self.reverse('post:list') # when self.get_check_200(post_list_url) # then self.asser...
Add given, when, then comment
Add given, when, then comment
Python
mit
9XD/9XD,9XD/9XD,9XD/9XD,9XD/9XD
8958f8abb8798ff61af43199f0683c3e1c0ffcdd
checklisthq/main/models.py
checklisthq/main/models.py
from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager class Checklist(models.Model): title = models.CharField(max_length=512) owner = models.ForeignKey(User) content = models.TextField() created = models.DateTimeField(auto_now_add=True) ...
from django.db import models from django.contrib.auth.models import User from taggit.managers import TaggableManager class Checklist(models.Model): title = models.CharField(max_length=512) owner = models.ForeignKey(User) content = models.TextField() created = models.DateTimeField(auto_now_add=True) ...
Make tags an optional field of Checklist
Make tags an optional field of Checklist
Python
agpl-3.0
checklisthq/checklisthq.com,checklisthq/checklisthq.com
964da6a3df622b5217596ac190ca46bc18942616
api/urls.py
api/urls.py
from django.conf.urls import url from api import views urlpatterns = [ url(r'^machines/(?P<serial>.+)/$', views.machine_detail), url(r'^inventory/(?P<serial>.+)/$', views.machine_inventory), url(r'^machines/$', views.machine_list), url(r'^facts/(?P<serial>.+)/$', views.facts), url(r'^conditions/(?P...
from django.conf.urls import url from api import views urlpatterns = [ url(r'^machines/(?P<serial>.+)/inventory/$', views.machine_inventory), url(r'^machines/(?P<serial>.+)/$', views.machine_detail), url(r'^machines/$', views.machine_list), url(r'^facts/(?P<serial>.+)/$', views.facts), url(r'^condi...
Revert "Think this url is causing issues"
Revert "Think this url is causing issues" This reverts commit ca4df2f1f23b5ff85b7c1685c6bbcd015f9789cf.
Python
apache-2.0
erikng/sal,chasetb/sal,chasetb/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,erikng/sal,erikng/sal,salopensource/sal,chasetb/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,chasetb/sal,erikng/sal
ff7239b915093c6915d05c15362c5e86341bd6cb
lib/dns_lookup.py
lib/dns_lookup.py
# -*- coding: utf-8 -*- import network BLOCK_SIZE = 256 PORT = 53 def listen(port): if port is None: port = PORT print('Listening for data via DNS.') l = network.get_listener('UDP', port) print('Data Received:') while 1: data, addr = l.recvfrom(1500) dns = network.parse_...
# -*- coding: utf-8 -*- import network BLOCK_SIZE = 256 PORT = 53 def listen(port): if port is None: port = PORT print('Listening for data via DNS on port {0}.'.format(port)) l = network.get_listener('UDP', port) print('Data Received:') while 1: data, addr = l.recvfrom(1500) ...
Add port to logging. Fix print statement.
Add port to logging. Fix print statement.
Python
bsd-3-clause
averagesecurityguy/exfil
c286722965ce7f5ea9acc201aa9cf289cfe16105
openstackclient/tests/functional/common/test_availability_zone.py
openstackclient/tests/functional/common/test_availability_zone.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
# 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 # d...
Refactor availability zone functional test
Refactor availability zone functional test Using json format output in availability zone list functional test Change-Id: I7098b1c3bee680e47e414dcb4fa272628cdec1eb
Python
apache-2.0
dtroyer/python-openstackclient,openstack/python-openstackclient,dtroyer/python-openstackclient,openstack/python-openstackclient
f4b3c2ca7d9fdf6bc96202d6c2ad3b16cb6fc3be
sedfitter/timer.py
sedfitter/timer.py
from __future__ import print_function, division import time import numpy as np class Timer(object): def __init__(self): self.time1 = time.time() self.n = 0 self.step = 1 print(" # Sources CPU time (sec) Sources/sec ") print(" ------------------------------------...
from __future__ import print_function, division import time import numpy as np class Timer(object): def __init__(self): self.time1 = time.time() self.n = 0 self.step = 1 print(" # Sources CPU time (sec) Sources/sec ") print(" ------------------------------------...
Fix division by zero error
Fix division by zero error
Python
bsd-2-clause
astrofrog/sedfitter
2c2a5b4af2fa3fe4daff088810ced044ce73af0c
services/disqus.py
services/disqus.py
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
Reword the permissions for Disqus
Reword the permissions for Disqus
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org,foauth/oauth-proxy
0e1384ab777a2d7e30036ccc7d8ed0e17093f4e1
src/ggrc_basic_permissions/roles/ProgramAuditReader.py
src/ggrc_basic_permissions/roles/ProgramAuditReader.py
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = "AuditImplied" description = """ A user with the ProgramReader role fo...
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = "AuditImplied" description = """ A user with the ProgramReader role fo...
Remove CD permissions for program audit reader
Remove CD permissions for program audit reader
Python
apache-2.0
NejcZupec/ggrc-core,j0gurt/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-c...
be8b36b141d32372e9c08e73cbbe4620d86effac
chainer/ya/utils/range_logger.py
chainer/ya/utils/range_logger.py
import logging logger = logging.getLogger() logger.setLevel(getattr(logging, 'INFO')) logger.addHandler(logging.StreamHandler()) class rangelog: def __init__(self, name): self.name = name def __enter__(self): logger.info("--> Start: {}".format(self.name)) return logger def __ex...
import logging class rangelog: logger = None @classmethod def set_logger(cls, logger=None): if logger is None: cls.logger = logging.getLogger() cls.logger.setLevel(getattr(logging, 'INFO')) cls.logger.addHandler(logging.StreamHandler()) elif isinstance(...
Change to use class variable as logger
Change to use class variable as logger
Python
mit
yasuyuky/chainer-ya-utils
f26202f688f7612971e35b0ae33a2f961a117876
select_multiple_field/widgets.py
select_multiple_field/widgets.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import widgets from django.forms.util import flatatt from django.utils.safestring import mark_safe class SelectMultipleField(widgets.SelectMultiple): """Multiple select widget ready for jQuery multiselect.js""" allow_multiple_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.forms import widgets from django.forms.util import flatatt from django.utils.safestring import mark_safe try: from django.utils.html import format_html except ImportError: def format_html(format_string, *args, **kwargs): retur...
Use format_html if it is available, fallback for dj 1.4
Use format_html if it is available, fallback for dj 1.4
Python
bsd-3-clause
kelvinwong-ca/django-select-multiple-field,kelvinwong-ca/django-select-multiple-field,kelvinwong-ca/django-select-multiple-field
1a00149b13a771ee18033a1abf1a3c30526b3d81
signac/__init__.py
signac/__init__.py
""" signac aids in the management, access and analysis of large-scale computational investigations. The framework provides a simple data model, which helps to organize data production and post-processing as well as distribution among collaboratos. """ # The VERSION string represents the actual (development) version o...
""" signac aids in the management, access and analysis of large-scale computational investigations. The framework provides a simple data model, which helps to organize data production and post-processing as well as distribution among collaboratos. """ # The VERSION string represents the actual (development) version o...
Remove everything but the VERSION constants from global namespace.
Remove everything but the VERSION constants from global namespace.
Python
bsd-3-clause
csadorf/signac,csadorf/signac
8baff5cb627ed55f748123d536273c4a4e648d77
obelisk-cardiograph.py
obelisk-cardiograph.py
#!/usr/bin/env python """ obelisk-cardiograph Monitor obelisk servers' heartbeat. Author: Noel Maersk <veox ta wemakethings tod net> Based on "Pubsub envelope subscriber" example from zguide Author: Guillaume Aubert (gaubert) <guillaume(dot)aubert(at)gmail(dot)com> """ import zmq def main(): """ main method ...
#!/usr/bin/env python """ obelisk-cardiograph Monitor obelisk servers' heartbeat. Author: Noel Maersk <veox ta wemakethings tod net> Based on "Pubsub envelope subscriber" example from zguide Author: Guillaume Aubert (gaubert) <guillaume(dot)aubert(at)gmail(dot)com> """ import zmq def main(): """ main method ...
Put servers in a list, use FQDNs if available, rename context var.
Put servers in a list, use FQDNs if available, rename context var.
Python
agpl-3.0
veox/obelisk-cardiograph
584b707fe83a49264c95b7cfa6fd84cfcce96a52
csunplugged/utils/group_lessons_by_age.py
csunplugged/utils/group_lessons_by_age.py
"""Return ordered groups of lessons.""" from collections import OrderedDict def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. Returns: A ordered dictionary of grouped lessons. ...
"""Return ordered groups of lessons.""" from collections import OrderedDict def group_lessons_by_age(lessons): """Return ordered groups of lessons. Lessons are grouped by the lesson minimum age and maximum ages, and then order by number. Args: lessons: QuerySet of Lesson objects (QuerySet)....
Add missing args docstring details
Add missing args docstring details
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
a73cc6d6ad8460d492b29db60df2c0e8eaff932e
openerp_conventions.py
openerp_conventions.py
# -*- coding: utf-8 -*- """OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' ...
# -*- coding: utf-8 -*- """OpenERP community addons standard plugin for flake8""" from __future__ import absolute_import import common_checker from common_checker.base_checker import BaseChecker # When OpenERP version 8 API will be frozen # We wille be able to do version toggle here import v7 __version__ = '0.0.1' ...
Improve BaseChecker class by using __metaclass__ keyword + add a filename setter
Improve BaseChecker class by using __metaclass__ keyword + add a filename setter
Python
mit
nbessi/openerp-conventions
3b7b15db24ac738c143e3d2d38c740500ac73fd0
jinja2_time/jinja2_time.py
jinja2_time/jinja2_time.py
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.ext...
# -*- coding: utf-8 -*- import arrow from jinja2 import nodes from jinja2.ext import Extension class TimeExtension(Extension): tags = set(['now']) def __init__(self, environment): super(TimeExtension, self).__init__(environment) # add the defaults to the environment environment.ext...
Change environment attribute name to datetime_format
Change environment attribute name to datetime_format
Python
mit
hackebrot/jinja2-time
c5fc667a6d50677936d8ae457734562d207a034b
bluesky/tests/test_vertical_integration.py
bluesky/tests/test_vertical_integration.py
from metadatastore.utils.testing import mds_setup, mds_teardown from dataportal import DataBroker as db from bluesky.examples import * from bluesky.standard_config import RE def setup(): mds_setup() def teardown(): mds_teardown() def test_scan_and_get_data(): uid = RE(stepscan(det, motor), group='foo',...
from metadatastore.utils.testing import mds_setup, mds_teardown from dataportal import DataBroker as db from bluesky.examples import stepscan, det, motor from bluesky.standard_config import gs def setup(): mds_setup() def teardown(): mds_teardown() def test_scan_and_get_data(): uid = gs.RE(stepscan(det...
Update test after RE -> gs.RE change.
TST: Update test after RE -> gs.RE change.
Python
bsd-3-clause
sameera2004/bluesky,ericdill/bluesky,klauer/bluesky,klauer/bluesky,ericdill/bluesky,dchabot/bluesky,sameera2004/bluesky,dchabot/bluesky
310016762927dd9796109712be1c59ce0c1a658c
runcurldrop.py
runcurldrop.py
#!/usr/bin/env python import os import tornado from curldrop import StreamHandler, config from contextlib import closing import sqlite3 schema = '''drop table if exists files; create table files ( id integer primary key autoincrement, file_id text not null, timestamp integer not null, ip text not null, origi...
#!/usr/bin/env python import os import tornado from curldrop import StreamHandler, config from contextlib import closing import sqlite3 schema = '''drop table if exists files; create table files ( id integer primary key autoincrement, file_id text not null, timestamp integer not null, ip text not null, origi...
Add handler to main app
Add handler to main app
Python
mit
Xarthisius/curldrop
a25d12d7d3eab68dff1d65382543ad93fb8a22bd
mint/rest/api/models/__init__.py
mint/rest/api/models/__init__.py
from mint.rest.modellib import Model from mint.rest.modellib import fields class RbuilderStatus(Model): version = fields.CharField() conaryVersion = fields.CharField() products = fields.UrlField('products', None) users = fields.UrlField('users', None) from mint.rest.api.models.membe...
from mint.rest.modellib import Model from mint.rest.modellib import fields class RMCUrlField(fields.CalculatedField): def getValue(self, controller, request, class_, parent, value): return request.getHostWithProtocol() + '/catalog' class RbuilderStatus(Model): id = fields.AbsoluteUrlField...
Add extra fields to status info page
Add extra fields to status info page
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
6f103bd78f188c2a090c6dd522884c361e85d832
cyder/cydhcp/validation.py
cyder/cydhcp/validation.py
# encoding: utf-8 from django.core.exceptions import ValidationError import re ERROR_TOO_LONG = 'MAC address is too long' mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$') def validate_mac(mac): if mac == ERROR_TOO_LONG: raise ValidationError(ERROR_TOO_LONG) elif mac == '00:00:00:00:00:00...
# encoding: utf-8 from django.core.exceptions import ValidationError import re ERROR_TOO_LONG = 'MAC address is too long' mac_pattern = re.compile(r'^([0-9a-f]{2}:){5}[0-9a-f]{2}$') def validate_mac(mac): if mac == ERROR_TOO_LONG: raise ValidationError(ERROR_TOO_LONG) elif mac == '00:00:00:00:00:00...
Validate dynamic interface's range's container, not dynamic interface's range's domain's container.
Validate dynamic interface's range's container, not dynamic interface's range's domain's container.
Python
bsd-3-clause
drkitty/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,drkitty/cyder,OSU-Net/cyder,drkitty/cyder,OSU-Net/cyder
9d796a4fe8f6c4b38eb1428d4d43f1edc041c1cd
dlchainer/__init__.py
dlchainer/__init__.py
#-*- coding: utf-8 -*- from .dA import dA
#-*- coding: utf-8 -*- from .dA import dA from .SdA import SdAClassifier, SdARegressor
Add importing SdA in init script.
Add importing SdA in init script.
Python
mit
duonys/deep-learning-chainer
d011f0279f868e56b0a36bb672f432ca2bfc2b35
mlbgame/league.py
mlbgame/league.py
#!/usr/bin/env python """Module that is used for getting information about the (MLB) league and the teams in it. """ import mlbgame.data import lxml.etree as etree def get_league_object(): """Returns the xml object corresponding to the league Only designed for internal use""" # get data data = ...
#!/usr/bin/env python """Module that is used for getting information about the (MLB) league and the teams in it. """ import mlbgame.data import lxml.etree as etree def get_league_object(): """Returns the xml object corresponding to the league Only designed for internal use""" # get data data = ...
Add function to parse team info
Add function to parse team info
Python
mit
zachpanz88/mlbgame,panzarino/mlbgame
164ac322110407ec3ab7b9dc8b6675a405efa6a9
pymantic/__init__.py
pymantic/__init__.py
# from rdflib.plugin import register from rdflib.serializer import Serializer from rdflib.parser import Parser import re # Fix rdflib's ntriples parser from rdflib.plugins.parsers import ntriples ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?' ntriples.r_literal = re.compile(ntriple...
# from rdflib.plugin import register from rdflib.serializer import Serializer from rdflib.parser import Parser import re # Fix rdflib's ntriples parser from rdflib.plugins.parsers import ntriples ntriples.litinfo = r'(?:@([a-z]+(?:-[a-zA-Z0-9]+)*)|\^\^' + ntriples.uriref + r')?' ntriples.r_literal = re.compile(ntriple...
Expand rdflib to content-type mapping.
Expand rdflib to content-type mapping.
Python
bsd-3-clause
igor-kim/blazegraph-python,SYSTAP/blazegraph-python,blazegraph/blazegraph-python,SYSTAP/blazegraph-python,blazegraph/blazegraph-python,igor-kim/blazegraph-python,syapse/pymantic
a0fe1cb563a6aff55744def8e43a3af8b0d672cc
python/web_socket.py
python/web_socket.py
#!/bin/python import urllib.request import json class RESTfulApi: """ Generic REST API call """ def __init__(self): """ Constructor """ pass def request(self, url): """ Web request :param: url: The url link :return JSON object ...
#!/bin/python try: import urllib.request as urlrequest except ImportError: import urllib as urlrequest import json class RESTfulApi: """ Generic REST API call """ def __init__(self): """ Constructor """ pass def request(self, url): """ Web...
Support python 2 and 3 compatability
Support python 2 and 3 compatability
Python
apache-2.0
Aurora-Team/BitcoinExchangeFH
558a44643b37e82f5b77038c34e826f38dcb6358
qsimcirq/_version.py
qsimcirq/_version.py
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.11.1"
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.11.2.dev20220104"
Update to dev version 2022-01-04
Update to dev version 2022-01-04
Python
apache-2.0
quantumlib/qsim,quantumlib/qsim,quantumlib/qsim,quantumlib/qsim
be4aad346f25f7daf0ba8e61b083f9e15e8f6b6a
luigi/tasks/release/utils/generic.py
luigi/tasks/release/utils/generic.py
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
# -*- coding: utf-8 -*- """ Copyright [2009-2017] EMBL-European Bioinformatics Institute 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...
Make file pattern quote the name
Make file pattern quote the name Might not be the right place for it, but this does need to be done.
Python
apache-2.0
RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline
b959783f7c8db26df03760bb03227ab49f1975ba
pywikibot/families/wikitech_family.py
pywikibot/families/wikitech_family.py
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikitech family class Family(family.Family): def __init__(self): super(Family, self).__init__() self.name = 'wikitech' self.langs = { 'en': 'wikitech.wikimedia.org', } def version(s...
# -*- coding: utf-8 -*- __version__ = '$Id$' from pywikibot import family # The Wikitech family class Family(family.Family): def __init__(self): super(Family, self).__init__() self.name = 'wikitech' self.langs = { 'en': 'wikitech.wikimedia.org', } def version(s...
Remove overide of default scriptpath
Remove overide of default scriptpath git-svn-id: 9a050473c2aca1e14f53d73349e19b938c2cf203@11370 6a7f98fc-eeb0-4dc1-a6e2-c2c589a08aa6
Python
mit
legoktm/pywikipedia-rewrite
a757ee7cff8f90ddf8cddb859e9924821a948f37
steve/_version.py
steve/_version.py
####################################################################### # This file is part of steve. # # Copyright (C) 2012, 2013 Will Kahn-Greene # Licensed under the Simplified BSD License. See LICENSE for full # license. ####################################################################### # See http://www.pytho...
####################################################################### # This file is part of steve. # # Copyright (C) 2012, 2013 Will Kahn-Greene # Licensed under the Simplified BSD License. See LICENSE for full # license. ####################################################################### # See http://www.pytho...
Fix version back to .dev
Fix version back to .dev
Python
bsd-2-clause
pyvideo/steve,CarlFK/steve,CarlFK/steve,willkg/steve,willkg/steve,pyvideo/steve,willkg/steve,pyvideo/steve,CarlFK/steve
3d5d52f7d529183bd56da43df2503a53fe3b6fc8
oauth2/_compat.py
oauth2/_compat.py
try: TEXT = unicode except NameError: #pragma NO COVER Py3k TEXT = str STRING_TYPES = (str, bytes) else: #pragma NO COVER Python2 STRING_TYPES = (unicode, bytes) def u(x, encoding='ascii'): if isinstance(x, TEXT): #pragma NO COVER return x try: return x.decode(encoding) exce...
try: TEXT = unicode except NameError: #pragma NO COVER Py3k TEXT = str STRING_TYPES = (str, bytes) def b(x, encoding='ascii'): return bytes(x, encoding) else: #pragma NO COVER Python2 STRING_TYPES = (unicode, bytes) def b(x, encoding='ascii'): if isinstance(x, unicode): ...
Add a 'b()' utility for forcing encoding to bytes.
Add a 'b()' utility for forcing encoding to bytes. In Python2, the 'bytes()' builtin doesn't take an encoding argument.
Python
mit
CentricWebEstate/python-oauth2,squirro/python-oauth2,arthurian/python-oauth2,CestusMagnus/python-oauth2,joestump/python-oauth2,jackiekazil/python-oauth2,simplegeo/python-oauth2,edworboys/python-oauth2
35a0bfaf499029fa54d33d6ea712e255cc41e1de
core/migrations/0003_set_homepage.py
core/migrations/0003_set_homepage.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def set_homepage(apps, schema_editor): Site = apps.get_model('wagtailcore.Site') HomePage = apps.get_model("core", "HomePage") homepage = HomePage.objects.get(slug="home") # Create default site ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models def set_homepage(apps, schema_editor): Site = apps.get_model('wagtailcore.Site') HomePage = apps.get_model("core", "HomePage") homepage = HomePage.objects.get(slug="home") Site.objects.filter(hos...
Delete existing localhost entry for site.
Delete existing localhost entry for site.
Python
mit
albertoconnor/website,albertoconnor/website,OpenCanada/website,OpenCanada/website,OpenCanada/website,albertoconnor/website,albertoconnor/website,OpenCanada/website
74b94564583c2cc5de50bb86be048afe3b0ca67e
links/maker/serializers.py
links/maker/serializers.py
from rest_framework import serializers from maker.models import Maker class RegistrationRequestSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(required=True) first_name = serializers.CharField(required=True) last_name = serializers.C...
from rest_framework import serializers from maker.models import Maker class RegistrationRequestSerializer(serializers.Serializer): email = serializers.EmailField(required=True) password = serializers.CharField(required=True) first_name = serializers.CharField(required=True) last_name = serializers.C...
Add email change process serializer
Add email change process serializer
Python
mit
projectweekend/Links-API,projectweekend/Links-API
7d6580f2eb0e142a7ff7c77e6fc1d75f2a3d71b3
isort/pylama_isort.py
isort/pylama_isort.py
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys.stdout = devnull yield sys...
import os import sys from contextlib import contextmanager from typing import Any, Dict, List from pylama.lint import Linter as BaseLinter from isort.exceptions import FileSkipped from . import api @contextmanager def supress_stdout(): stdout = sys.stdout with open(os.devnull, "w") as devnull: sys....
Fix pylama integration to work with file skip comments
Fix pylama integration to work with file skip comments
Python
mit
PyCQA/isort,PyCQA/isort
e7999bd8afa05854aac25cc5f16fd8555031aa5b
ci/run_all_spiders.py
ci/run_all_spiders.py
from scrapy.utils.project import get_project_settings from scrapy.crawler import CrawlerProcess if __name__ == '__main__': settings = get_project_settings() settings.set('LOG_FILE', 'all_spiders.log') settings.set('LOG_LEVEL', 'ERROR') settings.set('TELNETCONSOLE_ENABLED', False) settings.set('FE...
from scrapy.utils.project import get_project_settings from scrapy.crawler import CrawlerProcess from scrapy import signals if __name__ == '__main__': settings = get_project_settings() settings.set('LOG_FILE', 'all_spiders.log') settings.set('LOG_LEVEL', 'ERROR') settings.set('TELNETCONSOLE_ENABLED', ...
Print some stats in the crawler
Print some stats in the crawler
Python
mit
iandees/all-the-places,iandees/all-the-places,iandees/all-the-places
df9caa5a5735e8e74639f640272705fec886206e
test/factories.py
test/factories.py
# coding: utf-8 import string import factory from django.contrib.auth.models import User from message.models import Message from test.utils import generate_string, lorem_ipsum class UserFactory(factory.Factory): FACTORY_FOR = User first_name = "Boy" last_name = "Factory" email = factory.LazyAttrib...
# coding: utf-8 import string import factory import random from django.contrib.auth.models import User from message.models import Message, MessageType from test.utils import generate_string, lorem_ipsum class UserFactory(factory.Factory): FACTORY_FOR = User first_name = "Boy" last_name = "Factory" ...
Add messageType to message factory
Add messageType to message factory
Python
mit
sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/flowofkindness
567821c91b83e9251339a5e1caa81ea1839d8db1
day-04-1.py
day-04-1.py
import hashlib puzzle_input = 'iwrupvqb'
import hashlib puzzle_input = b'iwrupvqb' number = 100000 while True: key = puzzle_input + str(number).encode() if hashlib.md5(key).hexdigest()[:5] == '00000': break number += 1 print(number) # Runs way faster than I expected, lol # My answer: 346386
Complete day 4 part 1
Complete day 4 part 1
Python
mit
foxscotch/advent-of-code,foxscotch/advent-of-code
677c4eb7672d2d5510ae7d8346563200e1c480d6
skeleton/__init__.py
skeleton/__init__.py
""" Basic Template system for project skeleton. skeleton is similar to the template part of PasteScript but without any dependencies; it should also be compatible with Python 3. However in this early phase of development, it only target python 2.5+, and tests require Mock. """ from skeleton.core import Skeleton, Va...
""" Basic Template system for project skeleton. skeleton is similar to the template part of PasteScript but without any dependencies. """ from skeleton.core import Skeleton, Var from skeleton.utils import insert_into_file
Add insert_into_file to skeleton module
Add insert_into_file to skeleton module
Python
bsd-2-clause
dinoboff/skeleton
eb79cce84fbb9d801d6f5087b9216e66d56bfa51
scripts/generate_global_kwargs_doc.py
scripts/generate_global_kwargs_doc.py
#!/usr/bin/env python from os import path from pyinfra.api.operation_kwargs import OPERATION_KWARGS def build_global_kwargs_doc(): this_dir = path.dirname(path.realpath(__file__)) docs_dir = path.abspath(path.join(this_dir, '..', 'docs')) lines = [] for category, kwarg_configs in OPERATION_KWARGS....
#!/usr/bin/env python from os import path from pyinfra.api import Config from pyinfra.api.operation_kwargs import OPERATION_KWARGS def build_global_kwargs_doc(): pyinfra_config = Config() this_dir = path.dirname(path.realpath(__file__)) docs_dir = path.abspath(path.join(this_dir, '..', 'docs')) li...
Include defaults in generated global args list.
Include defaults in generated global args list.
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
ff96f3fd6835f11f3725ab398b2a6b7ba4275e93
thinglang/compiler/references.py
thinglang/compiler/references.py
class Reference(object): def __init__(self, type): super().__init__() self._type = type @property def type(self): return self._type class ElementReference(Reference): def __init__(self, thing, element): super(ElementReference, self).__init__(element.type) ...
class Reference(object): def __init__(self, type): super().__init__() self._type = type @property def type(self): return self._type class ElementReference(Reference): def __init__(self, thing, element, local=None): super(ElementReference, self).__init__(elemen...
Add locally referenced subtype to element referenced opcodes
Add locally referenced subtype to element referenced opcodes
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
b9b8d77898c81afa5d918cc93c9011ace6f23965
content_editor/renderer.py
content_editor/renderer.py
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from django.db.models import Model from django.utils.html import conditional_escape, mark_safe class PluginRenderer(object): def __init__(self): self._renderers = OrderedDict((( Model, la...
from __future__ import absolute_import, unicode_literals from collections import OrderedDict from django.db.models import Model from django.utils.html import conditional_escape, mark_safe __all__ = ('PluginRenderer',) class RenderedContents(object): def __init__(self, contents): self.contents = conten...
Allow iterating over rendered contents
Allow iterating over rendered contents
Python
bsd-3-clause
matthiask/feincms2-content,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor
9c83b5b064a50b6813bb3819927c9d268f89aaa1
ninja/files.py
ninja/files.py
from typing import Any, Callable, Iterable, Optional, Type from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile from pydantic.fields import ModelField __all__ = ["UploadedFile"] class UploadedFile(DjangoUploadedFile): @classmethod def __get_validators__(cls: Type["UploadedFile"]) ->...
from typing import Any, Callable, Dict, Iterable, Optional, Type from django.core.files.uploadedfile import UploadedFile as DjangoUploadedFile from pydantic.fields import ModelField __all__ = ["UploadedFile"] class UploadedFile(DjangoUploadedFile): @classmethod def __get_validators__(cls: Type["UploadedFile...
Add missing type hint for field_schema parameter
Add missing type hint for field_schema parameter
Python
mit
vitalik/django-ninja,vitalik/django-ninja,vitalik/django-ninja
6cb9b6af77768466d7b6fd8e5d0964611da55282
tests/__init__.py
tests/__init__.py
from django.conf import settings from django.core.management import call_command settings.configure( DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } }, INSTALLED_APPS = [ 'fandjango', 'south', 'tests.app' ], ROOT_U...
from django.conf import settings from django.core.management import call_command settings.configure( DATABASES = { 'default': { 'ENGINE': 'sqlite3', 'NAME': ':memory:' } }, INSTALLED_APPS = [ 'fandjango', 'south', 'tests.app' ], ROOT_U...
Fix a bug that caused tests to raise a DatabaseError
Fix a bug that caused tests to raise a DatabaseError
Python
mit
jgorset/fandjango,jgorset/fandjango
a19d0c2d77102c1f14823e0fbc255de3b0b2d4f4
tests/conftest.py
tests/conftest.py
# -*- coding: utf-8 -*- """ Acolyte Tests """ import pytest from acolyte import create_app from acolyte.database import db from config import TestConfig, TestConfigCRSF @pytest.yield_fixture(scope='function') def app(request): app = create_app(TestConfig) app.app_context().push() db.create_all() ...
# -*- coding: utf-8 -*- """Acolyte test fixtures """ import pytest from acolyte import create_app from acolyte.database import db from config import TestConfig, TestConfigCRSF @pytest.yield_fixture(scope='function') def app(): """Pytest fixture to yield a fully initialised Acolyte Decorators: p...
Add docstrings to test fixtures
Add docstrings to test fixtures
Python
mit
rabramley/frostgrave_acolyte,rabramley/frostgrave_acolyte
34cf1f2467a7fb09850f834d7c1dd165457e36c2
tests/conftest.py
tests/conftest.py
import sys collect_ignore = [] if sys.version_info < (3, 5): collect_ignore.append("test_async.py") if sys.version_info < (3, 4): collect_ignore.append("test_coroutines.py")
"""Configuration for test environment""" import sys from .fixtures import * collect_ignore = [] if sys.version_info < (3, 5): collect_ignore.append("test_async.py") if sys.version_info < (3, 4): collect_ignore.append("test_coroutines.py")
Add hug_api fixture, and all future fixtures to default test config
Add hug_api fixture, and all future fixtures to default test config
Python
mit
timothycrosley/hug,timothycrosley/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,timothycrosley/hug
98c1f2b21c55d0f4926602fa6d3534faa623b9ab
orges/orges.py
orges/orges.py
def optimize(f, param_spec=None, return_spec=None): """Assume f has to be minimized for now.""" if __name__ == '__main__': pass
from test.algorithms.saes import f as saes from paramspec import ParamSpec from args import ArgsCreator, call def optimize(f, param_spec=None, return_spec=None): """Assume f has to be minimized for now.""" if param_spec is None: param_spec = ParamSpec(f) args_creator = ArgsCreator(param_spec) for args in...
Add prototype implementation for optimize()
Add prototype implementation for optimize() It is currently doing a "Grid search" without actually searching for anything ;)
Python
bsd-3-clause
cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt
92c01be43b80247ce2233851dd74b041bb9d44b0
csunplugged/resources/views/BarcodeChecksumPosterResourceGenerator.py
csunplugged/resources/views/BarcodeChecksumPosterResourceGenerator.py
"""Class for Barcode Checksum Poster resource generator.""" from PIL import Image from utils.BaseResourceGenerator import BaseResourceGenerator class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerator): """Class for Grid resource generator.""" additional_valid_options = { "barcode_length":...
"""Class for Barcode Checksum Poster resource generator.""" from PIL import Image, ImageDraw from utils.BaseResourceGenerator import BaseResourceGenerator from utils.TextBoxDrawer import TextBoxDrawer from django.utils.translation import ugettext as _ class BarcodeChecksumPosterResourceGenerator(BaseResourceGenerato...
Modify Barcode Checksum Poster resource to dynamically overlay text
Modify Barcode Checksum Poster resource to dynamically overlay text
Python
mit
uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged
f636420211821faeb3e26a501fbe5a9a7e3eef5e
normal_admin/user_admin.py
normal_admin/user_admin.py
__author__ = 'weijia' from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate ERROR_MESSAGE = _("Please enter the correct username and pa...
from django.contrib.admin.sites import AdminSite from django.contrib.admin.forms import AdminAuthenticationForm from django import forms from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import authenticate __author__ = 'weijia' ERROR_MESSAGE = _("Please enter the correct username and p...
Fix login error in Django 1.8.
Fix login error in Django 1.8.
Python
bsd-3-clause
weijia/normal_admin,weijia/normal_admin
ea2979c75f8f771a70617e607b8398809dba8dac
twython/compat.py
twython/compat.py
# -*- coding: utf-8 -*- """ twython.compat ~~~~~~~~~~~~~~ This module contains imports and declarations for seamless Python 2 and Python 3 compatibility. """ import sys import numpy as np _ver = sys.version_info #: Python 2.x? is_py2 = (_ver[0] == 2) #: Python 3.x? is_py3 = (_ver[0] == 3) try: import simplej...
# -*- coding: utf-8 -*- """ twython.compat ~~~~~~~~~~~~~~ This module contains imports and declarations for seamless Python 2 and Python 3 compatibility. """ import sys _ver = sys.version_info #: Python 2.x? is_py2 = (_ver[0] == 2) #: Python 3.x? is_py3 = (_ver[0] == 3) try: import simplejson as json except ...
Remove this merge as numpy shouldn't be a dependency
Remove this merge as numpy shouldn't be a dependency
Python
mit
ryanmcgrath/twython
b8f03556991cabab858bb31e5c8cb2f043ad14ce
packages/pcl-reference-assemblies.py
packages/pcl-reference-assemblies.py
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='mono-pcl-profiles', version='2013-10-23', sources=['http://storage.bos.xamarin.com/mono-pcl/58/5825e...
import glob import os import shutil class PCLReferenceAssembliesPackage(Package): def __init__(self): Package.__init__(self, name='mono-pcl-profiles-2013-10-25', version='2013-10-25', sources=['http://storage.bos.xamarin.com/bot-pr...
Use a versioned filename for the PCL profiles.
Use a versioned filename for the PCL profiles.
Python
mit
mono/bockbuild,mono/bockbuild
4f9b0fc97b873a1e43a4312ae3a4b12d8b7bec35
ui.py
ui.py
def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | O | | | | ...
from terminaltables import SingleTable def render(object, **kw): if object == 'gallows': render_gallows(**kw) if object == 'bank': render_bank(**kw) if object == 'game_state': render_game_state(**kw) def render_gallows(parts=0, **kw): print(""" ______ | | ...
Use terminaltables.SingleTable for displaying letter bank
Use terminaltables.SingleTable for displaying letter bank
Python
mit
tml/python-hangman-2017-summer
5d622e350784ede5af2490495ce3119a2589b1e9
hb_res/resources/build_assets.py
hb_res/resources/build_assets.py
from .Resource import names_registered, resource_by_name def build(): for name in names_registered(): resource = resource_by_name(name)() for explanation in resource: r = explanation for functor in resource.modifiers: r = functor(r) # write res i...
from .Resource import names_registered, resource_by_name def build(): for name in names_registered(): resource = resource_by_name(name)() for explanation in resource: r = explanation for functor in resource.modifiers: if r is None: break ...
Add None check while applying modifiers
Add None check while applying modifiers
Python
mit
hatbot-team/hatbot_resources
766b8564f524c9fcad2d82d08c8ec370532b7411
crm_department/models/crm_department.py
crm_department/models/crm_department.py
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmDepartment(...
# -*- encoding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file in root directory ############################################################################## from openerp import models, fields class CrmDepartment(...
Set some fields as tranlate
Set some fields as tranlate
Python
agpl-3.0
acsone/partner-contact,diagramsoftware/partner-contact,Therp/partner-contact,Endika/partner-contact,open-synergy/partner-contact
e7e8c9aee3b57187e8d239cb28a03125ab488886
fix_data.py
fix_data.py
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key ...
from datetime import datetime, timedelta from functools import wraps import makerbase from makerbase.models import * def for_class(*classes): def do_that(fn): @wraps(fn) def do_for_class(): for cls in classes: keys = cls.get_bucket().get_keys() for key ...
Add data fixers to reindex for search by re-saving everything
Add data fixers to reindex for search by re-saving everything
Python
mit
markpasc/makerbase,markpasc/makerbase
49c99399c5b0e741e356cf320e338d019e06567d
taca/utils/config.py
taca/utils/config.py
"""Load and parse configuration file.""" import yaml from io import open CONFIG = {} def load_config(config_file): """Loads a configuration file.""" config = {} if type(config_file) is file: config.update(yaml.load(config_file, Loader=yaml.FullLoader) or {}) return config else: ...
"""Load and parse configuration file.""" import yaml from io import open CONFIG = {} def load_config(config_file): """Loads a configuration file.""" config = {} try: with open(config_file, 'r') as f: content = yaml.load(f, Loader=yaml.FullLoader) config.update(content) ...
Remove unused file type check
Remove unused file type check
Python
mit
SciLifeLab/TACA,SciLifeLab/TACA,SciLifeLab/TACA
8df58655f5a7a46a781fc0e126b148943a8d5b50
tests/sentry/metrics/test_datadog.py
tests/sentry/metrics/test_datadog.py
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('...
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('...
Remove no longer valid test
Remove no longer valid test
Python
bsd-3-clause
BuildingLink/sentry,mvaled/sentry,jean/sentry,kevinlondon/sentry,imankulov/sentry,mitsuhiko/sentry,nicholasserra/sentry,ifduyue/sentry,gencer/sentry,fotinakis/sentry,mvaled/sentry,alexm92/sentry,alexm92/sentry,kevinlondon/sentry,beeftornado/sentry,looker/sentry,korealerts1/sentry,jean/sentry,beeftornado/sentry,fotinaki...
7dc34b159f837d4fdc71666233f66d340cfd3419
src/info_retrieval/info_retrieval.py
src/info_retrieval/info_retrieval.py
# LING 573 Question Answering System # Code last updated 4/17/14 by Clara Gordon # This code implements an InfoRetriever for the question answering system. from pymur import * from general_classes import * class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collection def...
# LING 573 Question Answering System # Code last updated 4/17/14 by Clara Gordon # This code implements an InfoRetriever for the question answering system. from pymur import * from general_classes import * import sys class InfoRetriever: # builds a QueryEnvironment associated with the indexed document collect...
Add debugging statement to retrieve_passages function
Add debugging statement to retrieve_passages function
Python
mit
amkahn/question-answering,amkahn/question-answering
dc04c35177815ff2aee46088cac7d6790e6831dd
swimlane/core/search/search_result.py
swimlane/core/search/search_result.py
"""This module provides a SearchResults class.""" from types import GeneratorType from ..resources import Record, StatsResult from ..swimlane_dict import SwimlaneDict __metaclass__ = type class SearchResult: """A class that wraps a Swimlane search result.""" def __init__(self, report, resp): """In...
"""This module provides a SearchResults class.""" from types import GeneratorType from ..resources import Record, StatsResult from ..swimlane_dict import SwimlaneDict __metaclass__ = type class SearchResult: """A class that wraps a Swimlane search result.""" def __init__(self, report, resp): """In...
Fix a KeyError that is raised when there are no reuslts
Fix a KeyError that is raised when there are no reuslts
Python
mit
Swimlane/sw-python-client
4eca24ce59e9bffd0b8eb56ed75a16ccf9dfed89
tensorflow_datasets/proto/__init__.py
tensorflow_datasets/proto/__init__.py
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
Fix waymo open dataset proto import.
Fix waymo open dataset proto import. PiperOrigin-RevId: 355350302
Python
apache-2.0
tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets
121c886dfe02ed8cd71075a03e268d51bcb137fc
institutions/respondants/search_indexes.py
institutions/respondants/search_indexes.py
from haystack import indexes from respondants.models import Institution class InstitutionIndex(indexes.SearchIndex, indexes.Indexable): """Search Index associated with an institution. Allows for searching by name or lender id""" text = indexes.CharField(document=True, model_attr='name') text_auto = i...
from haystack import indexes from respondants.models import Institution class InstitutionIndex(indexes.SearchIndex, indexes.Indexable): """Search Index associated with an institution. Allows for searching by name or lender id""" text = indexes.CharField(document=True, model_attr='name') text_auto = i...
Revert "adding 2013 to search query"
Revert "adding 2013 to search query"
Python
cc0-1.0
mehtadev17/mapusaurus,mehtadev17/mapusaurus,mehtadev17/mapusaurus
09f429e76a7b2cd49ea66b70d314bb4510971a5f
gui.py
gui.py
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="") win = MainWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main()
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk class MainWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Text Playing Game") self.set_border_width(10) self.set_size_request(500, 400) win = MainWindow() win.connect("delete-event", Gtk.ma...
Set GUI title and size
Set GUI title and size
Python
mit
Giovanni21M/Text-Playing-Game
c1e5c98995898148396d5a3d19cd6f390aa681de
is_irred.py
is_irred.py
# tests to determine whether a polynomial is irreducible over a finite field import numpy def eisenstein(poly, p): """ returns true if poly is irreducible by Eisenstein's sufficient condition: p is prime p does not divide the leading coefficient p divides every other coefficient p squared doe...
# tests to determine whether a polynomial is irreducible over Q[x] from fractions import Fraction import numpy def is_prime(num): """ return True if num is a prime :param num: int :return: Bool """ return True def rational_root(poly): """ rational root test :param poly: numpy.po...
Add rational root test stub
Add rational root test stub
Python
mit
richardmillson/galois
26bd5e00cf30446860438cc5796ec348aecf7e2b
product_configurator/models/stock.py
product_configurator/models/stock.py
# -*- coding: utf-8 -*- from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' product_id = fields.Many2one(domain=[('config_ok', '=', False)])
# -*- coding: utf-8 -*- from ast import literal_eval from odoo import models, fields class StockMove(models.Model): _inherit = 'stock.move' def _get_product_domain(self): if literal_eval(self.env['ir.config_parameter'].sudo().get_param('product_configurator.product_selectable', default='False')): ...
Put configurable product in Picking list
Put configurable product in Picking list
Python
agpl-3.0
microcom/odoo-product-configurator,microcom/odoo-product-configurator,microcom/odoo-product-configurator
311989f227278ce9d433ab2852b50ffcdee188d6
npc.py
npc.py
#!/usr/bin/env python3.5 import npc import sys if __name__ == '__main__': npc.cli(sys.argv[1:])
#!/usr/bin/env python3.5 """ Executable entry point for the NPC CLI interface. """ import sys import npc if __name__ == '__main__': npc.cli(sys.argv[1:])
Add module docstring and reorder imports
Add module docstring and reorder imports
Python
mit
aurule/npc,aurule/npc
9825d76b6bff7e04d1e277539ece6bda928b648b
wtl/wtlib/forms.py
wtl/wtlib/forms.py
from django import forms from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): worker = GithubWorker() self.repository, self.project = worker.analyze_repo(self.cleaned_data['git_url']) return self.repository, self.p...
from django import forms from django.forms.util import ErrorList from django.utils.translation import ugettext_lazy as _ from github import UnknownObjectException from wtl.wtgithub.worker import GithubWorker class AnalyzeForm(forms.Form): git_url = forms.CharField() def analyze(self): if 'git_url' n...
Validate repo exists in `AnalyzeForm`
Validate repo exists in `AnalyzeForm`
Python
mit
elegion/djangodash2013,elegion/djangodash2013
43135538ac08a6a64ae8da935e188224999a1a16
indy_node/server/validator_info_tool.py
indy_node/server/validator_info_tool.py
import importlib from indy_node.__metadata__ import __version__ as node_pgk_version from plenum.server.validator_info_tool import none_on_fail, \ ValidatorNodeInfoTool as PlenumValidatorNodeInfoTool class ValidatorNodeInfoTool(PlenumValidatorNodeInfoTool): @property def info(self): info = super(...
import importlib from indy_node.__metadata__ import __version__ as node_pgk_version from plenum.server.validator_info_tool import none_on_fail, \ ValidatorNodeInfoTool as PlenumValidatorNodeInfoTool class ValidatorNodeInfoTool(PlenumValidatorNodeInfoTool): @property def info(self): info = super(...
Add new dict format into node validator-info
[INDY-1175] Add new dict format into node validator-info Signed-off-by: Andrew Nikitin <3988702a677b83abef1980fca266e406bb150845@dsr-corporation.com>
Python
apache-2.0
spivachuk/sovrin-node,spivachuk/sovrin-node,spivachuk/sovrin-node,spivachuk/sovrin-node
5b9024ea424abe6494f6e26f72f7838c189eea3c
kuryr/common/exceptions.py
kuryr/common/exceptions.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# 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 t...
Modify KuryrException extend Exception appropriately
Modify KuryrException extend Exception appropriately This patch modifies KuryrException call the initializer of the super class. This fixes Kuryr not to return the empty error response. Change-Id: I728a24df6f20a81090c98aac46be22f3d27cd884 Signed-off-by: Taku Fukushima <d385cb54d860d8a5dcc6157b54cf213091772451@gmail.c...
Python
apache-2.0
midonet/kuryr,celebdor/kuryr-libnetwork,celebdor/kuryr,celebdor/kuryr-libnetwork,celebdor/kuryr,openstack/kuryr,openstack/kuryr,midonet/kuryr,celebdor/kuryr-libnetwork,midonet/kuryr
ea287349360f6102369df3bdc8efb64a684a95ca
program/templatetags/timeslots.py
program/templatetags/timeslots.py
from django import template from datetime import datetime, time, timedelta register = template.Library() @register.simple_tag def height(start, end): if start.year == 2020 and int(start.strftime('%V')) >= 5 and start.hour == 12 and start.minute == 0: return '30' else: return '%d' % ((end - s...
from django import template from datetime import datetime, time, timedelta register = template.Library() @register.simple_tag def height(start, end): if start.year == 2020 and int(start.strftime('%V')) >= 5 and start.hour == 12 and start.minute == 0: if end.minute == 5: return '30' r...
Add exception to to return extended height of the show
Add exception to to return extended height of the show
Python
unknown
radio-helsinki-graz/pv,radio-helsinki-graz/pv,nnrcschmdt/helsinki,radio-helsinki-graz/pv,nnrcschmdt/helsinki,nnrcschmdt/helsinki
aa6e5e93406cc614d1935f0ee61f28dbc955c2c0
forms.py
forms.py
from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import StringField, IntegerField, SelectField, BooleanField csrf = CsrfProtect() class Submission(Form): submission = StringField('Submission URL') comments = BooleanField('Include comments') comments_style = SelectField('Comm...
from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import StringField, IntegerField, SelectField, BooleanField csrf = CsrfProtect() class Submission(Form): submission = StringField('Submission URL') comments = BooleanField('Include comments') comments_style = SelectField('Comm...
Make numbers the default comments style
Make numbers the default comments style
Python
mit
JamieMagee/reddit2kindle,JamieMagee/reddit2kindle
e3bbaf9421bdc5e0ac538c57a9821b5dba0382ef
dataviva/apps/title/models.py
dataviva/apps/title/models.py
from dataviva import db class GraphTitle(db.Model): __tablename__ = 'graph_title' id = db.Column(db.Integer, primary_key=True) title_en = db.Column(db.String(255)) subtitle_en = db.Column(db.String(255)) title_pt = db.Column(db.String(255)) subtitle_pt = db.Column(db.String(255)) dataset =...
from dataviva import db class GraphTitle(db.Model): __tablename__ = 'graph_title' id = db.Column(db.Integer, primary_key=True) title_en = db.Column(db.String(255)) subtitle_en = db.Column(db.String(255)) title_pt = db.Column(db.String(255)) subtitle_pt = db.Column(db.String(255)) dataset =...
Add column to title model
Add column to title model
Python
mit
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
2f055184a3832d4a44b151f6c3caf4089e80aa6d
devicehive/device_hive_api.py
devicehive/device_hive_api.py
from devicehive.handler import Handler from devicehive.device_hive import DeviceHive class ApiCallHandler(Handler): """Api call handler class.""" def __init__(self, api, call, *call_args, **call_kwargs): super(ApiCallHandler, self).__init__(api) self._call = call self._call_args = cal...
from devicehive.handler import Handler from devicehive.device_hive import DeviceHive class ApiCallHandler(Handler): """Api call handler class.""" def __init__(self, api, call, *call_args, **call_kwargs): super(ApiCallHandler, self).__init__(api) self._call = call self._call_args = cal...
Add get_property, set_property and delete_property functions
Add get_property, set_property and delete_property functions
Python
apache-2.0
devicehive/devicehive-python
e435832edccd3444a90763386d8c81ab9f595cf7
tests/test_cli_search.py
tests/test_cli_search.py
# -*- coding: utf-8 -*- import pathlib import json import pytest @pytest.fixture def templates_file(): return 'tests/templates.json' def scenarios(): yield ['django', 'docker'], ['cookiecutter-django'] yield ['pytest'], [ 'cookiecutter-pylibrary', 'cookiecutter-pypackage', 'co...
# -*- coding: utf-8 -*- import pathlib import json import pytest @pytest.fixture def templates_file(): return 'tests/templates.json' def scenarios(): yield ['django', 'docker'], ['cookiecutter-django'] yield ['pytest'], [ 'cookiecutter-pylibrary', 'cookiecutter-pypackage', 'co...
Implement a search test for when there is no matching template
Implement a search test for when there is no matching template
Python
bsd-3-clause
hackebrot/cibopath
debcec2e64e85aafec3a11860042401e9d9955a7
metafunctions/tests/test_star.py
metafunctions/tests/test_star.py
from metafunctions.util import node, star from metafunctions.tests.util import BaseTestCase class TestUnit(BaseTestCase): def test_simple_star(self): @node def f(*args): return args cmp = (a | b) | star(f) self.assertEqual(cmp('_'), ('_', 'a', 'b')) def test_str_r...
from metafunctions.util import node, star from metafunctions.tests.util import BaseTestCase class TestUnit(BaseTestCase): def test_simple_star(self): @node def f(*args): return args cmp = (a | b) | star(f) self.assertEqual(cmp('_'), ('_', 'a', 'b')) def test_str_r...
Add more expected star str
Add more expected star str
Python
mit
ForeverWintr/metafunctions
1cff4ec8cdac7253be979936a1b06c5bc8264195
misc/sample_project/ser/snake.py
misc/sample_project/ser/snake.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals __all__ = ('is_snake',) def is_snake(word): if not word.isalpha(): raise ValueError("String '{}' is not a word") if word.lower() == 'python': return True if word.lower() == 'питон': return True return False de...
# -*- coding: utf-8 -*- from __future__ import unicode_literals __all__ = ('is_snake',) def is_snake(word): """Checks if an animal is a snake Parameters ---------- word : str Animal name Returns ------- bool Example ------- Check if a bear is a snake >>> from...
Add doctest to the sample project
Add doctest to the sample project
Python
mit
hombit/scientific_python,hombit/scientific_python,hombit/scientific_python,hombit/scientific_python,hombit/scientific_python
57cc05d5cf61779994656aaacc53f8fcccc25ca3
ade25/assetmanager/tool.py
ade25/assetmanager/tool.py
# -*- coding: utf-8 -*- """Module providing an image asset asignment factory.""" class AssetAssignmentTool(object): """ Factory providing CRUD oparations for project assets """
# -*- coding: utf-8 -*- """Module providing an image asset asignment factory.""" import json import time from plone import api from Products.CMFPlone.utils import safe_unicode from zope.lifecycleevent import modified class AssetAssignmentTool(object): """ Factory providing CRUD oparations for project assets """ ...
Move create method as example implementation
Move create method as example implementation Copy method/function from exusting tool integration for reference concerning the layout of the json object
Python
mit
ade25/ade25.assetmanager
7f396cfd88fd08466db2f9cd77bf40e91345d2a2
nodeconductor/core/authentication.py
nodeconductor/core/authentication.py
from __future__ import unicode_literals import nodeconductor.logging.middleware import rest_framework.authentication def user_capturing_auth(auth): class CapturingAuthentication(auth): def authenticate(self, request): result = super(CapturingAuthentication, self).authenticate(request) ...
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ import rest_framework.authentication from rest_framework import exceptions import nodeconductor.logging.middleware TOKEN_KEY = 'x-auth-token' class TokenAuthentication(rest_framework.authentication.TokenAuthentication)...
Use get parameter in token auth (nc-544)
Use get parameter in token auth (nc-544)
Python
mit
opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor
2c204e02607e75d0cfb696a1dfbaa1b7997fbb55
sections/transportation/ferrys.py
sections/transportation/ferrys.py
# from . import has_required_data_maker, obtain_data_maker PATH = 'ferry_paths.json' def has_required_data(data_dir): return False # def obtain_data(data_dir): # with open(join(data_dir, PATH), 'w') as fh: # json.dump(get_paths(['Railways']).tolist(), fh)
import requests from ..image_provider import ImageProvider PATH = 'ferry_paths.json' BASE = 'http://journeyplanner.silverrailtech.com/JourneyPlannerService/V2' DATASET = 'PerthRestricted' class FerryImageProvider(ImageProvider): def has_required_data(self): return self.data_dir_exists(PATH) def obt...
Work on ferry routes display
Work on ferry routes display Will either need to pull data from google, or aggregate if we want to do all those in australia
Python
mit
Mause/statistical_atlas_of_au
ff23541ce41bb20f5f535026238d8dd879e8a894
drf_enum_field/fields.py
drf_enum_field/fields.py
from rest_framework.fields import ChoiceField class EnumField(ChoiceField): default_error_messages = { 'invalid': ("No matching enum type.",) } def __init__(self, **kwargs): self.enum_type = kwargs.pop("enum_type") kwargs.pop("choices", None) super(EnumField, self).__init_...
from django.utils.translation import ugettext_lazy as _ from rest_framework.fields import ChoiceField class EnumField(ChoiceField): default_error_messages = { 'invalid': _("No matching enum type.") } def __init__(self, **kwargs): self.enum_type = kwargs.pop("enum_type") kwargs.pop...
Return translation instead of tuple
Return translation instead of tuple Fixes Attributerror: 'tuple' object has no attribute 'format' when POSTing with no value for an Enum field.
Python
mit
seebass/drf-enum-field
3814db4e512fb0822b455afc77566e526a3a6afe
examples/example_helper.py
examples/example_helper.py
import json import os import shutil from scipy_data_fitting import Plot def save_example_fit(fit): """ Save fit result to a json file and a plot to an svg file. """ json_directory = os.path.join('examples', 'json') plot_directory = os.path.join('examples', 'plots') if not os.path.isdir(json_dir...
import json import os import shutil import sys sys.path.insert(0, os.path.abspath('.')) from scipy_data_fitting import Plot def save_example_fit(fit): """ Save fit result to a json file and a plot to an svg file. """ json_directory = os.path.join('examples', 'json') plot_directory = os.path.join(...
Fix examples by adding package to path
Fix examples by adding package to path
Python
mit
razor-x/scipy-data_fitting
0056d2e4667810af45a820e6b8893c49e2f1cf49
salt/utils/verify.py
salt/utils/verify.py
''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <jeffschroeder@computer.org> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = zmq.__version__...
''' A few checks to make sure the environment is sane ''' # Original Author: Jeff Schroeder <jeffschroeder@computer.org> import logging log = logging.getLogger(__name__) __all__ = ('zmq_version', 'check_root', 'run') def zmq_version(): '''ZeroMQ python bindings >= 2.1.9 are required''' import zmq ver = z...
Make check_root use proper logging and exit cleanly
Make check_root use proper logging and exit cleanly
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
476c97edf8489be59d5e96ce36aa9214ae4ca00c
run_tracker.py
run_tracker.py
import sys, json from cloudtracker import main as tracker_main def run_tracker(input): print( " Running the cloud-tracking algorithm... " ) print( " Input dir: \"" + input + "\" \n" ) # Read .json configuration file with open('model_config.json', 'r') as json_file: config = json.load(json...
import sys, json from cloudtracker.main import main from cloudtracker.load_config import config from cloudtracker.load_config import c def run_tracker(): print( " Running the cloud-tracking algorithm... " ) # Print out model parameters from config.json print( " \n Model parameters: " ) print( " ...
Read model parameters and output at the beginning
Read model parameters and output at the beginning
Python
bsd-2-clause
lorenghoh/loh_tracker
f312b856046cb46255971bcd30b8c418d7040455
__openerp__.py
__openerp__.py
# -*- coding: utf-8 -*- { 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ ...
# -*- coding: utf-8 -*- { 'name': 'Human Employee Streamline', 'version': '1.2', 'author': 'XCG Consulting', 'category': 'Human Resources', 'description': """ enchancements to the hr module to streamline its usage """, 'website': 'http://www.openerp-experts.com', 'depends': [ ...
Add dependencies on hr_contract as it should have been done
Add dependencies on hr_contract as it should have been done
Python
agpl-3.0
xcgd/hr_streamline
206c687570233c4d71063f1c688c25bbbd9847ab
tests/test_system.py
tests/test_system.py
import datetime from decimal import Decimal from mock import Mock import ubersmith.order # TODO: setup/teardown module with default request handler # TODO: mock out requests library vs mocking out request handler def test_order_list(): handler = Mock() response = { "60": { "client_id": ...
import datetime from decimal import Decimal import json from mock import Mock import ubersmith import ubersmith.api import ubersmith.order def setup_module(): ubersmith.init(**{ 'base_url': '', 'username': '', 'password': '', }) def teardown_module(): ubersmith.api._DEFAULT_REQ...
Refactor system tests to mock out requests library vs mocking out request handler.
Refactor system tests to mock out requests library vs mocking out request handler.
Python
mit
jasonkeene/python-ubersmith,hivelocity/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith
254a1a0b0c438c0f913b80af16b96fc54b3a58bd
app/tests/test_fixtures.py
app/tests/test_fixtures.py
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ from flask import Flask # type: ignore def test_simple_app(app): """Verify basic application.""" assert isinstance(app, Flask) def test_simple_config(config): """Verify basic application configuration.""" assert isinstan...
""" Test fixtures. :copyright: (c) 2017 Derek M. Frank :license: MPL-2.0 """ from flask import Flask # type: ignore def test_simple_app(app): """Verify basic application.""" assert isinstance(app, Flask) def test_simple_config(config): """Verify basic application configuration.""" assert isinstan...
Merge fixture tests to reduce live servers and time
refactor(app-tests): Merge fixture tests to reduce live servers and time
Python
mpl-2.0
defrank/roshi
0da7c7931f7abc8775087aab5054cfea63120f60
scripts/dumpcmaps.py
scripts/dumpcmaps.py
import numpy as np import Image def makeImage(cmap, fname): cmarr = (cmap*255).astype(np.uint8) im = Image.fromarray(cmarr[np.newaxis]) im.save(fname) def cmList(additional): cmaps = {} values = np.linspace(0, 1, 256) from matplotlib import cm, colors for cmname in dir(cm): cmap = ...
import numpy as np import Image import scipy.io as sio def makeImage(cmap, fname): cmarr = (cmap*255).astype(np.uint8) im = Image.fromarray(cmarr[np.newaxis]) im.save(fname) def cmList(additional): cmaps = {} values = np.linspace(0, 1, 256) from matplotlib import cm, colors for cmname in d...
Add all the J* colormaps
Add all the J* colormaps
Python
bsd-2-clause
gallantlab/pycortex,smerdis/pycortex,smerdis/pycortex,CVML/pycortex,gallantlab/pycortex,CVML/pycortex,smerdis/pycortex,CVML/pycortex,CVML/pycortex,CVML/pycortex,gallantlab/pycortex,smerdis/pycortex,smerdis/pycortex,gallantlab/pycortex,gallantlab/pycortex
b470cb1825f5d54ff4a48875a216dbb0cdf44eb7
apps/innovate/tests/test_views.py
apps/innovate/tests/test_views.py
from django.core.urlresolvers import reverse from django.test import Client from projects.models import Project from innovate import urls def test_routes(): c = Client() for pattern in urls.urlpatterns: response = c.get(reverse(pattern.name)) assert response.status_code == 301 assert ...
from django.core.urlresolvers import reverse from django.test import Client from django.test.client import RequestFactory from projects.models import Project from innovate import urls from innovate.views import handle404, handle500 def test_routes(): c = Client() for pattern in urls.urlpatterns: resp...
Add tests for the 404 and 500 error handlers.
Add tests for the 404 and 500 error handlers.
Python
bsd-3-clause
mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm
307a125dc21e31fdf06862dafb30f8283db6c8a2
python/custom_type.py
python/custom_type.py
import math class Circle: def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius * self.radius c = Circle(10) assert(type(c) == Circle) assert(type(Circle) == type) assert(str(type(Circle.area)) == "<class 'function'>") assert(str(type(c.area)) == "<cla...
import math class Circle: def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius * self.radius c = Circle(10) assert(type(c) == Circle) # Circle is a type! assert(type(Circle) == type) # It really is! assert(str(type(Circle.area)) == ...
Tidy up Python class example
Tidy up Python class example
Python
mit
rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal...
2e1b189727616b4c93ad4244299530c738304428
httpobs/scanner/utils.py
httpobs/scanner/utils.py
import socket import tld def valid_hostname(hostname: str) -> bool: """ :param hostname: The hostname requested in the scan :return: True if it's a valid hostname (fqdn in DNS that's not an IP address), False otherwise """ # First, let's try to see if it's an IPv4 address try: soc...
import socket def valid_hostname(hostname: str): """ :param hostname: The hostname requested in the scan :return: Hostname if it's valid, otherwise None """ # First, let's try to see if it's an IPv4 address try: socket.inet_aton(hostname) # inet_aton() will throw an exception if ...
Remove TLD check, allow for www
Remove TLD check, allow for www
Python
mpl-2.0
april/http-observatory,april/http-observatory,april/http-observatory,mozilla/http-observatory,mozilla/http-observatory,mozilla/http-observatory
2b48e786c3e2439876ff41fc82bd814b42d40ca4
app.py
app.py
from flask import Flask import socket app = Flask(__name__) @app.route("/") def index(): return "Hello from FLASK. My Hostname is: %s \n" % (socket.gethostname()) if __name__ == "__main__": app.run(host='0.0.0.0')
#!/usr/bin/env python from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello from FLASK" if __name__ == "__main__": app.run(host='0.0.0.0')
Revert "Added the output for hostname"
Revert "Added the output for hostname" This reverts commit 490fa2d10d8a61ede28b794ed446e569f2f30318.
Python
bsd-2-clause
vioan/minflask
c7a424cb3fb0a037cda04c30d44606515aed829d
chrome/test/functional/test_pyauto.py
chrome/test/functional/test_pyauto.py
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest import pyauto_functional # Must be imported before pyauto import pyauto class PyAutoTest(pyauto.PyUITest): ""...
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest import pyauto_functional # Must be imported before pyauto import pyauto class PyAutoTest(pyauto.PyUITest): ""...
Update testSetCustomChromeFlags to only append to chrome flags, not override
Update testSetCustomChromeFlags to only append to chrome flags, not override This is in keeping with the spirit of the ExtraChromeFlags() method. Whenever it's overridden, it should only ever append to the list of chrome flags, never completely override it. BUG=None TEST=None R=dennisjeffrey@chromium.org Review URL...
Python
bsd-3-clause
Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,keishi/chromium,jaruba/chromium.src,junmin-zhu...
e28f0accf06462ba365151de571d3d781e62fa9a
skylines/__init__.py
skylines/__init__.py
from flask import Flask from flask.ext.babel import Babel from flask.ext.assets import Environment def create_app(): app = Flask(__name__, static_folder='public') babel = Babel(app) assets = Environment(app) return app app = create_app() import skylines.views
from flask import Flask from flask.ext.babel import Babel from flask.ext.assets import Environment from webassets.loaders import PythonLoader def create_app(): app = Flask(__name__, static_folder='public') babel = Babel(app) bundles = PythonLoader('skylines.assets.bundles').load_bundles() assets = En...
Load asset bundles into webassets environment
flask: Load asset bundles into webassets environment
Python
agpl-3.0
Turbo87/skylines,snip/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,kerel-fs/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,TobiasLohner/SkyLines,RBE-Avionik/skylines,TobiasLohner/SkyLines,Turbo87/skylines,kerel-fs/skylines,snip/skylines,Turbo87/skylines,snip/skylines,Harry-R/skylines,RBE-Avionik...
ae3d07788bb5f95127d83c837976e46d369f0629
salt/runners/state.py
salt/runners/state.py
''' Execute overstate functions ''' # Import salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) for...
''' Execute overstate functions ''' # Import salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' stage_num = 0 overstate = salt.overstate.OverState(__opts__, e...
Make output data cleaner on the eyes :)
Make output data cleaner on the eyes :)
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
38a4629e034f00c65979910109b34499c077687b
plasmapy/utils/import_helpers.py
plasmapy/utils/import_helpers.py
import importlib import warnings from distutils.version import LooseVersion def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for ...
import importlib import warnings import distutils.version as dv def check_versions(minimum_versions): """Raises an ImportError if a dependent package is not installed and at the required version number, or provides a warning if the version of the dependent package cannot be found.""" for module_name i...
Make namespaces more clear in input_helpers.py
Make namespaces more clear in input_helpers.py
Python
bsd-3-clause
StanczakDominik/PlasmaPy