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
d1d7684edb6d687206deea75d2ba13194046e376
sixquiprend/models/chosen_card.py
sixquiprend/models/chosen_card.py
from sixquiprend.sixquiprend import app, db class ChosenCard(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE")) game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASCADE")) card_id = db.Column(db.Integer...
from sixquiprend.sixquiprend import app, db from sixquiprend.models.card import Card class ChosenCard(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE")) game_id = db.Column(db.Integer, db.ForeignKey('game.id', ondelete="CASC...
Move an import to top
Move an import to top
Python
mit
nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend,nyddogghr/SixQuiPrend
166c1a4dde981d5bd7d20a00c8329d7bbb4a3c00
nipype/interfaces/setup.py
nipype/interfaces/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('interfaces', parent_package, top_path) config.add_data_dir('tests') config.add_data_dir('data') config.add_data_dir('script_templates') return config if __name__ ==...
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('interfaces', parent_package, top_path) config.add_data_dir('tests') config.add_data_dir('script_templates') return config if __name__ == '__main__': from numpy.dist...
Remove reference to non-existing data directory.
Remove reference to non-existing data directory. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@513 ead46cd0-7350-4e37-8683-fc4c6f79bf00
Python
bsd-3-clause
arokem/nipype,gerddie/nipype,iglpdc/nipype,pearsonlab/nipype,carlohamalainen/nipype,Leoniela/nipype,glatard/nipype,dgellis90/nipype,satra/NiPypeold,glatard/nipype,mick-d/nipype,carolFrohlich/nipype,blakedewey/nipype,dgellis90/nipype,pearsonlab/nipype,mick-d/nipype_source,FCP-INDI/nipype,dgellis90/nipype,carolFrohlich/n...
56ac100c8ca357a5600db7a16859cca1483ccb13
blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
blueprints/multi_node_kubernetes_cluster/teardown_kubernetes_cluster/teardown_kubernetes_cluster.py
""" Teardown the CloudBolt resources (container_orchestrator, environment) associated with this Kubernetes cluster. """ from common.methods import set_progress from containerorchestrators.kuberneteshandler.models import Kubernetes def run(job, *args, **kwargs): resource = job.resource_set.first() contain...
""" Teardown the CloudBolt resources (container_orchestrator, environment) associated with this Kubernetes cluster. """ from common.methods import set_progress from containerorchestrators.kuberneteshandler.models import Kubernetes from utilities.run_command import execute_command def run(job, *args, **kwargs): re...
Remove config files from filesystem on teardown
Remove config files from filesystem on teardown [DEV-13843]
Python
apache-2.0
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
f1d2bb08dfde9402b7fc858d57130b43e3f1cd4d
bootstrap/hooks.py
bootstrap/hooks.py
# coding: utf-8 from os.path import join, dirname, pardir, abspath from shutil import copy import subprocess BOOTSTRAP = abspath(dirname(__file__)) ROOT = abspath(join(BOOTSTRAP, pardir)) # Path where venv will be created. It's imported by bootstrapX.Y.py VIRTUALENV = abspath(join(BOOTSTRAP, pardir)) ACTIVATE = jo...
# coding: utf-8 from os.path import join, dirname, pardir, abspath from shutil import copy import subprocess BOOTSTRAP = abspath(dirname(__file__)) ROOT = abspath(join(BOOTSTRAP, pardir)) # Path where venv will be created. It's imported by bootstrapX.Y.py VIRTUALENV = join(BOOTSTRAP, pardir) VIRTUALENV_BIN = join(VI...
Fix wrong destination for postactivate file.
Fix wrong destination for postactivate file.
Python
mit
henriquebastos/virtualenv-bootstrap,henriquebastos/virtualenv-bootstrap
8e72ef3fa525c961786e9b60c039c847bc2c710f
caSandbox.py
caSandbox.py
import map import curses # Set up Curses screen screen = curses.initscr() curses.noecho() screen.keypad(True) curses.cbreak() curses.halfdelay(5) # Wait for half a second for input before continuing curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_WH...
import map import curses # Set up Curses screen screen = curses.initscr() curses.noecho() screen.keypad(True) curses.cbreak() curses.halfdelay(5) # Wait for half a second for input before continuing curses.start_color() curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_WH...
Make program close on any keypress
Make program close on any keypress
Python
mit
cferwin/CA-Sandbox
bf38a26ea239ce70fd4fc3748912b243fb1f7d88
tools/perf/benchmarks/pica.py
tools/perf/benchmarks/pica.py
# Copyright 2013 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 telemetry import test from telemetry.page import page_measurement class PicaMeasurement(page_measurement.PageMeasurement): def MeasurePage(self, _, t...
# Copyright 2013 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 telemetry import test from telemetry.page import page_measurement class PicaMeasurement(page_measurement.PageMeasurement): def CustomizeBrowserOption...
Enable native custom elements for Pica benchmark
Enable native custom elements for Pica benchmark R=tonyg@chromium.org BUG=245358 Review URL: https://codereview.chromium.org/22884003 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217042 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,Chilledheart/chromium,mogoweb/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium...
2f72f75da7ba03e331927c5ab0a5702c150b2f9a
perfrunner/celeryremote.py
perfrunner/celeryremote.py
BROKER_URL = 'amqp://couchbase:couchbase@ci.sc.couchbase.com:5672/broker' CELERY_RESULT_BACKEND = 'amqp' CELERY_RESULT_EXCHANGE = 'perf_results' CELERY_RESULT_PERSISTENT = False
BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker' CELERY_RESULT_BACKEND = 'amqp' CELERY_RESULT_EXCHANGE = 'perf_results' CELERY_RESULT_PERSISTENT = False
Use broker IP instead of domain name
Use broker IP instead of domain name Change-Id: Ide27c97a00c18ac62c1a92e2ec51c74c5af4cf30 Reviewed-on: http://review.couchbase.org/81029 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couchbase.com> Reviewed-by: Pavel Paulau <dd88eded64e90046a680e3a6c0828ceb8fe8a0e7@gmail.com>
Python
apache-2.0
couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner
a5bc36df3435258fad9700c150985998e9663ff9
haas/tests/test_coverage.py
haas/tests/test_coverage.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals try: import coverage except ImportErr...
# -*- coding: utf-8 -*- # Copyright (c) 2013-2014 Simon Jagoe # All rights reserved. # # This software may be modified and distributed under the terms # of the 3-clause BSD license. See the LICENSE.txt file for details. from __future__ import absolute_import, unicode_literals try: import coverage from ..cover...
Fix test error when coverage is not installed
Fix test error when coverage is not installed
Python
bsd-3-clause
itziakos/haas,scalative/haas,sjagoe/haas,sjagoe/haas,scalative/haas,itziakos/haas
49bf8bd8137928a1dc5165f38f8abfe423f5e7f0
pi_director/controllers/user_controls.py
pi_director/controllers/user_controls.py
from pyramid.response import Response from pi_director.models.models import ( DBSession, MyModel, ) from pi_director.models.UserModel import UserModel def authorize_user(email): user=DBSession.query(UserModel).filter(UserModel.email==email).one() user.AccessLevel=2 DBSession.flush() def delet...
from pyramid.response import Response from pi_director.models.models import ( DBSession, MyModel, ) from pi_director.models.UserModel import UserModel def authorize_user(email): user=DBSession.query(UserModel).filter(UserModel.email==email).one() user.AccessLevel=2 DBSession.flush() def delet...
Create the user if it isn't already in the database first, then make it an admin.
Create the user if it isn't already in the database first, then make it an admin.
Python
mit
selfcommit/pi_director,PeterGrace/pi_director,selfcommit/pi_director,PeterGrace/pi_director,PeterGrace/pi_director,selfcommit/pi_director
6d450dccc7e89e4e90fd1f0f27cdf2aa67166859
conanfile.py
conanfile.py
from conans import ConanFile, CMake class SocketwConan(ConanFile): name = "SocketW" version = "3.10.36" license = "GNU Lesser General Public License v2.1" url = "https://github.com/RigsOfRods/socketw/issues" description = "SocketW is a library which provides cross-platform socket abstraction" ...
from conans import ConanFile, CMake class SocketwConan(ConanFile): name = "SocketW" version = "3.10.36" license = "GNU Lesser General Public License v2.1" url = "https://github.com/RigsOfRods/socketw/issues" description = "SocketW is a library which provides cross-platform socket abstraction" ...
Use collect_libs for finding libs
Use collect_libs for finding libs
Python
lgpl-2.1
Hiradur/mysocketw,Hiradur/mysocketw
0a02b896c7f8499504a855652de22bab10824c69
database_setup.py
database_setup.py
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80),...
import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Restaurant(Base): __tablename__ = 'restaurant' name = Column(String(80),...
Add description column to Restaurant
feat: Add description column to Restaurant
Python
mit
gsbullmer/restaurant-menu-directory,gsbullmer/restaurant-menu-directory
3e02a38a9ae52603f620a7969ce532b61de531d7
libgreader/__init__.py
libgreader/__init__.py
# -*- coding: utf-8 -*- # libgreader # Copyright (C) 2012 Matt Behrens <askedrelic@gmail.com> # Python library for the Google Reader API __author__ = "Matt Behrens <askedrelic@gmail.com>" __version__ = "0.8.0" __copyright__ = "Copyright (C) 2012 Matt Behrens" from .googlereader import GoogleReader from .auth impo...
# -*- coding: utf-8 -*- # libgreader # Copyright (C) 2012 Matt Behrens <askedrelic@gmail.com> # Python library for the Google Reader API __author__ = "Matt Behrens <askedrelic@gmail.com>" __version__ = "0.8.0" __copyright__ = "Copyright (C) 2012 Matt Behrens" try: import requests except ImportError: # Wil...
Fix import error during setup.py install
Fix import error during setup.py install
Python
mit
smurfix/librssreader,askedrelic/libgreader
3d8d82be3528cc0150dac0c8ade1f6c306b412e4
channels/apps.py
channels/apps.py
from django.apps import AppConfig #from .binding.base import BindingMetaclass from .package_checks import check_all class ChannelsConfig(AppConfig): name = "channels" verbose_name = "Channels" def ready(self): # Check versions check_all() # Do django monkeypatches from ....
from django.apps import AppConfig # We import this here to ensure the reactor is installed very early on # in case other packages accidentally import twisted.internet.reactor # (e.g. raven does this). import daphne.server # noqa #from .binding.base import BindingMetaclass from .package_checks import check_all clas...
Add early import to fix problems with other packages and Twisted.
Add early import to fix problems with other packages and Twisted.
Python
bsd-3-clause
andrewgodwin/channels,andrewgodwin/django-channels,django/channels
b94f849fe28918a343a142da57b6055064d5b194
tests/test_abort_generate_on_hook_error.py
tests/test_abort_generate_on_hook_error.py
# -*- coding: utf-8 -*- import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures('clean_system') def test_pre_gen_hook(tmpdir): context = { 'cookiecutter': { "repo_dir": "foobar", "abort_pre_gen": "yes", "abort_post_...
# -*- coding: utf-8 -*- import pytest from cookiecutter import generate from cookiecutter import exceptions @pytest.mark.usefixtures('clean_system') def test_pre_gen_hook(tmpdir): context = { 'cookiecutter': { "repo_dir": "foobar", "abort_pre_gen": "yes", "abort_post_...
Test that an error in post_gen_project aborts generation
Test that an error in post_gen_project aborts generation
Python
bsd-3-clause
dajose/cookiecutter,pjbull/cookiecutter,willingc/cookiecutter,audreyr/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,hackebrot/cookiecutter,Springerle/cookiecutter,dajose/cookiecutter,audreyr/cookiecutter,stevepiercy/cookiecutter,terryjbates/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,will...
1f66670b94d2eca70ecf8e26b21f8b28986154b9
test-mm.py
test-mm.py
from psautohint import autohint from psautohint import psautohint baseDir = "tests/data/source-code-pro" masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") glyphList = None fonts = [] for master in masters: print("Hinting %s" % master) path = "%s/%s/font.otf" % (baseDir, mas...
from psautohint import autohint from psautohint import psautohint baseDir = "tests/data/source-code-pro" masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") glyphList = None fonts = [] for master in masters: print("Hinting %s" % master) options = autohint.ACOptions() opti...
Use the UFOs not the OTFs
Use the UFOs not the OTFs Oops, the OTF are not interpolation compatible due to overlap removal, I should have use the UFOs all along. Now the script passes without errors, still need to verify the output.
Python
apache-2.0
khaledhosny/psautohint,khaledhosny/psautohint
7f6da4dee6464e48a0e6b491f3f740a750e86ed2
dataactcore/scripts/resetAlembicVersion.py
dataactcore/scripts/resetAlembicVersion.py
import argparse from dataactcore.models.errorInterface import ErrorInterface from dataactcore.models.jobTrackerInterface import JobTrackerInterface from dataactcore.models.userInterface import UserInterface from dataactcore.models.validationInterface import ValidationInterface from sqlalchemy import MetaData, Table fro...
import argparse from sqlalchemy import MetaData, Table from sqlalchemy.sql import update from dataactcore.interfaces.db import GlobalDB from dataactvalidator.app import createApp def reset_alembic(alembic_version): with createApp().app_context(): db = GlobalDB.db() engine = db.engine s...
Remove db interfaces from the alembic version reset helper script.
Remove db interfaces from the alembic version reset helper script. Arguably, this script is no longer especially useful now that we only have a single database for the broker. That said, removed the interfaces in case folks are still using it.
Python
cc0-1.0
fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend
14329daf571400812594c0388eac87538cd10079
denim/api.py
denim/api.py
from fabric import api as __api # Setup some default values. __api.env.deploy_user = 'webapps' from denim.paths import (cd_deploy, cd_package, deploy_path, package_path) from denim import (scm, service, system, virtualenv, webserver) from denim.decorators import deploy_env @__api.task(name="help") def show_help(): ...
from fabric import api as _api # Setup some default values. _api.env.deploy_user = 'webapps' from denim.paths import (cd_deploy, cd_application, deploy_path, application_path) from denim import (scm, service, system, virtualenv, webserver) from denim.decorators import deploy_env # Pending deprecation from denim.path...
Break out items pending deprecation, remove double underscores
Break out items pending deprecation, remove double underscores
Python
bsd-2-clause
timsavage/denim
770f9dd75a223fb31a18af2fcb089398663f2065
concentration.py
concentration.py
from major import Major class Concentration(Major): def __init__(self, dept="NONE"): super().__init__(dept, path="concentrations/") if __name__ == '__main__': tmp = [ Concentration(dept="Asian") ] for i in tmp: print(i)
from major import Major class Concentration(Major): def __init__(self, dept="NONE"): super().__init__(dept, path="concentrations/") def getConcentrationRequirement(self, string): return self.requirements[string] if __name__ == '__main__': tmp = [ Concentration(dept="Asian") ] for i in tmp: print(i)
Add a getConcentrationRequirement to corrospond to getMajorRequirement
Add a getConcentrationRequirement to corrospond to getMajorRequirement
Python
agpl-3.0
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
1f61ece6f6b0950706ebef159665eafbfeeaa1fd
app/api/utils/containerMapper.py
app/api/utils/containerMapper.py
def getContainerDetails(container): ip = 'N/A' if container.state().network != None and container.state().network.get('eth0') != None: if len(container.state().network.get('eth0')['addresses']) > 0: ip = container.state().network['eth0']['addresses'][0].get('address', 'N/A') return { ...
def getContainerDetails(container): ip = 'N/A' if container.state().network != None and container.state().network.get('eth0') != None: if len(container.state().network.get('eth0')['addresses']) > 0: ip = container.state().network['eth0']['addresses'][0].get('address', 'N/A') image = '...
Fix container list bug when missing image
Fix container list bug when missing image
Python
apache-2.0
AdaptiveScale/lxdui,AdaptiveScale/lxdui,AdaptiveScale/lxdui,AdaptiveScale/lxdui
7fc576f3dd4d8d7dbe64dbecfc6dcc9ac9ad6b12
conman/routes/utils.py
conman/routes/utils.py
import os def split_path(path): """ Split a url path into its sub-paths. A url's sub-paths consist of all substrings ending in / and starting at the start of the url. """ paths = ['/'] path = path.rstrip('/') while path: paths.insert(1, path + '/') path = os.path.spli...
from collections import deque def split_path(path): """ Split a url path into its sub-paths. A url's sub-paths consist of all substrings ending in / and starting at the start of the url. eg: /path/containing/subpaths/ becomes: / /path/ /path/containing/ /path/con...
Refactor split_path code for brevity and clarity
Refactor split_path code for brevity and clarity
Python
bsd-2-clause
meshy/django-conman,meshy/django-conman
15c773250b52a03196a023e286f4f3a2405ba94e
backend/uclapi/dashboard/app_helpers.py
backend/uclapi/dashboard/app_helpers.py
from binascii import hexlify import os def generate_api_token(): key = hexlify(os.urandom(30)).decode() dashes_key = "" for idx, char in enumerate(key): if idx % 15 == 0 and idx != len(key)-1: dashes_key += "-" else: dashes_key += char final = "uclapi" + dashes...
from binascii import hexlify from random import choice import os import string def generate_api_token(): key = hexlify(os.urandom(30)).decode() dashes_key = "" for idx, char in enumerate(key): if idx % 15 == 0 and idx != len(key)-1: dashes_key += "-" else: dashes_k...
Add helpers to the dashboard code to generate OAuth keys
Add helpers to the dashboard code to generate OAuth keys
Python
mit
uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi
5bb4c61e9950de4c8c000a4ab02b0c901e0b06ff
version.py
version.py
""" automatically maintains the latest git tag + revision info in a python file """ import imp import os import subprocess def get_project_version(version_file): version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), version_file) try: module = imp.load_source("verfile", version_fi...
""" automatically maintains the latest git tag + revision info in a python file """ import importlib import os import subprocess def get_project_version(version_file): version_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), version_file) try: module = importlib.load_module(version_f...
Migrate from deprecated imp to importlib
Migrate from deprecated imp to importlib
Python
apache-2.0
aiven/aiven-client
d641d7d843899258d88da0d1dffaa762c1378712
opps/fields/widgets.py
opps/fields/widgets.py
#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, Option, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] values ...
#!/usr/bin/env python # -*- coding: utf-8 -* import json from django import forms from django.template.loader import render_to_string from .models import Field, FieldOption class JSONField(forms.TextInput): model = Field def render(self, name, value, attrs=None): elements = [] try: ...
Fix bug TypeError, not exist values (json) is dict None
Fix bug TypeError, not exist values (json) is dict None
Python
mit
williamroot/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps
ea57d89c1acc82a473a648f1c53430fadc27f7b2
opps/polls/__init__.py
opps/polls/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copy...
#!/usr/bin/env python # -*- coding: utf-8 -*- VERSION = (0, 1, 4) __version__ = ".".join(map(str, VERSION)) __status__ = "Development" __description__ = u"Poll App for Opps CMS" __author__ = u"Bruno Cezar Rocha" __credits__ = [] __email__ = u"rochacbruno@gmail.com" __license__ = u"MIT License" __copyright__ = u"Copy...
Fix Copyright application, YACOWS to Opps Projects
Fix Copyright application, YACOWS to Opps Projects
Python
mit
opps/opps-polls,opps/opps-polls
ebfeba2704dc73c136fa2ed217ef4337265b92dd
addie/utilities/__init__.py
addie/utilities/__init__.py
import os from qtpy.uic import loadUi def load_ui(ui_filename, baseinstance): ui_filename = os.path.split(ui_filename)[-1] # directory containing this file filename = __file__ if not os.path.isdir(filename): filename = os.path.split(filename)[0] # get the location of the designer directory...
import os from qtpy.uic import loadUi def load_ui(ui_filename, baseinstance): cwd = os.getcwd() ui_filename = os.path.split(ui_filename)[-1] # get the location of the designer directory # this function assumes that all ui files are there filename = os.path.join(cwd, 'designer', ui_filename) r...
Fix path for designer directory with ui files
Fix path for designer directory with ui files
Python
mit
neutrons/FastGR,neutrons/FastGR,neutrons/FastGR
7643635278fc1c92289e8fdd456614ce85a2c2f3
addons/osfstorage/models.py
addons/osfstorage/models.py
import logging from addons.base.models import BaseNodeSettings, BaseStorageAddon logger = logging.getLogger(__name__) class NodeSettings(BaseStorageAddon, BaseNodeSettings): pass
import logging from addons.base.models import BaseNodeSettings, BaseStorageAddon logger = logging.getLogger(__name__) class NodeSettings(BaseStorageAddon, BaseNodeSettings): # Required overrides complete = True has_auth = True
Add required overrides to osfstorage.NodeSettings
Add required overrides to osfstorage.NodeSettings
Python
apache-2.0
felliott/osf.io,CenterForOpenScience/osf.io,laurenrevere/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,caneruguz/osf.io,Nesiehr/osf.io,alexschiller/osf.io,aaxelb/osf.io,caseyrollins/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,mluo613/osf.io,chrisseto/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,...
3875b14e6c94c4a6a7ad47a3eb55cae62096d0e4
agateremote/table_remote.py
agateremote/table_remote.py
#!/usr/bin/env python """ This module contains the Remote extension to :class:`Table <agate.table.Table>`. """ import agate import requests import six def from_url(cls, url, callback=agate.Table.from_csv, binary=False, **kwargs): """ Download a remote file and pass it to a :class:`.Table` parser. :param...
#!/usr/bin/env python """ This module contains the Remote extension to :class:`Table <agate.table.Table>`. """ import agate import requests import six def from_url(cls, url, callback=agate.Table.from_csv, requests_encoding=None, binary=False, **kwargs): """ Download a remote file and pass it to a :class:`.Ta...
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
Add 'requests_encoding' parameter Allows user to override Requests' 'educated guess' about encoding of a response. Useful when loading a remote CSV that has a BOM that has been served with a 'text/csv' content-type, which Requests guesses needs a 'ISO-8859-1' encoding.
Python
mit
wireservice/agate-remote
9262dad14237d57a3817a199f9a8b04371de9607
mis_bot/scraper/database.py
mis_bot/scraper/database.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base # Database engine = create_engine('sqlite:///files/chats.db', convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, ...
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.pool import StaticPool # Database engine = create_engine('sqlite:///files/chats.db', convert_unicode=True, connect_args= {'check_...
Allow sharing db connection across threads
Allow sharing db connection across threads
Python
mit
ArionMiles/MIS-Bot
a04116d32931c5e85de417b5da048c91d495261b
pyeventstore/client.py
pyeventstore/client.py
import asyncio import uuid import json import requests from requests.exceptions import HTTPError from pyeventstore.events import (get_all_events, start_subscription, publish_events) from pyeventstore.stream_page import StreamPage class Client: d...
import asyncio import uuid import json from pyeventstore.events import (get_all_events, start_subscription, publish_events) class Client: def __init__(self, host, secure=False, port=2113): proto = "https" if secure else "http" self...
Remove projections methods for now
Remove projections methods for now
Python
mit
cjlarose/pyeventstore
5a3ffb93131c83f81eb123c2969714dcc80513ca
django/crashreport/processor/signals.py
django/crashreport/processor/signals.py
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ # # 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/. # from .processor import MinidumpPro...
# -*- Mode: python; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ # # 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/. # from .processor import MinidumpPro...
Revert "make the uwsgi spooler code also work with the fallback"
Revert "make the uwsgi spooler code also work with the fallback" This reverts commit 84ab847b444fbd41b9cc17e5c79a609efdcdf6cf.
Python
mpl-2.0
mmohrhard/crash,mmohrhard/crash,Liongold/crash,Liongold/crash,mmohrhard/crash,Liongold/crash
98dafbc7578209b9768e6ca6ccfa7854f70deb16
runTwircBot.py
runTwircBot.py
from TwircBot import TwircBot as tw bot = tw("config/sampleConfig.sample") bot.print_config() bot.connect()
from TwircBot import TwircBot as tw import sys bot = tw(sys.argv[1]) bot.print_config() bot.connect()
Modify runTwirc.py to accept system arguments
Modify runTwirc.py to accept system arguments
Python
mit
johnmarcampbell/twircBot
f868b126b3bd81ec900f378ff1fa8bd29ab8ea4c
transformations/Transformations.py
transformations/Transformations.py
from transformations.BackTranslation import BackTranslation from transformations.ButterFingersPerturbation import ButterFingersPerturbation from transformations.ChangeNamedEntities import ChangeNamedEntities from transformations.SentenceTransformation import SentenceTransformation from transformations.WithoutPunctuatio...
from transformations.BackTranslation import BackTranslation from transformations.ButterFingersPerturbation import ButterFingersPerturbation from transformations.ChangeNamedEntities import ChangeNamedEntities from transformations.SentenceTransformation import SentenceTransformation from transformations.WithoutPunctuati...
Add interface for source+label pertubation
Add interface for source+label pertubation
Python
mit
GEM-benchmark/NL-Augmenter
44226dabb65cb06522c128539660e407e53ca602
parseHTML.py
parseHTML.py
from bs4 import BeautifulSoup #uses beautiful soup to parse html file #finds the correct span tag #Gets the percentage of ink left in the printer soup = BeautifulSoup(open("test/test.html")) res = soup.find('span',{'class':'hpConsumableBlockHeaderText'}).text num = res[24] + res[25]
from bs4 import BeautifulSoup #uses beautiful soup to parse html file #finds the correct span tag #Gets the percentage of ink left in the printer soup = BeautifulSoup(open("test/test.html")) res = soup.find('span',{'class':'hpConsumableBlockHeaderText'}).text num = res[24] + res[25] file = open('test/data.csv', 'w+'...
Write information from test.html to csv file
Write information from test.html to csv file
Python
mit
tfahl/printfo,tfahl/printfo
2b603ebe92e308aa78928772e8681f3cc46775cb
numba/cloudpickle/compat.py
numba/cloudpickle/compat.py
import sys if sys.version_info < (3, 8): try: import pickle5 as pickle # noqa: F401 from pickle5 import Pickler # noqa: F401 except ImportError: import pickle # noqa: F401 from pickle import _Pickler as Pickler # noqa: F401 else: import pickle # noqa: F401 from _pi...
import sys if sys.version_info < (3, 8): # NOTE: pickle5 is disabled due to problems in testing. # try: # import pickle5 as pickle # noqa: F401 # from pickle5 import Pickler # noqa: F401 # except ImportError: import pickle # noqa: F401 from pickle import _Pickler as Pickler # n...
Disable pickle5 use in cloudpickle
Disable pickle5 use in cloudpickle
Python
bsd-2-clause
numba/numba,IntelLabs/numba,stuartarchibald/numba,stonebig/numba,seibert/numba,cpcloud/numba,stonebig/numba,cpcloud/numba,numba/numba,IntelLabs/numba,stuartarchibald/numba,seibert/numba,cpcloud/numba,numba/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,cpcloud/numba,stonebig/numba,stonebig/numba,stuartarchibald/numb...
bbd3b1939712d9784fe61884d9b06faa95c36006
tests/test_project/test_app/models.py
tests/test_project/test_app/models.py
from django.db import models class TestModel(models.Model): name = models.CharField(max_length=63, unique=True, verbose_name='Name') image = models.ImageField(verbose_name='Image')
from django.db import models class TestModel(models.Model): name = models.CharField(max_length=63, unique=True, verbose_name='Name') image = models.ImageField(verbose_name='Image', upload_to='uploads/')
Test compatibility with older Django versions.
Test compatibility with older Django versions.
Python
mit
dessibelle/sorl-thumbnail-serializer-field
59ce3ca9c1572dcf71aa5de5cdb354def594a36c
downloads/urls.py
downloads/urls.py
from django.conf.urls import patterns, url from functools import partial from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(r'solutions/(?P<path>.*)$', partial(download_protected_file, path_prefix='solutio...
from django.conf.urls import patterns, url from functools import partial from problems.models import UserSolution from .views import download_protected_file urlpatterns = patterns('', url(r'solutions/(?P<path>.*)$', download_protected_file, dict(path_prefix='solutions/', model_class=UserSolution), ...
Remove unnecessary usage of functools.partial
downloads: Remove unnecessary usage of functools.partial
Python
mit
matus-stehlik/roots,rtrembecky/roots,matus-stehlik/roots,tbabej/roots,rtrembecky/roots,tbabej/roots,tbabej/roots,rtrembecky/roots,matus-stehlik/roots
6cb9008ee2ed49d9630735378bd84727aef3caef
dipy/core/tests/test_qball.py
dipy/core/tests/test_qball.py
""" Testing qball """ import numpy as np import dipy.core.qball as qball from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric @parametric def test_real_sph_harm(): rea...
""" Testing qball """ import numpy as np import dipy.core.qball as qball from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric @parametric def test_sph_harm_ind_list(): ...
TEST - some real_sph_harm tests
TEST - some real_sph_harm tests
Python
bsd-3-clause
villalonreina/dipy,samuelstjean/dipy,jyeatman/dipy,sinkpoint/dipy,mdesco/dipy,Messaoud-Boudjada/dipy,maurozucchelli/dipy,villalonreina/dipy,nilgoyyou/dipy,beni55/dipy,demianw/dipy,FrancoisRheaultUS/dipy,rfdougherty/dipy,JohnGriffiths/dipy,mdesco/dipy,Messaoud-Boudjada/dipy,JohnGriffiths/dipy,samuelstjean/dipy,samuelstj...
46ab8d71824f80ba5d02349a9f89328e5c47f434
app/views.py
app/views.py
from app import app, \ cors_header from flask import request, \ make_response, \ send_from_directory import json import os @app.route('/', methods=['GET']) @cors_header def index(): if 'X-Forwarded-For' in request.headers: ipAddress = request.headers['X-...
from app import app, \ cors_header from flask import request, \ make_response, \ send_from_directory import json import re import os @app.route('/', methods=['GET']) @cors_header def index(): if 'X-Forwarded-For' in request.headers: ipAddress = request.h...
Handle instance where we get multiple IP addresess in the response
Handle instance where we get multiple IP addresess in the response
Python
mit
taeram/gipsy
3439eb09916212cd71650aecc49ae1c22f650274
apps/package/templatetags/package_tags.py
apps/package/templatetags/package_tags.py
from datetime import timedelta from datetime import datetime from django import template from github2.client import Github from package.models import Package, Commit register = template.Library() github = Github() @register.filter def commits_over_52(package): current = datetime.now() weeks = [] comm...
from datetime import datetime, timedelta from django import template from package.models import Commit register = template.Library() @register.filter def commits_over_52(package): current = datetime.now() weeks = [] commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True) ...
Clean up some imports in the package app's template_tags.py file.
Clean up some imports in the package app's template_tags.py file.
Python
mit
nanuxbe/djangopackages,QLGu/djangopackages,cartwheelweb/packaginator,nanuxbe/djangopackages,nanuxbe/djangopackages,miketheman/opencomparison,QLGu/djangopackages,benracine/opencomparison,cartwheelweb/packaginator,audreyr/opencomparison,pydanny/djangopackages,miketheman/opencomparison,QLGu/djangopackages,benracine/openco...
b034eeda25fcf55e7da018f3c91a23a5e252ae2f
bm/app/models.py
bm/app/models.py
from django.db import models from django.conf import settings class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=21) row_number = models.IntegerField(default=0) column_number = models.IntegerField(default=0) progress_bar_color = models.CharField(max...
from django.db import models from django.conf import settings class Category(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) name = models.CharField(max_length=21) row_number = models.IntegerField(default=0) column_number = models.IntegerField(default=0) progress_bar_color = models.CharField(max...
Change str() of Category for easier form handling
Change str() of Category for easier form handling
Python
mit
GSC-RNSIT/bookmark-manager,rohithpr/bookmark-manager,rohithpr/bookmark-manager,GSC-RNSIT/bookmark-manager
bf17a86bccf25ead90d11dd15a900cb784d9cb9f
raco/myrial/myrial_test.py
raco/myrial/myrial_test.py
import collections import math import unittest import raco.fakedb import raco.myrial.interpreter as interpreter import raco.myrial.parser as parser from raco.myrialang import compile_to_json class MyrialTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() self.parse...
import collections import math import unittest import raco.fakedb import raco.myrial.interpreter as interpreter import raco.myrial.parser as parser class MyrialTestCase(unittest.TestCase): def setUp(self): self.db = raco.fakedb.FakeDatabase() self.parser = parser.Parser() self.processor ...
Revert "Add compile_to_json invocation in Myrial test fixture"
Revert "Add compile_to_json invocation in Myrial test fixture" This reverts commit ceb848021d5323b5bad8518ac7ed850a51fc89ca.
Python
bsd-3-clause
uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco
2bdc5c33b1e9eb394eb62533f4ae4df081ea1452
numpy/setup.py
numpy/setup.py
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy', parent_package, top_path) config.add_subpackage('compat') config.add_subpackage('core') config.add_subpackage('distutils') config.add_s...
#!/usr/bin/env python3 def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('numpy', parent_package, top_path) config.add_subpackage('_array_api') config.add_subpackage('compat') config.add_subpackage('core') config.add_...
Make the _array_api submodule install correctly
Make the _array_api submodule install correctly
Python
bsd-3-clause
seberg/numpy,mhvk/numpy,mattip/numpy,endolith/numpy,seberg/numpy,mattip/numpy,numpy/numpy,simongibbons/numpy,simongibbons/numpy,charris/numpy,endolith/numpy,charris/numpy,rgommers/numpy,rgommers/numpy,simongibbons/numpy,anntzer/numpy,pdebuyl/numpy,jakirkham/numpy,endolith/numpy,mattip/numpy,anntzer/numpy,jakirkham/nump...
29cc95bbdb12e50d09e8079bfae5841a7e734743
plinth/modules/help/urls.py
plinth/modules/help/urls.py
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
# # This file is part of Plinth. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distribute...
Make help accessible for logged-in non-admin users
Make help accessible for logged-in non-admin users Signed-off-by: Hemanth Kumar Veeranki <hemanthveeranki@gmail.com> Reviewed-by: Johannes Keyser <187051b70230423a457adbc3e507f9e4fff08d4b@posteo.de>
Python
agpl-3.0
vignanl/Plinth,vignanl/Plinth,kkampardi/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth,kkampardi/Plinth,kkampardi/Plinth,vignanl/Plinth,kkampardi/Plinth,harry-7/Plinth,kkampardi/Plinth,vignanl/Plinth,harry-7/Plinth,harry-7/Plinth
5edddcc85b0e21bb576b71db63d082c8ace5cf70
examples/boilerplates/samples/google_test.py
examples/boilerplates/samples/google_test.py
''' Google.com testing example ''' from seleniumbase import BaseCase from google_objects import HomePage, ResultsPage class GoogleTests(BaseCase): def test_google_dot_com(self): self.open('http://www.google.com') self.assert_element(HomePage.search_button) self.assert_element(HomePage.fe...
''' Google.com testing example ''' from seleniumbase import BaseCase from google_objects import HomePage, ResultsPage class GoogleTests(BaseCase): def test_google_dot_com(self): self.open('http://www.google.com') self.assert_element(HomePage.search_button) self.assert_element(HomePage.fe...
Update Google boilerplate test. (Logo frequently changes)
Update Google boilerplate test. (Logo frequently changes)
Python
mit
seleniumbase/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase
7b88a2e65b0010ceef49fdbce61949ee10420cd8
desertbot/modules/utils/CommandHandler.py
desertbot/modules/utils/CommandHandler.py
""" Created on Feb 28, 2018 @author: StarlitGhost """ from twisted.plugin import IPlugin from desertbot.moduleinterface import IModule, BotModule from zope.interface import implementer @implementer(IPlugin, IModule) class CommandHandler(BotModule): def actions(self): return super(CommandHandler, self).a...
""" Created on Feb 28, 2018 @author: StarlitGhost """ from twisted.plugin import IPlugin from desertbot.moduleinterface import IModule, BotModule from zope.interface import implementer @implementer(IPlugin, IModule) class CommandHandler(BotModule): def __init__(self): BotModule.__init__(self) se...
Load the command handler before the commands
Load the command handler before the commands
Python
mit
DesertBot/DesertBot
3b75a6f3654e8f325060779ca56b6df93fe0cabe
genome_designer/main/demo_view_overrides.py
genome_designer/main/demo_view_overrides.py
"""View overrides for demo mode. """ from django.contrib.auth import authenticate from django.contrib.auth import login from django.http import HttpResponseRedirect def login_demo_account(request): new_user = authenticate(username='gmcdev', password='g3n3d3z') login(request, new_user) return ...
"""View overrides for demo mode. """ from django.contrib.auth import authenticate from django.contrib.auth import login from django.http import HttpResponseRedirect def login_demo_account(request): new_user = authenticate(username='gmcdev', password='g3n3d3z') login(request, new_user) redirec...
Handle redirect_url in demo login bypass.
Handle redirect_url in demo login bypass.
Python
mit
churchlab/millstone,churchlab/millstone,churchlab/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone_accidental_source,woodymit/millstone_accidental_source,woodymit/millstone,woodymit/millstone,woodymit/millstone,churchlab/millstone
b6f3c619e8c3fa375ac9b66e7ce555c77f02f152
pytest_raisesregexp/plugin.py
pytest_raisesregexp/plugin.py
import re import py.code import pytest def pytest_namespace(): return {'raises_regexp': raises_regexp} class raises_regexp(object): def __init__(self, expected_exception, regexp): self.exception = expected_exception self.regexp = regexp self.excinfo = None def __enter__(self): ...
import re import py.code import pytest def pytest_namespace(): return {'raises_regexp': raises_regexp} class raises_regexp(object): def __init__(self, expected_exception, regexp): self.exception = expected_exception self.regexp = regexp self.excinfo = None def __enter__(self): ...
Add originally raised exception value to pytest error message
Add originally raised exception value to pytest error message
Python
mit
kissgyorgy/pytest-raisesregexp
5b8da0d318d7b37b3f1a3d868980507b15aa4213
salt/renderers/json.py
salt/renderers/json.py
from __future__ import absolute_import import json def render(json_data, env='', sls='', **kws): if not isinstance(json_data, basestring): json_data = json_data.read() if json_data.startswith('#!'): json_data = json_data[json_data.find('\n')+1:] return json.loads(json_data)
from __future__ import absolute_import import json def render(json_data, env='', sls='', **kws): if not isinstance(json_data, basestring): json_data = json_data.read() if json_data.startswith('#!'): json_data = json_data[json_data.find('\n')+1:] if not json_data.strip(): return {} ...
Add missed changes for the previous commit.
Add missed changes for the previous commit.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
3ad64c06f917efdaa94ad5debc23941f4d95105a
fuzzy_happiness/attributes.py
fuzzy_happiness/attributes.py
#!/usr/bin/python # # Copyright 2013 Rackspace Australia # # 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 o...
#!/usr/bin/python # # Copyright 2013 Rackspace Australia # # 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 o...
Return table name not model object name.
Return table name not model object name.
Python
apache-2.0
rcbau/fuzzy-happiness
dbbd6e1e87964db6b2279a661a63751da31213e5
millipede.py
millipede.py
#!/usr/bin/env python3 class millipede: def __init__(self, size, comment=None): self._millipede = "" if comment: self._millipede = comment + "\n\n" self._millipede += " ╚⊙ ⊙╝ \n" padding = 2 direction = -1 while (size): for i in range(0, ...
#!/usr/bin/env python3 class millipede: def __init__(self, size, comment=None, reverse=False): self._padding_offsets = [2, 1, 0, 1, 2, 3, 4, 4, 3] head = " ╔⊙ ⊙╗\n" if reverse else " ╚⊙ ⊙╝\n" body = "".join([ "{}{}\n".format( " " * self._padding_offsets[...
Rewrite body generation and add reverse option
Rewrite body generation and add reverse option
Python
bsd-3-clause
evadot/millipede-python,getmillipede/millipede-python,moul/millipede-python,EasonYi/millipede-python,EasonYi/millipede-python,evadot/millipede-python,moul/millipede-python,getmillipede/millipede-python
8233abab6084db39df064b87d256fd0caffecb89
simpy/test/test_simulation.py
simpy/test/test_simulation.py
from simpy import Simulation, InterruptedException def test_simple_process(): def pem(ctx, result): while True: result.append(ctx.now) yield ctx.wait(1) result = [] Simulation(pem, result).simulate(until=4) assert result == [0, 1, 2, 3] def test_interrupt(): def p...
from simpy import Simulation, InterruptedException def test_simple_process(): def pem(ctx, result): while True: result.append(ctx.now) yield ctx.wait(1) result = [] Simulation(pem, result).simulate(until=4) assert result == [0, 1, 2, 3] def test_interrupt(): def r...
Define subprocesses in the context of the root process. Maybe this is more readable?
Define subprocesses in the context of the root process. Maybe this is more readable?
Python
mit
Uzere/uSim
1b0edd2eeb722397e9c6c7da04ab6cbd3865a476
reddit_adzerk/adzerkads.py
reddit_adzerk/adzerkads.py
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" site_name = getattr(c.site, "analy...
from urllib import quote from pylons import c, g from r2.lib.pages import Ads as BaseAds from r2.models.subreddit import DefaultSR FRONTPAGE_NAME = "-reddit.com" class Ads(BaseAds): def __init__(self): BaseAds.__init__(self) url_key = "adzerk_https_url" if c.secure else "adzerk_url" si...
Move special frontpage name to variable.
Move special frontpage name to variable.
Python
bsd-3-clause
madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk
2cb03ff8c3d21f36b95103eaf9ae0fb3e43077bd
pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py
pinax_theme_bootstrap/templatetags/pinax_theme_bootstrap_tags.py
from django import template from django.contrib.messages.utils import get_level_tags LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns the message's level_tag prefixed with Bootstrap's "alert-" prefix along with any tags includ...
from django import template from django.contrib.messages.utils import get_level_tags from django.utils.encoding import force_text LEVEL_TAGS = get_level_tags() register = template.Library() @register.simple_tag() def get_message_tags(message): """ Returns the message's level_tag prefixed with Bootstrap's "...
Allow for lazy translation of message tags
Allow for lazy translation of message tags
Python
mit
foraliving/foraliving,druss16/danslist,grahamu/pinax-theme-bootstrap,foraliving/foraliving,grahamu/pinax-theme-bootstrap,druss16/danslist,jacobwegner/pinax-theme-bootstrap,jacobwegner/pinax-theme-bootstrap,druss16/danslist,grahamu/pinax-theme-bootstrap,jacobwegner/pinax-theme-bootstrap,foraliving/foraliving
3973e0d2591b2554e96da0a22b2d723a71d2423e
imgaug/augmenters/__init__.py
imgaug/augmenters/__init__.py
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import GammaContrast, SigmoidContrast, LogContrast, LinearContrast from imgaug.augmenters.convolutional import * from imgaug.augmen...
from __future__ import absolute_import from imgaug.augmenters.arithmetic import * from imgaug.augmenters.blur import * from imgaug.augmenters.color import * from imgaug.augmenters.contrast import * from imgaug.augmenters.convolutional import * from imgaug.augmenters.flip import * from imgaug.augmenters.geometric import...
Switch import from contrast to all
Switch import from contrast to all Change import from contrast.py in augmenters/__init__.py to * instead of selective, as * should not import private methods anyways.
Python
mit
aleju/ImageAugmenter,aleju/imgaug,aleju/imgaug
ad558a5acc93e1e5206ed27b2dc679089b277890
me_api/app.py
me_api/app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .middleware import github, keybase, medium from .cache import cache def create_app(config): app = Flask(__name__) app.config.from_object(config)...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from flask import Flask from .middleware.me import me from .cache import cache def _register_module(app, module): if module == 'github': from .middleware import github app.register_blueprint(...
Fix giant bug: crash when don't config all modules
Fix giant bug: crash when don't config all modules that's bacause you import all the modules > from .middleware import github, keybase, medium while each module need to get configurations from modules.json, e.g. > config = Config.modules['modules']['github'] but can't get anything at all, so it will crash. that's not...
Python
mit
lord63/me-api
42b330e5629b25db45e7a0f3f08bdb21e608b106
skimage/viewer/qt.py
skimage/viewer/qt.py
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object ...
has_qt = True try: from matplotlib.backends.qt_compat import QtGui, QtCore, QtWidgets except ImportError: try: from matplotlib.backends.qt4_compat import QtGui, QtCore QtWidgets = QtGui except ImportError: # Mock objects class QtGui(object): QMainWindow = object ...
Add QWidget to the mock Qt
Add QWidget to the mock Qt
Python
bsd-3-clause
ClinicalGraphics/scikit-image,bsipocz/scikit-image,rjeli/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,pratapvardhan/scikit-image,juliusbierk/scikit-image,keflavich/scikit-image,warmspringwinds/scikit-image,Britefury/scikit-image,oew1v07/scikit-image,bennlich/scikit-image,ClinicalGraphics/scikit-i...
bd3d97cefe61886ab8c2fa24eecd624ca1c6f751
profile_collection/startup/90-settings.py
profile_collection/startup/90-settings.py
import logging # metadata set at startup RE.md['owner'] = 'xf11id' RE.md['beamline_id'] = 'CHX' # removing 'custom' as it is raising an exception in 0.3.2 # gs.RE.md['custom'] = {} def print_scanid(name, doc): if name == 'start': print('Scan ID:', doc['scan_id']) print('Unique ID:', doc['uid']) ...
import logging # metadata set at startup RE.md['owner'] = 'xf11id' RE.md['beamline_id'] = 'CHX' # removing 'custom' as it is raising an exception in 0.3.2 # gs.RE.md['custom'] = {} def print_md(name, doc): if name == 'start': print('Metadata:\n', repr(doc)) RE.subscribe(print_scanid) #from eiger_io.fs_h...
Remove redundant Scan ID printing (there is another one elsewhere)
Remove redundant Scan ID printing (there is another one elsewhere)
Python
bsd-2-clause
NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd
ad60b0cd3326c0729237afbb094d22f4415fb422
laboratory/experiment.py
laboratory/experiment.py
import traceback from laboratory.observation import Observation, Test from laboratory import exceptions class Experiment(object): def __init__(self, name='Experiment', raise_on_mismatch=False): self.name = name self.raise_on_mismatch = raise_on_mismatch self._control = None self...
import traceback from laboratory.observation import Observation, Test from laboratory import exceptions class Experiment(object): def __init__(self, name='Experiment', raise_on_mismatch=False): self.name = name self.raise_on_mismatch = raise_on_mismatch self._control = None self...
Call Experiment.publish in run method
Call Experiment.publish in run method
Python
mit
joealcorn/laboratory,shaunvxc/laboratory
9560ccf476a887c20b2373eca52f38f186b6ed58
conanfile.py
conanfile.py
from conans import ConanFile, CMake class NostalgiaConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable", "qt/5.14.1@bincrafters/stable", "sqlite3/3.31.0", "libiconv/1.16" generators = "cmake", "cmake_find_package", "cmake_paths" ...
from conans import ConanFile, CMake class NostalgiaConan(ConanFile): settings = "os", "compiler", "build_type", "arch" requires = "jsoncpp/1.9.2", "sdl2/2.0.10@bincrafters/stable" generators = "cmake", "cmake_find_package", "cmake_paths" #default_options = { # "sdl2:nas": False #}
Remove conan Qt, as it is currently being ignored
[nostalgia] Remove conan Qt, as it is currently being ignored
Python
mpl-2.0
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
a284a69432b2e0052fd2da4121cf4512fc9423da
lemon/dashboard/admin.py
lemon/dashboard/admin.py
from django.conf import settings from lemon import extradmin as admin from lemon.dashboard import views from lemon.dashboard.base import dashboard, Widget class DashboardAdmin(admin.AppAdmin): instance = dashboard @property def urls(self): return self.instance.get_urls(self), 'dashboard', 'dash...
from django.conf import settings from lemon import extradmin as admin from lemon.dashboard import views from lemon.dashboard.base import dashboard, Widget class DashboardAdmin(admin.AppAdmin): dashboard = dashboard @property def urls(self): return self.dashboard.get_urls(self), 'dashboard', 'da...
Rename instance to dashboard in DashboardAdmin
Rename instance to dashboard in DashboardAdmin
Python
bsd-3-clause
trilan/lemon,trilan/lemon,trilan/lemon
8541ec09e237f1401095d31177bdde9ac1adaa39
util/linkJS.py
util/linkJS.py
#!/usr/bin/env python import os def linkJS(target_fn, file_list_fn, source_base, prologue="", module_dirs=[]): with open(target_fn, "wb") as target: target.write(prologue) # Add files listed in file_list_fn with open(file_list_fn) as file_list: for source_fn in file_list: ...
#!/usr/bin/env python import os def linkJS(target_fn, file_list_fn, source_base, prologue="", module_dirs=[]): with open(target_fn, "wb") as target: target.write(prologue) # Add files listed in file_list_fn with open(file_list_fn) as file_list: for source_fn in file_list: ...
Include full path to original files
Include full path to original files
Python
mpl-2.0
MozillaSecurity/funfuzz,nth10sd/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz
2117778d777120293e506eca9743f97619b5ad5c
kiwi/interface.py
kiwi/interface.py
class Menu(object): def __init__(self, dialog, items, title, caller = None): self.d = dialog self.caller = caller self.entries = [] self.dispatch_table = {} tag = 1 self.title = title for entry, func in items: self.entries.append(tuple([str(tag)...
class MenuItem(object): def __init__(self, func=None): if func: self.function = func # Wrapper for child.function() that creates a call stack def run(self, ret=None): self.function() if ret: ret() class Menu(MenuItem): def __init__(self, dialog, items, title): self.d = ...
Create object MenuItem that wraps functions to create a call stack
Create object MenuItem that wraps functions to create a call stack
Python
mit
jakogut/KiWI
ccf285c30a0110f2ff59b91ec0166f9b5306239d
dukpy/evaljs.py
dukpy/evaljs.py
import json from . import _dukpy try: from collections.abc import Iterable except ImportError: from collections import Iterable try: # pragma: no cover unicode string_types = (str, unicode) except NameError: # pragma: no cover string_types = (bytes, str) class JSInterpreter(object): """Jav...
import json from . import _dukpy try: from collections.abc import Iterable except ImportError: from collections import Iterable try: # pragma: no cover unicode string_types = (str, unicode) jscode_type = str except NameError: # pragma: no cover string_types = (bytes, str) jscode_type = s...
Fix unicode source code on py3
Fix unicode source code on py3
Python
mit
amol-/dukpy,amol-/dukpy,amol-/dukpy
08fe9e7beb4285feec9205012a62d464b3489bcf
natasha/grammars/person/interpretation.py
natasha/grammars/person/interpretation.py
from enum import Enum from collections import Counter from yargy.interpretation import InterpretationObject class PersonObject(InterpretationObject): class Attributes(Enum): Firstname = 0 # владимир Middlename = 1 # владимирович Lastname = 2 # путин Descriptor = 3 # президент ...
# coding: utf-8 from __future__ import unicode_literals from enum import Enum from collections import Counter from yargy.interpretation import InterpretationObject class PersonObject(InterpretationObject): class Attributes(Enum): Firstname = 0 # владимир Middlename = 1 # владимирович La...
Fix encoding for python 2.x
Fix encoding for python 2.x
Python
mit
natasha/natasha
3d3a81efc36e39888929e62287b9d895922d8615
tests/sentry/filters/test_web_crawlers.py
tests/sentry/filters/test_web_crawlers.py
from __future__ import absolute_import from sentry.filters.web_crawlers import WebCrawlersFilter from sentry.testutils import TestCase class WebCrawlersFilterTest(TestCase): filter_cls = WebCrawlersFilter def apply_filter(self, data): return self.filter_cls(self.project).test(data) def get_mock...
from __future__ import absolute_import from sentry.filters.web_crawlers import WebCrawlersFilter from sentry.testutils import TestCase class WebCrawlersFilterTest(TestCase): filter_cls = WebCrawlersFilter def apply_filter(self, data): return self.filter_cls(self.project).test(data) def get_mock...
Add unit tests for filtering Twitterbot and Slack.
Add unit tests for filtering Twitterbot and Slack.
Python
bsd-3-clause
ifduyue/sentry,mvaled/sentry,gencer/sentry,gencer/sentry,mvaled/sentry,JackDanger/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,jean/sentry,looker/sentry,looker/sentry,jean/sentry,looker/sentry,mvaled/sentry,looker/sentry,ifduyue/sentry,ifduyue/sentry,mvaled/sentry,JackDanger/sentry,gencer/sentry,gencer/sentry,...
6bd088acd0ec0cfa5298051e286ce76e42430067
shuup/front/themes/views/_product_preview.py
shuup/front/themes/views/_product_preview.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from shuup.front.views.product import ProductDetailView class ProductPrevi...
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from shuup.front.views.product import ProductDetailView class ProductPrevi...
Remove reference to nonexistent file
Front: Remove reference to nonexistent file
Python
agpl-3.0
shoopio/shoop,shoopio/shoop,shawnadelic/shuup,suutari-ai/shoop,shawnadelic/shuup,hrayr-artunyan/shuup,suutari/shoop,suutari/shoop,shoopio/shoop,suutari-ai/shoop,hrayr-artunyan/shuup,shawnadelic/shuup,suutari/shoop,suutari-ai/shoop,hrayr-artunyan/shuup
a347c699be3ce5659db4b76a26ce253a209e232e
webapp_health_monitor/verificators/base.py
webapp_health_monitor/verificators/base.py
from webapp_health_monitor import errors class Verificator(object): verificator_name = None def __init__(self, **kwargs): pass def run(self): raise NotImplementedError() def __str__(self): if self.verificator_name: return self.verificator_name else: ...
from webapp_health_monitor import errors class Verificator(object): verificator_name = None def __init__(self, **kwargs): pass def run(self): raise NotImplementedError() def __str__(self): if self.verificator_name: return self.verificator_name else: ...
Delete unused value extractor attribute.
Delete unused value extractor attribute.
Python
mit
pozytywnie/webapp-health-monitor,serathius/webapp-health-monitor
47672fe44673fe9cae54a736bdc9eb496494ab58
UI/utilities/synchronization_core.py
UI/utilities/synchronization_core.py
# -*- coding: utf-8 -*- # Synchronization core module for Storj GUI Client # class StorjFileSynchronization(): def start_sync_thread(self): return 1 def reload_sync_configuration(self): return 1 def add_file_to_sync_queue(self): return 1
# -*- coding: utf-8 -*- # Synchronization core module for Storj GUI Client # import time from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import threading HANDLE_ON_MOVE_EVENT = True HANDLE_ON_DELETE_EVENT = True class StorjFileSynchronization(): def start_sync_thr...
Add synchronization directory observer and handler
Add synchronization directory observer and handler
Python
mit
lakewik/storj-gui-client
f4c9482e41ec2ee6c894a413e8fcb0349a9edbd1
tapiriik/web/templatetags/displayutils.py
tapiriik/web/templatetags/displayutils.py
from django import template import json register = template.Library() @register.filter(name="format_meters") def meters_to_kms(value): try: return round(value / 1000) except: return "NaN" @register.filter(name='json') def jsonit(obj): return json.dumps(obj) @register.filter(name='dict_ge...
from django import template import json register = template.Library() @register.filter(name="format_meters") def meters_to_kms(value): try: return round(value / 1000) except: return "NaN" @register.filter(name='json') def jsonit(obj): return json.dumps(obj) @register.filter(name='dict_ge...
Fix broken diagnostic dashboard with new sync progress values
Fix broken diagnostic dashboard with new sync progress values
Python
apache-2.0
campbellr/tapiriik,niosus/tapiriik,gavioto/tapiriik,cheatos101/tapiriik,cheatos101/tapiriik,brunoflores/tapiriik,abhijit86k/tapiriik,mjnbike/tapiriik,dlenski/tapiriik,abhijit86k/tapiriik,cpfair/tapiriik,marxin/tapiriik,abhijit86k/tapiriik,dlenski/tapiriik,cheatos101/tapiriik,abs0/tapiriik,niosus/tapiriik,dmschreiber/ta...
03eb0081a4037e36775271fb2373277f8e89835b
src/mcedit2/resourceloader.py
src/mcedit2/resourceloader.py
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import zipfile log = logging.getLogger(__name__) class ResourceNotFound(KeyError): pass class ResourceLoader(object): def __init__(self): super(ResourceLoader, self).__init__() ...
""" ${NAME} """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import zipfile log = logging.getLogger(__name__) class ResourceNotFound(KeyError): pass class ResourceLoader(object): def __init__(self): super(ResourceLoader, self).__init__() ...
Add function to ResourceLoader for listing all block models
Add function to ResourceLoader for listing all block models xxx only lists Vanilla models. haven't looked at mods with models yet.
Python
bsd-3-clause
vorburger/mcedit2,vorburger/mcedit2,Rubisk/mcedit2,Rubisk/mcedit2
de4f43613b5f3a8b6f49ace6b8e9585a242d7cb2
src/build.py
src/build.py
# Copyright 2007 Pompeu Fabra University (Computational Imaging Laboratory), Barcelona, Spain. Web: www.cilab.upf.edu. # This software is distributed WITHOUT ANY WARRANTY; # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # Script to automate CSnake calls from cruise contro...
# Copyright 2007 Pompeu Fabra University (Computational Imaging Laboratory), Barcelona, Spain. Web: www.cilab.upf.edu. # This software is distributed WITHOUT ANY WARRANTY; # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # Script to automate CSnake calls from cruise contro...
Exit with the proper value.
Exit with the proper value. git-svn-id: a26c1b3dc012bc7b166f1b96505d8277332098eb@265 9ffc3505-93cb-cd4b-9e5d-8a77f6415fcf
Python
bsd-3-clause
csnake-org/CSnake,csnake-org/CSnake,msteghofer/CSnake,msteghofer/CSnake,csnake-org/CSnake,msteghofer/CSnake
55464daa00ca68b07737433b0983df4667432a9c
system/plugins/info.py
system/plugins/info.py
__author__ = 'Gareth Coles' import weakref class Info(object): data = None core = None info = None def __init__(self, yaml_data, plugin_object=None): """ :param yaml_data: :type yaml_data: dict :return: """ self.data = yaml_data if plugin_...
__author__ = 'Gareth Coles' import weakref class Info(object): data = None core = None info = None def __init__(self, yaml_data, plugin_object=None): """ :param yaml_data: :type yaml_data: dict :return: """ self.data = yaml_data if plugin_...
Fix missing dependencies on core
Fix missing dependencies on core
Python
artistic-2.0
UltrosBot/Ultros,UltrosBot/Ultros
985dd1ada1b2ad9ceaae111fa32b1d8e54b61786
mailqueue/tasks.py
mailqueue/tasks.py
from celery.task import task from .models import MailerMessage @task(name="tasks.send_mail") def send_mail(pk): message = MailerMessage.objects.get(pk=pk) message._send() @task() def clear_sent_messages(): from mailqueue.models import MailerMessage MailerMessage.objects.clear_sent_messages()
from celery.task import task from .models import MailerMessage @task(name="tasks.send_mail", default_retry_delay=5, max_retries=5) def send_mail(pk): message = MailerMessage.objects.get(pk=pk) message._send() # Retry when message is not sent if not message.sent: send_mail.retry([message.pk...
Add retry to celery task
Add retry to celery task Messages do not always get delivered. Built in a retry when message is not sent. Max retry count could also be a setting.
Python
mit
Goury/django-mail-queue,dstegelman/django-mail-queue,winfieldco/django-mail-queue,Goury/django-mail-queue,styrmis/django-mail-queue,dstegelman/django-mail-queue
8d8798554d996776eecc61b673adcbc2680f327a
mastermind/main.py
mastermind/main.py
from __future__ import (absolute_import, print_function, division) from itertools import repeat from mitmproxy.main import mitmdump import os from . import (cli, proxyswitch, say) def main(): parser = cli.args() args, extra_args = parser.parse_known_args() try: config = cli.config(args) excep...
from __future__ import (absolute_import, print_function, division) from itertools import repeat from mitmproxy.main import mitmdump import os from . import (cli, proxyswitch, say) def main(): parser = cli.args() args, extra_args = parser.parse_known_args() try: config = cli.config(args) excep...
Write PID to a file
Write PID to a file
Python
mit
ustwo/mastermind,ustwo/mastermind
9ee0f3f7be90046f796f3395b2149288a2b52a26
src/zeit/magazin/preview.py
src/zeit/magazin/preview.py
# Copyright (c) 2013 gocept gmbh & co. kg # See also LICENSE.txt import grokcore.component as grok import zeit.cms.browser.preview import zeit.magazin.interfaces @grok.adapter(zeit.magazin.interfaces.IZMOContent, basestring) @grok.implementer(zeit.cms.browser.interfaces.IPreviewURL) def preview_url(content, preview_...
# Copyright (c) 2013 gocept gmbh & co. kg # See also LICENSE.txt import grokcore.component as grok import zeit.cms.browser.preview import zeit.magazin.interfaces @grok.adapter(zeit.magazin.interfaces.IZMOContent, basestring) @grok.implementer(zeit.cms.browser.interfaces.IPreviewURL) def preview_url(content, preview_...
Remove oddity marker, it's been resolved in zeit.find now
Remove oddity marker, it's been resolved in zeit.find now
Python
bsd-3-clause
ZeitOnline/zeit.magazin
ee0f28abd70396bf1e094592028aa693e5d6fe6c
rechunker/executors/python.py
rechunker/executors/python.py
import itertools from functools import partial import math from typing import Any, Callable, Iterable from rechunker.types import CopySpec, StagedCopySpec, Executor Thunk = Callable[[], None] class PythonExecutor(Executor[Thunk]): """An execution engine based on Python loops. Supports copying between any...
import itertools from functools import partial import math from typing import Callable, Iterable from rechunker.types import CopySpec, StagedCopySpec, Executor # PythonExecutor represents delayed execution tasks as functions that require # no arguments. Task = Callable[[], None] class PythonExecutor(Executor[Task...
Remove 'thunk' jargon from PythonExecutor
Remove 'thunk' jargon from PythonExecutor
Python
mit
pangeo-data/rechunker
ddc03637b19059f6fb06d72dc380afaf4fba57c2
indra/tests/test_context.py
indra/tests/test_context.py
from indra.databases import context_client def test_get_protein_expression(): res = context_client.get_protein_expression('EGFR', 'BT20_BREAST') assert(res is not None) assert(res.get('EGFR') is not None) assert(res['EGFR'].get('BT20_BREAST') is not None) assert(res['EGFR']['BT20_BREAST'] > 1000) ...
from indra.databases import context_client def test_get_protein_expression(): res = context_client.get_protein_expression('EGFR', 'BT20_BREAST') assert(res is not None) assert(res.get('EGFR') is not None) assert(res['EGFR'].get('BT20_BREAST') is not None) assert(res['EGFR']['BT20_BREAST'] > 1000) ...
Remove deprecated context client test
Remove deprecated context client test
Python
bsd-2-clause
johnbachman/belpy,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,jmuhlich/indra,jmuhlich/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,jmuhlich/indra,bgyori/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/ind...
a1f5a392d5270dd6f80a40e45c5e25b6ae04b7c3
embed_video/fields.py
embed_video/fields.py
from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field f...
from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from .backends import detect_backend, UnknownIdException, \ UnknownBackendException __all__ = ('EmbedVideoField', 'EmbedVideoFormField') class EmbedVideoField(models.URLField): """ Model field f...
Simplify validate method in FormField.
Simplify validate method in FormField.
Python
mit
yetty/django-embed-video,jazzband/django-embed-video,jazzband/django-embed-video,mpachas/django-embed-video,yetty/django-embed-video,mpachas/django-embed-video
7f6167ef9f62b9b79e3c30b358c796caae69a2e6
PyWXSB/exceptions_.py
PyWXSB/exceptions_.py
"""Extensions of standard exceptions for PyWXSB events. Yeah, I'd love this module to be named exceptions.py, but it can't because the standard library has one of those, and we need to reference it below. """ import exceptions class PyWXSBException (exceptions.Exception): """Base class for exceptions that indica...
"""Extensions of standard exceptions for PyWXSB events. Yeah, I'd love this module to be named exceptions.py, but it can't because the standard library has one of those, and we need to reference it below. """ import exceptions class PyWXSBException (exceptions.Exception): """Base class for exceptions that indica...
Add an exception to throw when a document does have the expected structure
Add an exception to throw when a document does have the expected structure
Python
apache-2.0
jonfoster/pyxb-upstream-mirror,jonfoster/pyxb-upstream-mirror,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,CantemoInternal/pyxb,jonfoster/pyxb2,balanced/PyXB,CantemoInternal/pyxb,jonfoster/pyxb1,pabigot/pyxb,jonfoster/pyxb2,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,balanced/PyXB
36298a9f9a7a373a716e44cac6226a0ec8c8c40c
__main__.py
__main__.py
from twisted.internet.endpoints import TCP4ServerEndpoint from twisted.internet import reactor import editorFactory if __name__ == "__main__": server = editorFactory.EditorFactory() TCP4ServerEndpoint(reactor, 4567).listen(server) reactor.run()
from twisted.internet.endpoints import TCP4ServerEndpoint from twisted.internet import reactor import editorFactory if __name__ == "__main__": server = editorFactory.EditorFactory() TCP4ServerEndpoint(reactor, 4567).listen(server) print('Starting up...') reactor.run()
Print something at the start
Print something at the start
Python
apache-2.0
Floobits/floobits-emacs
602c01caa23df0c6dad5963412a340087012f692
thinc/tests/integration/test_shape_check.py
thinc/tests/integration/test_shape_check.py
import pytest import numpy from ...neural._classes.model import Model def test_mismatched_shapes_raise_ShapeError(): X = numpy.ones((3, 4)) model = Model(10, 5) with pytest.raises(ValueError): y = model.begin_training(X)
import pytest import numpy from ...neural._classes.model import Model from ...exceptions import UndefinedOperatorError, DifferentLengthError from ...exceptions import ExpectedTypeError, ShapeMismatchError def test_mismatched_shapes_raise_ShapeError(): X = numpy.ones((3, 4)) model = Model(10, 5) with pyte...
Update test and import errors
Update test and import errors
Python
mit
explosion/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc
838012c457d6c963707bb16259cd72d28c231672
cellcounter/accounts/decorators.py
cellcounter/accounts/decorators.py
__author__ = 'jvc26'
from functools import wraps from ratelimit.exceptions import Ratelimited from ratelimit.helpers import is_ratelimited def registration_ratelimit(ip=True, block=False, method=['POST'], field=None, rate='1/h', skip_if=None, keys=None): def decorator(fn): @wraps(fn) def _w...
Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors
Use custom decorator to allow ratelimiting only on successful POST - prevents blocking form errors
Python
mit
haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter,cellcounter/cellcounter,cellcounter/cellcounter,haematologic/cellcounter
4742f587e3e66fd1916dcb7200517e2ac06ddcf4
uconnrcmpy/__init__.py
uconnrcmpy/__init__.py
from .ignitiondelayexp import ExperimentalIgnitionDelay from .compare_to_sim import CompareToSimulation from .volume_trace import VolumeTraceBuilder from .nonreactive import NonReactiveExperiments __all__ = [ 'ExperimentalIgnitionDelay', 'CompareToSimulation', 'VolumeTraceBuilder', 'NonReactiveExperime...
import sys if sys.version_info[0] < 3 and sys.version_info[1] < 4: raise Exception('Python 3.4 is required to use this package.') from .ignitiondelayexp import ExperimentalIgnitionDelay from .compare_to_sim import CompareToSimulation from .volume_trace import VolumeTraceBuilder from .nonreactive import NonReactive...
Enforce Python >= 3.4 on import of the package
Enforce Python >= 3.4 on import of the package Python 3.4 is required for the pathlib module
Python
bsd-3-clause
bryanwweber/UConnRCMPy
77cf2fb0f63a5520de3b8b3456ce4c9181b91d16
spacy/tests/regression/test_issue595.py
spacy/tests/regression/test_issue595.py
from __future__ import unicode_literals import pytest from ...symbols import POS, VERB, VerbForm_inf from ...tokens import Doc from ...vocab import Vocab from ...lemmatizer import Lemmatizer @pytest.fixture def index(): return {'verb': {}} @pytest.fixture def exceptions(): return {'verb': {}} @pytest.fixtu...
from __future__ import unicode_literals import pytest from ...symbols import POS, VERB, VerbForm_inf from ...tokens import Doc from ...vocab import Vocab from ...lemmatizer import Lemmatizer @pytest.fixture def index(): return {'verb': {}} @pytest.fixture def exceptions(): return {'verb': {}} @pytest.fixtu...
Remove unnecessary argument in test
Remove unnecessary argument in test
Python
mit
oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,s...
bca3c8f7b2c12b86e0d200009d23201bdc05d716
make_spectra.py
make_spectra.py
# -*- coding: utf-8 -*- import randspectra as rs import sys import os.path as path snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'...
# -*- coding: utf-8 -*- import randspectra as rs import sys import os.path as path snapnum=sys.argv[1] sim=sys.argv[2] #base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/" #savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'...
Handle the case where the savefile already exists by moving it out of the way
Handle the case where the savefile already exists by moving it out of the way
Python
mit
sbird/vw_spectra
bed7f5c80f6c5b5ce9b9a17aea5c9eadd047ee47
mfr/conftest.py
mfr/conftest.py
"""Project-wide test configuration, including fixutres that can be used by any module. Example test: :: def test_my_renderer(fakefile): assert my_renderer(fakefile) == '..expected result..' """ import io import pytest @pytest.fixture def fakefile(): return io.BytesIO(b'foo')
"""Project-wide test configuration, including fixutres that can be used by any module. Example test: :: def test_my_renderer(fakefile): assert my_renderer(fakefile) == '..expected result..' """ import pytest import mock @pytest.fixture def fakefile(): """A simple file-like object.""" return mock...
Make fakefile a mock instead of an io object
Make fakefile a mock instead of an io object Makes it possible to mutate attributes, e.g. the name, for tests
Python
apache-2.0
felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,CenterForOpenScience/modular-file-renderer,Johnetordoff/modular-file-renderer,mfraezz/modular-file-renderer,icereval/modular-file-renderer,icereval/modular-file-renderer,AddisonSchiller/modular-file-renderer,chrisset...
3770095f087309efe901c2f22afd29ba6f3ddd18
comrade/core/context_processors.py
comrade/core/context_processors.py
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['current_site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: ...
from django.conf import settings from django.contrib.sites.models import Site from settings import DeploymentType def default(request): context = {} context['DEPLOYMENT'] = settings.DEPLOYMENT context['current_site'] = Site.objects.get_current() if settings.DEPLOYMENT != DeploymentType.PRODUCTION: ...
Add a context processor that adds the UserProfile to each context.
Add a context processor that adds the UserProfile to each context.
Python
mit
bueda/django-comrade
921e315e61355d80caea673ce09f8944388d86e2
tests/unit/util/test_cache.py
tests/unit/util/test_cache.py
"""Test praw.util.cache.""" from .. import UnitTest from praw.util.cache import cachedproperty class TestCachedProperty(UnitTest): class Klass: @cachedproperty def nine(self): """Return 9.""" return 9 def ten(self): return 10 ten = cachedprop...
"""Test praw.util.cache.""" from .. import UnitTest from praw.util.cache import cachedproperty class TestCachedProperty(UnitTest): class Klass: @cachedproperty def nine(self): """Return 9.""" return 9 def ten(self): return 10 ten = cachedprop...
Test for property ten as well
Test for property ten as well
Python
bsd-2-clause
praw-dev/praw,gschizas/praw,praw-dev/praw,gschizas/praw
6f29293e6f447dfd80d10c173b7c5a6cc13a4243
main/urls.py
main/urls.py
from django.conf.urls import url from django.views import generic from . import views app_name = 'main' urlpatterns = [ url(r'^$', views.AboutView.as_view(), name='about'), url(r'^chas/$', views.AboutChasView.as_view(), name='chas'), url(r'^evan/$', views.AboutEvanView.as_view(), name='evan'), ]
from django.urls import include, path from . import views app_name = 'main' urlpatterns = [ path('', views.AboutView.as_view(), name='about'), path('chas/', views.AboutChasView.as_view(), name='chas'), path('evan/', views.AboutEvanView.as_view(), name='evan'), ]
Move some urlpatterns to DJango 2.0 preferred method
Move some urlpatterns to DJango 2.0 preferred method
Python
mit
evanepio/dotmanca,evanepio/dotmanca,evanepio/dotmanca
3de9cd44ef803b7c7f3e05e29ecaa30113caf1ba
test/db/relations.py
test/db/relations.py
import unittest from firmant.db.relations import schema class TestSchemaLoad(unittest.TestCase): def testLoad(self): if schema('loader-works') != 'SCHEMA LOAD WORKING PROPERLY': self.fail() suite = unittest.TestLoader().loadTestsFromTestCase(TestSchemaLoad)
import unittest from firmant.db.relations import schema class TestSchemaLoad(unittest.TestCase): def testLoad(self): self.assertEqual(schema('loader-works'), 'SCHEMA LOAD WORKING PROPERLY') suite = unittest.TestLoader().loadTestsFromTestCase(TestSchemaLoad)
Update the schema load test.
Update the schema load test. It now has 100% coverage if the tests pass.
Python
bsd-3-clause
rescrv/firmant
ad7e1149081461d2d34578e06cf5f470d2d20e71
tomviz/python/Subtract_TiltSer_Background.py
tomviz/python/Subtract_TiltSer_Background.py
def transform_scalars(dataset): from tomviz import utils import numpy as np #----USER SPECIFIED VARIABLES-----# ###XRANGE### ###YRANGE### ###ZRANGE### #---------------------------------# data_bs = utils.get_array(dataset) #get data as numpy array if data_bs is None: #Check if ...
def transform_scalars(dataset): from tomviz import utils import numpy as np #----USER SPECIFIED VARIABLES-----# ###XRANGE### ###YRANGE### ###ZRANGE### #---------------------------------# data_bs = utils.get_array(dataset) #get data as numpy array data_bs = data_bs.astype(np.float3...
Change tilt series type to float in manual background sub.
Change tilt series type to float in manual background sub.
Python
bsd-3-clause
cjh1/tomviz,cryos/tomviz,cjh1/tomviz,mathturtle/tomviz,thewtex/tomviz,OpenChemistry/tomviz,cryos/tomviz,cryos/tomviz,OpenChemistry/tomviz,thewtex/tomviz,thewtex/tomviz,cjh1/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
850c5c6f133fdfd131605eb1bf1e971b33dd7416
website/addons/twofactor/tests/test_views.py
website/addons/twofactor/tests/test_views.py
from nose.tools import * from webtest_plus import TestApp from tests.base import OsfTestCase from tests.factories import AuthUserFactory from website.app import init_app from website.addons.twofactor.tests import _valid_code app = init_app( routes=True, set_backends=False, settings_module='website.setting...
from nose.tools import * from webtest.app import AppError from webtest_plus import TestApp from tests.base import OsfTestCase from tests.factories import AuthUserFactory from website.app import init_app from website.addons.twofactor.tests import _valid_code app = init_app( routes=True, set_backends=False, ...
Add test for failure to confirm 2FA code
Add test for failure to confirm 2FA code
Python
apache-2.0
doublebits/osf.io,brianjgeiger/osf.io,billyhunt/osf.io,cwisecarver/osf.io,CenterForOpenScience/osf.io,barbour-em/osf.io,wearpants/osf.io,MerlinZhang/osf.io,alexschiller/osf.io,brandonPurvis/osf.io,haoyuchen1992/osf.io,SSJohns/osf.io,HalcyonChimera/osf.io,dplorimer/osf,amyshi188/osf.io,SSJohns/osf.io,chrisseto/osf.io,ti...
4744f3b3e5193ad66a4bba64d8a8d8c4e328fdcc
pychat.py
pychat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib.login import Login def pychat(): login = Login login() if __name__ == '__main__': pychat()
#!/usr/bin/env python # -*- coding: utf-8 -*- from lib.login import Login from lib.client import Client from Tkinter import * class PyChat(object): def __init__(self): self.root = Tk() self.root.geometry("300x275+400+100") def login(self): self.login = Login(self.root, self.create_c...
Rework to have a central root window controlled from a top class
Rework to have a central root window controlled from a top class
Python
mit
tijko/PyChat
e40ef4cbe59c5c3d064e60f02f60f19b0bb202a4
test_daily_parser.py
test_daily_parser.py
#!/usr/bin/env python # -*- coding: latin-1 -*- """Unit tests.""" import unittest from daily_parser import url_from_args class TestDailyParser(unittest.TestCase): """Testing methods from daily_parser.""" def test_url_from_args(self): output = url_from_args(2014, 1) expected = 'https://dons...
#!/usr/bin/env python # -*- coding: latin-1 -*- """Unit tests.""" import unittest from daily_parser import url_from_args, DonationsParser class TestDailyParser(unittest.TestCase): """Testing methods from daily_parser.""" def test_url_from_args(self): output = url_from_args(2014, 1) expecte...
Add unit test for DonationsParser.get_csv
Add unit test for DonationsParser.get_csv
Python
mit
Commonists/DonationsLogParser,Commonists/DonationsLogParser
2377f500d4667623da9a2921c62862b00d7f404c
school/frontend/views.py
school/frontend/views.py
from flask import Blueprint, render_template, url_for, redirect, flash from flask.ext.login import login_required, logout_user, current_user, login_user from .forms import LoginForm from school.config import FLASH_SUCCESS, FLASH_INFO, FLASH_WARNING frontend = Blueprint('frontend', __name__) @frontend.route('/login',...
from flask import Blueprint, render_template, url_for, redirect, flash from flask.ext.login import login_required, logout_user, current_user, login_user from .forms import LoginForm from school.config import FLASH_SUCCESS, FLASH_INFO, FLASH_WARNING frontend = Blueprint('frontend', __name__) @frontend.route('/login',...
Remove flash success message when logging in.
Remove flash success message when logging in.
Python
mit
leyyin/university-SE,leyyin/university-SE,leyyin/university-SE
7aedc2151035174632a7f3e55be7563f71e65117
tests/audio/test_loading.py
tests/audio/test_loading.py
import pytest @pytest.mark.xfail def test_missing_file(audiomgr): sound = audiomgr.get_sound('/not/a/valid/file.ogg') assert sound is None
import pytest def test_missing_file(audiomgr): sound = audiomgr.get_sound('/not/a/valid/file.ogg') assert str(sound).startswith('NullAudioSound')
Update audio test to recognize missing sounds as NullAudioSound
tests: Update audio test to recognize missing sounds as NullAudioSound
Python
bsd-3-clause
chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d,chandler14362/panda3d
66c50cdeda974f2159259b466995339244ffb694
training/level-2-command-line-interfaces/dragon-warrior/tmarsha1/primes/Tests/PrimeFinderTests.py
training/level-2-command-line-interfaces/dragon-warrior/tmarsha1/primes/Tests/PrimeFinderTests.py
""" Test the Prime Finder class Still working on getting dependency injection working. """ import unittest from primes.Primes import PrimeFinder #from primes.Primes import PrimeGenerator class PrimeFinderTests(unittest.TestCase): def test_find_prime(self): prime_finder = PrimeFinder.PrimeFinder(PrimeGene...
""" Test the Prime Finder class Still working on getting dependency injection working. Injecting the Generator into the Finder allows for many possibilities. From the testing perspective this would allow me to inject a mock object for the Generator that returns a set value speeding up the testing of the Prime Finder c...
Add additional comments regarding Dependency Injection
Add additional comments regarding Dependency Injection
Python
artistic-2.0
bigfatpanda-training/pandas-practical-python-primer,bigfatpanda-training/pandas-practical-python-primer
7a7729e9af8e91411526525c19c5d434609e0f21
logger.py
logger.py
MSG_INFO = 0x01 MSG_WARNING = 0x02 MSG_ERROR = 0x04 MSG_VERBOSE = 0x08 MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE def logi(msg): print("[INFO] " + msg) def logv(msg): print("[VERBOSE] " + msg) def logw(msg): print("[WARNING] " + msg) def loge(msg): print("[ERROR] " + msg) clas...
MSG_INFO = 0x01 MSG_WARNING = 0x02 MSG_ERROR = 0x04 MSG_VERBOSE = 0x08 MSG_ALL = MSG_INFO | MSG_WARNING | MSG_ERROR | MSG_VERBOSE def logi(msg): print("[INFO] " + msg) def logv(msg): print("[VERBOSE] " + msg) def logw(msg): print("[WARNING] " + msg) def loge(msg): print("\033[1;31m[ERROR] " + ...
Add color for error message.
Add color for error message.
Python
mit
PyOCL/oclGA,PyOCL/OpenCLGA,PyOCL/OpenCLGA,PyOCL/oclGA,PyOCL/oclGA,PyOCL/TSP,PyOCL/TSP,PyOCL/oclGA,PyOCL/OpenCLGA
4f71339cad35b2444ea295fd4b518e539f1088bb
fluent_faq/urls.py
fluent_faq/urls.py
from django.conf.urls import patterns, url from .views import FaqQuestionList, FaqCategoryDetail, FaqQuestionDetail urlpatterns = patterns('', url(r'^$', FaqQuestionList.as_view(), name='faqquestion_index'), url(r'^(?P<slug>[^/]+)/$', FaqCategoryDetail.as_view(), name='faqcategory_detail'), url(r'^(?P<cat_...
from django.conf.urls import url from .views import FaqQuestionList, FaqCategoryDetail, FaqQuestionDetail urlpatterns = [ url(r'^$', FaqQuestionList.as_view(), name='faqquestion_index'), url(r'^(?P<slug>[^/]+)/$', FaqCategoryDetail.as_view(), name='faqcategory_detail'), url(r'^(?P<cat_slug>[^/]+)/(?P<slug>...
Fix Django 1.9 warnings about patterns('', ..)
Fix Django 1.9 warnings about patterns('', ..)
Python
apache-2.0
edoburu/django-fluent-faq,edoburu/django-fluent-faq
f113123a3f31e176ae7165f1ca11118dc00625a3
tests/test_backend_forms.py
tests/test_backend_forms.py
import floppyforms.__future__ as floppyforms from django.test import TestCase from django_backend.backend.base.forms import BaseBackendForm from .models import OneFieldModel class OneFieldForm(BaseBackendForm): class Meta: model = OneFieldModel exclude = () class BaseBackendFormTests(TestCase)...
import floppyforms.__future__ as floppyforms from django.test import TestCase from django_backend.forms import BaseBackendForm from .models import OneFieldModel class OneFieldForm(BaseBackendForm): class Meta: model = OneFieldModel exclude = () class BaseBackendFormTests(TestCase): def tes...
Fix forms import in tests
Fix forms import in tests
Python
bsd-3-clause
team23/django_backend,team23/django_backend,team23/django_backend,team23/django_backend,team23/django_backend