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
38bb089a4885053c2058ba65ea9380fcc7c99f62
ulp/urlextract.py
ulp/urlextract.py
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.getenv('HOM...
# coding=utf-8 import re import os import sys # Regex for matching URLs # See https://mathiasbynens.be/demo/url-regex url_regex = re.compile(r"((https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?)") ansi_escape_regex = re.compile(r"(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]", re.IGNORECASE) INPUT_FILE = os.path.join(os.path.expand...
Use expanduser instead of env
Use expanduser instead of env
Python
mit
victal/ulp,victal/ulp
32c7baf89057741a898b10a01a7535c4af3f41b3
maestro/exceptions.py
maestro/exceptions.py
# Copyright (C) 2013 SignalFuse, Inc. # # Docker container orchestration utility. class MaestroException(Exception): """Base class for Maestro exceptions.""" pass class DependencyException(MaestroException): """Dependency resolution error.""" pass class ParameterException(MaestroException): ""...
# Copyright (C) 2013 SignalFuse, Inc. # # Docker container orchestration utility. class MaestroException(Exception): """Base class for Maestro exceptions.""" pass class DependencyException(MaestroException): """Dependency resolution error.""" pass class ParameterException(MaestroException): ""...
Add exception to denote YAML environment configuration issues
Add exception to denote YAML environment configuration issues Signed-off-by: Maxime Petazzoni <0706025b2bbcec1ed8d64822f4eccd96314938d0@signalfuse.com>
Python
apache-2.0
jorge-marques/maestro-ng,jorge-marques/maestro-ng,signalfuse/maestro-ng,signalfx/maestro-ng,Anvil/maestro-ng,Anvil/maestro-ng,ivotron/maestro-ng,signalfuse/maestro-ng,ivotron/maestro-ng,signalfx/maestro-ng,zsuzhengdu/maestro-ng,zsuzhengdu/maestro-ng
9120cfa9bb31e1cca5adba77ac7a872ed3b8dc99
tweets/models.py
tweets/models.py
from django.conf import settings from django.db import models class HashTag(models.Model): # The hash tag length can't be more than the body length minus the `#` text = models.CharField(max_length=139) def __str__(self): return self.text class Message(models.Model): user = models.ForeignKey...
from django.conf import settings from django.db import models class HashTag(models.Model): # The hash tag length can't be more than the body length minus the `#` text = models.CharField(max_length=139) def __str__(self): return self.text class Message(models.Model): user = models.ForeignKey...
Add blank to allow no stars/tags in admin
Add blank to allow no stars/tags in admin
Python
mit
pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone
fd4dc4bdd32283b67577630c38624d3df705efd3
mathphys/functions.py
mathphys/functions.py
"""Useful functions.""" import numpy as _np def polyfit(x, y, monomials, algorithm='lstsq'): """Implement Custom polyfit.""" X = _np.zeros((len(x), len(monomials))) N = _np.zeros((len(x), len(monomials))) for i in range(X.shape[1]): X[:, i] = x N[:, i] = monomials[i] XN = X ** N ...
"""Useful functions.""" import numpy as _np def polyfit(x, y, monomials): """Implement Custom polyfit.""" coef = _np.polynomial.polynomial.polyfit(x, y, deg=monomials) # finds maximum diff and its base value y_fitted = _np.polynomial.polynomial.polyval(x, coef) y_diff = abs(y_fitted - y) idx...
Change implementaton of polyfit method.
API: Change implementaton of polyfit method. Use new numpy.polynomial.polynomial.polyfit instead of implementing leastsquares by hand. This method is supposed to be more robust to numerical errors. With this change, the keyword argument algorithm was removed.
Python
mit
lnls-fac/mathphys
4a0516e6f7abee9378a5c46b7a262848a76d7f49
employees/serializers.py
employees/serializers.py
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last...
from .models import Employee from rest_framework import serializers class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee depth = 1 fields = ('pk', 'username', 'email', 'first_name', 'last...
Remove categories from employee serializer
Remove categories from employee serializer
Python
apache-2.0
belatrix/BackendAllStars
5ee949626b2d5b132f8ec1ce7d597a7ad401cfa5
epydemiology/__init__.py
epydemiology/__init__.py
# These are the functions that can be accessed from epydemiology. # Other functions that are used internally cannot be accessed # directly by end-users. from .phjCalculateProportions import phjCalculateBinomialProportions from .phjCalculateProportions import phjCalculateMultinomialProportions from .phjCleanData ...
# These are the functions that can be accessed from epydemiology. # Other functions that are used internally cannot be accessed # directly by end-users. from .phjCalculateProportions import phjCalculateBinomialProportions from .phjCalculateProportions import phjCalculateMultinomialProportions from .phjCleanData ...
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns
Add phjCollapseOnPatientID and remove phjGetCollapsedPatientDataframeColumns
Python
mit
lvphj/epydemiology
c147751066d8fb4e36a30f26d0acc614f0b2275f
transfers/models.py
transfers/models.py
import os from sqlalchemy import create_engine from sqlalchemy import Sequence from sqlalchemy import Column, Boolean, Integer, String, Text from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker db_path = os.path.join(os.path.dirname(__file__), 'transfers.db') engine = create...
import os from sqlalchemy import create_engine from sqlalchemy import Sequence from sqlalchemy import Column, Binary, Boolean, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker db_path = os.path.join(os.path.dirname(__file__), 'transfers.db') engine = crea...
Automate Transfers: Paths stored as binary to handle encodings
Automate Transfers: Paths stored as binary to handle encodings
Python
agpl-3.0
artefactual/automation-tools,finoradin/automation-tools,artefactual/automation-tools
22173c249ea0ee8eeceb9238f8f7418b7c3b29d8
misp_modules/modules/expansion/hashdd.py
misp_modules/modules/expansion/hashdd.py
import json import requests misperrors = {'error': 'Error'} mispattributes = {'input': ['md5'], 'output': ['text']} moduleinfo = {'version': '0.1', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']} moduleconfig = [...
import json import requests misperrors = {'error': 'Error'} mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']} moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']...
Update to support sha1 & sha256 attributes
add: Update to support sha1 & sha256 attributes
Python
agpl-3.0
VirusTotal/misp-modules,amuehlem/misp-modules,MISP/misp-modules,amuehlem/misp-modules,MISP/misp-modules,MISP/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,amuehlem/misp-modules
abf48b4c3ab7c78e44bc2d28ef6f3271c00abc42
ylio/__init__.py
ylio/__init__.py
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if ap...
from flask import Flask from flask.ext.assets import Environment, Bundle app = Flask(__name__, static_folder=None) app.config.from_pyfile('config.py') # Route static folder to /static in dev # and a subdomain in production app.static_folder = 'static' static_path = '/<path:filename>' static_subdomain = 'static' if ap...
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
Put static folder on a subdomain if SERVER_NAME isn't None, not if debug is False
Python
mit
joealcorn/yl.io,joealcorn/yl.io
c3c1234fb566ad20d7e67e55f8d8d908dbda55ad
post/urls.py
post/urls.py
from django.conf.urls import patterns, include, url from jmbo.urls import v1_api from jmbo.views import ObjectDetail from post.api import PostResource v1_api.register(PostResource()) # xxx: may need to include ckeditor urls here. check! urlpatterns = patterns( '', url( r'^(?P<slug>[\w-]+)/$', ...
from django.conf.urls import patterns, include, url from jmbo.urls import v1_api from jmbo.views import ObjectDetail from post.api import PostResource v1_api.register(PostResource()) # xxx: may need to include ckeditor urls here. check! urlpatterns = patterns( '', url( r'^(?P<category_slug>[\w-]+)...
Add post categorized view urlconf
Add post categorized view urlconf
Python
bsd-3-clause
praekelt/jmbo-post,praekelt/jmbo-post
63109e4d91f66c135c634752d3feb0e6dd4b9b97
nn/models/char2doc.py
nn/models/char2doc.py
import tensorflow as tf from ..embedding import embeddings_to_embedding, ids_to_embeddings, embeddings from ..linear import linear from ..dropout import dropout def char2doc(forward_document, backward_document, *, char_space_size, char_embedding_size, ...
import tensorflow as tf from ..embedding import id_sequence_to_embedding, embeddings from ..linear import linear from ..dropout import dropout def char2doc(document, *, char_space_size, char_embedding_size, document_embedding_size, dropout_prob, ...
Use id_sequence_to_embedding and only forward document
Use id_sequence_to_embedding and only forward document
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
76bc58d577e6d529dff3fc770667897bc48f6bfc
mainPage.py
mainPage.py
import sys from Tkinter import * mainWindow = Tk() windowWidth = 700 windowHeight = 600 screenXpos = (mainWindow.winfo_screenwidth() / 2) - (windowWidth / 2) screenYpos = (mainWindow.winfo_screenheight() / 2) - (windowHeight / 2) mainWindow.geometry(str(windowWidth) + 'x' + str(windowHeight) +\ '...
import sys from Tkinter import * # Define click functions def clickHome(): topLabelText.set("Home Screen") return def clickConstraint(): topLabelText.set("Constraint Screen") return def clickView(): topLabelText.set("View Screen") return def clickMisc(): topLabelText.set("Misc Screen") ...
Add side buttons, changing header label on click
Add side buttons, changing header label on click
Python
mit
donnell74/CSC-450-Scheduler
9bc3b7b24e185b1dd8bf8f979c8341fb332a401f
mm1_main.py
mm1_main.py
#!/usr/bin/env python # encoding: utf-8 import argparse import mm1 import sim import time ### Parse command line arguments parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script") parser.add_argument('sim_duration', metavar='simulation_duration', type=int, help='simul...
#!/usr/bin/env python # encoding: utf-8 import argparse import mm1 import sim import time ### Parse command line arguments parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script") parser.add_argument('sim_duration', metavar='simulation_duration', type=int, help='simul...
Add arguments for interarrival and service rates.
Add arguments for interarrival and service rates.
Python
mit
kubkon/des-in-python
051695d90b241323e650cd4931187de1750d924b
dataportal/tests/test_broker.py
dataportal/tests/test_broker.py
import unittest from datetime import datetime import numpy as np import pandas as pd from ..sources import channelarchiver as ca from ..sources import switch from ..broker.simple_broker import POPULAR_CHANNELS class TestBroker(unittest.TestCase): def setUp(self): switch(channelarchiver=False, metadatasto...
import unittest from datetime import datetime import numpy as np import pandas as pd from ..sources import channelarchiver as ca from ..sources import switch class TestBroker(unittest.TestCase): def setUp(self): switch(channelarchiver=False, metadatastore=False, filestore=False) start, end = '201...
Update tests after major broker refactor.
FIX: Update tests after major broker refactor.
Python
bsd-3-clause
NSLS-II/dataportal,ericdill/datamuxer,ericdill/datamuxer,danielballan/datamuxer,danielballan/datamuxer,NSLS-II/datamuxer,danielballan/dataportal,tacaswell/dataportal,tacaswell/dataportal,ericdill/databroker,ericdill/databroker,danielballan/dataportal,NSLS-II/dataportal
453abc420db1a9daf3b8d92d7f8ee8a8ace5bf9f
07/test_address.py
07/test_address.py
import unittest from address import has_reflection, is_compatible class TestAddress(unittest.TestCase): def test_has_reflection(self): assert has_reflection(['mnop']) == False assert has_reflection(['abba', 'qrst']) == True def test_is_compatible(self): assert is_compatible('abba[mno...
import unittest from address import has_reflection, is_compatible, load_addresses class TestAddress(unittest.TestCase): def test_has_reflection(self): assert has_reflection(['mnop']) == False assert has_reflection(['abba', 'qrst']) == True def test_is_compatible(self): assert is_comp...
Add tests for second protocol.
Add tests for second protocol.
Python
mit
machinelearningdeveloper/aoc_2016
e152213012c95dd820b341d11d940a172ca467d0
ethereum/tests/test_tester.py
ethereum/tests/test_tester.py
# -*- coding: utf8 -*- import json from os import path import pytest from ethereum.tester import state, ABIContract from ethereum._solidity import get_solidity, compile_file SOLIDITY_AVAILABLE = get_solidity() is not None CONTRACTS_DIR = path.join(path.dirname(__file__), 'contracts') @pytest.mark.skipif(not SOLIDI...
# -*- coding: utf8 -*- import json from os import path import pytest from ethereum.tester import state, ABIContract from ethereum._solidity import ( get_solidity, compile_file, solidity_get_contract_data, ) SOLIDITY_AVAILABLE = get_solidity() is not None CONTRACTS_DIR = path.join(path...
Adjust test to new compiler versions
Adjust test to new compiler versions
Python
mit
ethereum/pyethereum,ethereum/pyethereum,karlfloersch/pyethereum,karlfloersch/pyethereum
11d25c3f4391d3e9eb95c5b8fb1a2b73cbf123a0
cli/commands/cmd_stripe.py
cli/commands/cmd_stripe.py
import logging import click import stripe from config import settings from catwatch.blueprints.billing.services import StripePlan from catwatch.app import create_app app = create_app() @click.group() def cli(): """ Perform various tasks with Stripe's API. """ stripe.api_key = app.config.get('STRIPE_SECRET...
import logging import click import stripe from config import settings as settings_ from catwatch.blueprints.billing.services import StripePlan try: from instance import settings except ImportError: logging.error('Your instance/ folder must contain an __init__.py file') exit(1) @click.group() def cli():...
Remove the need to create an app in the stripe CLI
Remove the need to create an app in the stripe CLI
Python
mit
nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask,z123/build-a-saas-app-with-flask,nickjj/build-a-saas-app-with-flask
bb23c2bfa31913658b526b9dbaf812c749e9523c
pentai/gui/goodbye_screen.py
pentai/gui/goodbye_screen.py
import kivy.core.window import pentai.db.zodb_dict as z_m from pentai.gui.screen import Screen class GoodByeScreen(Screen): def __init__(self, *args, **kwargs): super(GoodByeScreen, self).__init__(*args, **kwargs) print "init goodbye screen" def on_enter(self, *args, **kwargs): app = ...
import kivy.core.window from kivy.clock import Clock import pentai.db.zodb_dict as z_m from pentai.gui.screen import Screen class GoodByeScreen(Screen): def __init__(self, *args, **kwargs): super(GoodByeScreen, self).__init__(*args, **kwargs) print "init goodbye screen" def on_enter(self, *ar...
Fix prob with wooden board leftover.
Fix prob with wooden board leftover.
Python
mit
cropleyb/pentai,cropleyb/pentai,cropleyb/pentai
6203b25a2d8d742f066917dd7e5f2c8dc0ee9e7c
pavement.py
pavement.py
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def push(): """Install the app and start it.""" call('palm-package', '.') call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') call('palm-install', '--device=...
import subprocess from paver.easy import * def call(*args, **kwargs): return subprocess.call(args, **kwargs) @task def push(): """Install the app and start it.""" call('palm-package', '.') call('palm-install', '--device=emulator', '-r', 'org.markpasc.paperplain') call('palm-install', '--device=...
Add a task for tailing the app's log on the emulator
Add a task for tailing the app's log on the emulator
Python
mit
markpasc/paperplain,markpasc/paperplain
0925c1f2ab3332ddfaeefed81f379dc72dd41644
openid/test/test_urinorm.py
openid/test/test_urinorm.py
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc ...
import os import unittest import openid.urinorm class UrinormTest(unittest.TestCase): def __init__(self, desc, case, expected): unittest.TestCase.__init__(self) self.desc = desc self.case = case self.expected = expected def shortDescription(self): return self.desc ...
Make urinorm tests runnable on their own
Make urinorm tests runnable on their own
Python
apache-2.0
misli/python3-openid,misli/python3-openid,moreati/python3-openid,misli/python3-openid,necaris/python3-openid,isagalaev/sm-openid,moreati/python3-openid,moreati/python3-openid,necaris/python3-openid
bb602407a176813cc1727423e1b344f0a1b0bea7
tests/test_Science.py
tests/test_Science.py
""" Scientific tests for SLCosmo package """ import matplotlib matplotlib.use('Agg') import unittest import desc.slcosmo class SLCosmoScienceTestCase(unittest.TestCase): def setUp(self): self.message = 'Testing SLCosmo - For Science!' def tearDown(self): pass def test_round_trip(self): ...
""" Scientific tests for SLCosmo package """ import matplotlib matplotlib.use('Agg') import os import unittest import desc.slcosmo class SLCosmoScienceTestCase(unittest.TestCase): def setUp(self): self.message = 'Testing SLCosmo - For Science!' self.Lets = desc.slcosmo.SLCosmo() def tearDown(...
Clean up after science test
Clean up after science test
Python
bsd-3-clause
DarkEnergyScienceCollaboration/SLCosmo,DarkEnergyScienceCollaboration/SLCosmo
ade960c76de6773a176d2cd982ac9a26a2d072ae
tests/unit/network/CubicTemplateTest.py
tests/unit/network/CubicTemplateTest.py
import openpnm as op from skimage.morphology import ball, disk class CubicTemplateTest: def setup_class(self): pass def teardown_class(self): pass def test_2D_template(self): net = op.network.CubicTemplate(template=disk(10), spacing=1) assert net.Np == 317 assert ...
import numpy as np import openpnm as op from skimage.morphology import ball, disk class CubicTemplateTest: def setup_class(self): pass def teardown_class(self): pass def test_2D_template(self): net = op.network.CubicTemplate(template=disk(10), spacing=1) assert net.Np == ...
Add test for CubicTemplate to ensure proper labeling
Add test for CubicTemplate to ensure proper labeling
Python
mit
TomTranter/OpenPNM,PMEAL/OpenPNM
44f232e179a2fe152ef6a7aa9e6e5cd52a4f201e
plasmapy/physics/__init__.py
plasmapy/physics/__init__.py
from .parameters import (Alfven_speed, ion_sound_speed, electron_thermal_speed, ion_thermal_speed, electron_gyrofrequency, ion_gyrofrequency, electron_gyroradius, ...
# 'physics' is a tentative name for this subpackage. Another # possibility is 'plasma'. The organization is to be decided by v0.1. from .parameters import (Alfven_speed, ion_sound_speed, electron_thermal_speed, ion_thermal_speed, ...
Comment that physics is a tentative subpackage name
Comment that physics is a tentative subpackage name
Python
bsd-3-clause
StanczakDominik/PlasmaPy
10ae930f6f14c2840d0b87cbec17054b4cc318d2
facebook_auth/models.py
facebook_auth/models.py
from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models.TextField(blank=True, null=True) app_friends = models...
from uuid import uuid1 from django.conf import settings from django.contrib.auth import models as auth_models from django.db import models import facepy import simplejson from facebook_auth import utils class FacebookUser(auth_models.User): user_id = models.BigIntegerField(unique=True) access_token = models....
Add support for server side authentication.
Add support for server side authentication. Change-Id: Iff45fa00b5a5b389f998570827e33d9d232f5d1e Reviewed-on: http://review.pozytywnie.pl:8080/5087 Reviewed-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com> Tested-by: Tomasz Wysocki <f17c2dc043305c950a029074ababd304e0373387@gmail.com>
Python
mit
pozytywnie/django-facebook-auth,pozytywnie/django-facebook-auth,jgoclawski/django-facebook-auth,jgoclawski/django-facebook-auth
887149522b4cbce5e84fe25897358600e88be29d
inbox/notify/__init__.py
inbox/notify/__init__.py
from redis import StrictRedis, BlockingConnectionPool from inbox.config import config import json REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME') REDIS_DB = int(config.get('NOTIFY_QUEUE_REDIS_DB')) MAX_CONNECTIONS = 40 redis_pool = BlockingConnectionPool( max_connections=MAX_CONNECTIONS, host=REDI...
import json from redis import StrictRedis, BlockingConnectionPool from inbox.config import config from nylas.logging import get_logger log = get_logger() REDIS_HOSTNAME = config.get('NOTIFY_QUEUE_REDIS_HOSTNAME') REDIS_PORT = int(config.get('NOTIFY_QUEUE_REDIS_PORT', 6379)) REDIS_DB = int(config.get('NOTIFY_QUEUE_REDI...
Add logger an try/except logic
Add logger an try/except logic
Python
agpl-3.0
jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine
6a410b9079cffec380ac44cf390be381be929e5d
autoencoder/api.py
autoencoder/api.py
from .io import preprocess from .train import train from .network import autoencoder from .encode import encode def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True, mask=None, type='normal', activation='relu', learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0....
from .io import preprocess from .train import train from .network import autoencoder from .encode import encode def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True, mask=None, type='normal', activation='relu', testset=False, learning_rate=1e-2, hidden_size=(256,64,2...
Make preprocess testset argument accessible through API
Make preprocess testset argument accessible through API
Python
apache-2.0
theislab/dca,theislab/dca,theislab/dca
aaa74513f8b947cf542b59408816be9ed1867644
atc/atcd/setup.py
atc/atcd/setup.py
#!/usr/bin/env python # # Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # # ...
#!/usr/bin/env python # # Copyright (c) 2014, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # # ...
Make atcd depends on atc_thrift package implicitely
Make atcd depends on atc_thrift package implicitely
Python
bsd-3-clause
jamesblunt/augmented-traffic-control,linearregression/augmented-traffic-control,biddyweb/augmented-traffic-control,beni55/augmented-traffic-control,linearregression/augmented-traffic-control,duydb2/ZTC,shinyvince/augmented-traffic-control,Endika/augmented-traffic-control,drptbl/augmented-traffic-control,shinyvince/augm...
c87be7a48d496cffe24f31ca46db0a7629a0b2a8
utilkit/stringutil.py
utilkit/stringutil.py
""" String/unicode helper functions """ def safe_unicode(obj, *args): """ return the unicode representation of obj """ try: return unicode(obj, *args) except UnicodeDecodeError: # obj is byte string ascii_text = str(obj).encode('string_escape') return unicode(ascii_text) de...
""" String/unicode helper functions """ def safe_unicode(obj, *args): """ return the unicode representation of obj """ try: return unicode(obj, *args) # pylint:disable=undefined-variable except UnicodeDecodeError: # obj is byte string ascii_text = str(obj).encode('string_escape') ...
Disable error-checking that assumes Python 3 for these Python 2 helpers
Disable error-checking that assumes Python 3 for these Python 2 helpers
Python
mit
aquatix/python-utilkit
66289d6620758de0da80e91c6a492e39626c9029
tests/integration.py
tests/integration.py
#!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'...
#!/usr/bin/env python import unittest import subprocess class TestSimpleMapping(unittest.TestCase): def test_map_1_read(self): subprocess.run(['python', 'bin/sillymap', 'index', 'tests/test_data/reference.fa']) result = subprocess.run(['python', 'bin/sillymap', 'map', 'tests/test_data/reference.fa'...
Remove index file created in test
Remove index file created in test
Python
mit
alneberg/sillymap
21d940192fa390b1a2de3183e099194bceaeeafe
tests/test_arrays.py
tests/test_arrays.py
from thinglang.thinglang import run def test_simple_arrays(): assert run(""" thing Program does start array names = ["yotam", "andrew", "john"] Output.write(names) """).output == """['yotam', 'andrew', 'john']"""
from thinglang.thinglang import run def test_simple_arrays(): assert run(""" thing Program does start array names = ["yotam", "andrew", "john"] Output.write(names) """).output == """['yotam', 'andrew', 'john']""" def test_array_initialization_over_function_calls(): assert run(""" th...
Add test for more complex array initization case
Add test for more complex array initization case
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
f682e0bc4b8506a45846a74fe537917ba0ffd5bb
tests/test_format.py
tests/test_format.py
from unittest.mock import MagicMock, patch import pytest from hypothesis_auto import auto_pytest_magic import isort.format auto_pytest_magic(isort.format.show_unified_diff) def test_ask_whether_to_apply_changes_to_file(): with patch("isort.format.input", MagicMock(return_value="y")): assert isort.forma...
from unittest.mock import MagicMock, patch import pytest from hypothesis_auto import auto_pytest_magic import isort.format auto_pytest_magic(isort.format.show_unified_diff, auto_allow_exceptions_=(UnicodeEncodeError,)) def test_ask_whether_to_apply_changes_to_file(): with patch("isort.format.input", MagicMock(...
Fix test case to be more explicit
Fix test case to be more explicit
Python
mit
PyCQA/isort,PyCQA/isort
1e3109f154ab86273996e4b598cea706c766cb8b
spec/settings_spec.py
spec/settings_spec.py
# -*- coding: utf-8 -*- from mamba import describe, context, before from sure import expect from mamba.settings import Settings IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1' with describe('Settings') as _: @before.each def create_settings(): _.settings = Settings() with context('when loading defaults...
# -*- coding: utf-8 -*- from mamba import describe, context from sure import expect from mamba.settings import Settings IRRELEVANT_SLOW_TEST_THRESHOLD = '0.1' with describe(Settings) as _: with context('when loading defaults'): def it_should_have_75_millis_as_slow_test_threshold(): expect(_...
Use subject for test settings
Use subject for test settings
Python
mit
jaimegildesagredo/mamba,nestorsalceda/mamba,alejandrodob/mamba,angelsanz/mamba,eferro/mamba,markng/mamba,dex4er/mamba
6e04a5c4953ef3fde5f2f5b3ef4f7fd8b7e8437e
tests/test_server.py
tests/test_server.py
def test_info(logged_rocket): info = logged_rocket.info().json() assert "info" in info assert info.get("success") def test_statistics(logged_rocket): statistics = logged_rocket.statistics().json() assert statistics.get("success") def test_statistics_list(logged_rocket): statistics_list = log...
from rocketchat_API.rocketchat import RocketChat def test_info(logged_rocket): info = logged_rocket.info().json() assert "info" in info assert info.get("success") def test_statistics(logged_rocket): statistics = logged_rocket.statistics().json() assert statistics.get("success") def test_statis...
Add a test to check that authentication using the token directly works
Add a test to check that authentication using the token directly works
Python
mit
jadolg/rocketchat_API
0f08eb828091204c6131ee868a43f2a8f3ed73f4
tests/test_widget.py
tests/test_widget.py
from django.conf import settings from django.test import TestCase from localized_fields.value import LocalizedValue from localized_fields.widgets import LocalizedFieldWidget class LocalizedFieldWidgetTestCase(TestCase): """Tests the workings of the :see:LocalizedFieldWidget class.""" @staticmethod def t...
import re from django.conf import settings from django.test import TestCase from localized_fields.value import LocalizedValue from localized_fields.widgets import LocalizedFieldWidget class LocalizedFieldWidgetTestCase(TestCase): """Tests the workings of the :see:LocalizedFieldWidget class.""" @staticmethod...
Add test on render method
Add test on render method
Python
mit
SectorLabs/django-localized-fields,SectorLabs/django-localized-fields,SectorLabs/django-localized-fields
96513ab379341d6db0aa7ce16aa20b8d1a93dc69
runtests.py
runtests.py
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "account", "forums", "forums.tests" ], DATABAS...
#!/usr/bin/env python import os import sys import django from django.conf import settings DEFAULT_SETTINGS = dict( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", "account", "pinax.forums", "pinax.forums.tests" ],...
Fix two left over renames
Fix two left over renames
Python
mit
pinax/pinax-forums
0398c7539c1bebcaa6622576f4acef970394d6a7
runtests.py
runtests.py
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.ses...
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.ses...
Fix test runner for trunk
Fix test runner for trunk
Python
mit
treyhunner/django-email-log,treyhunner/django-email-log
ae8b0d5eab43a349f33d3eb907565cb2931e15cd
jedi/api/replstartup.py
jedi/api/replstartup.py
""" To use Jedi completion in Python interpreter, add the following in your shell setup (e.g., ``.bashrc``):: export PYTHONSTARTUP="$(python -m jedi repl)" Then you will be able to use Jedi completer in your Python interpreter:: $ python Python 2.7.2+ (default, Jul 20 2012, 22:15:08) [GCC 4.6.1] on l...
""" To use Jedi completion in Python interpreter, add the following in your shell setup (e.g., ``.bashrc``):: export PYTHONSTARTUP="$(python -m jedi repl)" Then you will be able to use Jedi completer in your Python interpreter:: $ python Python 2.7.2+ (default, Jul 20 2012, 22:15:08) [GCC 4.6.1] on l...
Print the Jedi version when REPL completion is used
Print the Jedi version when REPL completion is used This also makes debugging easier, because people see which completion they're actually using.
Python
mit
tjwei/jedi,mfussenegger/jedi,WoLpH/jedi,mfussenegger/jedi,jonashaag/jedi,flurischt/jedi,WoLpH/jedi,flurischt/jedi,jonashaag/jedi,dwillmer/jedi,dwillmer/jedi,tjwei/jedi
e50333baa8390ae3bedb77f1442c9d90cf6ea4b0
mint/userlisting.py
mint/userlisting.py
# # Copyright (c) 2005 rpath, Inc. # # All Rights Reserved # ( USERNAME_ASC, USERNAME_DES, FULLNAME_ASC, FULLNAME_DES, CREATED_ASC, CREATED_DES, ACCESSED_ASC, ACCESSED_DES ) = range(0, 8) blurbindex = 5 blurbtrunclength = 300 sqlbase = """SELECT userid, username, fullname, timeCreated,...
# # Copyright (c) 2005 rpath, Inc. # # All Rights Reserved # ( USERNAME_ASC, USERNAME_DES, FULLNAME_ASC, FULLNAME_DES, CREATED_ASC, CREATED_DES, ACCESSED_ASC, ACCESSED_DES ) = range(0, 8) blurbindex = 5 blurbtrunclength = 300 sqlbase = """SELECT userid, username, fullname, timeCreated,...
Hide yet-to-be-activated usernames from listings
Hide yet-to-be-activated usernames from listings
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
d45df810c6ae9482f935ccfddef6c96438d893a3
OpenPNM/Geometry/models/pore_centroid.py
OpenPNM/Geometry/models/pore_centroid.py
r""" =============================================================================== pore_centroid =============================================================================== """ import scipy as _sp def voronoi(network, geometry, vertices='throat.centroid', **kwargs): r""" Calculate the centroid from the...
r""" =============================================================================== pore_centroid =============================================================================== """ import scipy as _sp def voronoi(network, geometry, vertices='throat.centroid', **kwargs): r""" Calculate the centroid from the...
Fix bug in pore centroid
Fix bug in pore centroid
Python
mit
amdouglas/OpenPNM,PMEAL/OpenPNM,TomTranter/OpenPNM,stadelmanma/OpenPNM,amdouglas/OpenPNM
4d4279cf97d6b925e687423a0681793c9ab3ef56
runtests.py
runtests.py
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitema...
#!/usr/bin/env python from os.path import dirname, abspath import sys from django.conf import settings if not settings.configured: from django import VERSION settings_dict = dict( INSTALLED_APPS=( 'localeurl', 'localeurl.tests', 'django.contrib.sites', # for sitema...
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
Add SITE_ID to test settings since contrib.sites is in INSTALLED_APPS.
Python
mit
eugena/django-localeurl
60ed71891d628989fa813f2f750e8cb9d1f19f9d
runtests.py
runtests.py
#!/usr/bin/env python import sys from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS=( ...
#!/usr/bin/env python import sys import django from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } }, INSTALLED_APPS...
Call django.setup() for Django >= 1.7.0
Call django.setup() for Django >= 1.7.0
Python
bsd-3-clause
rochapps/django-secure-input,rochapps/django-secure-input,rochapps/django-secure-input
1cccb432d0f7abc468a36a22ee5c9d3845fbd636
runtests.py
runtests.py
#!/usr/bin/env python import sys import unittest from os.path import dirname, abspath import tests def runtests(*test_args): suite = unittest.TestLoader().loadTestsFromModule(tests) result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit() if __name__ == '__main__': runtests(*sys.argv[1:])...
#!/usr/bin/env python import sys import unittest from os.path import dirname, abspath import tests def runtests(*test_args): suite = unittest.TestLoader().loadTestsFromModule(tests) result = unittest.TextTestRunner(verbosity=2).run(suite) sys.exit(bool(result.failures)) if __name__ == '__main__': ru...
Return exit code indicating failure
Return exit code indicating failure
Python
mit
giserh/peewee,coleifer/peewee,Dipsomaniac/peewee,coreos/peewee,d1hotpep/peewee,jarrahwu/peewee,mackjoner/peewee,d1hotpep/peewee,bopo/peewee,bopo/peewee,coleifer/peewee,jarrahwu/peewee,jnovinger/peewee,wenxer/peewee,coleifer/peewee,fuzeman/peewee,fuzeman/peewee,new-xiaji/peewee,wenxer/peewee,zhang625272514/peewee,Sunzhi...
7648ac7ae01ee6cde8871128e162e8a4d5322b87
s3upload.py
s3upload.py
#!/usr/bin/python import sys import boto3 s3 = boto3.resource('s3') object = s3.Bucket('ictrp-data').upload_file(sys.argv[1], sys.argv[1]) object.Acl().put(ACL='public-read')
#!/usr/bin/python import sys import boto3 s3 = boto3.resource('s3') with open(sys.argv[1], 'rb') as f: object = s3.Bucket('ictrp-data').put_object(Key=sys.argv[1], Body=f) object.Acl().put(ACL='public-read')
Fix failing attempt to set ACL
Fix failing attempt to set ACL
Python
mit
gertvv/ictrp-retrieval,gertvv/ictrp-retrieval
80aa4574da8754db544d66167b61823de1cbf281
source/globals/fieldtests.py
source/globals/fieldtests.py
# -*- coding: utf-8 -*- ## \package globals.fieldtests # MIT licensing # See: LICENSE.txt import wx ## Tests if a wx control/instance is enabled/disabled # # Function for compatibility between wx versions # \param field # \b \e wx.Window : the wx control to check # \param enabled # \b \e bool : Check i...
# -*- coding: utf-8 -*- ## \package globals.fieldtests # MIT licensing # See: LICENSE.txt import wx ## Tests if a wx control/instance is enabled/disabled # # Function for compatibility between wx versions # \param field # \b \e wx.Window : the wx control to check # \param enabled # \b \e bool : Check i...
Fix FieldsEnabled function & add 'enabled' argument
Fix FieldsEnabled function & add 'enabled' argument
Python
mit
AntumDeluge/desktop_recorder,AntumDeluge/desktop_recorder
7060e3f1b1e8bda4c96cdc4b0c84ae344ac81c76
Sketches/MPS/test/test_Selector.py
Sketches/MPS/test/test_Selector.py
#!/usr/bin/python import unittest import sys; sys.path.append("../") from Selector import Selector if __name__=="__main__": unittest.main()
#!/usr/bin/python import unittest import sys; sys.path.append("../") from Selector import Selector class SmokeTests_Selector(unittest.TestCase): def test_SmokeTest(self): """__init__ - Called with no arguments succeeds""" S = Selector() self.assert_(isinstance(S, Axon.Component.component)...
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.
Add the most basic smoke test. We make a check that the resulting object is a minimal component at least.
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
2b5e33bf178cd1fdd8e320051d0c99a45d7613a1
models/product_bundle.py
models/product_bundle.py
# -*- encoding: utf-8 -*- from openerp import fields, models, _ import openerp.addons.decimal_precision as dp class product_bundle(models.Model): _name = 'product.bundle' _description = 'Product bundle' name = fields.Char(_('Name'), help=_('Product bundle name'), required=True) bundle_line_ids = fie...
# -*- encoding: utf-8 -*- from openerp import fields, models, _ import openerp.addons.decimal_precision as dp class product_bundle(models.Model): _name = 'product.bundle' _description = 'Product bundle' name = fields.Char(_('Name'), help=_('Product bundle name'), required=True) bundle_line_ids = fie...
Use of product.template instead of product.product in bundle line
Use of product.template instead of product.product in bundle line
Python
agpl-3.0
akretion/sale-workflow,richard-willowit/sale-workflow,ddico/sale-workflow,Eficent/sale-workflow,anas-taji/sale-workflow,BT-cserra/sale-workflow,BT-fgarbely/sale-workflow,fevxie/sale-workflow,diagramsoftware/sale-workflow,adhoc-dev/sale-workflow,thomaspaulb/sale-workflow,kittiu/sale-workflow,factorlibre/sale-workflow,nu...
b52a23c87bed0370c41da39785812b9064688af0
passman/__main__.py
passman/__main__.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto import commandline import database import encry...
#!/usr/bin/python3 # -*- coding: utf-8 -*- ''' Main driver of the program ''' import sys import random import os import json import argparse import time import getpass import hashlib import ast import threading import base64 import pymongo import pyperclip import Crypto from passman.login import handleLogin, handleOf...
Remove unnecessary imports from main
Remove unnecessary imports from main
Python
mit
regexpressyourself/passman
72068701db46dc3d66cde295187b7d167cbfd880
gather/account/api.py
gather/account/api.py
# -*- coding:utf-8 -*- from flask import g, jsonify from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instance_id`, t...
# -*- coding:utf-8 -*- from flask import g, jsonify, request from gather.account.models import Account from gather.api import need_auth, EXCLUDE_COLUMNS from gather.extensions import api_manager __all__ = ["bp"] def patch_single_preprocessor(instance_id=None, data=None, **kw): """Accepts two arguments, `instan...
Add API to change password
Add API to change password
Python
mit
whtsky/Gather,whtsky/Gather
5b4049b3aa27a8a2e02c768eb411b35f4518821e
predict_imagenet.py
predict_imagenet.py
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __...
from __future__ import print_function from __future__ import absolute_import from keras.applications.imagenet_utils import decode_predictions from keras.preprocessing import image import numpy as np from mobilenets import MobileNets def preprocess_input(x): x /= 255. x -= 0.5 x *= 2. return x if __...
Remove extra support for 1000 classes as no longer needed
Remove extra support for 1000 classes as no longer needed
Python
apache-2.0
titu1994/MobileNetworks
f4837fd60ce09b69d334fcad1403b721723d3504
tests/test_conf.py
tests/test_conf.py
import sys from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Setting...
from unittest import mock import pytest from bottery.conf import Settings @pytest.fixture def mocked_settings(): settings = mock.MagicMock() sys.modules['settings'] = settings yield settings del sys.modules['settings'] @pytest.mark.skip def test_global_settings(): settings = Settings() as...
Remove unused sys import from conf tests
Remove unused sys import from conf tests
Python
mit
rougeth/bottery
b60e76f6d6c5363ed4d07b43338911b3cdb8ca39
ofp_app/demo/conntest.py
ofp_app/demo/conntest.py
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest') @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn in conns.stats: ...
from ofp_app import ofp_app, ofp_run import asyncio app = ofp_app('conntest', kill_on_exception=True) @app.event('start') async def start(_): while True: await asyncio.sleep(1) # Obtain a list of connections. conns = await app.rpc_call('OFP.LIST_CONNECTIONS', conn_id=0) for conn ...
Terminate app if handler throws exception.
Terminate app if handler throws exception.
Python
mit
byllyfish/pylibofp,byllyfish/pylibofp
89b14bd0add6a56d9128f2ce3fa4ca710f64d5d7
opal/tests/test_utils.py
opal/tests/test_utils.py
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) class Itersubc...
""" Unittests for opal.utils """ from django.test import TestCase from django.db.models import ForeignKey, CharField from opal import utils class StringportTestCase(TestCase): def test_import(self): import collections self.assertEqual(collections, utils.stringport('collections')) def test_im...
Add some tests for stringport
Add some tests for stringport
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
265e169570db18b53b86a55b94871f1eb25dfd4d
gvi/transactions/models.py
gvi/transactions/models.py
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.Fore...
from django.db import models class Category(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=50, unique=True) def __str__(self): return self.number class Subcategory(models.Model): name = models.CharField(max_length=50) category = models.Fore...
Change the field type of amount and balance to DecimalField
Change the field type of amount and balance to DecimalField
Python
mit
m1k3r/gvi-accounts,m1k3r/gvi-accounts,m1k3r/gvi-accounts
dc47c88d5f1c6f1e78322c5bfcb585e54b3a0c0a
python/colorTest.py
python/colorTest.py
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / ...
#!/usr/bin/env python from rgbmatrix import RGBMatrix from random import randint import time rows = 16 chains = 1 parallel = 1 ledMatrix = RGBMatrix(rows, chains, parallel) height = ledMatrix.height width = ledMatrix.width for x in range(width): for y in range(height): r = int(y % 8 / 7.0 * 255) g = int(x % 8 / ...
Remove print and increase speed
Remove print and increase speed
Python
mit
DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix
458f1e269646f432ef52774230114a4b05351211
controllers/default.py
controllers/default.py
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resou...
import os def index(): def GET(): return locals() @request.restful() def api(): response.view = 'generic.json' def GET(resource,resource_id): if not resource=='study': raise HTTP(400) # return the correct nexson of study_id return _get_nexson(resource_id) def POST(resou...
Use the new location of study NexSON
Use the new location of study NexSON Each study now has a distinct directory. Currently we only plan to store a single JSON file in each directory, until one becomes larger than 50MB. Additionally, this allows various metadata/artifacts about a study to live near the actually study data.
Python
bsd-2-clause
leto/new_opentree_api,leto/new_opentree_api
57428c3ef4c80733c2309aea2db71624b188a055
oath_toolkit/_compat.py
oath_toolkit/_compat.py
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # 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...
# -*- coding: utf-8 -*- # # Copyright 2013 Mark Lee # # 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...
Fix broken test on Python 3.3
Fix broken test on Python 3.3
Python
apache-2.0
malept/pyoath-toolkit,malept/pyoath-toolkit,malept/pyoath-toolkit
5b8fe62647eade5d9c060c027e5658cf0eb531f2
pygraphc/clustering/__init__.py
pygraphc/clustering/__init__.py
from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterEvaluation import * from pygraphc.clustering.ClusterUtility import * from pygraphc.clustering.ConnectedComponents import * from pygraphc.clustering.KCliquePercolation import * from pygraphc.clustering.MaxCliquesPercolation import * impor...
import pygraphc.clustering.ClusterDistance import pygraphc.clustering.ClusterUtility import pygraphc.clustering.ConnectedComponents import pygraphc.clustering.KCliquePercolation import pygraphc.clustering.MaxCliquesPercolation from pygraphc.clustering.ClusterDistance import * from pygraphc.clustering.ClusterUtility imp...
Change path for the module ClusterEvaluation
Change path for the module ClusterEvaluation
Python
mit
studiawan/pygraphc
4339b61aad98d10f91f44c82b72376bc88c3ec22
pivot/views/data_api.py
pivot/views/data_api.py
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf ...
import os try: from urllib.parse import urljoin from urllib.request import urlopen except: # for Python 2.7 compatibility from urlparse import urljoin from urllib2 import urlopen from django.shortcuts import render from django.views import View from django.http import HttpResponse from django.conf ...
Clean up now that we're no longer trying to use CSV_URL.
Clean up now that we're no longer trying to use CSV_URL.
Python
apache-2.0
uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot,uw-it-aca/pivot
05551b6b7ed1ed9a97be635f3d32b5bd4f26f635
tests/mltils/test_infrequent_value_encoder.py
tests/mltils/test_infrequent_value_encoder.py
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', '...
# pylint: disable=missing-docstring, invalid-name, import-error import pandas as pd from mltils.encoders import InfrequentValueEncoder def test_infrequent_value_encoder_1(): ive = InfrequentValueEncoder() assert ive is not None def test_infrequent_value_encoder_2(): df = pd.DataFrame({'A': ['a', 'a', '...
Add more unit tests for InfrequentValueEncoder
Add more unit tests for InfrequentValueEncoder
Python
mit
rladeira/mltils
d879d74aa078ca5a89a7e7cbd1bebe095449411d
snobol/constants.py
snobol/constants.py
# Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0.497, 0.7078, 0.576, -0.713, 0.239, -0.027] #...
"""Constants for use by the bolometric correction routine """ # Coefficients for polynomial fit to bolometric correction - color relation coeff_BminusV = [-0.823, 5.027, -13.409, 20.133, -18.096, 9.084, -1.950] coeff_VminusI = [-1.355, 6.262, -2.676, -22.973, 35.524, -15.340] coeff_BminusI = [-1.096, 3.038, -2.246, -0...
Add documentation string for cosntants module
Add documentation string for cosntants module
Python
mit
JALusk/SNoBoL,JALusk/SNoBoL,JALusk/SuperBoL
39bf1013c5b2b4a18be6de3a3f2002908bf36014
test/all.py
test/all.py
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Softwa...
#! /usr/bin/env python ######################################################################## # SimpleFIX # Copyright (C) 2016, David Arnold. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Softwa...
Add init tests to CI.
Add init tests to CI.
Python
mit
da4089/simplefix
86a44c855ebc84d422b2338090f4ca6d0d01cee5
cf_predict/__init__.py
cf_predict/__init__.py
import sys from flask import Flask from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION: # pragma: no cover (manual test) sys.exit("Python {}.{}+ is r...
import sys from flask import Flask from mockredis import MockRedis from flask_redis import FlaskRedis from .config import config from .api import api_bp __project__ = 'cf-predict' __version__ = '0.0.0' VERSION = "{0} v{1}".format(__project__, __version__) PYTHON_VERSION = 3, 4 if sys.version_info < PYTHON_VERSION:...
Add Redis client from flask-redis
Add Redis client from flask-redis
Python
mit
ronert/cf-predict,ronert/cf-predict
c35887025a2127a527862e664d1ef3bb5c4f528a
Constants.py
Constants.py
IRC_numeric_to_name = {"001": "RPL_WELCOME", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
IRC_numeric_to_name = {"001": "RPL_WELCOME", "315": "RPL_ENDOFWHO", "352": "RPL_WHOREPLY", "372": "RPL_MOTD", "375": "RPL_MOTDSTART", "376": "RPL_ENDOFMOTD", "433": "ERR_NICKNAMEINUSE"} CTCP_DELIMITER = chr(1)
Add some needed IRC numerics
Add some needed IRC numerics
Python
mit
Didero/DideRobot
b5672d55beb837f21d761f50740b93c5b1e0dc5d
napalm/exceptions.py
napalm/exceptions.py
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are 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 requi...
# Copyright 2015 Spotify AB. All rights reserved. # # The contents of this file are 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 requi...
Raise ConnectionException when device unusable
Raise ConnectionException when device unusable
Python
apache-2.0
napalm-automation/napalm-base,napalm-automation/napalm-base,Netflix-Skunkworks/napalm-base,napalm-automation/napalm,Netflix-Skunkworks/napalm-base,spotify/napalm,bewing/napalm-base,spotify/napalm,bewing/napalm-base
7086b1967c3a3666260e6358c72cb15c74213bea
sunpy/net/tests/test_attr.py
sunpy/net/tests/test_attr.py
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & other) is other
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> from __future__ import absolute_import from sunpy.net import attr from sunpy.net.vso import attrs def test_dummyattr(): one = attr.DummyAttr() other = attr.ValueAttr({'a': 'b'}) assert (one | other) is other assert (one & othe...
Add tests for Attr nesting
Add tests for Attr nesting
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
b0699b4683a241449889ee712ae57bb13f0e3eaa
tests/backends/gstreamer.py
tests/backends/gstreamer.py
import unittest from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) class GStreamerCurrentPlaylistHandlerTest(BaseCurrentPlaylistControllerTest, unittest.TestCase): uris =...
import unittest import os from mopidy.backends.gstreamer import GStreamerBackend from tests.backends.basetests import (BasePlaybackControllerTest, BaseCurrentPlaylistControllerTest) folder = os.path.dirname(__file__) folder = os.path.join(folder, '..', 'data') folder = os.path.a...
Use actuall mp3s for testing
Use actuall mp3s for testing
Python
apache-2.0
dbrgn/mopidy,SuperStarPL/mopidy,kingosticks/mopidy,adamcik/mopidy,hkariti/mopidy,ali/mopidy,jodal/mopidy,jmarsik/mopidy,rawdlite/mopidy,tkem/mopidy,priestd09/mopidy,abarisain/mopidy,pacificIT/mopidy,vrs01/mopidy,diandiankan/mopidy,quartz55/mopidy,mopidy/mopidy,swak/mopidy,liamw9534/mopidy,mokieyue/mopidy,bencevans/mopi...
430246e54add2ef99fd3d8e87b05ba4b178e0336
tests/test_subgenerators.py
tests/test_subgenerators.py
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) ...
import pytest from resumeback import send_self from . import CustomError, defer, wait_until_finished, State def test_subgenerator_next(): ts = State() def subgenerator(this): yield defer(this.next) ts.run = True @send_self def func(this): yield from subgenerator(this) ...
Use return value in subgenerator test
Use return value in subgenerator test
Python
mit
FichteFoll/resumeback
fea7a2c0e4f4f3da50935d03db4b9e19a0fc477c
shakespearelang/utils.py
shakespearelang/utils.py
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_l...
def parseinfo_context(parseinfo, context_amount = 3): buffer = parseinfo.buffer context_start_line = max(parseinfo.line - 1 - context_amount, 0) before_context_lines = buffer.get_lines(context_start_line, parseinfo.line - 1) lines = buffer.get_lines(parseinfo.line, parseinfo.endline) after_context_l...
Use ">>" for indicating next event, fix bug with indexing
Use ">>" for indicating next event, fix bug with indexing
Python
mit
zmbc/shakespearelang,zmbc/shakespearelang,zmbc/shakespearelang
da097ed41010961cc0814d55d8784787f3ea8a63
skimage/util/arraypad.py
skimage/util/arraypad.py
from __future__ import division, absolute_import, print_function from numpy import pad as numpy_pad def pad(array, pad_width, mode, **kwargs): return numpy_pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = numpy_pad.__doc__
from __future__ import division, absolute_import, print_function import numpy as np def pad(array, pad_width, mode, **kwargs): return np.pad(array, pad_width, mode, **kwargs) # Pull function info / docs from NumPy pad.__doc__ = np.pad.__doc__
Change import structure for doctests
Change import structure for doctests
Python
bsd-3-clause
rjeli/scikit-image,paalge/scikit-image,rjeli/scikit-image,vighneshbirodkar/scikit-image,vighneshbirodkar/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,rjeli/scikit-image,paalge/scikit-image
14110deb4d31d27f74d16ff062030ee9dccc221e
multi_schema/middleware.py
multi_schema/middleware.py
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): ...
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class Schem...
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Python
bsd-3-clause
luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse
eb90169c2d38244af61e135ed279b8d42f1a8ef5
test/test_sampling.py
test/test_sampling.py
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) ...
# -*- coding: utf-8 -*- from __future__ import division import sys import pytest from profiling.sampling import SamplingProfiler from profiling.sampling.samplers import ItimerSampler from utils import find_stats, spin def spin_100ms(): spin(0.1) def spin_500ms(): spin(0.5) @pytest.mark.flaky(reruns=10) ...
Increase test coverage of `profiling.sampling`
Increase test coverage of `profiling.sampling`
Python
bsd-3-clause
sublee/profiling,JeanPaulShapo/profiling,JeanPaulShapo/profiling,what-studio/profiling,sublee/profiling,what-studio/profiling
504ae635e08ccf0784db0a0586e8796f5bd360bb
test_chatbot_brain.py
test_chatbot_brain.py
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def te...
import chatbot_brain stock = u"What a funny thing to say!" def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 ...
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Add test_i_filter_random_words_not_in_lexicon() to assert the stock phrase is returned if all the words are not in the lexicon
Python
mit
corinnelhh/chatbot,corinnelhh/chatbot
20147b8b8a80ef8ab202d916bf1cdfb67d4753d3
SelfTests.py
SelfTests.py
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correc...
import os import unittest from Logger import Logger class TestLogger(unittest.TestCase): def test_file_handling(self): testLog = Logger("testLog") ## Check if program can create and open file self.assertTrue(testLog.opened) returns = testLog.close() ## Check if logger correc...
Test of logger is testing an testPhrase instead of two manually writen strings
Test of logger is testing an testPhrase instead of two manually writen strings Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
Python
mit
TeaPackCZ/RobotZed,TeaPackCZ/RobotZed
0c00acb19274626241f901ea85a124511dfe4526
server/lepton_server.py
server/lepton_server.py
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo fr...
#!/usr/bin/env python import sys import time import zmq import numpy as np try: import progressbar except ImportError: progressbar = None try: import pylepton except ImportError: print "Couldn't import pylepton, using Dummy data!" Lepton = None # importing packages in parent folders is voodoo fr...
Remove third dimension from image array
Remove third dimension from image array
Python
mit
wonkoderverstaendige/raspi_lepton
822ae0442bf5091be234dc9470a79c83f909ff35
txircd/modules/conn_join.py
txircd/modules/conn_join.py
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.chan...
from txircd.channel import IRCChannel from txircd.modbase import Module class Autojoin(Module): def joinOnConnect(self, user): if "client_join_on_connect" in self.ircd.servconfig: for channel in self.ircd.servconfig["client_join_on_connect"]: user.join(self.ircd.channels[channel] if channel in self.ircd.chan...
Fix once again nobody being allowed to connect
Fix once again nobody being allowed to connect
Python
bsd-3-clause
Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd
c498bb6ac7a80ac2668fef22fa6600de6fc9af89
dakota/plugins/base.py
dakota/plugins/base.py
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define defa...
#! /usr/bin/env python """An abstract base class for all Dakota component plugins.""" from abc import ABCMeta, abstractmethod class PluginBase(object): """Describe features common to all Dakota plugins.""" __metaclass__ = ABCMeta @abstractmethod def __init__(self, **kwargs): """Define defa...
Update argument lists for abstract methods
Update argument lists for abstract methods
Python
mit
csdms/dakota,csdms/dakota
883ec0d68140995cfedc2d64d7d80cac1e234f39
app/oauth.py
app/oauth.py
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, ...
# -*- coding: utf-8 -*- import logging import httplib2 import json import time import random from apiclient import errors from apiclient.discovery import build from oauth2client.client import SignedJwtAssertionCredentials class OAuth(): __services = dict() @staticmethod def getCredentials(email, scopes, ...
Revert "Revert "Do not cache discovery""
Revert "Revert "Do not cache discovery"" This reverts commit e8aca80abcf8c309c13360c386b9505a595e1998.
Python
mit
lumapps/lumRest
1eaae78c14b26378a606221eb61f97ec15134baa
src/gpl/test/simple01-td.py
src/gpl/test/simple01-td.py
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design...
from openroad import Design, Tech import helpers import gpl_aux tech = Tech() tech.readLiberty("./library/nangate45/NangateOpenCellLibrary_typical.lib") tech.readLef("./nangate45.lef") design = Design(tech) design.readDef("./simple01-td.def") design.evalTclString("create_clock -name core_clock -period 2 clk") design...
Remove dead code from test
Remove dead code from test Signed-off-by: Don MacMillen <1f1e67e5fdb25d2e5cd18ddc0fee425272daab56@macmillen.net>
Python
bsd-3-clause
The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,The-OpenROAD-Project/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD,QuantamHD/OpenROAD
d1bd82008c21942dee0ed29ba6d4f9eb54f2af33
issues/signals.py
issues/signals.py
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal(providing_args=('request', 'issue'))
from django.dispatch import Signal #: Signal fired when a new issue is posted via the API. issue_posted = Signal() # Provides arguments: ('request', 'issue')
Remove documenting argument from Signal
Remove documenting argument from Signal
Python
mit
6aika/issue-reporting,6aika/issue-reporting,6aika/issue-reporting
c36c4e36c5f2ef5f270923172be04d528ad37090
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '44c71d88d9c098ece5dbf3e1fcc93ab87d8193cd' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', ...
#!/usr/bin/env python import platform import sys BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '7e0bebc8666de8438c5baf4967fdabfc7646b3ed' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[0], 'win32': '32bit', ...
Upgrade libchromiumcontent to fix linking error
Upgrade libchromiumcontent to fix linking error
Python
mit
pombredanne/electron,thompsonemerson/electron,jjz/electron,tonyganch/electron,bobwol/electron,electron/electron,voidbridge/electron,howmuchcomputer/electron,gbn972/electron,Jacobichou/electron,leftstick/electron,wolfflow/electron,jlord/electron,robinvandernoord/electron,eriser/electron,destan/electron,Jonekee/electron,...
85c9206dd0a4af52a31d7b6e9283bc7c103e3953
demos/dlgr/demos/iterated_drawing/models.py
demos/dlgr/demos/iterated_drawing/models.py
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of ...
import base64 import json import os import random from dallinger.nodes import Source class DrawingSource(Source): """A Source that reads in a random image from a file and transmits it.""" __mapper_args__ = {"polymorphic_identity": "drawing_source"} def _contents(self): """Define the contents of ...
Fix encoding of source image to work on Python3
Fix encoding of source image to work on Python3
Python
mit
Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger
0230c94110e99f31aea413230a908bae8cce467d
testfixtures/tests/test_docs.py
testfixtures/tests/test_docs.py
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from os.path import dirname,join,pardir from . import compat def test_suite(): m = doctest.Manue...
# Copyright (c) 2009-2012 Simplistix Ltd # # See license.txt for more details. from doctest import REPORT_NDIFF,ELLIPSIS from glob import glob from manuel import doctest, capture from manuel.testing import TestSuite from nose.plugins.skip import SkipTest from os.path import dirname, join, pardir import os from . imp...
Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)
Allow docs to test to be found elsewhere. (they're not unpacked by installing the sdist)
Python
mit
nebulans/testfixtures,Simplistix/testfixtures
18910b6cfa94a88763d2295c4b4644ed099ef382
tests/test_options.py
tests/test_options.py
from av.option import Option from common import * class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') self.assertIs...
from common import * from av.option import Option, OptionTypes as types class TestOptions(TestCase): def test_mov_options(self): mov = av.ContainerFormat('mov') options = mov.descriptor.options by_name = {opt.name: opt for opt in options} opt = by_name.get('use_absolute_path') ...
Fix the one broken test due to OptionType enum.
Fix the one broken test due to OptionType enum.
Python
bsd-3-clause
pupil-labs/PyAV,pupil-labs/PyAV,pupil-labs/PyAV,PyAV-Org/PyAV,pupil-labs/PyAV,mikeboers/PyAV,mikeboers/PyAV,PyAV-Org/PyAV
35c9740826d2b7636647e45afab4ec87075647a6
timm/utils/metrics.py
timm/utils/metrics.py
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 ...
""" Eval metrics and related Hacked together by / Copyright 2020 Ross Wightman """ import torch class AverageMeter: """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 sel...
Fix accuracy when topk > num_classes
Fix accuracy when topk > num_classes
Python
apache-2.0
rwightman/pytorch-image-models,rwightman/pytorch-image-models
f935a14967f8b66342d34efca9ceff9eecd384be
app.py
app.py
#!/usr/bin/env python import os from flask import Flask, render_template app = Flask(__name__) @app.route('/') def root(): genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Rap' },\ { 'rank':'2', 'title':'Started from the Bottom',...
#!/usr/bin/env python import os from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) genres = ('Hip Hop', 'Electronic', 'R&B') songs = [\ { 'rank':'1', 'title':'The Motto', 'artist':'Drake', 'year':'2013', 'genre':'Hip Hop' },\ { 'rank':'2', 'title':'Started from the Bottom', ...
Enable submission of new songs via form.
Enable submission of new songs via form.
Python
mit
alykhank/Tunezout,alykhank/Tunezout
c873fa541f58e2c8be35d0854da7d5aa3491267a
src/sentry/status_checks/celery_alive.py
src/sentry/status_checks/celery_alive.py
from __future__ import absolute_import from time import time from sentry import options from .base import StatusCheck, Problem class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:last_worker_ping') or 0 if last_ping >= time() - 300: return [] ...
from __future__ import absolute_import from time import time from django.core.urlresolvers import reverse from sentry import options from sentry.utils.http import absolute_uri from .base import Problem, StatusCheck class CeleryAliveCheck(StatusCheck): def check(self): last_ping = options.get('sentry:l...
Add link to queue graphs for `CeleryAliveCheck` result.
Add link to queue graphs for `CeleryAliveCheck` result.
Python
bsd-3-clause
mvaled/sentry,beeftornado/sentry,mvaled/sentry,BuildingLink/sentry,mitsuhiko/sentry,BuildingLink/sentry,mvaled/sentry,fotinakis/sentry,jean/sentry,JamesMura/sentry,alexm92/sentry,zenefits/sentry,mvaled/sentry,mitsuhiko/sentry,jean/sentry,JamesMura/sentry,beeftornado/sentry,JackDanger/sentry,looker/sentry,jean/sentry,lo...
42cc93590bef8e97c76e79110d2b64906c34690d
config_template.py
config_template.py
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } ate = { 'path': '', 'python_env': '' } neuroate = { 'path': '', 'pyth...
chatbot_ubuntu = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_swisscom = { 'path': '', 'model_id': '', 'python_env': '' } chatbot_ubuntu_seq2seq = { 'socket_address': '', 'socket_port': '' } chatbot_goaloriented = { 'socket_address': '127.0.0.1', 'socket_port': 8889 ...
Add ports and fix bug
Add ports and fix bug
Python
mit
nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos,nachoaguadoc/aimlx-demos
b00cc9aa45a455b187bec869e367422bb78785c1
luigi_td/targets/tableau.py
luigi_td/targets/tableau.py
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 't...
from luigi_td.targets.result import ResultTarget import urllib import logging logger = logging.getLogger('luigi-interface') class TableauServerResultTarget(ResultTarget): # required server = None username = None password = None datasource = None # optional ssl = 'true' ssl_verify = 't...
Fix the option name for Tableau server version
Fix the option name for Tableau server version
Python
apache-2.0
treasure-data/luigi-td
78c13173fadbdc3d261ab3690ffb9c37d8f8a72d
bootstrap.py
bootstrap.py
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin ...
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin ...
Update to reflect new create_app signature
Update to reflect new create_app signature
Python
mit
openannotation/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,ningyifan/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,happybelly/annotator-store
bf790bb1ad59cca3034715e9e5c92e128bd1902e
apps/users/admin.py
apps/users/admin.py
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user', 'reason') admin.site.reg...
from django.contrib import admin from users.models import UserBan class UserBanAdmin(admin.ModelAdmin): fields = ('user', 'by', 'reason', 'is_active') list_display = ('user', 'by', 'reason') list_filter = ('is_active',) raw_id_fields = ('user',) search_fields = ('user__username', 'reason') admi...
Use explicit related-lookup syntax in ban search.
Use explicit related-lookup syntax in ban search.
Python
mpl-2.0
biswajitsahu/kuma,davehunt/kuma,SphinxKnight/kuma,escattone/kuma,yfdyh000/kuma,ronakkhunt/kuma,carnell69/kuma,tximikel/kuma,darkwing/kuma,YOTOV-LIMITED/kuma,SphinxKnight/kuma,safwanrahman/kuma,a2sheppy/kuma,safwanrahman/kuma,MenZil/kuma,tximikel/kuma,bluemini/kuma,SphinxKnight/kuma,whip112/Whip112,biswajitsahu/kuma,ana...
72a5f58d7c7fe18f5ce4c2e02cf8a26146777f27
social/apps/pyramid_app/__init__.py
social/apps/pyramid_app/__init__.py
def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{backend}') config.add_route('social.disconnect_association', '/disconnect/{backend}/{association_...
from social.strategies.utils import set_current_strategy_getter from social.apps.pyramid_app.utils import load_strategy def includeme(config): config.add_route('social.auth', '/login/{backend}') config.add_route('social.complete', '/complete/{backend}') config.add_route('social.disconnect', '/disconnect/{...
Set current strategy on pyramid app
Set current strategy on pyramid app
Python
bsd-3-clause
SeanHayes/python-social-auth,SeanHayes/python-social-auth,JerzySpendel/python-social-auth,ariestiyansyah/python-social-auth,bjorand/python-social-auth,drxos/python-social-auth,tkajtoch/python-social-auth,ByteInternet/python-social-auth,VishvajitP/python-social-auth,lawrence34/python-social-auth,JerzySpendel/python-soci...
c0a6a18363e3bdaab67c4abb15add441e7a975ca
glaciercmd/command_upload_file_to_vault.py
glaciercmd/command_upload_file_to_vault.py
import boto class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_access_key=config.get('configuration', 'aws_secret')) try: vault = glacier_connection.get_vault(args[5]) ...
import boto import time import os from boto.dynamodb2.table import Table from boto.dynamodb2.layer1 import DynamoDBConnection class CommandUploadFileToVault(object): def execute(self, args, config): glacier_connection = boto.connect_glacier(aws_access_key_id=config.get('configuration', 'aws_key'), aws_secret_a...
Save archive ids to dynamodb
Save archive ids to dynamodb
Python
mit
carsonmcdonald/glacier-cmd
5cc071958aa63f46ec7f3708648f80a8424c661b
Lib/compositor/cmap.py
Lib/compositor/cmap.py
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): cmap = {} cmapIDs = [(3, 10), (0, 3), (3, 1)] for i in range(len(cmapIDs)): if ttFont["cmap"].getcmap(*cmapIDs[i]): cmap = ttFont["cmap"].getcmap(*cmapIDs[i]).cmap break ...
""" Utilities for handling the cmap table and character mapping in general. """ def extractCMAP(ttFont): for platformID, encodingID in [(3, 10), (0, 3), (3, 1)]: cmapSubtable = ttFont["cmap"].getcmap(platformID, encodingID) if cmapSubtable is not None: return cmapSubtable.cmap from ...
Make the code more compact
Make the code more compact
Python
mit
typesupply/compositor,anthrotype/compositor,anthrotype/compositor,typesupply/compositor
6cd9b0c731839a75cd8e8bd2ab1e5d2f2687c96a
shirka/responders/__init__.py
shirka/responders/__init__.py
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(obj...
# vim: set fileencoding=utf-8 : class Responder(object): def support(message): pass def generate(message): pass def on_start(self, consumer): return False def support(self, request): return request.content[0:len(self.name())] == self.name() class Response(obj...
Remove import for graphite responder
Remove import for graphite responder
Python
mit
rande/python-shirka,rande/python-shirka
9b79f940806dbcd7a7326c955b2bc3bbd47892ea
test_results/plot_all.py
test_results/plot_all.py
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot(num_plots, 1, count) ...
import glob import csv import numpy as np import matplotlib.pyplot as plt for file in glob.glob("*.csv"): data = np.genfromtxt(file, delimiter = ',', names = True) plt.figure() plt.suptitle(file) num_plots = len(data.dtype.names) count = 1 for col_name in data.dtype.names: plt.subplot...
Add test name to plot as title, maximize plot window
Add test name to plot as title, maximize plot window
Python
agpl-3.0
BrewPi/firmware,BrewPi/firmware,glibersat/firmware,BrewPi/firmware,etk29321/firmware,BrewPi/firmware,BrewPi/firmware,BrewPi/firmware,glibersat/firmware,etk29321/firmware,etk29321/firmware,etk29321/firmware,glibersat/firmware,glibersat/firmware,BrewPi/firmware,glibersat/firmware,etk29321/firmware,glibersat/firmware,glib...
601b35c2ad07d7927c9473c6cbf500d1fec3e307
tests/test_invariants.py
tests/test_invariants.py
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataCla...
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.hypothesis2 import examples from tests.hypothesis2.strategies import deques, optionals from tests.test_entities import (DataCla...
Rename encode/decode parameterization in test
Rename encode/decode parameterization in test
Python
mit
lidatong/dataclasses-json,lidatong/dataclasses-json
cd8407831091d169677d278d3ad9b5b92600b30a
generator/generator.py
generator/generator.py
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def)...
""" Main class for doing the work. """ from helper import Helper from renderer import Renderer class Generator(object): @classmethod def generate_statements(cls, class_list_def): """ :type class_list_def: str """ class_def_list = Helper.parse_definition_string(class_list_def)...
Fix exception handling syntax error
Fix exception handling syntax error
Python
apache-2.0
HappyRay/php-di-generator
cbb59747af48ae60473f27b6de976a08a741ab54
tests/test_test_utils.py
tests/test_test_utils.py
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] @classm...
""" Tests for our testing utilities. """ from itertools import product from unittest import TestCase from zipline.utils.test_utils import parameter_space class TestParameterSpace(TestCase): x_args = [1, 2] y_args = [3, 4] @classmethod def setUpClass(cls): cls.xy_invocations = [] cls....
Add test for parameter_space ordering.
TEST: Add test for parameter_space ordering.
Python
apache-2.0
magne-max/zipline-ja,florentchandelier/zipline,Scapogo/zipline,florentchandelier/zipline,bartosh/zipline,wilsonkichoi/zipline,bartosh/zipline,alphaBenj/zipline,wilsonkichoi/zipline,humdings/zipline,humdings/zipline,umuzungu/zipline,alphaBenj/zipline,enigmampc/catalyst,enigmampc/catalyst,magne-max/zipline-ja,quantopian/...
ce7d3e1da44d9f33474684db674f3a7660587320
source/services/rotten_tomatoes_service.py
source/services/rotten_tomatoes_service.py
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self...
import requests from bs4 import BeautifulSoup from source.models.rt_rating import RTRating class RottenTomatoesService: __URL = 'http://www.rottentomatoes.com/m/' __SEPERATOR = '_' def __init__(self, title): self.title = title def get_rt_rating(self): search_url = self.__URL + self...
Add character replacements for RT search
Add character replacements for RT search
Python
mit
jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu
494b628ab57c38335368a1b7a2734c7abafc5277
buildcert.py
buildcert.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request for request in Request.query.filter(Request.generation_date == None).all(): # noqa prompt = "Do you want to generate a certificate for {}, {} ?" print(prompt.format(...
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from subprocess import call from ca import app, db from ca.models import Request from flask import Flask, render_template from flask_mail import Mail, Message def mail_certificate(id, email): msg = Message('Freifunk Vpn03 Key', sender = 'no-reply@ca...
Add mail_certificate which sends email with flask-mail
Add mail_certificate which sends email with flask-mail Replace COMMAND_MAIL. Send certs from /etc/openvpn/client/ Use template /templates/mail.txt
Python
mit
freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net,freifunk-berlin/ca.berlin.freifunk.net