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
90eafe038adfeddf5379e950b03ec0727d0c5d36
ci/__init__.py
ci/__init__.py
from cisd import CISD
from pyscf.ci import cisd def CISD(mf, frozen=[], mo_coeff=None, mo_occ=None): from pyscf import scf if isinstance(mf, (scf.uhf.UHF, scf.rohf.ROHF)): raise NotImplementedError('RO-CISD, UCISD are not available in this pyscf version') return cisd.CISD(mf, frozen, mo_coeff, mo_occ)
Improve error message for CISD
Improve error message for CISD
Python
apache-2.0
gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,gkc1000/pyscf
a19b043c910274277ce5a6a777f686030f6ef7d0
media_manager/migrations/0001_initial.py
media_manager/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', models.AutoField(verbo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Course', fields=[ ('id', mod...
Mark initial migration so django knows to skip it.
Mark initial migration so django knows to skip it.
Python
bsd-3-clause
Harvard-ATG/media_management_lti,Harvard-ATG/media_management_lti,Harvard-ATG/media_management_lti,Harvard-ATG/media_management_lti
5e6f2828ec36a57a46f8220cc9263b643792573b
ereuse_devicehub/scripts/updates/snapshot_software.py
ereuse_devicehub/scripts/updates/snapshot_software.py
from pydash import find from ereuse_devicehub.resources.device.domain import DeviceDomain from ereuse_devicehub.resources.event.device import DeviceEventDomain from ereuse_devicehub.scripts.updates.update import Update class SnapshotSoftware(Update): """ Changes the values of SnapshotSoftware and adds it to ...
from pydash import find from ereuse_devicehub.resources.device.domain import DeviceDomain from ereuse_devicehub.resources.event.device import DeviceEventDomain from ereuse_devicehub.scripts.updates.update import Update class SnapshotSoftware(Update): """ Changes the values of SnapshotSoftware and adds it to ...
Fix getting snapshotsoftware on old snapshots
Fix getting snapshotsoftware on old snapshots
Python
agpl-3.0
eReuse/DeviceHub,eReuse/DeviceHub
0612ea6aea5a10e5639a710500c321e3c9e02495
interfaces/python/setup.py
interfaces/python/setup.py
#!/usr/bin/env python """ setup.py file for compiling Infomap module """ from distutils.core import setup, Extension import fnmatch import os import re cppSources = [] for root, dirnames, filenames in os.walk('.'): if root == 'src': cppSources.append(os.path.join(root, 'Infomap.cpp')) else: for filen...
#!/usr/bin/env python """ setup.py file for compiling Infomap module """ from distutils.core import setup, Extension from distutils.file_util import copy_file import sysconfig import fnmatch import os import re cppSources = [] for root, dirnames, filenames in os.walk('.'): if root == 'src': cppSources.append(os....
Fix python library problem due to ABI tagged .so files
Fix python library problem due to ABI tagged .so files
Python
agpl-3.0
mapequation/infomap,mapequation/infomap,mapequation/infomap,mapequation/infomap
c7030e461026e718c46b86dadecc9681d226c27c
cupy/util.py
cupy/util.py
import atexit import functools from cupy import cuda _memoized_funcs = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it ...
import atexit import functools from cupy import cuda _memos = [] def memoize(for_each_device=False): """Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes ...
Fix unintended late finalization of memoized functions
Fix unintended late finalization of memoized functions
Python
mit
ktnyt/chainer,niboshi/chainer,niboshi/chainer,laysakura/chainer,tscohen/chainer,benob/chainer,chainer/chainer,cupy/cupy,aonotas/chainer,cupy/cupy,jnishi/chainer,cupy/cupy,tkerola/chainer,cemoody/chainer,ktnyt/chainer,chainer/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,truongdq/chainer,kashif/chainer,w...
447a9c82e229eb801df028d2531764d89b28c923
genderbot.py
genderbot.py
import random import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_article_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketba...
import re from twitterbot import TwitterBot import wikipedia class Genderbot(TwitterBot): boring_article_regex = (r"municipality|village|town|football|genus|family|" "administrative|district|community|region|hamlet|" "school|actor|mountain|basketball|city|specie...
Remove import random now that it's not being used
Remove import random now that it's not being used
Python
mit
DanielleSucher/genderbot
3c8d3bfea2ef1c82a62ef1b7455c29c044c7cfa3
ensure_zero_padding_in_numbering_of_files.py
ensure_zero_padding_in_numbering_of_files.py
import argparse import os import re import sys def main(cmdline): parser = argparse.ArgumentParser( description='Ensure zero padding in numbering of files.') parser.add_argument('path', type=str, help='path to the directory containing the files') args = parser.parse_args() path = args....
#!/usr/bin/env python3 import argparse import os import re import sys def main(): parser = argparse.ArgumentParser( description='Ensure zero padding in numbering of files.') parser.add_argument( 'path', type=str, help='path to the directory containing the files') args = p...
Convert to py3, fix style issues (flake8, pylint).
Convert to py3, fix style issues (flake8, pylint).
Python
mit
dwinston/cli-utils
eadf481f352e4277001f3b9e83c7ffbbd58c789c
openstack/tests/functional/network/v2/test_service_provider.py
openstack/tests/functional/network/v2/test_service_provider.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Fix the network service provider test
Fix the network service provider test This test was pretty lame before since it just verified that the result was a string. Now it verifies that at least one service provider exists and I think I picked one that should be aroudn for a while. The test failure message also prints the list of providers now so it should...
Python
apache-2.0
stackforge/python-openstacksdk,briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,openstack/python-openstacksdk
644e4301d0a73756750a48226b9db00e51a9e46c
fmproject/urls.py
fmproject/urls.py
"""ssoproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
"""ssoproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-...
Add url mapping for github callback
Add url mapping for github callback
Python
mit
favoritemedium/sso-prototype,favoritemedium/sso-prototype
14762a73617007f0b65880e1d99cd5b47e03bfff
vimeo/auth/authorization_code.py
vimeo/auth/authorization_code.py
#! /usr/bin/env python # encoding: utf-8 from __future__ import absolute_import import urllib from .base import AuthenticationMixinBase from . import GrantFailed class AuthorizationCodeMixin(AuthenticationMixinBase): """Implement helpers for the Authorization Code grant for OAuth2.""" def auth_url(self, sco...
#! /usr/bin/env python # encoding: utf-8 from __future__ import absolute_import import urllib from .base import AuthenticationMixinBase from . import GrantFailed try: basestring except NameError: basestring = str class AuthorizationCodeMixin(AuthenticationMixinBase): """Implement helpers for the Authori...
Make basestring work in Python 3
Make basestring work in Python 3
Python
apache-2.0
vimeo/vimeo.py,greedo/vimeo.py,blorenz/vimeo.py,gabrielgisoldo/vimeo.py
303d256bd6615bfef7d26a1b5dadf474dbbb26af
cortex/main.py
cortex/main.py
'''Main file for running experiments. ''' import logging from cortex._lib import (config, data, exp, optimizer, setup_cortex, setup_experiment, train) from cortex._lib.utils import print_section import torch __author__ = 'R Devon Hjelm' __author_email__ = 'erroneus@gmail.com' logger = l...
'''Main file for running experiments. ''' import logging from cortex._lib import (config, data, exp, optimizer, setup_cortex, setup_experiment, train) from cortex._lib.utils import print_section import torch __author__ = 'R Devon Hjelm' __author_email__ = 'erroneus@gmail.com' logger = l...
Terminate viz process at end of experiment.
Terminate viz process at end of experiment.
Python
bsd-3-clause
rdevon/cortex,rdevon/cortex
5b038b468af0f5a060eaea3bd2956ff85ad09071
conman/redirects/views.py
conman/redirects/views.py
from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" permanent = False # Set to django 1.9's default to avoid RemovedInDjango19Warning def get_redirect_url(self, *args, **kwargs): """ Return the route's target url. ...
from django.views.generic import RedirectView class RouteRedirectView(RedirectView): """Redirect to the target Route.""" permanent = False # Set to django 1.9's default to avoid RemovedInDjango19Warning def get_redirect_url(self, *args, route, **kwargs): """ Return the route's target url...
Use explicit kwarg over kwargs dictionary access
Use explicit kwarg over kwargs dictionary access
Python
bsd-2-clause
meshy/django-conman,meshy/django-conman,Ian-Foote/django-conman
780b84a2ed7aff91de8ab7b5505e496649d3ddfa
nlppln/wfgenerator.py
nlppln/wfgenerator.py
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir) self.load(step_file='https://raw.githubusercontent.com/nlppln/' ...
from scriptcwl import WorkflowGenerator as WFGenerator from .utils import CWL_PATH class WorkflowGenerator(WFGenerator): def __init__(self, working_dir=None): WFGenerator.__init__(self, steps_dir=CWL_PATH, working_dir=working_dir) self.load(step_file='https://raw.githubusercontent.com/nlppln/' ...
Make default saving option relative
Make default saving option relative Saving workflows with wd=True only works when you use a working dir. Since this is optional, it makes more sense to use relative paths (and assume the user uses the nlppln CWL_PATH to save their workflows).
Python
apache-2.0
WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln
c6021a20cacea609398bd07adabfba3d7782b7ef
rovercode/drivers/grovepi_ultrasonic_ranger_binary.py
rovercode/drivers/grovepi_ultrasonic_ranger_binary.py
""" Class for communicating with the GrovePi ultrasonic ranger. Here we treat it as a binary sensor. """ import logging logging.basicConfig() LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.getLevelName('INFO')) try: from grovepi import ultrasonicRead except ImportError: LOGGER.warning("GrovePi l...
""" Class for communicating with the GrovePi ultrasonic ranger. Here we treat it as a binary sensor. """ import logging logging.basicConfig() LOGGER = logging.getLogger(__name__) LOGGER.setLevel(logging.getLevelName('INFO')) try: from grovepi import ultrasonicRead except ImportError: LOGGER.warning("GrovePi l...
Fix sensor to be active high
Fix sensor to be active high
Python
apache-2.0
aninternetof/rover-code,aninternetof/rover-code,aninternetof/rover-code
6e19ff22ea0e8c78e7faaa2ba58626de383dfee3
djangae/contrib/mappers/urls.py
djangae/contrib/mappers/urls.py
from django.conf.urls import url from djangae.utils import djangae_webapp from django.views.decorators.csrf import csrf_exempt try: from mapreduce.main import create_handlers_map wrapped_urls = [url(url_re.replace('.*/', '^', 1), csrf_exempt(djangae_webapp(func))) for url_re, func in create_handlers_map()] ex...
from django.conf.urls import url from djangae.utils import djangae_webapp from django.views.decorators.csrf import csrf_exempt # The Mapreduce status UI uses inline JS, which will fail If we have django-csp # installed and are not allowing 'unsafe-inline' as a SCRIPT_SRC. try: from csp.decorators import csp_updat...
Allow the Mapreduce status UI to function when a CSP is enforced with django-csp.
Allow the Mapreduce status UI to function when a CSP is enforced with django-csp.
Python
bsd-3-clause
potatolondon/djangae,grzes/djangae,grzes/djangae,kirberich/djangae,potatolondon/djangae,grzes/djangae,kirberich/djangae,kirberich/djangae
92a5712bdb04ae265120a41d688b37b60507d9dd
opps/core/__init__.py
opps/core/__init__.py
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ( 'opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'django_thumbor', 'googl', ...
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.conf import settings trans_app_label = _('Opps') settings.INSTALLED_APPS += ( 'opps.article', 'opps.image', 'opps.channel', 'opps.source', 'django.contrib.redirects', 'django_thumbor', 'googl', ...
Set class process site map
Set class process site map
Python
mit
YACOWS/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,williamroot/opps,YACOWS/opps,williamroot/opps,opps/opps,opps/opps,YACOWS/opps,opps/opps,YACOWS/opps
f46226ed4b5a1c0bf2592692aba8481cc777414f
exp/views/dashboard.py
exp/views/dashboard.py
from django.shortcuts import redirect from django.urls import reverse_lazy from django.views import generic from exp.views.mixins import ExperimenterLoginRequiredMixin class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView): ''' ExperimenterDashboard will show a customized view...
from django.shortcuts import redirect from django.urls import reverse_lazy from django.views import generic from exp.views.mixins import ExperimenterLoginRequiredMixin class ExperimenterDashboardView(ExperimenterLoginRequiredMixin, generic.TemplateView): ''' ExperimenterDashboard will show a customized view...
Check if user has is_researcher attribute before accessing it to accommodate AnonymousUser.
Check if user has is_researcher attribute before accessing it to accommodate AnonymousUser.
Python
apache-2.0
CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api
2b3e165a5dbf34d8ed94eda1453b20099d88618f
BasicSequences/__init__.py
BasicSequences/__init__.py
from RabiAmp import RabiAmp from Ramsey import Ramsey from FlipFlop import FlipFlop from SPAM import SPAM from RB import SingleQubitRB, SingleQubitRB_AC, SingleQubitRBT
from RabiAmp import RabiAmp from Ramsey import Ramsey from FlipFlop import FlipFlop from SPAM import SPAM from RB import SingleQubitRB, SingleQubitRB_AC, SingleQubitRBT from itertools import product import operator from ..PulsePrimitives import Id, X def create_cal_seqs(qubits, numCals): """ Helper function to c...
Add a helper function to create calibration sequences.
Add a helper function to create calibration sequences.
Python
apache-2.0
BBN-Q/QGL,BBN-Q/QGL
091f9daf8758e56c82dbe7a88a50489ab279f793
adhocracy/lib/helpers/site_helper.py
adhocracy/lib/helpers/site_helper.py
from pylons import config, g from pylons.i18n import _ def name(): return config.get('adhocracy.site.name', _("Adhocracy")) def base_url(instance, path=None): url = "%s://" % config.get('adhocracy.protocol', 'http').strip() if instance is not None and g.single_instance is None: url += instance.k...
from pylons import config, g from pylons.i18n import _ def domain(): return config.get('adhocracy.domain').split(':')[0] def name(): return config.get('adhocracy.site.name', _("Adhocracy")) def base_url(instance, path=None): url = "%s://" % config.get('adhocracy.protocol', 'http').strip() if insta...
Add h.site.domain() to return the domian without the port
Add h.site.domain() to return the domian without the port
Python
agpl-3.0
DanielNeugebauer/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,SysTheron/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,DanielNeugebauer/a...
ede07cc5f2e410481b71bd7ba0cf1aa2fce26e08
astroquery/simbad/tests/test_simbad.py
astroquery/simbad/tests/test_simbad.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from ... import simbad def test_simbad(): r = simbad.QueryAroundId('m31', radius='0.5s').execute() print r.table assert "M 31" in r.table["MAIN_ID"] def test_multi(): result = simbad.QueryMulti( [simbad.QueryId('m31'), ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from ... import simbad import sys is_python3 = (sys.version_info >= (3,)) def test_simbad(): r = simbad.QueryAroundId('m31', radius='0.5s').execute() print r.table if is_python3: m31 = b"M 31" else: m31 = "M 31" asse...
Fix python3 tests for simbad.
Fix python3 tests for simbad.
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
095678fa910f78de1cac80bef46d0e29323a120c
camz/camera.py
camz/camera.py
import io import picamera class Camera(object): def __init__(self): self.camera = picamera.PiCamera() self.camera.resolution = (800, 600) self.camera.framerate = 30 self.camera.rotation = 180 self.camera.led = False self.recording = False self.loopStream = ...
import io import picamera class Camera(object): def __init__(self): self.camera = picamera.PiCamera() self.camera.resolution = (640, 480) self.camera.rotation = 180 self.camera.led = False self.recording = False self.loopStream = picamera.PiCameraCircularIO(self.ca...
Remove recording wait, works better
Remove recording wait, works better
Python
mit
calston/pirnv
4fa76c04a3455ebce6251b59aea54f5a769f3deb
invite/utils.py
invite/utils.py
from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is None or type(days) != int: return None else: if days >= 0: return date.today() - timedelta(days=days) else: r...
from datetime import date, timedelta def get_cutoff_date(days): """Calculate the cutoff date or return None if no time period was set.""" if days is None or type(days) != int: return None else: if days > 0: return date.today() - timedelta(days=days) elif days == 0: ...
Make it so a cutoff of 0 leads to no invites/registrations being shown.
Make it so a cutoff of 0 leads to no invites/registrations being shown.
Python
bsd-3-clause
unt-libraries/django-invite,unt-libraries/django-invite
7206db27eb5fccde808f7a4e2b9bea974181bdbc
fluenttest/__init__.py
fluenttest/__init__.py
from fluenttest.class_based import ClassTester, lookup_class, the_class from fluenttest.test_case import TestCase __all__ = [ 'ClassTester', 'TestCase', 'lookup_class', 'the_class', ]
from fluenttest.class_based import ClassTester, lookup_class, the_class from fluenttest.test_case import TestCase version_info = (1, 1, 0) __version__ = '.'.join(str(x) for x in version_info) __all__ = [ 'ClassTester', 'TestCase', 'lookup_class', 'the_class', '__version__', 'version_info', ]
Add __version__ attribute to fluenttest.
Add __version__ attribute to fluenttest. The __version__ attribute is the public version identifier and is server safe. The version_info tuple contains the full version.
Python
bsd-2-clause
dave-shawley/fluent-test
ae4f144ea9256b4b53fe497a656be38f32213277
TwitterDataIngestSource.py
TwitterDataIngestSource.py
import sys from itertools import ifilter from requests_oauthlib import OAuth1Session class TwitterDataIngestSource: """Ingest data from Twitter""" def __init__(self, config): self.config = config def __iter__(self): if 'track' in self.config: self.track = self.config['track'] else: self...
import sys from itertools import ifilter from requests_oauthlib import OAuth1Session import json class TwitterDataIngestSource: """Ingest data from Twitter""" def __init__(self, config): self.config = config def __iter__(self): if 'track' in self.config: self.track = self.config['track'] else...
Fix tweet formatting issues when streaming from twitter
Fix tweet formatting issues when streaming from twitter
Python
mit
W205-Social-Media/w205-data-ingest,abessou/w251-FinalProject,abessou/w251-FinalProject
f50efcb65d794985185f5cc82c697673f50e4c47
synapse/replication/slave/storage/keys.py
synapse/replication/slave/storage/keys.py
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applica...
# -*- coding: utf-8 -*- # Copyright 2015, 2016 OpenMarket Ltd # # 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 applica...
Replace SlavedKeyStore with a shim
Replace SlavedKeyStore with a shim since we're pulling everything out of KeyStore anyway, we may as well simplify it.
Python
apache-2.0
matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse
62c9322cf1508eafa6bd3061d1f047ce42b95804
byceps/blueprints/ticketing/views.py
byceps/blueprints/ticketing/views.py
""" byceps.blueprints.ticketing.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.party import service as party_service from ...services.ticketing import ticket_service from ...util.frame...
""" byceps.blueprints.ticketing.views ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2017 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from flask import abort, g from ...services.party import service as party_service from ...services.ticketing import ticket_service from ...util.frame...
Hide revoked tickets from user in personal ticket list
Hide revoked tickets from user in personal ticket list
Python
bsd-3-clause
m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps
3de1b3c8538a473c29189ef4df02f93e67e221ac
migrations/versions/420_dos_is_coming.py
migrations/versions/420_dos_is_coming.py
"""DOS is coming Revision ID: 420 Revises: 410_remove_empty_drafts Create Date: 2015-11-16 14:10:35.814066 """ # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op import sqlalchemy as sa from app.models import Framework def upgrade(): op.e...
"""DOS is coming Revision ID: 420 Revises: 410_remove_empty_drafts Create Date: 2015-11-16 14:10:35.814066 """ # revision identifiers, used by Alembic. revision = '420' down_revision = '410_remove_empty_drafts' from alembic import op def upgrade(): op.execute("COMMIT") op.execute("ALTER TYPE framework_enu...
Use `op` instead of `app` so that `list_migrations` still works
Use `op` instead of `app` so that `list_migrations` still works By importing `app` the `list_migrations.py` script broke because it doesn't have the `app` context.
Python
mit
alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api
bb18029c9ca75b420aa486e393b2f79e8f2e009b
examples/echobot.py
examples/echobot.py
# -*- coding: utf-8 -*- from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = m...
# -*- coding: utf-8 -*- from linepy import * client = LineClient() #client = LineClient(authToken='AUTHTOKEN') client.log("Auth Token : " + str(client.authToken)) poll = LinePoll(client) # Receive messages from LinePoll def RECEIVE_MESSAGE(op): msg = op.message text = msg.text msg_id = m...
Change receiver contact to sender
Change receiver contact to sender
Python
bsd-3-clause
fadhiilrachman/line-py
0313743781fd046a587936545f030938beb71364
dataset/dataset/spiders/dataset_spider.py
dataset/dataset/spiders/dataset_spider.py
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items class DatasetSpider(CrawlSpider): pages = 9466 name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = [] for i in...
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items class DatasetSpider(CrawlSpider): pages = 9466 name = 'dataset' allowed_domains = ['data.gc.ca'] start_urls = [] for i in...
Add regex to filter out tab/space/newline
Add regex to filter out tab/space/newline
Python
mit
MaxLikelihood/CODE
92bac498d3ad8f2e49212ce73b7324d661620d63
grako/ast.py
grako/ast.py
from collections import OrderedDict, Mapping import json class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] = [value] e...
from collections import OrderedDict, Mapping import json __all__ = ['AST'] class AST(Mapping): def __init__(self, **kwargs): self._elements = OrderedDict(**kwargs) def add(self, key, value): previous = self._elements.get(key, None) if previous is None: self._elements[key] ...
Allow to set items in AST.
Allow to set items in AST.
Python
bsd-2-clause
swayf/grako,swayf/grako
5b91e6ce3b66721df9943f996368e7d977a1e1c9
footparse/_utils.py
footparse/_utils.py
import requests class BasePage: def __init__(self, data): self.data = data @classmethod def from_file(cls, path): with open(path) as f: raw = f.read() return cls(raw) @classmethod def from_url(cls, url): res = requests.get(url) return cls(res....
import requests class BasePage: def __init__(self, data): self.data = data @classmethod def from_file(cls, path): with open(path) as f: raw = f.read() return cls(raw) @classmethod def from_url(cls, url): res = requests.get(url) res.raise_for_s...
Raise an exception when request fails.
Raise an exception when request fails. In general, I think that it is safer to raise an exception when an HTTP request used to fetch a page fails.
Python
mit
kickoffai/footparse,kickoffai/footparse
6d6e0b780c62bea5fec43eae1411db827f13fa17
faker/providers/internet/uk_UA/__init__.py
faker/providers/internet/uk_UA/__init__.py
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as InternetProvider class Provider(InternetProvider): free_email_domains = [ 'email.ua', 'gmail.com', 'gov.ua', 'i.ua', 'meta.ua', 'ukr.net' ] tlds = ['com', 'info', 'net', 'org', 'ua', 'укр']
# coding=utf-8 from __future__ import unicode_literals from .. import Provider as InternetProvider class Provider(InternetProvider): free_email_domains = ( 'email.ua', 'gmail.com', 'gov.ua', 'i.ua', 'meta.ua', 'ukr.net' ) tlds = ('com', 'info', 'net', 'org', 'ua', 'укр') replacements = ( ...
Improve the Ukrainian Internet provider
Improve the Ukrainian Internet provider Add `replacements`. Replace lists by tuples
Python
mit
joke2k/faker,trtd/faker,danhuss/faker,joke2k/faker
364fde2dd6554760ca63c5b16e35222d5482999e
report/report_util.py
report/report_util.py
def compare_ledger_types(account, data, orm): selected_ledger = data['form']['ledger_type'] account_ledgers = [ledger.id for ledger in account.ledger_types] if not selected_ledger: return account_ledgers == [] return selected_ledger in account_ledgers def should_show_account(account, data): ...
def compare_ledger_types(account, data, orm): if not hasattr(account, 'ledger_types'): # Ignore this filter when alternate_ledger is not installed. return True selected_ledger = data['form']['ledger_type'] account_ledgers = [ledger.id for ledger in account.ledger_types] if not selected...
Fix errors when alternate_ledger is not installed
Fix errors when alternate_ledger is not installed
Python
agpl-3.0
lithint/account_report_webkit,xcgd/account_report_webkit,xcgd/account_report_webkit,lithint/account_report_webkit
51de7814ed881a7974f972aafc391584d0c2c517
kuryr/server.py
kuryr/server.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Remove app.debug as we do not use it any more.
Remove app.debug as we do not use it any more. Change-Id: I61497ae95dd304e60240f8ac731e63950351782f Closes-Bug: #1583663
Python
apache-2.0
openstack/kuryr,celebdor/kuryr-libnetwork,celebdor/kuryr-libnetwork,celebdor/kuryr,celebdor/kuryr,celebdor/kuryr-libnetwork,openstack/kuryr
657d5b1a79811df660857b7488895143fd4106fc
openacademy/model/openacademy_session.py
openacademy/model/openacademy_session.py
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6,2), help="Duration in days") seats = fields.Integer(string="Number of seats") in...
# -*- coding: utf-8 -*- from openerp import fields, models class Session(models.Model): _name = 'openacademy.session' name = fields.Char(required=True) start_date = fields.Date() duration = fields.Float(digits=(6,2), help="Duration in days") seats = fields.Integer(string="Number of seats") in...
Add domain | & ilike
[REF] openacademy: Add domain | & ilike
Python
apache-2.0
jorgescalona/openacademy-project
fb986717d5016b1cb3c6b953020ff2aff037b3dc
call_server/extensions.py
call_server/extensions.py
# define flask extensions in separate file, to resolve import dependencies from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail ...
# define flask extensions in separate file, to resolve import dependencies from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() from flask_caching import Cache cache = Cache() from flask_assets import Environment assets = Environment() from flask_babel import Babel babel = Babel() from flask_mail import Mail ...
Include script-src unsafe-eval to allow underscore templating Long term, we should pre-compile with webpack to avoid needing this
Include script-src unsafe-eval to allow underscore templating Long term, we should pre-compile with webpack to avoid needing this
Python
agpl-3.0
OpenSourceActivismTech/call-power,spacedogXYZ/call-power,18mr/call-congress,spacedogXYZ/call-power,spacedogXYZ/call-power,18mr/call-congress,OpenSourceActivismTech/call-power,OpenSourceActivismTech/call-power,spacedogXYZ/call-power,OpenSourceActivismTech/call-power,18mr/call-congress,18mr/call-congress
3ec333d8fc1ad7136b4324476001ed2279977356
pyfibot/util/twitter_application_auth.py
pyfibot/util/twitter_application_auth.py
import requests import base64 import sys if len(sys.argv) < 3: print "Usage: twitter_application_auth.py <consumer key> <consumer secret>" sys.exit(1) consumer_key = sys.argv[1] consumer_secret = sys.argv[2] token = consumer_key + ":" + consumer_secret encoded_token = base64.b64encode(token) payload = {'gran...
import requests import base64 import sys if len(sys.argv) < 3: print "Usage: twitter_application_auth.py <consumer key> <consumer secret>" sys.exit(1) consumer_key = sys.argv[1] consumer_secret = sys.argv[2] token = consumer_key + ":" + consumer_secret encoded_token = base64.b64encode(token) payload = {'gran...
Improve the instructions on twitter application auth
Improve the instructions on twitter application auth
Python
bsd-3-clause
aapa/pyfibot,lepinkainen/pyfibot,aapa/pyfibot,lepinkainen/pyfibot
46cd1dad595aeba0e238a88de9485b1bcbfdab57
txircd/modules/cmode_s.py
txircd/modules/cmode_s.py
from txircd.modbase import Mode class SecretMode(Mode): def listOutput(self, command, data): if command != "LIST": return data cdata = data["cdata"] if "s" in cdata["channel"].mode and cdata["channel"].name not in data["user"].channels: data["cdata"].clear() # other +s stuff is hiding in other modules. ...
from twisted.words.protocols import irc from txircd.modbase import Mode class SecretMode(Mode): def checkPermission(self, user, cmd, data): if cmd != "NAMES": return data remove = [] for chan in data["targetchan"]: if "p" in chan.mode and chan.name not in user.channels: user.sendMessage(irc.ERR_NOSUCH...
Hide secret channels from /NAMES users
Hide secret channels from /NAMES users
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
3c0ce6a3e4e16ff3991a838009c42efa2f5b237d
tviit/admin.py
tviit/admin.py
from django.contrib import admin from .models import Tviit admin.site.register(Tviit)
from django.contrib import admin from .models import Tviit class TviitAdmin(admin.ModelAdmin): readonly_fields=('uuid',) admin.site.register(Tviit, TviitAdmin)
Add uuid to be readable in Admin-panel
Add uuid to be readable in Admin-panel
Python
mit
DeWaster/Tviserrys,DeWaster/Tviserrys
ab8af0f34c468103a092f2c9d751c6c51c5522f1
bioconda_utils/__init__.py
bioconda_utils/__init__.py
""" Bioconda Utilities Package .. rubric:: Subpackages .. autosummary:: :toctree: bioconda_utils.bot bioconda_utils.lint .. rubric:: Submodules .. autosummary:: :toctree: aiopipe bioconductor_skeleton build circleci cli cran_skeleton docker_utils githandler github_integratio...
""" Bioconda Utilities Package .. rubric:: Subpackages .. autosummary:: :toctree: bioconda_utils.bot bioconda_utils.lint .. rubric:: Submodules .. autosummary:: :toctree: aiopipe bioconductor_skeleton build circleci cli cran_skeleton docker_utils githandler githubhandler ...
Fix leftover docs hook for github_integration module
Fix leftover docs hook for github_integration module
Python
mit
bioconda/bioconda-utils,bioconda/bioconda-utils,bioconda/bioconda-utils
575462ca4cf9f5345939026ce5571bdc7e8277ad
bonobo/execution/plugin.py
bonobo/execution/plugin.py
from bonobo.execution.base import LoopingExecutionContext, recoverable class PluginExecutionContext(LoopingExecutionContext): PERIOD = 0.5 def __init__(self, wrapped, parent): # Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure # plugins, f...
from bonobo.execution.base import LoopingExecutionContext, recoverable class PluginExecutionContext(LoopingExecutionContext): PERIOD = 0.5 def __init__(self, wrapped, parent): # Instanciate plugin. This is not yet considered stable, as at some point we may need a way to configure # plugins, f...
Check if PluginExecutionContext was started before shutting it down.
Check if PluginExecutionContext was started before shutting it down. If a `PluginExecutionContext().shutdown()` is called _before_ `PluginExecutionContext().start()` was called, this leads to an `AttributeError` exception since finalizer tries to access to attributes which were never defined.
Python
apache-2.0
hartym/bonobo,python-bonobo/bonobo,hartym/bonobo,python-bonobo/bonobo,python-bonobo/bonobo,hartym/bonobo
d7bce814c10ce13cf4c228fd87dcbdee75f8d0a1
integration-test/1211-fix-null-network.py
integration-test/1211-fix-null-network.py
from . import OsmFixtureTest class FixNullNetwork(OsmFixtureTest): def test_routes_with_no_network(self): # ref="N 4", route=road, but no network=* # so we should get something that has no network, but a shield text of # '4' self.load_fixtures(['http://www.openstreetmap.org/relatio...
from . import OsmFixtureTest class FixNullNetwork(OsmFixtureTest): def test_routes_with_no_network(self): # ref="N 4", route=road, but no network=* # so we should get something that has no network, but a shield text of # '4' self.load_fixtures( ['http://www.openstreetma...
Add clip to reduce fixture size.
Add clip to reduce fixture size.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
e3d1c8bbf238516d7a10e03aea0fbd378c4a4f6f
profile_collection/startup/99-bluesky.py
profile_collection/startup/99-bluesky.py
def detselect(detector_object, suffix="_stats_total1"): """Switch the active detector and set some internal state""" gs.DETS =[detector_object] gs.PLOT_Y = detector_object.name + suffix gs.TABLE_COLS = [gs.PLOT_Y]
def detselect(detector_object, suffix="_stats_total1"): """Switch the active detector and set some internal state""" gs.DETS =[detector_object] gs.PLOT_Y = detector_object.name + suffix gs.TABLE_COLS = [gs.PLOT_Y] def chx_plot_motor(scan): fig = None if gs.PLOTMODE == 1: fig = plt.gcf...
Add 'better' plotting control for live plots
ENH: Add 'better' plotting control for live plots
Python
bsd-2-clause
NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd
c64d35346ed8d7ae5b08bc8d5eb37f0c827da9f4
jesusmtnez/python/kata/tests/test_game.py
jesusmtnez/python/kata/tests/test_game.py
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) d...
import unittest from game import Game class BowlingGameTest(unittest.TestCase): def setUp(self): self.g = Game() def tearDown(self): self.g = None def _roll_many(self, n, pins): "Roll 'n' times a roll of 'pins' pins" for i in range(n): self.g.roll(pins) d...
Refactor rolling a spare in tests
[Python] Refactor rolling a spare in tests
Python
mit
JesusMtnez/devexperto-challenge,JesusMtnez/devexperto-challenge
dced68096d5c84c831866cf92e7430df6cf5f477
src/nodeconductor_saltstack/sharepoint/cost_tracking.py
src/nodeconductor_saltstack/sharepoint/cost_tracking.py
from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' ...
from django.contrib.contenttypes.models import ContentType from nodeconductor.cost_tracking import CostTrackingBackend from nodeconductor.cost_tracking.models import DefaultPriceListItem from .models import SharepointTenant class Type(object): USAGE = 'usage' STORAGE = 'storage' STORAGE_KEY = '1 MB' ...
Fix sharepoint tenant cost tracking
Fix sharepoint tenant cost tracking - itacloud-6123
Python
mit
opennode/nodeconductor-saltstack
893540d492b731b93a31f3c5158c99f4db9fc3e4
tasks.py
tasks.py
import urlparse import requests def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25): session = requests.session() headers = {"X-Fastly-Key": api_key, "Accept": "application/json"} all_tags = set(tags) purges = {} count = 0 while all_tags and not count > max_tries: ...
import urlparse import requests def purge_fastly_tags(domain, api_key, service_id, tags, max_tries=25): session = requests.session() headers = {"X-Fastly-Key": api_key, "Accept": "application/json"} all_tags = set(tags) purges = {} count = 0 while all_tags and not count > max_tries: ...
Increase the count so we don't spin forever
Increase the count so we don't spin forever
Python
bsd-3-clause
pydotorg/pypi,pydotorg/pypi,pydotorg/pypi,pydotorg/pypi
e817f726c20ccf40cd43d4e6cf36235187a27c20
objects/utils.py
objects/utils.py
"""Utils module.""" from inspect import isclass from .errors import Error def is_provider(instance): """Check if instance is provider instance.""" return (not isclass(instance) and hasattr(instance, '__IS_OBJECTS_PROVIDER__')) def ensure_is_provider(instance): """Check if instance is provi...
"""Utils module.""" from six import class_types from .errors import Error def is_provider(instance): """Check if instance is provider instance.""" return (not isinstance(instance, class_types) and hasattr(instance, '__IS_OBJECTS_PROVIDER__')) def ensure_is_provider(instance): """Check if i...
Fix of bug in Python 2.6 with failed isclass check in inspect module
Fix of bug in Python 2.6 with failed isclass check in inspect module
Python
bsd-3-clause
rmk135/dependency_injector,ets-labs/dependency_injector,ets-labs/python-dependency-injector,rmk135/objects
462656f9653ae43ea69080414735927b18e0debf
stats/random_walk.py
stats/random_walk.py
import neo4j import random from logbook import Logger log = Logger('trinity.topics') DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): # Pick random neighbor neighbors = {} i...
import neo4j import random DEFAULT_DEPTH = 5 NUM_WALKS = 100 # Passed sorted list (desc order), return top nodes TO_RETURN = lambda x: x[:10] random.seed() def random_walk(graph, node, depth=DEFAULT_DEPTH): if depth == 0: return [node] # Pick random neighbor neighbors = {} i = 0 for r in...
Modify random walk so that it works.
Modify random walk so that it works.
Python
mit
peplin/trinity
8eed621a15dafc8b0965c59b8da2296f8193d0ca
karabo_data/tests/test_agipd_geometry.py
karabo_data/tests/test_agipd_geometry.py
import numpy as np from karabo_data.geometry2 import AGIPD_1MGeometry def test_snap_assemble_data(): geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[ (-525, 625), (-550, -10), (520, -160), (542.5, 475), ]) snap_geom = geom.snap() stacked_data = np.zeros((16, 512,...
import numpy as np from karabo_data.geometry2 import AGIPD_1MGeometry def test_snap_assemble_data(): geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[ (-525, 625), (-550, -10), (520, -160), (542.5, 475), ]) snap_geom = geom.snap() stacked_data = np.zeros((16, 512,...
Add test of reading & writing CrystFEL geometry
Add test of reading & writing CrystFEL geometry
Python
bsd-3-clause
European-XFEL/h5tools-py
2e6823676dace8b3219aeeef69ab04a2a0dd533a
rally-scenarios/plugins/sample_plugin.py
rally-scenarios/plugins/sample_plugin.py
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# Copyright 2014 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
Fix outdated link in sample plugin
Fix outdated link in sample plugin Link in sample_plugin.py is outdated and is changed Change-Id: I2f3a7b59c6380e4584a8ce2a5313fe766a40a52a Closes-Bug: #1491975
Python
apache-2.0
steveb/heat,pratikmallya/heat,openstack/heat,gonzolino/heat,dragorosson/heat,dims/heat,steveb/heat,cwolferh/heat-scratch,openstack/heat,takeshineshiro/heat,dragorosson/heat,noironetworks/heat,noironetworks/heat,cwolferh/heat-scratch,jasondunsmore/heat,jasondunsmore/heat,maestro-hybrid-cloud/heat,dims/heat,maestro-hybri...
eb22e8931b9ffe9c82b52451a7c17943ea43625d
python-tool/script/project.py
python-tool/script/project.py
$py_copyright def _main(): print("Hello from $project_name") if __name__ == "__main__": _main()
#!/usr/bin/env python $py_copyright from __future__ import print_function def _main(): print("Hello from $project_name") if __name__ == "__main__": _main()
Add shebang and future import
Add shebang and future import
Python
mit
rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates,rcook/ptool-templates
879b15779c921445ca4412d5e63319408d8e32bf
python/islp/02statlearn-ex.py
python/islp/02statlearn-ex.py
import pandas as pd print('\nKNN\n---') d = {'X1': [ 0, 2, 0, 0, -1, 1 ], 'X2': [ 3, 0, 1, 1, 0, 1 ], 'X3': [ 0, 0, 3, 2, 1, 1 ], 'Y': ['R', 'R', 'R', 'G', 'G', 'R']} df = pd.DataFrame(data = d) df = df.assign(dist = (df.X1**2 + df.X2**2 + df.X3**2)**(0.5)) df = df.sort_val...
import matplotlib.pyplot as plt import pandas as pd print('\nKNN\n---') d = {'X1': [ 0, 2, 0, 0, -1, 1 ], 'X2': [ 3, 0, 1, 1, 0, 1 ], 'X3': [ 0, 0, 3, 2, 1, 1 ], 'Y': ['R', 'R', 'R', 'G', 'G', 'R']} df = pd.DataFrame(data = d) df = df.assign(dist = (df.X1**2 + df.X2**2 + df...
Add scatterplot matrix for college.csv.
Add scatterplot matrix for college.csv.
Python
apache-2.0
pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff,pdbartlett/misc-stuff
35514dcb70ed5ede39299802e82fa352188f3546
examples/nested_inline_tasksets.py
examples/nested_inline_tasksets.py
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet): ...
from locust import HttpUser, TaskSet, task, between class WebsiteUser(HttpUser): """ Example of the ability of inline nested TaskSet classes """ host = "http://127.0.0.1:8089" wait_time = between(2, 5) @task class TopLevelTaskSet(TaskSet): @task class IndexTaskSet(TaskSet)...
Use @task decorator in taskset example
Use @task decorator in taskset example
Python
mit
mbeacom/locust,locustio/locust,mbeacom/locust,locustio/locust,mbeacom/locust,mbeacom/locust,locustio/locust,locustio/locust
1a1aab7c0a107b2a02d08f13c40c515ff265b60b
tempwatcher/watch.py
tempwatcher/watch.py
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check...
import json import requests class TemperatureWatch(object): thermostat_url = None alert_high = 80 alert_low = 60 _last_response = None def get_info(self): r = requests.get(self.thermostat_url + '/tstat') self._last_response = json.loads(r.text) return r.text def check...
Break the alert into a method so subclasses can choose how the alert is relayed.
Break the alert into a method so subclasses can choose how the alert is relayed.
Python
bsd-3-clause
adamfast/tempwatcher
fff22f9305fd73f464a6ee9a66b676b66ef88cad
test/parseResults.py
test/parseResults.py
#!/usr/bin/env python3 import json import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not line...
#!/usr/bin/env python3 import ijson import sys PREFIXES = [ ["FAIL", "PASS"], ["EXPECTED FAIL", "UNEXPECTED PASS"], ] def parse_expected_failures(): expected_failures = set() with open("expected-failures.txt", "r") as fp: for line in fp: line = line.strip() if not lin...
Use ijson to parse the test262 results.
Use ijson to parse the test262 results. Parsing the output all at once can cause out-of-memory errors in automated testing.
Python
isc
js-temporal/temporal-polyfill,js-temporal/temporal-polyfill,js-temporal/temporal-polyfill
695ee95faf0ae80f0c69bf47e881af22ab0f00cd
l10n_it_esigibilita_iva/models/account.py
l10n_it_esigibilita_iva/models/account.py
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import models, fields class AccountTax(models.Model): _inherit = 'account.tax' payability = fields.Selection([ ('I', 'Immediate payability'), ('D', 'Deferred payability'), ('S', 'Split payment'), ], string="...
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). from odoo import models, fields class AccountTax(models.Model): _inherit = 'account.tax' payability = fields.Selection([ ('I', 'VAT payable immediately'), ('D', 'unrealized VAT'), ('S', 'split payments'), ], string="V...
Use correct english terms, from APPENDIX A -TECHNICAL SPECIFICATIONS
Use correct english terms, from APPENDIX A -TECHNICAL SPECIFICATIONS
Python
agpl-3.0
dcorio/l10n-italy,OCA/l10n-italy,OCA/l10n-italy,dcorio/l10n-italy,dcorio/l10n-italy,OCA/l10n-italy
628ab56107783841d1e64b11c4b82eac4806c019
selenium_testcase/testcases/content.py
selenium_testcase/testcases/content.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: # Assert that the DOM contains the given text def should_see_immediately(self, text): self.assertTrue(dom_contains(self.browser, text)) # Repeatedly look for the giv...
# -*- coding: utf-8 -*- from __future__ import absolute_import from .utils import dom_contains, wait_for class ContentTestMixin: def should_see_immediately(self, text): """ Assert that DOM contains the given text. """ self.assertTrue(dom_contains(self.browser, text)) @wait_for def shou...
Add should_not_see, has_not_title, title_does_not_contain to ContentTestMixin.
Add should_not_see, has_not_title, title_does_not_contain to ContentTestMixin. These methods cause a wait for the full duration of the @wait_for timeout when the assertion test is successful (and the given text is missing). It will fail fast, but success is slow. These negative information tests should be used sparin...
Python
bsd-3-clause
nimbis/django-selenium-testcase,nimbis/django-selenium-testcase
e23dd39880dc849a56d5376dca318f8bcb2cd998
discover/__init__.py
discover/__init__.py
import logging import socket import boto LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s' LOG_DATE = '%Y-%m-%d %I:%M:%S %p' logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.WARN) logger = logging.getLogger('yoda-discover') logger.level = logging.INFO def port_test(port, host, p...
import logging import socket from boto.utils import get_instance_metadata LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s' LOG_DATE = '%Y-%m-%d %I:%M:%S %p' logging.basicConfig(format=LOG_FORMAT, datefmt=LOG_DATE, level=logging.WARN) logger = logging.getLogger('yoda-discover') logger.level = logging....
Fix import error for boto.utils
Fix import error for boto.utils
Python
mit
totem/yoda-discover
12aaf389356966e7f82c4a588e0ae888073da8dd
discussion/models.py
discussion/models.py
from django.contrib.auth.models import User from django.db import models class Discussion(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() def __unicode__(self): return self.name class Post(models.Model): discussion = models...
from django.contrib.auth.models import User from django.db import models class Discussion(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=255) slug = models.SlugField() def __unicode__(self): return self.name class Post(models.Model): discussion = models...
Remove "name" from discussion post
Remove "name" from discussion post
Python
bsd-2-clause
incuna/django-discussion,incuna/django-discussion,lehins/lehins-discussion,lehins/lehins-discussion,lehins/lehins-discussion
a5d7306cdda9e109abbb673b8474f8955a371266
partner_contact_birthdate/__openerp__.py
partner_contact_birthdate/__openerp__.py
# -*- coding: utf-8 -*- # Odoo, Open Source Management Solution # Copyright (C) 2014-2015 Grupo ESOC <www.grupoesoc.es> # # 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 ...
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Contact's birthdate", "version": "9.0.1.0.0", "author": "Odoo Community Association (OCA)", "category": "Customer Relationship Management", "website": "https://odoo-comm...
Fix header to short version
Fix header to short version
Python
agpl-3.0
sergiocorato/partner-contact
a3c68f6f70a2d4d1ecdcdb982eda9ec15fa4c127
utils.py
utils.py
from google.appengine.api import users from google.appengine.ext import db from model import User @db.transactional def create_user(google_user): user = User( google_user=google_user ) user.put() return user def get_current_user(): google_user = users.get_current_user() user = get_use...
from google.appengine.api import users from google.appengine.ext import db from model import User latest_signup = None @db.transactional def create_user(google_user): global latest_signup user = User( google_user=google_user ) user.put() latest_signup = user return user def get_curre...
Fix bug where user could not be found
Fix bug where user could not be found This problem only occured when a request tried to find the user right after it had been created.
Python
mit
youtify/newscontrol,studyindenmark/newscontrol,studyindenmark/newscontrol,youtify/newscontrol
2cdb6a5eeb1730627cea2a812d590efed82d03fb
acceptance_tests/test_course_learners.py
acceptance_tests/test_course_learners.py
from unittest import skipUnless from bok_choy.web_app_test import WebAppTest from acceptance_tests import ENABLE_LEARNER_ANALYTICS from acceptance_tests.mixins import CoursePageTestsMixin from acceptance_tests.pages import CourseLearnersPage @skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled t...
from unittest import skipUnless from bok_choy.web_app_test import WebAppTest from acceptance_tests import ENABLE_LEARNER_ANALYTICS from acceptance_tests.mixins import CoursePageTestsMixin from acceptance_tests.pages import CourseLearnersPage @skipUnless(ENABLE_LEARNER_ANALYTICS, 'Learner Analytics must be enabled t...
Add test for learners help link
Add test for learners help link
Python
agpl-3.0
Stanford-Online/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard,edx/edx-analytics-dashboard,Stanford-Online/edx-analytics-dashboard,edx/edx-analytics-dashboard
743064dbe22e40928c50817417077b8d52de641c
twistedchecker/functionaltests/comments.py
twistedchecker/functionaltests/comments.py
# enable: W9401,W9402 #A comment does not begin with a whitespace. a = 1 + 2 # A comment begins with two whitespace. # a comment begins with a lowercase letter. # Good comment examples. # A sentence that spans multiple lines # doesn't need to have capitalization on second line. # Here's some code samples: # x ...
# enable: W9401,W9402 #A comment does not begin with a whitespace. a = 1 + 2 # A comment begins with two whitespace. # a comment begins with a lowercase letter. # Good comment examples. # A sentence that spans multiple lines # doesn't need to have capitalization on second line. # Here's some code samples: # x ...
Add example with back ticks.
Add example with back ticks.
Python
mit
twisted/twistedchecker
aabf28c02a4dff593e5e4b156052adb9b81a70c7
skflow/ops/tests/test_dropout_ops.py
skflow/ops/tests/test_dropout_ops.py
# Copyright 2015-present Scikit Flow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
# Copyright 2015-present Scikit Flow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
Test for dropout probability be a tensor
Test for dropout probability be a tensor
Python
apache-2.0
handroissuazo/tensorflow,elingg/tensorflow,awni/tensorflow,aselle/tensorflow,theflofly/tensorflow,ishay2b/tensorflow,XueqingLin/tensorflow,DavidNorman/tensorflow,odejesush/tensorflow,taknevski/tensorflow-xsmm,AndreasMadsen/tensorflow,Kongsea/tensorflow,hfp/tensorflow-xsmm,jhaux/tensorflow,JingJunYin/tensorflow,tensorfl...
a1a651acf48604ab135961b324d3b9e271a2128b
setup.py
setup.py
from distutils.core import setup with open('README.md') as readme: with open('HISTORY.md') as history: long_description = readme.read() + '\n\n' + history.read() VERSION = '1.0' setup( name='argparse-autogen', py_modules=['argparse_autogen'], version=VERSION, url='https://github.com/sashg...
from distutils.core import setup with open('README.md') as readme: with open('HISTORY.md') as history: long_description = readme.read() + '\n\n' + history.read() try: import pypandoc long_description = pypandoc.convert(long_description, 'rst') except(IOError, ImportError): long_description = ...
Convert md to rst readme specially for PyPi
Convert md to rst readme specially for PyPi
Python
mit
sashgorokhov/argparse-autogen
e5e6d4ac9e86aa7e44694cf4746c4c9ec91df107
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', long_description = ''' This project represents a basic python skeleton project that can be used as the basis for other projects. Feel free to fork this project...
#!/usr/bin/env python from distutils.core import setup setup(name = 'skeleton', version = '0.0', description = 'A python skeleton project', long_description = ''' This project represents a basic python skeleton project that can be used as the basis for other projects. Feel free to fork this project...
Move generic lib to botton of config.
Move generic lib to botton of config.
Python
bsd-2-clause
arlaneenalra/python-skeleton
0ef968528f31da5dd09f016134b4a1ffa6377f84
scripts/slave/chromium/package_source.py
scripts/slave/chromium/package_source.py
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A tool to package a checkout's source and upload it to Google Storage.""" import sys if '__main__' == __name__: sys.exit(0)
#!/usr/bin/python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A tool to package a checkout's source and upload it to Google Storage.""" import os import sys from common import chromium_utils ...
Create source snapshot and upload to GS.
Create source snapshot and upload to GS. BUG=79198 Review URL: http://codereview.chromium.org/7129020 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@88372 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
6c8dd596a0f5f84acee54938d2f948f25445327d
src/Scripts/correlation-histogram.py
src/Scripts/correlation-histogram.py
# Take the output of the BitFunnel correlate command and generate histograms. from collections import defaultdict import csv term_term_correlation = defaultdict(int) term_all_correlation = defaultdict(int) # TODO: don't hardcode name. with open("/tmp/Correlate-0.csv") as f: reader = csv.reader(f) for row in ...
# Take the output of the BitFunnel correlate command and generate histograms. from collections import defaultdict import csv term_term_correlation = defaultdict(lambda:defaultdict(int)) term_all_correlation = defaultdict(lambda:defaultdict(int)) def bf_correlate_to_dicts(term_term_correlation, ...
Put multple treatments into the same histogram.
Put multple treatments into the same histogram.
Python
mit
danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel
24f69b587ce38c581f9ee68e22978963b266f010
html_to_telegraph.py
html_to_telegraph.py
# encoding=utf8 from lxml import html def _recursive_convert(element): # All strings outside tags should be ignored if not isinstance(element, html.HtmlElement): return fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': ele...
# encoding=utf8 from lxml import html import json def _recursive_convert(element): # All strings outside tags should be ignored fragment_root_element = { '_': element.tag } content = [] if element.text: content.append({'t': element.text}) if element.attrib: fragment_...
Return string instead of list
Return string instead of list
Python
mit
mercuree/html-telegraph-poster
962fc49f734b04e717bf936745013ab0c19c4ee1
utils.py
utils.py
import cv2 import itertools import numpy as np def partition(pred, iterable): """ Partition the iterable into two disjoint entries based on the predicate. @return: Tuple (iterable1, iterable2) """ iter1, iter2 = itertools.tee(iterable) return itertools.filterfalse(pred, iter1), filter(pred, iter2) def ...
from six.moves import filterfalse import cv2 import itertools import numpy as np def partition(pred, iterable): """ Partition the iterable into two disjoint entries based on the predicate. @return: Tuple (iterable1, iterable2) """ iter1, iter2 = itertools.tee(iterable) return filterfalse(pred, iter1), ...
Fix python 2.7 compatibility issue
Fix python 2.7 compatibility issue
Python
mit
viswanathgs/dist-dqn,viswanathgs/dist-dqn
917ba14418f01fa2fc866fc1c18989cc500c2cfd
bin/license_finder_pip.py
bin/license_finder_pip.py
#!/usr/bin/env python import json import sys from pip._internal.req import parse_requirements from pip._internal.download import PipSession from pip._vendor import pkg_resources from pip._vendor.six import print_ requirements = [pkg_resources.Requirement.parse(str(req.req)) for req in parse_requiremen...
#!/usr/bin/env python import json import sys try: from pip._internal.req import parse_requirements except ImportError: from pip.req import parse_requirements try: from pip._internal.download import PipSession except ImportError: from pip.download import PipSession from pip._vendor imp...
Add backwards compatibility with pip v9
Add backwards compatibility with pip v9
Python
mit
pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder,pivotal/LicenseFinder
973c6a541deadb5a4b7c23dae191acf9d4c1be27
buffer/tests/test_link.py
buffer/tests/test_link.py
from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.link import Link def test_links_shares(): ''' Test link's shares retrieving from constructor ''' mocked_api = MagicMock() mocked_api.get.return_value = {'shares': 123} link = Link(api=mocked_api, url='www.google.co...
from nose.tools import eq_, raises from mock import MagicMock, patch from buffer.models.link import Link def test_links_shares(): ''' Test link's shares retrieving from constructor ''' mocked_api = MagicMock() mocked_api.get.return_value = {'shares': 123} link = Link(api=mocked_api, url='www.google.co...
Test link's shares retrieving using get_share method
Test link's shares retrieving using get_share method
Python
mit
bufferapp/buffer-python,vtemian/buffpy
fbf42c288a6faa13ac918047eac09985cbd6f6e0
cal/v1/network/drivers/openstack_network.py
cal/v1/network/drivers/openstack_network.py
""" OpenstackDriver for Network based on NetworkDriver """ from neutronclient.v2_0 import client from network_driver import NetworkDriver class OpenstackNetWorkDriver(NetworkDriver): """docstring for OpenstackNetWorkDriver""" def __init__(self, auth_url, project_name, username, password...
""" OpenstackDriver for Network based on NetworkDriver """ from neutronclient.v2_0 import client from network_driver import NetworkDriver class OpenstackNetWorkDriver(NetworkDriver): """docstring for OpenstackNetWorkDriver""" def __init__(self, auth_url, project_name, username, passwor...
Add neutron client without test
Add neutron client without test
Python
apache-2.0
cloudcomputinghust/CAL
10ae884bd68feca56b3893b84221b867f3b0aec3
orangecontrib/text/vectorization/base.py
orangecontrib/text/vectorization/base.py
import numpy as np from gensim import matutils from gensim.corpora import Dictionary class BaseVectorizer: """Base class for vectorization objects. """ name = NotImplemented def transform(self, corpus, copy=True): """Transforms a corpus to a new one with additional attributes. """ if copy...
import numpy as np from gensim import matutils from gensim.corpora import Dictionary class BaseVectorizer: """Base class for vectorization objects. """ name = NotImplemented def transform(self, corpus, copy=True): """Transforms a corpus to a new one with additional attributes. """ if copy...
Mark features to skip normalization
BoW: Mark features to skip normalization This fixes SVM on sparse data.
Python
bsd-2-clause
cheral/orange3-text,cheral/orange3-text,cheral/orange3-text
01059774f04d26b69a1ddc058416f627da396a58
src/tempel/models.py
src/tempel/models.py
from django.db import models from django.conf import settings from tempel import utils class Entry(models.Model): content = models.TextField() language = models.CharField(max_length=20, choices=utils.get_languages()) created = models.DateTimeField(auto_now_add=True) act...
from datetime import datetime from django.db import models from django.conf import settings from tempel import utils class Entry(models.Model): content = models.TextField() language = models.CharField(max_length=20, choices=utils.get_languages()) created = models.DateTimeF...
Replace Entry's created's auto_now_add=True with default=datetime.now
Replace Entry's created's auto_now_add=True with default=datetime.now
Python
agpl-3.0
fajran/tempel
5ebe17f5dc88fef7718d2c3665b905cc8d7fab7c
alembic/versions/147d1de2e5e4_add_periodicity_of_script.py
alembic/versions/147d1de2e5e4_add_periodicity_of_script.py
"""Add periodicity of script Revision ID: 147d1de2e5e4 Revises: Create Date: 2019-04-19 18:48:33.526449 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '147d1de2e5e4' down_revision = None branch_labels = None depends_on = None def upgrade(): op.add_colum...
"""Add periodicity of script Revision ID: 147d1de2e5e4 Revises: Create Date: 2019-04-19 18:48:33.526449 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '147d1de2e5e4' down_revision = None branch_labels = None depends_on = None def upgrade(): op.add_colum...
Handle downgrade on a sqlite db
Handle downgrade on a sqlite db
Python
mit
e-henry/scripto,e-henry/scripto,e-henry/scripto,e-henry/scripto
83c64e096ff8b79e2ae22edbcabb483dcf27302f
tests/conftest.py
tests/conftest.py
import pytest @pytest.fixture(autouse=True) def platform(request): marker = request.node.get_marker('platform') if marker: expected = marker.args[0] minion = request.getfuncargvalue('minion') platform = minion['container'].get_os_release()['ID'] action = marker.kwargs.get('acti...
import pytest @pytest.fixture(autouse=True) def platform(request): marker = request.node.get_marker('platform') if marker: expected = marker.args[0] minion = request.getfuncargvalue('minion') os_release = minion['container'].get_os_release() platform = os_release.get('ID', 'sle...
Fix platform detection for sles <12
Fix platform detection for sles <12
Python
mit
dincamihai/salt-toaster,dincamihai/salt-toaster
c5a0f1f26d2527f49ec00d842ffd56be5f0a9965
detect/findIgnoreLists.py
detect/findIgnoreLists.py
#!/usr/bin/env python import os THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) THIS_REPO_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir)) REPO_PARENT_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir)) # Lets us combine ignore lists: # from pr...
#!/usr/bin/env python import os THIS_SCRIPT_DIRECTORY = os.path.dirname(os.path.abspath(__file__)) THIS_REPO_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir)) REPO_PARENT_PATH = os.path.abspath(os.path.join(THIS_SCRIPT_DIRECTORY, os.pardir, os.pardir)) # Lets us combine ignore lists: # from pr...
Stop looking in the old fuzzing/ directory
Stop looking in the old fuzzing/ directory
Python
mpl-2.0
nth10sd/funfuzz,MozillaSecurity/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz,MozillaSecurity/funfuzz,nth10sd/funfuzz
72c00dca2c8310744c424296d8f712909bc95b95
infosystem/subsystem/capability/entity.py
infosystem/subsystem/capability/entity.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
Fix unique contraint in capability
Fix unique contraint in capability
Python
apache-2.0
samueldmq/infosystem
93c6a89bd6f0d8ff9a32e37d4f6e9c4ed0aa3f8f
openedx/core/djangoapps/schedules/apps.py
openedx/core/djangoapps/schedules/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class SchedulesConfig(AppConfig): name = 'openedx.core.djangoapps.schedules' verbose_name = _('Schedules') def ready(self): # noinspection PyUnresolvedReferences from . import signals, tasks # pylin...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class SchedulesConfig(AppConfig): name = 'openedx.core.djangoapps.schedules' verbose_name = _('Schedules') plugin_app = {} def ready(self): # noinspection PyUnresolvedReferences from . import si...
Update schedules app to be a Django App Plugin
Update schedules app to be a Django App Plugin
Python
agpl-3.0
EDUlib/edx-platform,ahmedaljazzar/edx-platform,procangroup/edx-platform,gsehub/edx-platform,edx/edx-platform,stvstnfrd/edx-platform,teltek/edx-platform,ahmedaljazzar/edx-platform,angelapper/edx-platform,EDUlib/edx-platform,ahmedaljazzar/edx-platform,kmoocdev2/edx-platform,appsembler/edx-platform,msegado/edx-platform,cp...
ca6a758f525c741f277e7e7be115b5b9d20fa5c1
openxc/tools/dump.py
openxc/tools/dump.py
""" This module contains the methods for the ``openxc-dump`` command line program. `main` is executed when ``openxc-dump`` is run, and all other callables in this module are internal only. """ from __future__ import absolute_import import argparse import time from openxc.formats.json import JsonFormatter from .commo...
""" This module contains the methods for the ``openxc-dump`` command line program. `main` is executed when ``openxc-dump`` is run, and all other callables in this module are internal only. """ from __future__ import absolute_import import argparse import time from openxc.formats.json import JsonFormatter from .commo...
Remove a resolved TODO - trace file formats now standardized.
Remove a resolved TODO - trace file formats now standardized.
Python
bsd-3-clause
openxc/openxc-python,openxc/openxc-python,openxc/openxc-python
b07037277b28f80aaa6d6f74d6f79d4146b5ee23
oshi_rest_server/oshi_rest_server/urls.py
oshi_rest_server/oshi_rest_server/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'oshi_rest_server.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
from django.conf.urls import patterns, include, url from django.contrib import admin from rest_framework import routers admin.autodiscover() urlpatterns = patterns('', url(r'^', include(routers.urls)), url(r'^admin/', include(admin.site.urls)), url...
Configure Django REST framework URLs
Configure Django REST framework URLs
Python
isc
ferrarimarco/OSHI-REST-server,ferrarimarco/OSHI-REST-server
72e509be8415e628613b2341c136018ff5bb0f44
openpathsampling/engines/openmm/__init__.py
openpathsampling/engines/openmm/__init__.py
def missing_openmm(*args, **kwargs): raise RuntimeError("Install OpenMM to use this feature") try: import simtk.openmm import simtk.openmm.app except ImportError: HAS_OPENMM = False Engine = missing_openmm empty_snapshot_from_openmm_topology = missing_openmm snapshot_from_pdb = missing_open...
def missing_openmm(*args, **kwargs): raise RuntimeError("Install OpenMM to use this feature") try: import simtk.openmm import simtk.openmm.app except ImportError: HAS_OPENMM = False Engine = missing_openmm empty_snapshot_from_openmm_topology = missing_openmm snapshot_from_pdb = missing_open...
Fix backward compatiblity for MDTrajTopology
Fix backward compatiblity for MDTrajTopology
Python
mit
openpathsampling/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,openpathsampling/openpathsampling,dwhswenson/openp...
f3be5184dfccdcbbf5b95c7fcd75fbbda8d2ce1c
packages/grid/backend/grid/core/security.py
packages/grid/backend/grid/core/security.py
# stdlib from datetime import datetime from datetime import timedelta from typing import Any from typing import Optional from typing import Union # third party from jose import jwt from passlib.context import CryptContext # grid absolute from grid.core.config import settings pwd_context = CryptContext(schemes=["bcry...
# stdlib from datetime import datetime from datetime import timedelta from typing import Any from typing import Optional from typing import Union # third party from jose import jwt from passlib.context import CryptContext # grid absolute from grid.core.config import settings pwd_context = CryptContext(schemes=["bcry...
UPDATE create_access_token to handle guest sessions
UPDATE create_access_token to handle guest sessions
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
ef41e90cf49856a6d0ca1b363440edb542dd2e0d
tests/test_config.py
tests/test_config.py
# Copyright 2015-2016 Masayuki Yamamoto # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
# Copyright 2015-2016 Masayuki Yamamoto # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
Add test case for user path
Add test case for user path Expect filepath joinning '.yanico.conf' under $HOME.
Python
apache-2.0
ma8ma/yanico
b910900f72d6b25cb05c56563968aad102429c25
gmrh/RepositoryHandler.py
gmrh/RepositoryHandler.py
import os.path import subprocess class DefaultRepositoryHandler(): def __init__(self, cwd): self.cwd = cwd def repository_exists(self, path): return os.path.exists(path + os.path.sep + '.git') def update_repository(self, path, remote_url, remote_branch): print 'Updating repositor...
import os.path import subprocess class DefaultRepositoryHandler(): def __init__(self, cwd): self.cwd = cwd def repository_exists(self, path): return os.path.exists(path + os.path.sep + '.git') def update_repository(self, path, remote_url, remote_branch): print 'Updating repositor...
Check the url of the remote & ensure the updating commands are executed in the correct directory
Check the url of the remote & ensure the updating commands are executed in the correct directory
Python
bsd-3-clause
solarnz/polygamy,solarnz/polygamy
5a1c48403a912eedc4f5d87215fafdb05eb49ed5
Python/find-all-duplicates-in-an-array.py
Python/find-all-duplicates-in-an-array.py
# Time: O(n) # Space: O(1) # Given an array of integers, 1 <= a[i] <= n (n = size of array), # some elements appear twice and others appear once. # Find all the elements that appear twice in this array. # Could you do it without extra space and in O(n) runtime? # # Example: # Input # # [4,3,2,7,8,2,3,1] # # Output # ...
# Time: O(n) # Space: O(1) # Given an array of integers, 1 <= a[i] <= n (n = size of array), # some elements appear twice and others appear once. # Find all the elements that appear twice in this array. # Could you do it without extra space and in O(n) runtime? # # Example: # Input # # [4,3,2,7,8,2,3,1] # # Output # ...
Add alternative solution for 'Find all duplicates in an array'
Add alternative solution for 'Find all duplicates in an array'
Python
mit
kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015
73243dc74b416fc42ccb8b684924f0b2a09919a3
SnakesLadders/SnakesLadders.py
SnakesLadders/SnakesLadders.py
class State(object): def __init__(self, ix): self.index = ix self.link = None # placeholder, not None if Snake or Ladder def process(self): """Action when landed upon""" if self.link: if self.link > self.index: # Ladder! return self.l...
class State(object): def __init__(self, ix): self.index = ix self.link = None # placeholder, not None if Snake or Ladder def process(self): """Action when landed upon""" if self.link: if self.link > self.index: # Ladder! return self.l...
Update to move and run
Update to move and run
Python
cc0-1.0
robclewley/DataScotties
a4e959c1aeb705128898f07bdf9c9fb315ba593c
flexget/tests/test_plugin_interfaces.py
flexget/tests/test_plugin_interfaces.py
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flexget import plugin class TestInterfaces(object): """Test that any plugins declaring certain interfaces at least superficially comply with those interfaces."""...
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin from flexget import plugin class TestInterfaces(object): """Test that any plugins declaring certain interfaces at least superficially comply with those interfaces."""...
Add tests for search interface plugins
Add tests for search interface plugins
Python
mit
malkavi/Flexget,tobinjt/Flexget,jacobmetrick/Flexget,jawilson/Flexget,tobinjt/Flexget,LynxyssCZ/Flexget,malkavi/Flexget,qk4l/Flexget,OmgOhnoes/Flexget,JorisDeRieck/Flexget,gazpachoking/Flexget,crawln45/Flexget,jacobmetrick/Flexget,jawilson/Flexget,jacobmetrick/Flexget,tobinjt/Flexget,poulpito/Flexget,JorisDeRieck/Flexg...
11cf55cf2859a23edd2d1dba56e574d01cacce4f
apps/funding/forms.py
apps/funding/forms.py
from django import forms from django.utils.translation import ugettext_lazy as _, ugettext as __ from .models import Funding from .widgets import PerksAmountWidget class FundingForm(forms.Form): required_css_class = 'required' amount = forms.DecimalField(label=_("Amount"), decimal_places=2, widget=Pe...
from django import forms from django.utils.translation import ugettext_lazy as _, ugettext as __ from .models import Funding from .widgets import PerksAmountWidget class FundingForm(forms.Form): required_css_class = 'required' amount = forms.DecimalField(label=_("Amount"), decimal_places=2, widget=Pe...
Set perks on form save.
Set perks on form save.
Python
agpl-3.0
fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury,fnp/wolnelektury
145a72dc8439d4479b64a79e7c94cbc12f4afdd7
test/__init__.py
test/__init__.py
"""Package for regression testing of the blender nif scripts.""" import bpy def setup(self): """Enables the nif scripts addon, so all tests can use it.""" bpy.ops.wm.addon_enable(module="io_scene_nif") def teardown(self): """Disables the nif scripts addon.""" bpy.ops.wm.addon_disable(module="io_scene...
"""Package for regression testing of the blender nif scripts.""" import bpy def setup(self): """Enables the nif scripts addon, so all tests can use it.""" bpy.ops.wm.addon_enable(module="io_scene_nif") # remove default objects for obj in bpy.data.objects[:]: bpy.context.scene.objects.unlink(ob...
Remove startup objects when setting up the test module.
Remove startup objects when setting up the test module.
Python
bsd-3-clause
amorilia/blender_nif_plugin,nightstrike/blender_nif_plugin,amorilia/blender_nif_plugin,nightstrike/blender_nif_plugin
5d6b384a2f1b8caa9421b428e5d81aaa1d9a82e1
tests/correct.py
tests/correct.py
"""Check ringtophat results against scipy.ndimage.convolve"""
"""Check ringtophat results against scipy.ndimage.convolve""" import unittest from numpy.testing import assert_equal, assert_almost_equal import numpy as np import ringtophat class TestKernels(unittest.TestCase): def test_binary_disk(self): actual = ringtophat.binary_disk(1) desired = np.array([[Fa...
Add first tests. disk and ring masks for simple cases.
Add first tests. disk and ring masks for simple cases.
Python
bsd-3-clause
gammapy/ringtophat,gammapy/ringtophat
2974972ce36f1cd2dec99a18edc49ac374cdf458
tools/fitsevt.py
tools/fitsevt.py
#! /usr/bin/python3 import sys import os import math from astropy.io import fits inputFolder = sys.argv[1] outputFolder = sys.argv[2] eLo = int(sys.argv[3]) eHi = int(sys.argv[4]) binSize = int(sys.argv[5]) fnames = os.listdir(inputFolder) for fname in fnames: print(fname) hdulist = fits.open(inputFolder+"/"+fna...
#! /usr/bin/python3 import sys import os import math from astropy.io import fits inputFolder = sys.argv[1] outputFolder = sys.argv[2] eLo = int(sys.argv[3]) eHi = int(sys.argv[4]) binSize = int(sys.argv[5]) fnames = os.listdir(inputFolder) for fname in fnames: print(fname) hdulist = fits.open(inputFolder+"/"+fnam...
Change output filenaming to have .txt
Change output filenaming to have .txt
Python
mit
fauzanzaid/IUCAA-GRB-detection-Feature-extraction
96871ef8de84653406749a2e503ef4b4fb800b2f
src/mist/io/tests/features/steps/shell.py
src/mist/io/tests/features/steps/shell.py
""" @given: ------- @when: ------ I type the "{command}" shell command --> shell_command @then: ------ I should see the "{command}" result in shell output --> shell_output ------ """ @when(u'I type the "{command}" shell command') def shell_command(context, command): shell_input = context.browser.fi...
""" @given: ------- @when: ------ I type the "{command}" shell command --> shell_command @then: ------ I should see the "{command}" result in shell output --> shell_output ------ """ @when(u'I type the "{command}" shell command') def shell_command(context, command): shell_input = context.browser.fi...
Fix Shell tests according to css changes
Fix Shell tests according to css changes
Python
agpl-3.0
kelonye/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,Lao-liu/mist.io,johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,munkiat/mist.io,Lao-liu/mist.io,afivos/mist.io,munkiat/mist.io,munkiat/mist.io,afivos/mist.io,johnnyWalnut/mist.io,Lao-liu/mist.io,munkiat/mist.io,DimensionDataCBUSydney/m...
c3ca44b17b9e14e8570083ab49be4da8e64757bc
scripts/filter_fasta_on_length.py
scripts/filter_fasta_on_length.py
#!/usr/bin/env python """filter_fasta_on_length.py Filter a fasta file so that the resulting sequences are all longer or equal to the length threshold parameter. Only accepts stdin.""" import argparse import sys from Bio import SeqIO def main(args): seqs = [] for i, seq in enumerate(SeqIO.parse(sys.stdin, ...
#!/usr/bin/env python """filter_fasta_on_length.py Filter a fasta file so that the resulting sequences are all longer or equal to the length threshold parameter. Only accepts stdin.""" import argparse import sys from Bio import SeqIO def main(args): seqs = [] if args.input_fasta is not None: input_...
Use either file input or stdin for filtering length
Use either file input or stdin for filtering length
Python
mit
EnvGen/toolbox,EnvGen/toolbox
3d97a2ca6c4c285d59e3c823fbee94a494e85ba0
app/tests/tests.py
app/tests/tests.py
import unittest from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load(self): self.page_test('/robots.txt', b...
import unittest from varsnap import TestVarSnap # noqa: F401 from app import serve class PageCase(unittest.TestCase): def setUp(self): serve.app.config['TESTING'] = True self.app = serve.app.test_client() def test_index_load(self): self.page_test('/', b'') def test_robots_load...
Add TestVarSnap as a TestCase
Add TestVarSnap as a TestCase
Python
mit
albertyw/base-flask,albertyw/base-flask,albertyw/base-flask,albertyw/base-flask
1975d5391f058f85272def4435b243440b72bff6
weather/admin.py
weather/admin.py
from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): openlayers_url = '//static.dpaw.wa.gov.au/static/libs/openlayers/2.13.1/OpenLayers.js' list_displ...
from django.contrib.admin import ModelAdmin, register from django.contrib.gis.admin import GeoModelAdmin from weather.models import WeatherStation, Location @register(Location) class LocationAdmin(GeoModelAdmin): list_display = ('pk', 'title', 'point', 'height') @register(WeatherStation) class WeatherStationAdm...
Remove custom OpenLayers.js from LocationAdmin.
Remove custom OpenLayers.js from LocationAdmin.
Python
bsd-3-clause
parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,parksandwildlife/resource_tracking,ropable/resource_tracking,ropable/resource_tracking,ropable/resource_tracking
b2d654cf2af71b608d81c6501b214a9b330e1ffe
battlenet/utils.py
battlenet/utils.py
import unicodedata import urllib def normalize(name): if not isinstance(name, unicode): name = name.decode('utf-8') return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8') def quote(name): if isinstance(name, unicode): name = normalize(name).encode('utf8') retur...
import unicodedata import urllib def normalize(name): if not isinstance(name, unicode): name = name.decode('utf-8') return unicodedata.normalize('NFKC', name.replace("'", '')).encode('utf-8') def quote(name): if isinstance(name, unicode): name = normalize(name) return urllib.quote(...
Normalize already returns encoded value.
Normalize already returns encoded value.
Python
mit
PuckCh/battlenet,vishnevskiy/battlenet
99b1edfcc317dbb71b8dad9ad501aaa21f8044f9
zorp/__init__.py
zorp/__init__.py
""" Zorp """ from zorp.client import Client from zorp.decorator import remote_method from zorp.server import Server
""" Zorp """ from zorp.client import Client, TriesExceededException from zorp.decorator import remote_method from zorp.server import Server
Add TriesExceededException to the base package
Add TriesExceededException to the base package
Python
mit
proxama/zorp
cec7922ad7636f62be864d115f8e341ac511bbc9
numba/tests/foreign_call/test_cffi_call.py
numba/tests/foreign_call/test_cffi_call.py
import os import ctypes import doctest from numba import * import numba try: import cffi ffi = cffi.FFI() except ImportError: ffi = None # ______________________________________________________________________ def test(): if ffi is not None: test_cffi_calls() # _____________________________...
import os import ctypes import doctest from numba import * import numba try: import cffi ffi = cffi.FFI() except ImportError: ffi = None # ______________________________________________________________________ def test(): if ffi is not None: test_cffi_calls() # _____________________________...
Fix CFFI test when executed multiple times
Fix CFFI test when executed multiple times
Python
bsd-2-clause
stefanseefeld/numba,jriehl/numba,IntelLabs/numba,stonebig/numba,gmarkall/numba,numba/numba,GaZ3ll3/numba,stefanseefeld/numba,numba/numba,IntelLabs/numba,cpcloud/numba,sklam/numba,cpcloud/numba,IntelLabs/numba,shiquanwang/numba,stuartarchibald/numba,sklam/numba,pitrou/numba,gdementen/numba,gmarkall/numba,seibert/numba,s...