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
cc71d25b85d991801f2dc980ad37aa7bdbe7e2f3
ocradmin/lib/nodetree/registry.py
ocradmin/lib/nodetree/registry.py
""" Registry class and global node registry. """ import inspect class NotRegistered(KeyError): pass class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node class in the node registry.""" self[node.name] = inspect.isclass(node) and node or nod...
""" Registry class and global node registry. This class was adapted from the Celery Project's task registry. """ import inspect class NotRegistered(KeyError): pass class NodeRegistry(dict): NotRegistered = NotRegistered def register(self, node): """Register a node class in the node registry.""...
Add a note acknowledging the source of this class
Add a note acknowledging the source of this class
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
279a7dfcdd854999d490164da3dc3790430e639a
membership/management/commands/public_memberlist.py
membership/management/commands/public_memberlist.py
# -*- encoding: utf-8 -*- from django.db.models import Q from django.core.management.base import NoArgsCommand from django.template.loader import render_to_string from django.conf import settings from membership.models import * from membership.public_memberlist import public_memberlist_data class Command(NoArgsComma...
# -*- encoding: utf-8 -*- from django.db.models import Q from django.core.management.base import NoArgsCommand from django.template.loader import render_to_string from django.conf import settings from membership.models import * from membership.public_memberlist import public_memberlist_data class Command(NoArgsComma...
Fix UnicodeDecodeError: Return text string, not bytes
Fix UnicodeDecodeError: Return text string, not bytes
Python
mit
kapsiry/sikteeri,AriMartti/sikteeri,kapsiry/sikteeri,kapsiry/sikteeri,annttu/sikteeri,joneskoo/sikteeri,annttu/sikteeri,AriMartti/sikteeri,kapsiry/sikteeri,joneskoo/sikteeri,AriMartti/sikteeri,annttu/sikteeri,joneskoo/sikteeri,annttu/sikteeri,AriMartti/sikteeri,joneskoo/sikteeri
763939db37e3b9f93f1201aada4e893bbe478249
17-createWallOfWoolWithRandomColour.py
17-createWallOfWoolWithRandomColour.py
#import the needed modules fo communication with minecraft world from mcpi.minecraft import * # import needed block defintiions from mcpi.block import * # needed to slow down the wall building from time import sleep # needed to generate a random number for the colour of wool from random import randint if __name__ == "...
#import the needed modules fo communication with minecraft world from mcpi.minecraft import * # import needed block defintiions from mcpi.block import WOOL # needed to slow down the wall building from time import sleep # needed to generate a random number for the colour of wool from random import randint # create a fu...
Change to use function for block generation
Change to use function for block generation Use a separate function for random block generation move code from loop to the function
Python
bsd-3-clause
hashbangstudio/Python-Minecraft-Examples
1b95969110f97af397cb3314b59c30679911da48
scripts/scrape-cdc-state-case-counts.py
scripts/scrape-cdc-state-case-counts.py
#!/usr/bin/env python import requests import lxml.html import pandas as pd import sys URL = "http://www.cdc.gov/zika/geo/united-states.html" INT_COLS = [ "travel_associated_cases", "locally_acquired_cases" ] COLS = [ "state_or_territory" ] + INT_COLS def scrape(): html = requests.get(URL).content dom = lxml....
#!/usr/bin/env python import requests import lxml.html import pandas as pd import re import sys URL = "http://www.cdc.gov/zika/geo/united-states.html" INT_COLS = [ "travel_associated_cases", "locally_acquired_cases" ] COLS = [ "state_or_territory" ] + INT_COLS paren_pat = re.compile(r"\([^\)]+\)") def parse_cell(t...
Update CDC scraper to handle new format
Update CDC scraper to handle new format
Python
mit
BuzzFeedNews/zika-data
697d30430fa908c6e2baf88285f0a464993d6636
formapi/compat.py
formapi/compat.py
# coding=utf-8 # flake8: noqa import sys if sys.version_info[0] == 3: from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u # noinspection PyUnresolvedReferences from urllib.parse import quote ifilter = filter b_str = bytes u_str = str iterite...
# coding=utf-8 # flake8: noqa import sys if sys.version_info[0] == 3: from django.utils.encoding import smart_bytes as smart_b, force_str as force_u, smart_text as smart_u # noinspection PyUnresolvedReferences from urllib.parse import quote ifilter = filter b_str = bytes u_str = str iterite...
Fix smart_u for Django 1.3
Fix smart_u for Django 1.3
Python
mit
5monkeys/django-formapi,andreif/django-formapi,5monkeys/django-formapi,andreif/django-formapi
d3e13351c514581a5460097624f82aa696398f78
iamhhb/views.py
iamhhb/views.py
from django.shortcuts import render from django.contrib import admin, auth # We don't need a user management admin.site.unregister(auth.models.User) admin.site.unregister(auth.models.Group) def index(request): return render(request, 'index.html') def about_me(request): return render(request, 'about-me.html...
from django.shortcuts import render from django.contrib import admin, auth # We don't need a user management admin.site.unregister(auth.models.User) admin.site.unregister(auth.models.Group) def index(request): return render(request, 'index.html') def about_me(request): return render(request, 'about-me.html...
Add travis-ci to `powerd by` page.
Add travis-ci to `powerd by` page.
Python
mit
graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb,graycarl/iamhhb
b011ccf5c4ce5f93c7b02f938385432325012569
tt/core/tt.py
tt/core/tt.py
# Here we import all necessary staff from external files # tools from .tools import matvec, col, kron, dot, mkron, concatenate, sum, reshape from .tools import eye, diag, Toeplitz, qshift, qlaplace_dd, IpaS from .tools import ones, rand, linspace, sin, cos, delta, stepfun, unit, xfun # main classes from .matrix impor...
# Here we import all necessary staff from external files # main classes from .matrix import matrix from .vector import vector, tensor # tools from .tools import matvec, col, kron, dot, mkron, concatenate, sum, reshape from .tools import eye, diag, Toeplitz, qshift, qlaplace_dd, IpaS from .tools import ones, rand, li...
Revert "Import order changed to break tools dependency"
Revert "Import order changed to break tools dependency" This reverts commit 3a75fd530b1ecb9e6466ac99532d06032ae3a049.
Python
mit
uranix/ttpy,uranix/ttpy
59fb7b9d1078a7b0199b9613a523f3d2fce80c13
pombola_sayit/models.py
pombola_sayit/models.py
from django.db import models from pombola.core.models import Person from speeches.models import Speaker from south.modelsinspector import add_introspection_rules add_introspection_rules([], ["^instances\.fields\.DNSLabelField"]) class PombolaSayItJoin(models.Model): """This model provides a join table between ...
from django.db import models from pombola.core.models import Person from speeches.models import Speaker class PombolaSayItJoin(models.Model): """This model provides a join table between Pombola and SsayIt people""" pombola_person = models.OneToOneField(Person, related_name='sayit_link') sayit_speaker =...
Remove the last reference to South - it can be pip uninstalled now
Remove the last reference to South - it can be pip uninstalled now
Python
agpl-3.0
mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola
e73e237a5c712aea9866168c8bb0fb7c56c21d90
gpytorch/kernels/white_noise_kernel.py
gpytorch/kernels/white_noise_kernel.py
import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): super(WhiteNoiseKernel, self).__init__() self.register_buffer("variances", variances) def forward(self, x1, x2): if self.traini...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import torch from . import Kernel from gpytorch.lazy import DiagLazyVariable, ZeroLazyVariable class WhiteNoiseKernel(Kernel): def __init__(self, variances): ...
Add missing py2py3 compatibility imports
Add missing py2py3 compatibility imports
Python
mit
jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch
20d7c4113a96c92f8353761da2c2a00ed7a35e0e
gym_ple/__init__.py
gym_ple/__init__.py
from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( ...
from gym.envs.registration import registry, register, make, spec from gym_ple.ple_env import PLEEnv # Pygame # ---------------------------------------- for game in ['Catcher', 'MonsterKong', 'FlappyBird', 'PixelCopter', 'PuckWorld', 'RaycastMaze', 'Snake', 'WaterWorld']: nondeterministic = False register( ...
Replace the timestep_limit call with the new tags api.
Replace the timestep_limit call with the new tags api.
Python
mit
lusob/gym-ple
8aceb4bcfeef05874bbd6eec66eeb7b69f20f02e
pinax/blog/templatetags/pinax_blog_tags.py
pinax/blog/templatetags/pinax_blog_tags.py
from django import template from ..models import Post, Section register = template.Library() @register.assignment_tag def latest_blog_posts(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(scoper=scoper) return qs[:5] @register.assignment_tag def latest_blog_post(scoper=Non...
from django import template from ..models import Post, Section register = template.Library() @register.assignment_tag def latest_blog_posts(scoper=None): qs = Post.objects.current() if scoper: qs = qs.filter(blog__scoper=scoper) return qs[:5] @register.assignment_tag def latest_blog_post(scop...
Fix small bug in templatetags
Fix small bug in templatetags
Python
mit
pinax/pinax-blog,pinax/pinax-blog,pinax/pinax-blog
ac6c9f4ad35a8c2c8ede616366b50995afff6992
hurricane/runner.py
hurricane/runner.py
#!/usr/bin/env python import multiprocessing import optparse from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_stopped def run(self): parser = optparse.Op...
#!/usr/bin/env python import multiprocessing import optparse from django.conf import settings as django_settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from hurricane.utils import run_until_stopped class ApplicationManager(object): @run_until_sto...
Configure django correctly when we setup our env
Configure django correctly when we setup our env
Python
bsd-3-clause
ericflo/hurricane,ericflo/hurricane
119025b231b0f3b9077445334fc08d1ad076abfc
generic_links/migrations/0001_initial.py
generic_links/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('contenttypes', '__first__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] o...
Remove Django 1.8 dependency in initial migration
Remove Django 1.8 dependency in initial migration The ('contenttypes', '0002_remove_content_type_name') migration was part of Django 1.8, replacing it with '__first__' allows the use of Django 1.7
Python
bsd-3-clause
matagus/django-generic-links,matagus/django-generic-links
c7941340336b3fe584dd192583c088eb1f1f972e
genomic_neuralnet/common/celeryconfig.py
genomic_neuralnet/common/celeryconfig.py
# Wait up to 15 minutes for each iteration. BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickle']
# Wait up to 15 minutes for each iteration. BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 60*60} # 60*60 Seconds = 1 hour. # Do not pre-fetch work. CELERYD_PREFETCH_MULTIPLIER = 1 # Do not ack messages until work is completed. CELERY_ACKS_LATE = True # Stop warning me about PICKLE. CELERY_ACCEPT_CONTENT = ['pickl...
Reduce result broker message timeout
Reduce result broker message timeout
Python
mit
rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet,rileymcdowell/genomic-neuralnet
2ae6974ee04a9c5d39ad18788fe14a432994f6bd
zou/event_stream.py
zou/event_stream.py
import os from flask import Flask from flask_sse import sse app = Flask(__name__) app.config["REDIS_URL"] = os.environ.get( "REDIS_URL", "redis://localhost/2" ) app.register_blueprint(sse, url_prefix='/events')
import os from flask import Flask from flask_sse import sse app = Flask(__name__) redis_host = os.environ.get("KV_HOST", "localhost") redis_port = os.environ.get("KV_PORT", "5379") redis_url = "redis://%s:%s/2" % (redis_host, redis_port) app.config["REDIS_URL"] = redis_url app.register_blueprint(sse, url_prefix='/...
Use right env variable to build redis url
Use right env variable to build redis url It is for the events stream daemon.
Python
agpl-3.0
cgwire/zou
8ffe293135c6ee80f185b6f6a8d6e9f096adc91c
knights/k_tags.py
knights/k_tags.py
import ast from .library import Library register = Library() @register.tag(name='block') def block(parser, token): token = token.strip() parser.build_method(token, endnodes=['endblock']) return ast.YieldFrom( value=ast.Call( func=ast.Attribute( value=ast.Name(id='sel...
import ast from .library import Library register = Library() @register.tag(name='block') def block(parser, token): token = token.strip() parser.build_method(token, endnodes=['endblock']) return ast.Expr(value=ast.YieldFrom( value=ast.Call( func=ast.Attribute( value=a...
Use ast.If not ast.IfExp for if tag
Use ast.If not ast.IfExp for if tag
Python
mit
funkybob/knights-templater,funkybob/knights-templater
22112e164005fcbf2c79a5f307d1e587d9146c95
store/admin.py
store/admin.py
from django.contrib import admin from .models import Image, Product, Review, Specification class ImageInline(admin.StackedInline): model = Image class SpecificationInline(admin.StackedInline): model = Specification class ProductAdmin(admin.ModelAdmin): list_display = ( 'name', 'price'...
from django.contrib import admin from .models import Image, Product, Review, Specification class ImageInline(admin.StackedInline): model = Image class SpecificationInline(admin.StackedInline): model = Specification class ProductAdmin(admin.ModelAdmin): list_display = ( 'name', 'price'...
Add featured field to ProductAdmin
Add featured field to ProductAdmin
Python
bsd-3-clause
kevgathuku/compshop,andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop
cf19d5a52237e6098dedc3c0bbfdaa3aedd180e0
loginza/models.py
loginza/models.py
from django.contrib.auth.models import User from django.db import models from django.utils import simplejson as json from .signals import post_associate class IdentityManager(models.Manager): def from_loginza_data(self, loginza_data): data = json.dumps(loginza_data) identity, created = self.get_...
from django.contrib.auth.models import User from django.db import models from django.utils import simplejson as json from .signals import post_associate class IdentityManager(models.Manager): def from_loginza_data(self, loginza_data): data = json.dumps(loginza_data) identity, created = self.get_...
Fix user creation with unique username
Fix user creation with unique username
Python
isc
xobb1t/django-loginza-auth
7d2277685a125e4ee2b57ed7782bcae62f64464b
matrix/example.py
matrix/example.py
class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return map(list, zip(*self.rows))
class Matrix(object): def __init__(self, s): self.rows = [[int(n) for n in row.split()] for row in s.split('\n')] @property def columns(self): return [list(tup) for tup in zip(*self.rows)]
Make matrix exercise compatible with Python3
Make matrix exercise compatible with Python3
Python
mit
exercism/python,pombredanne/xpython,outkaj/xpython,behrtam/xpython,smalley/python,orozcoadrian/xpython,orozcoadrian/xpython,exercism/xpython,ZacharyRSmith/xpython,de2Zotjes/xpython,oalbe/xpython,jmluy/xpython,N-Parsons/exercism-python,pheanex/xpython,behrtam/xpython,exercism/python,pombredanne/xpython,wobh/xpython,jmlu...
bab2c322a9861e9869e92a3952a0d19f1559b099
redis_commands/parse.py
redis_commands/parse.py
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): ...
#!/usr/bin/python # -*- coding: utf-8 -*- import lxml.etree, lxml.html import re url = "http://redis.io" output = "output.txt" f = open(output, "w"); tree = lxml.html.parse("download/raw.dat").getroot() commands = tree.find_class("command") data = {} for command in commands: for row in command.findall('a'): ...
Use a synopsis for usage examples
redis_commands: Use a synopsis for usage examples
Python
apache-2.0
nikhilsingh291/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,p12tic/zeroclickinfo-fathead,thinker3197/zeroclickinfo-fathead,samskeller/zeroclickinfo-fathead,nikhilsingh291/zeroclickinfo-fathead,dankolbrs/zeroclickinfo-fathead,rasikapohankar/zeroclickinfo-fathead,p12tic/zeroclickin...
db0aa94de30d73217f9091635c92f59b8af98ef7
alg_sum_list.py
alg_sum_list.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_for(num_ls): """Sum number list by for loop.""" _sum = 0 for num in num_ls: _sum += num return _sum def sum_list_recur(num_ls): """Sum number list by recursion.""" ...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def sum_list_iter(num_ls): """Sum number list by for loop.""" _sum = 0 for num in num_ls: _sum += num return _sum def sum_list_recur(num_ls): """Sum number list by recursion.""" ...
Rename to sum_list_iter() and revise main()'s num_ls
Rename to sum_list_iter() and revise main()'s num_ls
Python
bsd-2-clause
bowen0701/algorithms_data_structures
03a803bb87478d79f67b20275bc45b56e7c8300f
tests/similarity/test_new_similarity.py
tests/similarity/test_new_similarity.py
import unittest from similarity.nw_similarity import NWAlgorithm class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_nw_algorithm(self): t = NWAlgorithm('abcdefghij', 'dgj') t.print_matrix() (a, b) = t.alignments() prin...
import unittest from similarity.nw_similarity import NWAlgorithm class TestNewSimilarity(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_nw_algorithm(self): t = NWAlgorithm('abcdefghij', 'dgj') t.print_matrix() (a, b) = t.alignments()...
Fix incorrect import reference to nw_similarity
Fix incorrect import reference to nw_similarity
Python
mit
dpazel/tryinggithub
4c3786b0b1ad0969bad2865bb11b81be396b5f8d
CMake/vtkTestDriver.py
CMake/vtkTestDriver.py
r""" This is a script that can be used to run tests that require multiple executables to be run e.g. those client-server tests. Usage: python vtkTestDriver.py --process exe1 arg11 arg12 ... --process exe2 arg21 arg22 ... --process ... """ import sys import subproc...
r""" This is a script that can be used to run tests that require multiple executables to be run e.g. those client-server tests. Usage: python vtkTestDriver.py --process exe1 arg11 arg12 ... --process exe2 arg21 arg22 ... --process ... """ import sys import subproc...
Add a delay between process launches.
Add a delay between process launches. It so happens that the client process was launched before the server causing deadlocks in some cases. Fixed that by adding a small delay. In reality, we may need to logic to vtkTestDriver to make it more featured and parse outputs from processes to handle this correctly. We can do...
Python
bsd-3-clause
candy7393/VTK,sumedhasingla/VTK,mspark93/VTK,jmerkow/VTK,sankhesh/VTK,SimVascular/VTK,sankhesh/VTK,keithroe/vtkoptix,demarle/VTK,jmerkow/VTK,demarle/VTK,mspark93/VTK,jmerkow/VTK,candy7393/VTK,berendkleinhaneveld/VTK,mspark93/VTK,demarle/VTK,mspark93/VTK,sankhesh/VTK,hendradarwin/VTK,keithroe/vtkoptix,msmolens/VTK,johnk...
6358f3fb8a3ece53adeb71f9b59f96a5a3a9ca70
examples/system/ulp_adc/example_test.py
examples/system/ulp_adc/example_test.py
from __future__ import unicode_literals from tiny_test_fw import Utility import re import ttfw_idf @ttfw_idf.idf_example_test(env_tag='Example_GENERIC') def test_examples_ulp_adc(env, extra_data): dut = env.get_dut('ulp_adc', 'examples/system/ulp_adc') dut.start_app() dut.expect_all('Not ULP wakeup', ...
from __future__ import unicode_literals from tiny_test_fw import Utility import re import ttfw_idf @ttfw_idf.idf_example_test(env_tag='Example_GENERIC') def test_examples_ulp_adc(env, extra_data): dut = env.get_dut('ulp_adc', 'examples/system/ulp_adc') dut.start_app() dut.expect_all('Not ULP wakeup', ...
Fix regex in ulp_adc example test
CI: Fix regex in ulp_adc example test
Python
apache-2.0
espressif/esp-idf,espressif/esp-idf,espressif/esp-idf,espressif/esp-idf
fae25cfe1a19de44d950e1a04fb6caa4f452b818
test/test_pre_commit.py
test/test_pre_commit.py
import unittest from mock import Mock, patch from captainhook import pre_commit class TestMain(unittest.TestCase): @patch('captainhook.pre_commit.get_files') @patch('captainhook.pre_commit.HookConfig') @patch('captainhook.pre_commit.checks') def test_calling_run_without_args(self, checks, HookConfi...
import unittest from mock import Mock, patch from captainhook import pre_commit class TestMain(unittest.TestCase): def setUp(self): self.get_files_patch = patch('captainhook.pre_commit.get_files') get_files = self.get_files_patch.start() get_files.return_value = ['file_one'] se...
Replace pre-commit test patch decorators with setUp/tearDown patching.
Replace pre-commit test patch decorators with setUp/tearDown patching.
Python
bsd-3-clause
Friz-zy/captainhook,alexcouper/captainhook,pczerkas/captainhook
18ff5cc690fada5c437a1be8e99df57cd8edfaea
tests/extractor_test.py
tests/extractor_test.py
import numpy as np from unittest import TestCase from cartography.extractor import LibrosaFeatureExtractor def gen_signal(dur, sr, freq): return np.pi * 2 * freq * np.arange(dur * sr) / float(sr) class TestLibrosaFeatureExtractor(TestCase): @classmethod def setUpClass(cls): cls.test_dur = 2 cls.test_fr...
import numpy as np from unittest import TestCase from cartography.extractor import LibrosaFeatureExtractor def gen_signal(dur, sr, freq): return np.pi * 2 * freq * np.arange(dur * sr) / float(sr) class TestLibrosaFeatureExtractor(TestCase): @classmethod def setUpClass(cls): cls.test_dur = 2 ...
Fix spacing. Update mfcc test to check columns
Fix spacing. Update mfcc test to check columns
Python
mit
tingled/synthetic-cartography,tingled/synthetic-cartography
8989258dab574cff0bc8001f1d59232983d15f68
grammpy/Grammars/PrettyApiGrammar.py
grammpy/Grammars/PrettyApiGrammar.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 01.08.2017 07:33 :Licence GNUv3 Part of grammpy """ from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar class PrettyApiGrammar(Grammar): def __init__(self, terminals=None, nonterminals=None, ...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 01.08.2017 07:33 :Licence GNUv3 Part of grammpy """ from .MultipleRulesGrammar import MultipleRulesGrammar as Grammar class PrettyApiGrammar(Grammar): def __init__(self, terminals=None, nonterminals=None, ...
Add __copy__ method to grammar
Add __copy__ method to grammar
Python
mit
PatrikValkovic/grammpy
e4f7deee8c4154781c2e945bfc14cf2028586dc1
hellopython/print_method/__init__.py
hellopython/print_method/__init__.py
import codecs import io import sys from workshopper.problems import BaseProblem class Problem(BaseProblem): def test(self, file): old_stdout = sys.stdout sys.stdout = io.StringIO() eval(codecs.open(file).read()) message = sys.stdout.getvalue() sys.stdout = old_stdout ...
import codecs import io import sys from workshopper.problems import BaseProblem class Problem(BaseProblem): title = 'Print method' def test(self, file): old_stdout = sys.stdout sys.stdout = io.StringIO() eval(codecs.open(file).read()) message = sys.stdout.getvalue() s...
Add a title to the print_method problem
Add a title to the print_method problem
Python
mit
pyschool/hipyschool
debe3a250a04986583589b1192cb6111b8b6c228
pydelhiconf/uix/screens/screenabout.py
pydelhiconf/uix/screens/screenabout.py
from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivy.factory import Factory from functools import partial import webbrowser class ScreenAbout(Screen): Builder.load_string(''' <ScreenAbout> spacing: dp(9) name: 'ScreenAbout' ScrollView id: scroll ScrollGrid...
from kivy.uix.screenmanager import Screen from kivy.lang import Builder from kivy.factory import Factory from functools import partial import webbrowser class ScreenAbout(Screen): Builder.load_string(''' <ScreenAbout> spacing: dp(9) name: 'ScreenAbout' ScrollView id: scroll ScrollGrid...
Add button that links to website
Add button that links to website
Python
agpl-3.0
pydelhi/pydelhi_mobile,shivan1b/pydelhi_mobile,samukasmk/pythonbrasil_mobile,akshayaurora/PyDelhiMobile
46f10ffcf60166fe02e33a6cd686f272ae63674e
saleor/product/forms.py
saleor/product/forms.py
from django import forms from django.utils.translation import pgettext_lazy from ..cart.forms import AddToCartForm from ..product.models import GenericProduct class GenericProductForm(AddToCartForm): variant = forms.ChoiceField() def __init__(self, *args, **kwargs): super(GenericProductForm, self)._...
from django import forms from django.utils.translation import pgettext_lazy from ..cart.forms import AddToCartForm from ..product.models import GenericProduct class GenericProductForm(AddToCartForm): base_variant = forms.CharField(widget=forms.HiddenInput()) variant = forms.ChoiceField(required=False) d...
Hide variants select input when product has no variants
Hide variants select input when product has no variants
Python
bsd-3-clause
josesanch/saleor,HyperManTT/ECommerceSaleor,paweltin/saleor,josesanch/saleor,spartonia/saleor,car3oon/saleor,laosunhust/saleor,mociepka/saleor,arth-co/saleor,UITools/saleor,Drekscott/Motlaesaleor,KenMutemi/saleor,rodrigozn/CW-Shop,tfroehlich82/saleor,HyperManTT/ECommerceSaleor,rchav/vinerack,arth-co/saleor,rchav/vinera...
5beea76076aa0806f8ee2db5f2169846e7497ef1
euler_python/problem55.py
euler_python/problem55.py
""" problem55.py If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. How many Lychrel numbers are there below ten-thousand? (Only consider fifty iterations) """ from toolset import iterate, quantify,...
""" problem55.py If we take 47, reverse and add, 47 + 74 = 121, which is palindromic. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. How many Lychrel numbers are there below ten-thousand? (Only consider fifty iterations) """ from toolset import iterate, quantify,...
Simplify python solution to 55
Simplify python solution to 55
Python
mit
mjwestcott/projecteuler,mjwestcott/projecteuler,mjwestcott/projecteuler
91dee60bb768a8ab80530cab79649b60afdf7daf
mbed.py
mbed.py
from utils.helpers import error, find_mbed_dir, is_mbed_dir import sys, os from utils import set_project_dir from commands.set import CmdSet from commands.get import CmdGet from commands.clone import CmdClone from commands.compile import CmdCompile from commands.list import CmdList ###################################...
from utils.helpers import error, find_mbed_dir, is_mbed_dir import sys, os from utils import set_project_dir from commands.set import CmdSet from commands.get import CmdGet from commands.clone import CmdClone from commands.compile import CmdCompile from commands.list import CmdList ###################################...
Fix Python module search path
Fix Python module search path
Python
apache-2.0
bogdanm/mbed-clt
8d7f4e549a2f83e93de9d440a7aa979b73cfba38
examples/my_test_suite.py
examples/my_test_suite.py
''' NOTE: This test suite contains 2 passing tests and 2 failing tests. ''' from seleniumbase import BaseCase class MyTestSuite(BaseCase): def test_1(self): self.open("http://xkcd.com/1663/") self.find_text("Garden", "div#ctitle", timeout=3) for p in xrange(4): self.click('a[...
''' NOTE: This test suite contains 2 passing tests and 2 failing tests. ''' from seleniumbase import BaseCase class MyTestSuite(BaseCase): def test_1(self): self.open("http://xkcd.com/1663/") self.find_text("Garden", "div#ctitle", timeout=3) for p in xrange(4): self.click('a[...
Make it clear that a few example tests fail on purpose
Make it clear that a few example tests fail on purpose
Python
mit
mdmintz/seleniumspot,possoumous/Watchers,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,possoumous/Watchers,mdmintz/SeleniumBase,mdmintz/SeleniumBase,ktp420/SeleniumBase,ktp420/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,possoumous/Watchers,mdmintz/seleniumspot,seleniumbase/SeleniumBase,seleniumbase/SeleniumB...
e0cbe4bef0376a361ae931b82de3502b31227a54
examples/sponza/effect.py
examples/sponza/effect.py
import moderngl as mgl from demosys.effects import effect class SceneEffect(effect.Effect): """Generated default effect""" def __init__(self): self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True) self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0) def dr...
import moderngl from demosys.effects import effect class SceneEffect(effect.Effect): """Generated default effect""" def __init__(self): self.scene = self.get_scene("Sponza/glTF/Sponza.gltf", local=True) self.proj_mat = self.create_projection(fov=75.0, near=0.01, far=1000.0) def draw(self...
Enable face culling in sponza example
Enable face culling in sponza example
Python
isc
Contraz/demosys-py
ee6941b15a66394d2683d5baeb0fe6ee61c2d0d3
freight/http.py
freight/http.py
from __future__ import absolute_import __all__ = ['build_session', 'delete', 'get', 'post', 'put'] import freight import requests USER_AGENT = 'freight/{}'.format(freight.VERSION), def build_session(): session = requests.Session() session.headers.update({'User-Agent': USER_AGENT}) return session def ...
from __future__ import absolute_import __all__ = ['build_session', 'delete', 'get', 'post', 'put'] import freight import requests USER_AGENT = 'freight/{version} (https://github.com/getsentry/freight)'.format( version=freight.VERSION, ), def build_session(): session = requests.Session() session.headers...
Add url to user agent
Add url to user agent
Python
apache-2.0
klynton/freight,klynton/freight,rshk/freight,jkimbo/freight,rshk/freight,getsentry/freight,getsentry/freight,getsentry/freight,rshk/freight,jkimbo/freight,klynton/freight,jkimbo/freight,getsentry/freight,klynton/freight,jkimbo/freight,rshk/freight,getsentry/freight
dbbf8a8de7a3212ac0c91a74a9fe5dd197272483
VOIAnalyzer.py
VOIAnalyzer.py
#!/usr/bin/env python # coding : utf-8 """ Main module for VOI analyzer. """ import pandas as pd import numpy as np import argparse import os
#!/usr/bin/env python # coding : utf-8 """ Main module for VOI analyzer. """ import pandas as pd import numpy as np import argparse import os def _analysis(img_mat, voi_mat, voi_no, eps=1e-12): """ Extract VOI statistices for each VOI. """ vec = img_mat[voi_mat == voi_no] vec2 = vec[~np.isnan(vec)] ...
Implement basis for VOI analyzer.
Implement basis for VOI analyzer.
Python
mit
spikefairway/VOIAnalyzer
0853d74c1ee15b28f308cba6c4145741c7937f50
vcli/verror.py
vcli/verror.py
import re RE_MESSAGE = re.compile(r'Message: (.+), Sqlstate:') RE_SQLSTATE = re.compile(r'Sqlstate: (\d+)') RE_POSITION = re.compile(r'Position: (\d+)') def format_error(error): msg = str(error) if not hasattr(error, 'one_line_sql'): return msg result = '' match = RE_SQLSTATE.search(msg) ...
import re RE_MESSAGE = re.compile(r'Message: (.+), Sqlstate:') RE_SQLSTATE = re.compile(r'Sqlstate: (\d+)') RE_POSITION = re.compile(r'Position: (\d+)') def format_error(error): msg = str(error) if not hasattr(error, 'one_line_sql'): return msg result = '' match = RE_SQLSTATE.search(msg) ...
Format error message better in a long SQL
Format error message better in a long SQL
Python
bsd-3-clause
dbcli/vcli,dbcli/vcli
7821db4fb30bc013f8ae71c779faae5f6864da1d
falafel/__init__.py
falafel/__init__.py
import os from .core import LogFileOutput, MapperOutput, computed # noqa: F401 from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401 from .mappers import get_active_lines # noqa: F401 from .util import defaults, parse_table # noqa: F401 __here__ = os.path.dirname(os.path.abspath(__fi...
import os from .core import LogFileOutput, MapperOutput, computed # noqa: F401 from .core.plugins import mapper, reducer, make_response, make_metadata # noqa: F401 from .mappers import get_active_lines # noqa: F401 from .util import defaults, parse_table # noqa: F401 __here__ = os.path.dirname(os.path.abspath(__fi...
Allow rule repos to provide version information
Allow rule repos to provide version information Added a new method to the root package `add_status`. Rule repos should use it during initialization: import falafel falafel.add_status(name="my_rule_repo", nvr="my-rules-1.0.0-1", commit="abcdef")
Python
apache-2.0
RedHatInsights/insights-core,RedHatInsights/insights-core
9e87598ddaa19b565099685c2bdad636b29b3d4f
frappe/tests/test_boot.py
frappe/tests/test_boot.py
import unittest import frappe from frappe.boot import get_unseen_notes from frappe.desk.doctype.note.note import mark_as_seen class TestBootData(unittest.TestCase): def test_get_unseen_notes(self): frappe.db.delete("Note") frappe.db.delete("Note Seen By") note = frappe.get_doc( { "doctype": "Note", ...
import unittest import frappe from frappe.boot import get_unseen_notes from frappe.desk.doctype.note.note import mark_as_seen from frappe.tests.utils import FrappeTestCase class TestBootData(FrappeTestCase): def test_get_unseen_notes(self): frappe.db.delete("Note") frappe.db.delete("Note Seen By") note = frap...
Use FrappeTestCase as it rolls back test data
refactor: Use FrappeTestCase as it rolls back test data
Python
mit
frappe/frappe,StrellaGroup/frappe,frappe/frappe,StrellaGroup/frappe,StrellaGroup/frappe,frappe/frappe
a5ddab3208992ca6ab655ddef9a4155d5fc6bc55
tests/grammar_test.py
tests/grammar_test.py
import nose from parser_tool import get_parser, parse sentences = ( # N[s] V[i] "Brad drives", # N[s] V[t] N[p] "Angela drives cars", # N[s] V[t] Det N[s] "Brad buys the house", # Det[s] N[s] V[i] "a dog walks" ) grammar = get_parser("grammars/feat1.fcfg", trace=0) def test_grammar()...
import nose from parser_tool import get_parser, parse sentences = ( # PN V[i] "Brad drives", # PN V[t] N[p] "Angela drives cars", # PN V[t] Det N[s] "Brad buys the house", # Det[s] N[s] V[i] "a dog walks", # Det[p] N[p] V[i] "these dogs walk", # Det[p] N[p] V[t] Det N[s] ...
Increase testing coverage of grammar
Increase testing coverage of grammar * added some sample sentences with ajectives
Python
mit
caninemwenja/marker,kmwenja/marker
fff0087f82c3f79d5e60e32071a4e89478d8b85e
tests/test_element.py
tests/test_element.py
import pkg_resources pkg_resources.require('cothread') import cothread import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e.add_to_fami...
import pkg_resources pkg_resources.require('cothread') import cothread import rml import rml.element def test_create_element(): e = rml.element.Element('BPM', 6.0) assert e.get_type() == 'BPM' assert e.get_length() == 6.0 def test_add_element_to_family(): e = rml.element.Element('dummy', 0.0) e....
Make pvs in Element behave more realistically.
Make pvs in Element behave more realistically.
Python
apache-2.0
razvanvasile/RML,willrogers/pml,willrogers/pml
9075603da0ac5993836001749c7999dec6498f95
tests/test_process.py
tests/test_process.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_process ---------------------------------- Tests for process management. """ # system imports import unittest import os from subprocess import check_output from tempfile import NamedTemporaryFile # project imports from nrtest.process import source, execute, mon...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_process ---------------------------------- Tests for process management. """ # system imports import unittest import os from subprocess import check_output from tempfile import NamedTemporaryFile # project imports from nrtest.process import source, execute, mon...
Remove unreproducible test (sleep is too inaccurate)
Remove unreproducible test (sleep is too inaccurate)
Python
mit
davidchall/nrtest
34c0a728add7715a9420537f57f7c1a69176c57d
tests/serializer/abstract_test.py
tests/serializer/abstract_test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # hack for loading modules # import _path _path.fix() ## # python standard library # from functools import partial import unittest ## # pygrapes modules # from pygrapes.serializer import Base class BaseSerializerTestCase(unittest.TestCase): def test_method_dump...
#!/usr/bin/env python # -*- coding: utf-8 -*- ## # hack for loading modules # import _path _path.fix() ## # python standard library # from functools import partial import unittest ## # pygrapes modules # from pygrapes.serializer.abstract import Abstract class AbstractSerializerTestCase(unittest.TestCase): def...
Use abstract.Abstract instead of Base alias when testing pygrapes.serializer.abstract.Abstract class
Use abstract.Abstract instead of Base alias when testing pygrapes.serializer.abstract.Abstract class
Python
bsd-3-clause
michalbachowski/pygrapes,michalbachowski/pygrapes,michalbachowski/pygrapes
c174e7bffbfbbb2fe4a1d13d37d9c056d44d95d2
project/apps.py
project/apps.py
#!/usr/bin/env python """ Project Core Application Classes """ __author__ = "Gavin M. Roy" __email__ = "gavinmroy@gmail.com" __date__ = "2009-11-10" __version__ = 0.1 import project.data import project.handler class Home(project.handler.RequestHandler): def get(self): foo self.ren...
#!/usr/bin/env python """ Project Core Application Classes """ __author__ = "Gavin M. Roy" __email__ = "gavinmroy@gmail.com" __date__ = "2009-11-10" __version__ = 0.1 import project.data import project.handler class Home(project.handler.RequestHandler): def get(self): self.render('templat...
Remove the errror intentionally left for debugging
Remove the errror intentionally left for debugging
Python
bsd-3-clause
lucius-feng/tinman,gmr/tinman,lucius-feng/tinman,lucius-feng/tinman,gmr/tinman
d6b2c3fcae81ca30d406778f66c6f8b12cfb04d8
tests/window/WINDOW_CAPTION.py
tests/window/WINDOW_CAPTION.py
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the ...
#!/usr/bin/env python '''Test that the window caption can be set. Expected behaviour: Two windows will be opened, one with the caption "Window caption 1" counting up every second; the other with a Unicode string including some non-ASCII characters. Press escape or close either window to finished the ...
Make windows bigger in this test so the captions can be read.
Make windows bigger in this test so the captions can be read. Index: tests/window/WINDOW_CAPTION.py =================================================================== --- tests/window/WINDOW_CAPTION.py (revision 777) +++ tests/window/WINDOW_CAPTION.py (working copy) @@ -19,8 +19,8 @@ class WINDOW_CAPTION(unittest....
Python
bsd-3-clause
adamlwgriffiths/Pyglet,niklaskorz/pyglet,niklaskorz/pyglet,adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,seeminglee/pyglet64,niklaskorz/pyglet,seeminglee/pyglet64,niklaskorz/pyglet,seeminglee/pyglet64
4070507e3357d36f2412cc5c68a63780ae1b814d
glance_api_local_check.py
glance_api_local_check.py
#!/usr/bin/env python from maas_common import (get_auth_ref, get_glance_client, status_err, status_ok, metric) import sys IMAGE_ENDPOINT = 'http://127.0.0.1:9292' def check(token): glance = get_glance_client(token, IMAGE_ENDPOINT) if glance is None: status_err('Unable to obt...
#!/usr/bin/env python from maas_common import (status_ok, status_err, metric, get_keystone_client, get_auth_ref) from requests import Session from requests import exceptions as exc def check(auth_ref): keystone = get_keystone_client(auth_ref) tenant_id = keystone.tenant_id auth_t...
Make a direct call to glance-api using requests
Make a direct call to glance-api using requests This change makes this check no longer use the glanceclient tool so we can craft a request that doesn't hit the glance-registry. The reason for this is that the glance-registry itself is tested in a different check and therefore we just need to ensure the glance-api its...
Python
apache-2.0
cfarquhar/rpc-openstack,stevelle/rpc-openstack,robb-romans/rpc-openstack,byronmccollum/rpc-openstack,cloudnull/rpc-maas,byronmccollum/rpc-openstack,mattt416/rpc-openstack,nrb/rpc-openstack,hughsaunders/rpc-openstack,darrenchan/rpc-openstack,byronmccollum/rpc-openstack,jacobwagner/rpc-openstack,jpmontez/rpc-openstack,br...
f6491445d8811f0fcb5bf8937056a4e15ed985b4
tests/acceptance/test_ensure_index.py
tests/acceptance/test_ensure_index.py
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest from scalymongo import Document class IndexTestDocument(Document): structure = { 'number': int, 'name': unicode, 'descending': int, 'ascending': int, } indexes = [ {'fields': 'number'}, {'f...
from tests.acceptance.base_acceptance_test import BaseAcceptanceTest from scalymongo import Document class IndexTestDocument(Document): structure = { 'number': int, 'name': unicode, 'descending': int, 'ascending': int, } indexes = [ {'fields': 'number'}, {'f...
Fix acceptance test for MongoDB 2.0
indexes: Fix acceptance test for MongoDB 2.0 There were some minor changes for the test to work properly with 2.0: - The index versions are now 1 instead of 0 Don't bother checking the version of index since scalymongo has no control over it. - The `unique` key is now only provided when ``True``
Python
bsd-3-clause
allancaffee/scaly-mongo
05b8ae37fccb152fcdd618b09984f3d1d8beae45
fabfile.py
fabfile.py
import os from fabric.api import * base_path = os.path.dirname(__file__) project_root = "~/Gather" pip_path = os.path.join(project_root, "bin/pip") python_path = os.path.join(project_root, "bin/python") env.user = "gather" env.hosts = ["gather.whouz.com"] def update_from_github(): with cd(project_root): ...
import os from fabric.api import * base_path = os.path.dirname(__file__) project_root = "~/Gather" pip_path = os.path.join(project_root, "bin/pip") python_path = os.path.join(project_root, "bin/python") env.user = "gather" env.hosts = ["gather.whouz.com"] def update_from_github(): with cd(project_root): ...
Migrate database for small update
Migrate database for small update
Python
mit
whtsky/Gather,whtsky/Gather
9db8a4c37cb226f1606b711493ebec16573f3d46
polyaxon/libs/spec_validation.py
polyaxon/libs/spec_validation.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.core.exceptions import ValidationError from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError from polyaxon_schemas.polyaxonfile.specification import GroupSpecification def validate_spe...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function from django.core.exceptions import ValidationError from polyaxon_schemas.exceptions import PolyaxonfileError, PolyaxonConfigurationError from polyaxon_schemas.polyaxonfile.specification import GroupSpecification, Specification d...
Add tensorboard serializer * Add validation * Add tests
Add tensorboard serializer * Add validation * Add tests
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
d96b6fa97272057f0fb67f2440f1b5b642b92bbe
src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py
src/python/tensorflow_cloud/core/tests/examples/multi_file_example/scale_model.py
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 ...
# Copyright 2020 Google LLC. All Rights Reserved. # # 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 ...
Add storage bucket to run() call
Add storage bucket to run() call
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
656780b827202fc08992321ec2a98e91cb02da3b
utilities/__init__.py
utilities/__init__.py
#! /usr/bin/env python from subprocess import Popen, PIPE def _popen(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate()
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
Add a wrapper to get just stdout back
Add a wrapper to get just stdout back
Python
mit
IanLee1521/utilities
de3809a00703c5eaaaec856b152a2418debbb6c6
plugins/Tools/MirrorTool/__init__.py
plugins/Tools/MirrorTool/__init__.py
from . import MirrorTool def getMetaData(): return { 'type': 'tool', 'plugin': { 'name': 'Mirror Tool' }, 'tool': { 'name': 'Mirror', 'description': 'Mirror Object' }, } def register(app): return MirrorTool.MirrorTool()
from . import MirrorTool def getMetaData(): return { 'type': 'tool', 'plugin': { 'name': 'Mirror Tool' }, 'tool': { 'name': 'Mirror', 'description': 'Mirror Object', 'icon': 'mirror.png' }, } def register(app): return ...
Use the right icon for the mirror tool
Use the right icon for the mirror tool
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
0daa2132c071cb667aca5dbc416872a278e91a2b
pycoin/coins/groestlcoin/hash.py
pycoin/coins/groestlcoin/hash.py
import hashlib import groestlcoin_hash from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" return bytes_as_revhex(groestlcoin_hash.getHash(data, len(data)))
import hashlib from pycoin.encoding.hexbytes import bytes_as_revhex def sha256(data): return bytes_as_revhex(hashlib.sha256(data).digest()) def groestlHash(data): """Groestl-512 compound hash.""" try: import groestlcoin_hash except ImportError: t = 'Groestlcoin requires the groestlc...
Raise ImportError when GRS is used without dependency
Raise ImportError when GRS is used without dependency
Python
mit
richardkiss/pycoin,richardkiss/pycoin
b1b8e06b2b0ae6c79b94bd8e7b0b49721b7bdc13
web/attempts/tests.py
web/attempts/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from rest_framework.test import APIClient from users.models import User # Create your tests here. class TokenLoginTestCase(TestCase): fixtures = ['users.json'] def testAttemptSubmit(self): user = User.objects.get(username='matija') client = APIClient() ...
Add simple Attempt submit test
Add simple Attempt submit test
Python
agpl-3.0
matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo,matijapretnar/projekt-tomo,ul-fmf/projekt-tomo,ul-fmf/projekt-tomo,matijapretnar/projekt-tomo
4ed701a7afad4c8c3c04097e449e930cc4545e0d
mendel/admin.py
mendel/admin.py
from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from mendel.models import Keyword, Category, Document, Context, Review class KeywordAdmin(ImportExportModelAdmin): pass class CategoryAdmin(ImportExportModelAdmin): pass class Docum...
from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from mendel.models import Keyword, Category, Document, Context, Review class KeywordAdmin(ImportExportModelAdmin): list_display = ('id', 'name') pass class CategoryAdmin(ImportExportM...
Add list_displays for Admin views
Add list_displays for Admin views
Python
agpl-3.0
Architizer/mendel,Architizer/mendel,Architizer/mendel,Architizer/mendel
d879c6338449cd0c2f3c9a84162b3de688a55105
webdiff/gitwebdiff.py
webdiff/gitwebdiff.py
#!/usr/bin/env python '''This lets you run "git webdiff" instead of "git difftool".''' import os import subprocess import sys def any_nonflag_args(args): """Do any args not start with '-'? If so, this isn't a HEAD diff.""" return len([x for x in args if not x.startswith('-')]) > 0 def run(): if not any...
#!/usr/bin/env python '''This lets you run "git webdiff" instead of "git difftool".''' import os import subprocess import sys def any_nonflag_args(args): """Do any args not start with '-'? If so, this isn't a HEAD diff.""" return len([x for x in args if not x.startswith('-')]) > 0 def run(): if not any...
Exit cleanly from 'git webdiff'
Exit cleanly from 'git webdiff' - Don't allow a KeyboardInterrupt/sigint exception propagate up to the user when exiting webdiff with Ctrl-C
Python
apache-2.0
daytonb/webdiff,danvk/webdiff,daytonb/webdiff,daytonb/webdiff,danvk/webdiff,danvk/webdiff,danvk/webdiff,daytonb/webdiff,danvk/webdiff
a06f586ba95148643561122f051087db7b63fecb
registries/views.py
registries/views.py
from django.shortcuts import render from django.conf import settings from django.http import HttpResponse from rest_framework.generics import ListAPIView from registries.models import Organization from registries.serializers import DrillerListSerializer class APIDrillerListView(ListAPIView): queryset = Organizatio...
from django.shortcuts import render from django.conf import settings from django.http import HttpResponse from rest_framework.generics import ListAPIView from registries.models import Organization from registries.serializers import DrillerListSerializer class APIDrillerListView(ListAPIView): queryset = Organizatio...
Add prefetch to reduce queries on province_state
Add prefetch to reduce queries on province_state
Python
apache-2.0
rstens/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells
67fb6076b98a25f22a343f0c6ec62193ed86125a
bmi_ilamb/bmi_ilamb.py
bmi_ilamb/bmi_ilamb.py
#! /usr/bin/env python import sys import subprocess from basic_modeling_interface import Bmi class BmiIlamb(Bmi): _command = 'ilamb-run' _args = None _env = None def __init__(self): self._time = self.get_start_time() @property def args(self): return [self._command] + (self._a...
"""Basic Model Interface (BMI) for the ILAMB benchmarking system.""" import os import subprocess from basic_modeling_interface import Bmi from .config import Configuration class BmiIlamb(Bmi): _component_name = 'ILAMB' _command = 'ilamb-run' _args = None def __init__(self): self._time = self...
Update ILAMB BMI to use Configuration
Update ILAMB BMI to use Configuration I also set ILAMB_ROOT and MPLBACKEND at `initialize`. Not sure if there's a better location.
Python
mit
permamodel/bmi-ilamb
a657792c10f59ed94af3039807ef92318b5c23f9
src/graphql/pyutils/is_iterable.py
src/graphql/pyutils/is_iterable.py
from array import array from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView __all__ = ["is_collection", "is_iterable"] collection_types: Any = [Collection] if not isinstance({}.values(), Collection): # Python < 3.7.2 collection_types.append(ValuesView) if not isinstance(array, Co...
from array import array from typing import Any, ByteString, Collection, Iterable, Mapping, Text, ValuesView __all__ = ["is_collection", "is_iterable"] collection_types: Any = [Collection] if not isinstance({}.values(), Collection): # Python < 3.7.2 collection_types.append(ValuesView) if not issubclass(array, Co...
Correct a workaround for PyPy
Correct a workaround for PyPy
Python
mit
graphql-python/graphql-core
3749acbad597974ef2507b2e7e27240937658c0b
nilmtk/plots.py
nilmtk/plots.py
from __future__ import print_function, division import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np _to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf) def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs): """Plot function for series w...
from __future__ import print_function, division import matplotlib.pyplot as plt import matplotlib.dates as mdates import numpy as np _to_ordinalf_np_vectorized = np.vectorize(mdates._to_ordinalf) def plot_series(series, ax=None, label=None, date_format='%d/%m/%y %H:%M:%S', **kwargs): """Plot function for series w...
Fix bug where timezone was not used for xaxis.
Fix bug where timezone was not used for xaxis.
Python
apache-2.0
jaduimstra/nilmtk,josemao/nilmtk,pauldeng/nilmtk,AlexRobson/nilmtk,mmottahedi/nilmtk,nilmtk/nilmtk,nilmtk/nilmtk,HarllanAndrye/nilmtk
21ce1aeb0359ef760a7936ed4123041e29b4f0b1
scripts/maf_limit_to_species.py
scripts/maf_limit_to_species.py
#!/usr/bin/env python2.3 """ Read a maf file from stdin and write out a new maf with only blocks having all of the required in species, after dropping any other species and removing columns containing only gaps. usage: %prog species,species2,... < maf """ import psyco_full import bx.align.maf import copy import sys...
#!/usr/bin/env python2.3 """ Read a maf file from stdin and write out a new maf with only blocks having all of the required in species, after dropping any other species and removing columns containing only gaps. usage: %prog species,species2,... < maf """ import psyco_full import bx.align.maf import copy import sys...
Remove all-gap columns after removing rows of the alignment
Remove all-gap columns after removing rows of the alignment
Python
mit
bxlab/bx-python,bxlab/bx-python,bxlab/bx-python
9d44c515dbb253e214ac0cd1145bddacc2586380
example/urls.py
example/urls.py
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^comments/', include('fluent_comments.urls')), u...
from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.views.generic import RedirectView admin.autodiscover() urlpatterns = patterns('', url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^comme...
Fix running the example project with Django 1.5
Fix running the example project with Django 1.5
Python
apache-2.0
django-fluent/django-fluent-comments,akszydelko/django-fluent-comments,akszydelko/django-fluent-comments,Afnarel/django-fluent-comments,Afnarel/django-fluent-comments,edoburu/django-fluent-comments,Afnarel/django-fluent-comments,PetrDlouhy/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluen...
c92a56dc937dc414139e2bff958190cfb18de5d9
tests/basics/try2.py
tests/basics/try2.py
# nested try's try: print("try 1") try: print("try 2") foo() except: print("except 2") bar() except: print("except 1") try: print("try 1") try: print("try 2") foo() except TypeError: print("except 2") bar() except NameError: print...
# nested try's try: print("try 1") try: print("try 2") foo() except: print("except 2") bar() except: print("except 1") try: print("try 1") try: print("try 2") foo() except TypeError: print("except 2") bar() except NameError: print...
Add testcase with exception handler spread across functions.
Add testcase with exception handler spread across functions.
Python
mit
SHA2017-badge/micropython-esp32,skybird6672/micropython,vriera/micropython,SHA2017-badge/micropython-esp32,jimkmc/micropython,cnoviello/micropython,cloudformdesign/micropython,emfcamp/micropython,dhylands/micropython,xuxiaoxin/micropython,AriZuu/micropython,cloudformdesign/micropython,selste/micropython,ryannathans/mic...
33c7bd546236497aae9b0c96d6ae4c41f317a00e
saau/sections/transportation/data.py
saau/sections/transportation/data.py
from operator import itemgetter from itertools import chain from typing import List from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np def get_layers(service): layers = service.layers return { layer.name: layer for layer in layers ...
from operator import itemgetter from itertools import chain from typing import List import cgi from urllib.parse import parse_qs from ...utils.py3_hook import with_hook with with_hook(): from arcrest import Catalog import numpy as np cgi.parse_qs = parse_qs def get_layers(service): layers = service.layer...
Patch missing method on cgi package
Patch missing method on cgi package
Python
mit
Mause/statistical_atlas_of_au
b301d8b9860f93a2c1fecd552f8edda4c813c04a
controller.py
controller.py
import requests payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}} r = requests.post('http://localhost:3000/login', json=payload) print r.status_code
import requests payload = {'session':{'email':'david.armbrust@gmail.com','password':'Ovation1'}} session = requests.Session() r = session.post('http://localhost:3000/login', json=payload) print r.status_code payload = {'plant':{'name':'Test Name','species':'Test species','days_per_watering':'9','start_date':'9/9/19...
Add persistance of session across requests
Add persistance of session across requests
Python
mit
darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker,darmbrus/plant-watering-tracker
701a18199fd230f70793b2e2c23b84506b50014e
reports/urls.py
reports/urls.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from . import views urlpatterns = [ url(r'^reports/changes/lifetimes/(?P<slug>[^/.]+)/$', views.DiaperChangeLifetimesChildReport.as_view(), name='report-diaperchange-lifetimes-child'), url(r'^repo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from . import views urlpatterns = [ url(r'^children/(?P<slug>[^/.]+)/reports/changes/lifetimes/$', views.DiaperChangeLifetimesChildReport.as_view(), name='report-diaperchange-lifetimes-child'), ur...
Change reports URLs to extend from /children/<slug>.
Change reports URLs to extend from /children/<slug>.
Python
bsd-2-clause
cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy
96a313eef46c31af3308805f10ffa63e330cc817
02/test_move.py
02/test_move.py
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): ...
from move import load_moves, encode_moves, normalize_index, move import unittest class TestMove(unittest.TestCase): def setUp(self): self.moves = ['ULL', 'RRDDD', 'LURDL', 'UUUUD'] def test_load_moves(self): assert load_moves('example.txt') == self.moves def test_encode_moves(self): ...
Remove test of two-argument normalize function.
Remove test of two-argument normalize function.
Python
mit
machinelearningdeveloper/aoc_2016
496d7fd6e9b2b581bc470b57984473b29d084e74
contentpages/tests.py
contentpages/tests.py
from django.test import TestCase # Create your tests here.
from django.test import TestCase from django.urls import reverse from contentpages.views import ContentPage class TestContentPage(TestCase): def test_get_template(self): # test that the template view uses the template requested # using pliny as a view that will always be present route =...
Add coverage for content pages functionality
Add coverage for content pages functionality
Python
mit
bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject
09fed8f6bfb32f0f4c3aba45d16a153eaefe79e4
fetch.py
fetch.py
import fetchparser def print_parsed(): for line in fetchparser.parse_input(open("sample.fetch").read()): print line def print_lexed(): import fetchlexer l=fetchlexer.get_lexer() # Give the lexer some input l.input(open("sample.fetch").read()) # Tokenize while True: tok = ...
import fetchparser def print_parsed(): for line in fetchparser.parse_input(open("sample.fetch").read()): print line def print_lexed(): import fetchlexer l=fetchlexer.get_lexer() # Give the lexer some input l.input(open("sample.fetch").read()) # Tokenize while True: tok = ...
Kill dad code for old compiler
Kill dad code for old compiler
Python
mit
buffis/fetch
a5fdffe2f37e2e1c34044c259ef56c0e5feca0cb
allegedb/allegedb/tests/test_branch_plan.py
allegedb/allegedb/tests/test_branch_plan.py
import pytest import allegedb @pytest.fixture(scope='function') def orm(): with allegedb.ORM("sqlite:///:memory:") as it: yield it def test_single_plan(orm): g = orm.new_graph('graph') g.add_node(0) orm.turn = 1 g.add_node(1) with orm.plan(): orm.turn = 2 g.add_node(2...
import pytest import allegedb @pytest.fixture(scope='function') def orm(): with allegedb.ORM("sqlite:///:memory:") as it: yield it def test_single_plan(orm): g = orm.new_graph('graph') g.add_node(0) orm.turn = 1 g.add_node(1) with orm.plan(): orm.turn = 2 g.add_node(2...
Add an extra check in that test
Add an extra check in that test
Python
agpl-3.0
LogicalDash/LiSE,LogicalDash/LiSE
46ebeba28f8fbb9d43457aa3fa539b29048a581b
netbox/users/api/views.py
netbox/users/api/views.py
from django.contrib.auth.models import Group, User from django.db.models import Count from users import filters from users.models import ObjectPermission from utilities.api import ModelViewSet from utilities.querysets import RestrictedQuerySet from . import serializers # # Users and groups # class UserViewSet(Model...
from django.contrib.auth.models import Group, User from django.db.models import Count from users import filters from users.models import ObjectPermission from utilities.api import ModelViewSet from utilities.querysets import RestrictedQuerySet from . import serializers # # Users and groups # class UserViewSet(Model...
Set default ordering for user and group API endpoints
Set default ordering for user and group API endpoints
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
b9fbc9ba6ab2c379e26d6e599fcaaf6ab9b84473
server/slack.py
server/slack.py
#!/usr/bin/python2.7 import json import kartlogic.rank import logging import prettytable import util.web import util.slack def handler(event, context): logging.warning(event['body']) logging.warning(json.dumps(util.slack.parse_input(event['body']))) return util.web.respond_success("Successful") def rank...
#!/usr/bin/python2.7 import kartlogic.rank import prettytable import util.web as webutil import util.slack as slackutil def handler(event, context): input_data = slackutil.slack.parse_input(event['body']) if slackutil.validate_slack_token(input_data) is False: return webutil.respond_unauthorized("Inv...
Add Slack token validation to handler
Add Slack token validation to handler
Python
mit
groppe/mario
f347341d138bb4f610dcca9c9791001d54e734be
diceclient.py
diceclient.py
#!/usr/bin/env python import sys from twisted.internet import reactor, defer from twisted.internet.protocol import ClientCreator from twisted.protocols import amp from twisted.python import usage from diceserver import RollDice, default_port class Options(usage.Options): optParameters = [ ["hos...
#!/usr/bin/env python import sys from twisted.internet import reactor, defer from twisted.internet.protocol import ClientCreator from twisted.protocols import amp from twisted.python import usage from diceserver import RollDice, default_port class Options(usage.Options): optParameters = [ ["hos...
Add a command line option for number of sides.
Add a command line option for number of sides.
Python
mit
dripton/ampchat
b71a96f818c66b5578fb7c4475b67ecdcb16937a
recipes/recipe_modules/gclient/tests/sync_failure.py
recipes/recipe_modules/gclient/tests/sync_failure.py
# Copyright 2019 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. from recipe_engine import post_process DEPS = ['gclient'] def RunSteps(api): src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache') api.gclien...
# Copyright 2019 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. from recipe_engine import post_process DEPS = ['gclient'] def RunSteps(api): src_cfg = api.gclient.make_config(CACHE_DIR='[ROOT]/git_cache') api.gclien...
Replace customzied test failure assertion with ResultReasonRE from engine
Replace customzied test failure assertion with ResultReasonRE from engine This change is to facilitate the annotation protocol -> luciexe protocol migration in the future. The failure response structure will be changed after the migration. Therefore, we only need to change the implementation detail of ResultReasonRE a...
Python
bsd-3-clause
CoherentLabs/depot_tools,CoherentLabs/depot_tools
caab908d8f8948c3035c94018d7a1e31332edbad
udata/tests/frontend/__init__.py
udata/tests/frontend/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json import re from udata.tests import TestCase, WebTestMixin, SearchTestMixin from udata import frontend, api class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase): def create_app(self): app = super(FrontTestCase, self).crea...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json import re from udata.tests import TestCase, WebTestMixin, SearchTestMixin from udata import frontend, api class FrontTestCase(WebTestMixin, SearchTestMixin, TestCase): def create_app(self): app = super(FrontTestCase, self).crea...
Add traces if there is no JSON-LD while it was expected
Add traces if there is no JSON-LD while it was expected
Python
agpl-3.0
opendatateam/udata,opendatateam/udata,etalab/udata,jphnoel/udata,jphnoel/udata,etalab/udata,davidbgk/udata,davidbgk/udata,jphnoel/udata,etalab/udata,davidbgk/udata,opendatateam/udata
d7fdebdc4ce52e59c126a27ea06171994a6c846b
src/config/common/ssl_adapter.py
src/config/common/ssl_adapter.py
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both...
""" HTTPS Transport Adapter for python-requests, that allows configuration of SSL version""" # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 # @author: Sanju Abraham, Juniper Networks, OpenContrail from requests.adapters import HTTPAdapter try: # This is required for RDO, which installs both...
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__.
Add ssl_version to the list of attributes, required when vnc_api gets called via multiprocessing module. This will ensure ssl_version gets included when pickle calls __getstate__ and __setstate__. Courtesy: https://github.com/sigmavirus24/requests-toolbelt/commit/decadbd3512444889feb30cf1ff2f1448a3ecfca Closes-Bug:#1...
Python
apache-2.0
codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller,codilime/contrail-controller
01c17356bd9eed56979c55ccb55659508d08b218
src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py
src/waldur_openstack/openstack_tenant/migrations/0004_fill_tenant_id.py
from django.db import migrations def fill_tenant_id(apps, schema_editor): ServiceSettings = apps.get_model('structure', 'ServiceSettings') for service_settings in ServiceSettings.objects.filter(type='OpenStackTenant'): tenant = service_settings.scope if ( tenant and ten...
from django.core.exceptions import ObjectDoesNotExist from django.db import migrations def fill_tenant_id(apps, schema_editor): ServiceSettings = apps.get_model('structure', 'ServiceSettings') Tenant = apps.get_model('openstack', 'Tenant') for service_settings in ServiceSettings.objects.filter(type='OpenS...
Fix migration: don't use virtual field scope.
Fix migration: don't use virtual field scope.
Python
mit
opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
8bbdadc61611512dbd1bfbff2495ff0dee101054
adhocracy4/categories/forms.py
adhocracy4/categories/forms.py
from django import forms from adhocracy4.categories import models as category_models class CategorizableFieldMixin: category_field_name = 'category' def __init__(self, *args, **kwargs): module = kwargs.pop('module') super().__init__(*args, **kwargs) queryset = category_models.Categor...
from adhocracy4.categories import models as category_models class CategorizableFieldMixin: category_field_name = 'category' def __init__(self, *args, **kwargs): module = kwargs.pop('module') super().__init__(*args, **kwargs) field = self.fields[self.category_field_name] field...
Modify generated category form field instead of reinitialize it
Modify generated category form field instead of reinitialize it The category fields had not been translated as the field had been reinitialized instead of modified. With this PR the auto generated field (with its localized verbose_name) will be kept and adapted to the filtered queryset. Furthermore the required param...
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
957f3e82f13dc8a9bd09d40a25c1f65847e144b8
aiohttp_json_api/decorators.py
aiohttp_json_api/decorators.py
from functools import wraps from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): context = kwargs.get('context') ...
from functools import wraps from aiohttp import web from boltons.iterutils import first from .context import RequestContext from .errors import HTTPUnsupportedMediaType from .const import JSONAPI, JSONAPI_CONTENT_TYPE def jsonapi_content(handler): @wraps(handler) async def wrapper(*args, **kwargs): ...
Fix bug with arguments handling in JSON API content decorator
Fix bug with arguments handling in JSON API content decorator
Python
mit
vovanbo/aiohttp_json_api
fb59f2e0bd01d75c90ea3cc0089c24fc5db86e8e
config/jupyter/jupyter_notebook_config.py
config/jupyter/jupyter_notebook_config.py
import sys sys.path.append('/root/.jupyter/extensions/') c.JupyterApp.ip = '*' c.JupyterApp.port = 80 c.JupyterApp.open_browser = False c.JupyterApp.allow_credentials = True c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post'] c.JupyterApp.reraise_server_extension_failures = True c...
import json import os import sys sys.path.append('/root/.jupyter/extensions/') c.JupyterApp.ip = '*' c.JupyterApp.port = 80 c.JupyterApp.open_browser = False c.JupyterApp.allow_credentials = True c.JupyterApp.nbserver_extensions = ['jupyter_nbgallery.status', 'jupyter_nbgallery.post'] c.JupyterApp.reraise_server_exten...
Set $NBGALLERY_URL to override gallery location
Set $NBGALLERY_URL to override gallery location
Python
mit
jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker,jupyter-gallery/jupyter-docker
08c54be9e2e34b5655b2ea6f7778a83b606acade
src/lexus/lexical_simplifier.py
src/lexus/lexical_simplifier.py
__author__ = 's7a' # All imports from extras import Sanitizer from replacer import Replacer # The Lexical simplification class class LexicalSimplifier: # Constructor for the Lexical Simplifier def __init__(self): # Unused pass # Simplify a given content @staticmethod def simplif...
__author__ = 's7a' # All imports from extras import Sanitizer from replacer import Replacer # The Lexical simplification class class LexicalSimplifier: # Constructor for the Lexical Simplifier def __init__(self): # Unused pass # Simplify a given content @staticmethod def simplif...
Reduce the runtime of webapp api
Reduce the runtime of webapp api
Python
mit
Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify
6d1612698c2e42ab60d521915f31ff08832e3745
waterbutler/providers/dropbox/settings.py
waterbutler/providers/dropbox/settings.py
try: from waterbutler import settings except ImportError: settings = {} config = settings.get('DROPBOX_PROVIDER_CONFIG', {}) BASE_URL = config.get('BASE_URL', 'https://api.dropbox.com/1/') BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://api-content.dropbox.com/1/')
try: from waterbutler import settings except ImportError: settings = {} config = settings.get('DROPBOX_PROVIDER_CONFIG', {}) BASE_URL = config.get('BASE_URL', 'https://api.dropboxapi.com/1/') BASE_CONTENT_URL = config.get('BASE_CONTENT_URL', 'https://content.dropboxapi.com/1/')
Update drobox api urls h/t @felliott
Update drobox api urls h/t @felliott
Python
apache-2.0
RCOSDP/waterbutler,rdhyee/waterbutler,TomBaxter/waterbutler,felliott/waterbutler,CenterForOpenScience/waterbutler,Johnetordoff/waterbutler
9d78a7be6ea922844bc9c6a0795af8d7b7a247a3
bl/text.py
bl/text.py
import os, shutil, tempfile from bl.file import File from bl.string import String class Text(File): def __init__(self, fn=None, text=None, encoding='UTF-8', **args): File.__init__(self, fn=fn, encoding=encoding, **args) if text is not None: self.text = text elif fn ...
import os, shutil, tempfile from bl.file import File from bl.string import String class Text(File): def __init__(self, fn=None, text=None, encoding='UTF-8', **args): File.__init__(self, fn=fn, encoding=encoding, **args) if text is not None: self.text = text elif fn ...
Revert "allow to write Text with raw data"
Revert "allow to write Text with raw data" This reverts commit d05df9ea67bc626adc7a4940c9bad4881d672a38.
Python
mpl-2.0
BlackEarth/bl,BlackEarth/bl
c42092f643bf34c997f2b964e3d132ed95012755
scipy/testing/nulltester.py
scipy/testing/nulltester.py
''' Null tester (when nose not importable) Merely returns error reporting lack of nose package See pkgtester, nosetester modules ''' nose_url = 'http://somethingaboutorange.com/mrl/projects/nose' class NullTester(object): def __init__(self, *args, **kwargs): pass def test(self, labels=None, *args, ...
''' Null tester (when nose not importable) Merely returns error reporting lack of nose package See pkgtester, nosetester modules ''' nose_url = 'http://somethingaboutorange.com/mrl/projects/nose' class NullTester(object): def __init__(self, *args, **kwargs): pass def test(self, labels=None, *args, ...
Fix bench error on scipy import when nose is not installed
Fix bench error on scipy import when nose is not installed git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@3851 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt
d7a227ae5f0f53b5c620864df08c7b883402e968
netmiko/brocade/brocade_nos_ssh.py
netmiko/brocade/brocade_nos_ssh.py
"""Support for Brocade NOS/VDX.""" from __future__ import unicode_literals import time from netmiko.cisco_base_connection import CiscoSSHConnection class BrocadeNosSSH(CiscoSSHConnection): """Support for Brocade NOS/VDX.""" def enable(self, *args, **kwargs): """No enable mode on Brocade VDX.""" ...
"""Support for Brocade NOS/VDX.""" from __future__ import unicode_literals import time from netmiko.cisco_base_connection import CiscoSSHConnection class BrocadeNosSSH(CiscoSSHConnection): """Support for Brocade NOS/VDX.""" def enable(self, *args, **kwargs): """No enable mode on Brocade VDX.""" ...
Add save_config for brocade VDX
Add save_config for brocade VDX
Python
mit
ktbyers/netmiko,ktbyers/netmiko
457a40d3487d59147bcea71dd06f49317167c8d1
hash_table.py
hash_table.py
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self, key, value): self.key = key self.value = value cla...
#!/usr/bin/env python '''Implementation of a simple hash table. The table has `hash`, `get` and `set` methods. The hash function uses a very basic hash algorithm to insert the value into the table. ''' class HashItem(object): def __init__(self, key, value): self.key = key self.value = value cla...
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
Build out set function of hash table class; still need to deal with outcome of setting multiple values to same key
Python
mit
jwarren116/data-structures-deux
84783cdcdd52108df359cbe2add8c41b92b97e0b
openfisca_web_api/scripts/serve.py
openfisca_web_api/scripts/serve.py
# -*- coding: utf-8 -*- import os import sys from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp hostname = 'localhost' port = 2000 def main(): conf_file_path = os.path.join(sys.prefix, 'share', 'openfisca', 'openfisca-web-api', 'development-fr...
# -*- coding: utf-8 -*- import os import sys import argparse from logging.config import fileConfig from wsgiref.simple_server import make_server from paste.deploy import loadapp def main(): parser = argparse.ArgumentParser(description = __doc__) parser.add_argument('-p', '--port', action = 'store', default ...
Allow port to be changed
Allow port to be changed
Python
agpl-3.0
openfisca/openfisca-web-api,openfisca/openfisca-web-api
8dae2049c96932855cc0162437d799e258f94a53
test/absolute_import/local_module.py
test/absolute_import/local_module.py
""" This is a module that imports the *standard library* unittest, despite there being a local "unittest" module. It specifies that it wants the stdlib one with the ``absolute_import`` __future__ import. The twisted equivalent of this module is ``twisted.trial._synctest``. """ from __future__ import absolute_import i...
""" This is a module that imports the *standard library* unittest, despite there being a local "unittest" module. It specifies that it wants the stdlib one with the ``absolute_import`` __future__ import. The twisted equivalent of this module is ``twisted.trial._synctest``. """ from __future__ import absolute_import i...
Fix inaccuracy in test comment, since jedi now does the right thing
Fix inaccuracy in test comment, since jedi now does the right thing
Python
mit
dwillmer/jedi,flurischt/jedi,mfussenegger/jedi,tjwei/jedi,flurischt/jedi,jonashaag/jedi,jonashaag/jedi,mfussenegger/jedi,tjwei/jedi,WoLpH/jedi,WoLpH/jedi,dwillmer/jedi
e697e9887fa681918c9b10367ee2319969f591d0
test/auth/test_client_credentials.py
test/auth/test_client_credentials.py
from oauthlib.oauth2 import InvalidClientError import pytest from test import configure_mendeley, cassette def test_should_get_authenticated_session(): mendeley = configure_mendeley() auth = mendeley.start_client_credentials_flow() with cassette('fixtures/auth/client_credentials/get_authenticated_sessio...
from oauthlib.oauth2 import InvalidClientError import pytest from test import configure_mendeley, cassette def test_should_get_authenticated_session(): mendeley = configure_mendeley() auth = mendeley.start_client_credentials_flow() with cassette('fixtures/auth/client_credentials/get_authenticated_sessio...
Check for right kind of error in invalid creds test
Check for right kind of error in invalid creds test
Python
apache-2.0
Mendeley/mendeley-python-sdk
634e389ed260b404327e303afb4f5a1dc931ee36
storm/db.py
storm/db.py
from random import randrange import time from storm import error class Connection(object): def __init__(self, host='localhost', port=None, database=None, user=None, password=None): self.host = host self.port = port self.database = database self.user = user self.password = p...
import time from storm import error from tornado import gen class Connection(object): def __init__(self, host='localhost', port=None, database=None, user=None, password=None): self.host = host self.port = port self.database = database self.user = user self.password = passwo...
Make connection pool less smart
Make connection pool less smart You have to extend it and implement your own get_db function to use a connection pool now
Python
mit
liujiantong/storm,ccampbell/storm
2f65eba48e5bdeac85b12cac014cb648d068da46
tests/test_utils.py
tests/test_utils.py
import unittest from app import create_app, db from app.utils import get_or_create from app.models import User class TestUtils(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all() def t...
import unittest from app import create_app, db from app.utils import get_or_create, is_safe_url from app.models import User class TestUtils(unittest.TestCase): def setUp(self): self.app = create_app("testing") self.app_ctx = self.app.app_context() self.app_ctx.push() db.create_all...
Add unit test for is_safe_url utility function
Add unit test for is_safe_url utility function
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
b33654567ad3588ba51874ef109a9ee8efc0b0f0
tests/functional/firefox/test_hello.py
tests/functional/firefox/test_hello.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.hello import HelloPage @pytest.mark.smoke @pytest.mark.nondestructive def test_play_...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pytest from pages.firefox.hello import HelloPage @pytest.mark.smoke @pytest.mark.nondestructive def test_play_...
Fix failing Firefox Hello test
Fix failing Firefox Hello test
Python
mpl-2.0
sgarrity/bedrock,TheJJ100100/bedrock,alexgibson/bedrock,schalkneethling/bedrock,TheJJ100100/bedrock,gerv/bedrock,mozilla/bedrock,flodolo/bedrock,kyoshino/bedrock,TheoChevalier/bedrock,mozilla/bedrock,sgarrity/bedrock,craigcook/bedrock,pascalchevrel/bedrock,alexgibson/bedrock,sylvestre/bedrock,Sancus/bedrock,ericawright...
df790275ba9f06296f800ecd913eca8393c300c6
psyparse/handler/base_handler.py
psyparse/handler/base_handler.py
class BaseHandler(object): """ An abstract hanlder class to help define how a handler should behave. No methods are actually implemented and will raise a not-implemented error if an instance of a handler subclass does not implement any of the following methods. """ def new(self, entry): ...
class BaseHandler(object): """ An abstract hanlder class to help define how a handler should behave. No methods are actually implemented and will raise a not-implemented error if an instance of a handler subclass does not implement any of the following methods. """ def new(self, entry): ...
Fix bug in exception throwing (it caused an exception!).
Fix bug in exception throwing (it caused an exception!).
Python
mit
tnez/PsyParse
567d7c57def91c95620e8e5b1acda640b9c48a9d
src/startGUI.py
src/startGUI.py
# -*- coding: utf-8 -*- import util.colored_exceptions from gui import main_window from core import volumes, control from PySide import QtGui import sys import os import core.calculation if __name__ == '__main__': app = QtGui.QApplication(sys.argv) control = control.Control() window = main_window.MainWind...
# -*- coding: utf-8 -*- import util.colored_exceptions from gui import main_window from core import volumes, control from PySide import QtGui from PySide import QtCore import signal import sys import os import core.calculation if __name__ == '__main__': app = QtGui.QApplication(sys.argv) control = control.Con...
Allow quitting the application with SIGINT (Ctrl-C)
Allow quitting the application with SIGINT (Ctrl-C)
Python
mit
sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn,sciapp/pyMolDyn
370c49eba30253f259454884441e9921b51719ab
dudebot/ai.py
dudebot/ai.py
class BotAI(object): def set_nickname(self, nickname): self.nickname = nickname def initialise(self, init_params_as_dict): pass def respond(self, sender_nickname, message): pass class Echo(BotAI): def respond(self, sender_nickname, message): return True, message
class BotAI(object): def set_nickname(self, nickname): self.nickname = nickname def initialise(self, init_params_as_dict): pass def respond(self, sender_nickname, message): return False, '' class message_must_begin_with_prefix(object): """A simple decorator so that a bot AI ...
Add some decorators to make life easier.
Add some decorators to make life easier.
Python
bsd-2-clause
sujaymansingh/dudebot
96a08a9c7b11ce96de1c2034efcc19622c4eb419
drillion/ship_keys.py
drillion/ship_keys.py
from pyglet.window import key PLAYER_SHIP_KEYS = dict(left=[key.A, key.LEFT], right=[key.D, key.RIGHT], thrust=[key.W, key.UP], fire=[key.S, key.DOWN]) PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W], fire=[key.S]) PLAYER_2_SHIP_KEYS = dict(left=[...
from pyglet.window import key PLAYER_SHIP_KEYS = dict(left=[key.A, key.J], right=[key.D, key.L], thrust=[key.W, key.I], fire=[key.S, key.K]) PLAYER_1_SHIP_KEYS = dict(left=[key.A], right=[key.D], thrust=[key.W], fire=[key.S]) PLAYER_2_SHIP_KEYS = dict(left=[key.J], rig...
Change second ship controls to IJKL
Change second ship controls to IJKL
Python
mit
elemel/drillion
2b9efb699d557cbd47d54b10bb6ff8be24596ab4
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
src/nodeconductor_assembly_waldur/packages/tests/unittests/test_models.py
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory(components=[]) total = Decimal...
from decimal import Decimal import random from django.test import TestCase from .. import factories from ... import models class PackageTemplateTest(TestCase): def test_package_price_is_based_on_components(self): package_template = factories.PackageTemplateFactory() total = Decimal('0.00') ...
Update test according to factory usage
Update test according to factory usage
Python
mit
opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind
8c773a53902860409f83ff445402eb56d6376a88
app/utils/settings.py
app/utils/settings.py
from app.models import Setting class AppSettings(dict): def __init__(self): super().__init__() self.update({setting.name: setting.value for setting in Setting.query.all()}) self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page'))) def __setitem__(self, key, value): ...
from app.models import Setting class AppSettings(dict): def __init__(self): super().__init__() self.update({setting.name: setting.value for setting in Setting.query.all()}) try: self.__setitem__('posts_per_page', int(self.__getitem__('posts_per_page'))) except KeyError...
Add error handling for posts_per_page type conversion
Add error handling for posts_per_page type conversion
Python
mit
Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger
7dd467f474675c2c2535b6c3b925340b72959089
tests/settings.py
tests/settings.py
import os CONNECT_ARGS = [] CONNECT_KWARGS = {} LIVE_TEST = 'HOST' in os.environ if LIVE_TEST: HOST = os.environ['HOST'] DATABASE = os.environ.get('DATABASE', 'test') USER = os.environ.get('SQLUSER', 'sa') PASSWORD = os.environ.get('SQLPASSWORD', 'sa') USE_MARS = bool(os.environ.get('USE_MARS', Tr...
import os CONNECT_ARGS = [] CONNECT_KWARGS = {} LIVE_TEST = 'HOST' in os.environ if LIVE_TEST: HOST = os.environ['HOST'] DATABASE = os.environ.get('DATABASE', 'test') USER = os.environ.get('SQLUSER', 'sa') PASSWORD = os.environ.get('SQLPASSWORD', 'sa') USE_MARS = bool(os.environ.get('USE_MARS', Tr...
Use connection pool by default during testing
Use connection pool by default during testing
Python
mit
m32/pytds,m32/pytds,denisenkom/pytds,tpow/pytds,denisenkom/pytds,tpow/pytds
6d84cdb641d2d873118cb6cb26c5a7521ae40bd8
dcclient/dcclient.py
dcclient/dcclient.py
""" Main class from dcclient. Manages XML interaction, as well as switch and creates the actual networks """ import rpc from xml_manager.manager import ManagedXml from oslo.config import cfg class Manager: def __init__(self): self.rpc = rpc.RPC(cfg.CONF.ml2_datacom.dm_username, ...
""" Main class from dcclient. Manages XML interaction, as well as switch and creates the actual networks """ import rpc from xml_manager.manager import ManagedXml from neutron.openstack.common import log as logger from oslo.config import cfg LOG = logger.getLogger(__name__) class Manager: def __init__(self): ...
Add error treatment for existing network
Add error treatment for existing network
Python
apache-2.0
NeutronUfscarDatacom/DriverDatacom