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
cdc6390ec88a14b339cb336fcc0d77e747aae99a
sieve/sieve.py
sieve/sieve.py
def sieve(n): if n < 2: return [] not_prime = set() prime = [2] for i in range(3, n+1, 2): if i not in not_prime: prime.append(i) not_prime.update(range(i*i, n+1, i)) return prime
def sieve(n): return list(primes(n)) def primes(n): if n < 2: raise StopIteration yield 2 not_prime = set() for i in range(3, n+1, 2): if i not in not_prime: not_prime.update(range(i*i, n+1, i)) yield i
Revert back to a generator - it's actually slight faster
Revert back to a generator - it's actually slight faster
Python
agpl-3.0
CubicComet/exercism-python-solutions
b32900269b3f8c701702e74734ffe248c521fa73
dooblr/transformers/__init__.py
dooblr/transformers/__init__.py
from influxdbclient import InfluxDBClient, InfluxDBClientError, DooblrInfluxDBError __all__ = ["InfluxDBClient", "InfluxDBClientError", "DooblrInfluxDBError"]
from dooblr.transformers.influxdbclient import InfluxDBClient, InfluxDBClientError, DooblrInfluxDBError __all__ = ["InfluxDBClient", "InfluxDBClientError", "DooblrInfluxDBError"]
Fix py3 'relative' import error.
Fix py3 'relative' import error.
Python
isc
makerslocal/dooblr
288127c575c7672e3a41d7ada360d56a4853f279
scripts/examples/14-WiFi-Shield/fw_update.py
scripts/examples/14-WiFi-Shield/fw_update.py
# WINC Firmware Update Script. # # This script updates the ATWINC1500 WiFi module firmware. # Copy the firmware image to uSD card before running this script. # NOTE: Firmware version 19.5.2 does NOT support ATWINC1500-MR210PA. import network # Init wlan module in Download mode. wlan = network.WINC(mode=network.WINC.M...
# WINC Firmware Update Script. # # This script updates the ATWINC1500 WiFi module firmware. # Copy the firmware image to uSD card before running this script. # NOTE: Older fimware versions are no longer supported by the host driver. # NOTE: The latest firmware (19.6.1) only works on ATWINC1500-MR210PB. import network ...
Update WiFi firmware update script.
Update WiFi firmware update script.
Python
mit
openmv/openmv,openmv/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv
8f80099062a03fcf6be783f3e5260882f704ec22
scss/tests/test_files.py
scss/tests/test_files.py
from __future__ import absolute_import import glob import os.path import pytest from scss import Scss HERE = os.path.join(os.path.split(__file__)[0], 'files') @pytest.mark.parametrize( ('scss_fn', 'css_fn'), [ (scss_fn, os.path.splitext(scss_fn)[0] + '.css') for scss_fn in glob.glob(os.path.joi...
from __future__ import absolute_import import glob import os.path import pytest from scss import Scss HERE = os.path.join(os.path.split(__file__)[0], 'files') @pytest.mark.parametrize( ('scss_fn', 'css_fn'), [ (scss_fn, os.path.splitext(scss_fn)[0] + '.css') for scss_fn in glob.glob(os.path.joi...
Swap the test-file assertion, to make output more sensible.
Swap the test-file assertion, to make output more sensible.
Python
mit
cpfair/pyScss,cpfair/pyScss,Kronuz/pyScss,hashamali/pyScss,hashamali/pyScss,Kronuz/pyScss,Kronuz/pyScss,hashamali/pyScss,Kronuz/pyScss,cpfair/pyScss
7b3267b2bae436e0580e2a229a64bd8d6a04bc1f
manila_ui/local/local_settings.d/_90_manila_shares.py
manila_ui/local/local_settings.d/_90_manila_shares.py
# Copyright 2016 Red Hat Inc. # # 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...
# Copyright 2016 Red Hat Inc. # # 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...
Define the default policy file
Define the default policy file This change ensures that the default policy file for Manila API access is defined by default, so that operators can deploy their own policy more easily. Change-Id: Ie890766ea2a274791393304cdfe532e024171195
Python
apache-2.0
openstack/manila-ui,openstack/manila-ui,openstack/manila-ui
fd90fc7ce0c8a8070966e4a8273c69b8c13955d3
masters/master.tryserver.webrtc/master_site_config.py
masters/master.tryserver.webrtc/master_site_config.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. """ActiveMaster definition.""" from config_bootstrap import Master class WebRTCTryServer(Master.Master4): project_name = 'WebRTC Try Server' master_por...
# 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. """ActiveMaster definition.""" from config_bootstrap import Master class WebRTCTryServer(Master.Master4): project_name = 'WebRTC Try Server' master_por...
Make trybots use HEAD instead of LKGR
WebRTC: Make trybots use HEAD instead of LKGR It's about time we make this change, which turned out to be very simple. Review URL: https://codereview.chromium.org/776233003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@293261 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
d88a6afddcc9ac90b1fb2327d4df4ece29f1c031
docs/plans/wordpress/mysql_boot.py
docs/plans/wordpress/mysql_boot.py
#!/usr/bin/env python import sys import os import simplejson as json f = open("bootconf.json", "r") vals_dict = json.load(f) f.close() os.putenv('DEBIAN_FRONTEND', 'noninteractive') os.putenv('TERM', 'dumb') password=vals_dict['dbpassword'] dbname=vals_dict['dbname'] commands = [] commands.append('sudo -E apt-get ...
#!/usr/bin/env python import sys import os import simplejson as json f = open("bootconf.json", "r") vals_dict = json.load(f) f.close() os.putenv('DEBIAN_FRONTEND', 'noninteractive') os.putenv('TERM', 'dumb') password=vals_dict['dbpassword'] dbname=vals_dict['dbname'] commands = [] commands.append('sudo -E apt-get ...
Add create and delete permissions to mysql user in wordpress example
Add create and delete permissions to mysql user in wordpress example
Python
apache-2.0
buzztroll/cloudinit.d,nimbusproject/cloudinit.d,buzztroll/cloudinit.d,nimbusproject/cloudinit.d
68b499ea6b73232b3b8a860b3c8b808a1736b733
myfedora/controllers/template.py
myfedora/controllers/template.py
from ${package}.lib.base import * class TemplateController(BaseController): def view(self, url): """By default, the final controller tried to fulfill the request when no other routes match. It may be used to display a template when all else fails, e.g.:: def view(self, url): ...
from myfedora.lib.base import * class TemplateController(BaseController): def view(self, url): """By default, the final controller tried to fulfill the request when no other routes match. It may be used to display a template when all else fails, e.g.:: def view(self, url): ...
Fix a busted import statement in our TemplateController
Fix a busted import statement in our TemplateController
Python
agpl-3.0
Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages
926ddeb63f0366a59f14adbab5421ccb7f78f144
exercises/book-store/example.py
exercises/book-store/example.py
BOOK_PRICE = 8 def _group_price(size): discounts = [0, .05, .1, .2, .25] if not (0 < size <= 5): raise ValueError('size must be in 1..' + len(discounts)) return 8 * size * (1 - discounts[size - 1]) def calculate_total(books, price_so_far=0.): if not books: return price_so_far gr...
BOOK_PRICE = 8 def _group_price(size): discounts = [0, .05, .1, .2, .25] if not (0 < size <= 5): raise ValueError('size must be in 1..' + len(discounts)) return BOOK_PRICE * size * (1 - discounts[size - 1]) def calculate_total(books, price_so_far=0.): if not books: return price_so_fa...
Use book price constant in calculation
book-store: Use book price constant in calculation
Python
mit
N-Parsons/exercism-python,pheanex/xpython,jmluy/xpython,behrtam/xpython,exercism/xpython,smalley/python,exercism/xpython,exercism/python,N-Parsons/exercism-python,smalley/python,pheanex/xpython,jmluy/xpython,exercism/python,behrtam/xpython
a220a62e4444e75974ad28915e7216a276f60c9c
test_valid_object_file.py
test_valid_object_file.py
from astropy.table import Table from astropy.coordinates import ICRS, name_resolve from astropy import units as u TABLE_NAME = 'feder_object_list.csv' MAX_SEP = 5 # arcsec def test_table_can_be_read_and_coords_good(): objs = Table.read(TABLE_NAME, format='ascii', delimiter=',') columns = ['object', 'ra', 'd...
from astropy.table import Table from astropy.coordinates import ICRS, name_resolve from astropy import units as u TABLE_NAME = 'feder_object_list.csv' MAX_SEP = 5 # arcsec # increase timeout so that the Travis builds succeed name_resolve.NAME_RESOLVE_TIMEOUT.set(30) def test_table_can_be_read_and_coords_good(): ...
Increase timeout for satrapy name lookups
Increase timeout for satrapy name lookups
Python
bsd-2-clause
mwcraig/feder-object-list
5cd3b53f677fd6ab6e77bee5b7d42cf2ac85e47f
feincms/apps.py
feincms/apps.py
# flake8: noqa from feincms.content.application.models import *
def __getattr__(key): # Work around Django 3.2's autoloading of *.apps modules (AppConfig # autodiscovery) if key in { "ApplicationContent", "app_reverse", "app_reverse_lazy", "permalink", "UnpackTemplateResponse", "standalone", "unpack", }: ...
Add a workaround for the AppConfig autodiscovery crashes with Django 3.2
Add a workaround for the AppConfig autodiscovery crashes with Django 3.2
Python
bsd-3-clause
mjl/feincms,feincms/feincms,mjl/feincms,feincms/feincms,feincms/feincms,mjl/feincms
65e4aba86730525a75e915fe61eb15b681817cc3
app/commander.py
app/commander.py
import rethinkdb as r class Commander: def process_message(self, message): return "I got your message"
import re import rethinkdb as r class Commander: def process_message(self, message): return self.parse_message(message) def parse_message(self, message): stripped_message = message.strip() commander_match = re.match(r'commander\s*(.*)', stripped_me...
Add parsing for adding message
Add parsing for adding message
Python
mit
henryfjordan/incident-commander
a28826a0b57742d3cb2ac57c0a17b37f2afff302
homedisplay/control_milight/management/commands/listen_433.py
homedisplay/control_milight/management/commands/listen_433.py
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time class Command(BaseCommand): args = '' help = 'Listen for 433MHz radio messages' ITEM_MAP = { "5236713": "kitchen"...
from control_milight.utils import process_automatic_trigger from django.conf import settings from django.core.management.base import BaseCommand, CommandError import serial import time import logging logger = logging.getLogger("%s.%s" % ("homecontroller", __name__)) class Command(BaseCommand): args = '' help ...
Use logging. Remove hardcoded settings
Use logging. Remove hardcoded settings
Python
bsd-3-clause
ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display
c2fe4483ba70f0ca37b4713a51baf0804a68accd
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
lms/djangoapps/course_wiki/plugins/markdownedx/wiki_plugin.py
# -*- coding: utf-8 -*- from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX...
# -*- coding: utf-8 -*- from wiki.core.plugins.base import BasePlugin from wiki.core.plugins import registry as plugin_registry from course_wiki.plugins.markdownedx import mdx_mathjax, mdx_video class ExtendMarkdownPlugin(BasePlugin): """ This plugin simply loads all of the markdown extensions we use in edX...
Fix PEP8: E126 continuation line over-indented
Fix PEP8: E126 continuation line over-indented for hanging indent
Python
agpl-3.0
IndonesiaX/edx-platform,mbareta/edx-platform-ft,proversity-org/edx-platform,IONISx/edx-platform,Edraak/edx-platform,doganov/edx-platform,shabab12/edx-platform,lduarte1991/edx-platform,deepsrijit1105/edx-platform,pomegranited/edx-platform,prarthitm/edxplatform,fintech-circle/edx-platform,prarthitm/edxplatform,waheedahme...
351e88dd95db81418cc6d2deb4a943e2659292bc
wsgi.py
wsgi.py
import os import sys import site VIRTUALENV="venv" # Get site root from this file's location: SITE_ROOT=os.path.abspath(os.path.dirname(__file__)) # Add virtualenv path to site package root: site.addsitedir(os.path.join(SITE_ROOT, VIRTUALENV, "lib/python2.7/site-packages")) site.addsitedir(os.path.join(SITE_ROOT, VI...
import os # celery should now be available (on the virtualenv path) import djcelery djcelery.setup_loader() # Point Django to settings file: os.environ['DJANGO_SETTINGS_MODULE'] = 'toolkit.settings' from django.core.wsgi import get_wsgi_application application = get_wsgi_application()
Remove virtualenv setup from WSGI entrypoint
Remove virtualenv setup from WSGI entrypoint Handle it in front end server instead.
Python
agpl-3.0
BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit,BenMotz/cubetoolkit
da5ca6baf75b2230e3e8a62066bebaa96a16bf3d
test/server.py
test/server.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Server used for tests """ import sys import os # ensure sys knows about pyqode.core in the test env sys.path.insert(0, os.getcwd()) from pyqode.core import backend if __name__ == '__main__': print('Server started') print(sys.path) print(os.getcwd()) ba...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Server used for tests """ import sys import os # ensure sys knows about pyqode.core in the test env sys.path.insert(0, os.getcwd()) sys.path.insert(0, os.path.abspath("..")) from pyqode.core import backend if __name__ == '__main__': print('Server started') pri...
Fix test suite on travis (restore previous path config)
Fix test suite on travis (restore previous path config)
Python
mit
pyQode/pyqode.core,zwadar/pyqode.core,pyQode/pyqode.core
9a81d58bfb1088c8c6286c65150cd13c54c0b4c5
wagtail/wagtailredirects/middleware.py
wagtail/wagtailredirects/middleware.py
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404...
from django import http from wagtail.wagtailredirects import models # Originally pinched from: https://github.com/django/django/blob/master/django/contrib/redirects/middleware.py class RedirectMiddleware(object): def process_response(self, request, response): # No need to check for a redirect for non-404...
Refactor out a bare except: statement
Refactor out a bare except: statement It now catches `Redirect.DoesNotExist`, returning the normal 404 page if no redirect is found. Any other exception should not be caught here.
Python
bsd-3-clause
rjsproxy/wagtail,jnns/wagtail,chrxr/wagtail,Klaudit/wagtail,iansprice/wagtail,kaedroho/wagtail,wagtail/wagtail,mixxorz/wagtail,kurtrwall/wagtail,kurtrwall/wagtail,FlipperPA/wagtail,chrxr/wagtail,mayapurmedia/wagtail,JoshBarr/wagtail,Klaudit/wagtail,torchbox/wagtail,nrsimha/wagtail,nimasmi/wagtail,iansprice/wagtail,hams...
60efbb9b6b70036b72f3c756139524c4ca7698d2
carepoint/models/cph/fdb_gcn_seq.py
carepoint/models/cph/fdb_gcn_seq.py
# -*- coding: utf-8 -*- # © 2015-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from carepoint import Carepoint from sqlalchemy import (Column, Integer, String, Boolean, ) class Fd...
# -*- coding: utf-8 -*- # © 2015-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from carepoint import Carepoint from sqlalchemy import (Column, Integer, String, Boolean, ForeignKey, ...
Add foreign keys for form and route in Fdb Gcn Seq in carepoint cph
Add foreign keys for form and route in Fdb Gcn Seq in carepoint cph
Python
mit
laslabs/Python-Carepoint
628d777e3751ec8e38f1b98f558799b28cda1569
src/services/TemperatureMonitor/TemperatureMonitor.py
src/services/TemperatureMonitor/TemperatureMonitor.py
import sys from src.TemperatureMonitor import TemperatureMonitor from src.temperature import TemperatureSensor SENSOR_ADDRESS = 0x48 tempMonitor = TemperatureMonitor(TemperatureSensor(SENSOR_ADDRESS), observers=sys.argv[1:]) tempMonitor.run()
import sys from src.TemperatureMonitor import TemperatureMonitor from src.temperature import TemperatureSensor import argparse parser = argparse.ArgumentParser(description='Broadcast temperatures to URLs') parser.add_argument('observers', metavar='N', type=str, nargs='+', help='the observers', def...
Allow Control of Interval and Observers
Allow Control of Interval and Observers
Python
mit
IAPark/PITherm
f8c9cb7d353680f48146d0b37e01ac6761ad7904
example/bayesian-dark-knowledge/random_num_generator_bug.py
example/bayesian-dark-knowledge/random_num_generator_bug.py
import mxnet as mx import mxnet.ndarray as nd for i in range(1000): noise = mx.random.normal(0,10,(i,i),ctx=mx.gpu())
import mxnet as mx mx.random.normal(0,10,(3,3), ctx=mx.gpu()).asnumpy()
Update Bug for Normal Genrator
Update Bug for Normal Genrator
Python
apache-2.0
sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet
b77956a993f7f703626dbc9fc85003d6840b24fe
partner_compassion/models/partner_bank_compassion.py
partner_compassion/models/partner_bank_compassion.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Steve Ferry # # The licence is in the file __manifest__.py # ###############...
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Steve Ferry # # The licence is in the file __manifest__.py # ###############...
FIX only post message if a partner is existent
FIX only post message if a partner is existent
Python
agpl-3.0
CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland
031d31c65b66dafe15470aeefe6b2a3240bb4969
pysis/__init__.py
pysis/__init__.py
# -*- coding: utf-8 -*- import os ISIS_ROOT = os.environ.get('ISISROOT') if ISIS_ROOT is None: print 'Warning! ISISROOT is not defined. Bitch.' (ISIS_VERSION, ISIS_VERSION_MAJOR, ISIS_VERSION_MINOR, ISIS_VERSION_PATCH, ISIS_VERSION_BUILD) = 5 * (None,) else: with open(filename) as _f: ISI...
# -*- coding: utf-8 -*- import os, sys ISIS_ROOT = os.environ.get('ISISROOT') if ISIS_ROOT is None: sys.stderr.write('Warning! ISISROOT is not defined. Bitch.\n') (ISIS_VERSION, ISIS_VERSION_MAJOR, ISIS_VERSION_MINOR, ISIS_VERSION_PATCH, ISIS_VERSION_BUILD) = 5 * (None,) else: with open(filename)...
Write warning to std err instead.
Write warning to std err instead.
Python
bsd-3-clause
wtolson/pysis,wtolson/pysis,michaelaye/Pysis,michaelaye/Pysis
040324578680a26f3816aef6f05a731be54a377d
pyroSAR/tests/test_dev_config.py
pyroSAR/tests/test_dev_config.py
import pytest from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE class TestStorage: def test_insert(self): storage = Storage(a=1, b=2) assert storage.a == 1 assert storage.b == 2 class TestLookup: def test_suffix(self): assert LOOKUP.snap.suffix[0]['Apply-Orbit-Fil...
import pytest from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE class TestStorage: def test_insert(self): storage = Storage(a=1, b=2) assert storage.a == 1 assert storage.b == 2 class TestLookup: def test_suffix(self): assert LOOKUP.snap.suffix['Apply-Orbit-File']...
Update due to changes in LOOKUP.
Update due to changes in LOOKUP.
Python
mit
johntruckenbrodt/pyroSAR,johntruckenbrodt/pyroSAR
63afb46b7a39881c3a3655af645d5414bdd730ea
edumed/forum.py
edumed/forum.py
from pybb.permissions import DefaultPermissionHandler class ForumPermissionHandler(DefaultPermissionHandler): def may_post_as_admin(self, user): """ return True if `user` may post as admin """ return False
from pybb.permissions import DefaultPermissionHandler class ForumPermissionHandler(DefaultPermissionHandler): def may_post_as_admin(self, user): """ return True if `user` may post as admin """ return False def may_create_topic(self, user, forum): """ return True if `user` is allowed t...
Allow for authenticated non super users to create posts and topics
Allow for authenticated non super users to create posts and topics
Python
agpl-3.0
fnp/edumed,fnp/edumed,fnp/edumed
ff63299cde0fe34fe3bfdac16593e1a0a989bec4
Hydv2/ScreenTools.py
Hydv2/ScreenTools.py
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Olivier Larrieu' from gtk import gdk class ScreenProperties(object): """ Usefull to get basic screen informations """ @classmethod def screen_dimension(cls): """ Return a dic with the screen height and screen width ...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Olivier Larrieu' class ScreenProperties(object): """ Usefull to get basic screen informations """ @classmethod def screen_dimension(cls): """ Return a dic with the screen height and screen width """ f...
Use Xlib instead of gtk to get screen width and screen height This limit dependances
Use Xlib instead of gtk to get screen width and screen height This limit dependances
Python
artistic-2.0
OlivierLarrieu/HYDV2_EFL,OlivierLarrieu/HYDV2_EFL,OlivierLarrieu/HYDV2_EFL,OlivierLarrieu/HYDV2_EFL
7ce51c694e44e8503acd86de0f90dbc4078f4b82
user_deletion/managers.py
user_deletion/managers.py
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone user_deletion_config = apps.get_app_config('user_deletion') class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" ...
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone user_deletion_config = apps.get_app_config('user_deletion') class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" ...
Use threshold for time boundary in manager
Use threshold for time boundary in manager
Python
bsd-2-clause
incuna/django-user-deletion
58f8f4881a9e97206ddf49ea6cfb7f48dd34bfb3
example/urls.py
example/urls.py
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r"^$", TemplateView.as_view(template_name="homepage.html")), url(r"^remote.html$", TemplateView.as_view(template_name="remote.html"), name="remote.html"), ]
from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path('', TemplateView.as_view(template_name="homepage.html")), re_path(r"^remote.html$", TemplateView.as_view(template_name="remote.html"), name="remote.html"), ]
Upgrade code to Python 3.6+, Django 2.2 and remove deprecations
Upgrade code to Python 3.6+, Django 2.2 and remove deprecations
Python
bsd-3-clause
bashu/django-fancybox,bashu/django-fancybox
9912974a283912acd31fa4ee85de2fb44c2cf862
nn/model.py
nn/model.py
import abc import tensorflow as tf class Model(metaclass=abc.ABCMeta): @abc.astractmethod def __init__(self, **hyperparameters_and_initial_parameters): return NotImplemented @abc.astractmethod def train(self, *input_tensors) -> tf.Tensor: # scalar loss return NotImplemented @abc.astractmethod d...
import abc import tensorflow as tf class Model(metaclass=abc.ABCMeta): @abc.astractmethod def __init__(self, **hyperparameters_and_initial_parameters): return NotImplemented @abc.astractmethod def train(self, *input_tensors) -> tf.Operation: # training operation return NotImplemented @abc.astract...
Fix type annotation for Model.train()
Fix type annotation for Model.train()
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
33775cd9e740ac70e9213c37825077516e683e55
pyatv/support/device_info.py
pyatv/support/device_info.py
"""Lookup methods for device data.""" import re from pyatv.const import DeviceModel _MODEL_LIST = { "AppleTV2,1": DeviceModel.Gen2, "AppleTV3,1": DeviceModel.Gen3, "AppleTV3,2": DeviceModel.Gen3, "AppleTV5,3": DeviceModel.Gen4, "AppleTV6,2": DeviceModel.Gen4K, } # Incomplete list here! _VERSIO...
"""Lookup methods for device data.""" import re from pyatv.const import DeviceModel _MODEL_LIST = { "AppleTV2,1": DeviceModel.Gen2, "AppleTV3,1": DeviceModel.Gen3, "AppleTV3,2": DeviceModel.Gen3, "AppleTV5,3": DeviceModel.Gen4, "AppleTV6,2": DeviceModel.Gen4K, } # Incomplete list here! _VERSIO...
Add tvOS 13.4 build number
mrp: Add tvOS 13.4 build number
Python
mit
postlund/pyatv,postlund/pyatv
694a85c71c315ccdb3e2f2946f86ce95936ee684
sahara_dashboard/api/__init__.py
sahara_dashboard/api/__init__.py
from sahara_dashboard.api import sahara __all__ = [ "sahara" ]
# 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 the...
Add licensing info in source file.
Add licensing info in source file. [H102 H103] Source code should be licensed under the Apache 2.0 license. All source files should have the licensing header. Change-Id: I4f9ead44b5efa3616086f5a62a2e0e68854baf44
Python
apache-2.0
openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard,openstack/sahara-dashboard
3016872091618c78f60e17338f5581856a17f7af
endpoints/tests/test_utils.py
endpoints/tests/test_utils.py
from utils.testcase import EndpointTestCase from rest_framework import status from rest_framework.test import APIClient from django.utils.translation import ugettext_lazy as _ import sure class TestUtils(EndpointTestCase): def test_fail_authentication(self): client = APIClient() client.credentia...
from utils.testcase import EndpointTestCase from rest_framework import status from rest_framework.test import APIClient from django.utils.translation import ugettext_lazy as _ import sure class TestUtils(EndpointTestCase): def test_fail_authentication(self): client = APIClient() client.credentia...
Add test for no HTTP_AUTHORIZATION header at all
Add test for no HTTP_AUTHORIZATION header at all
Python
mit
Amoki/Amoki-Music,Amoki/Amoki-Music,Amoki/Amoki-Music
5e2943b8e17ee753ddfafd1420c9e8155c496aba
example/tests/test_parsers.py
example/tests/test_parsers.py
import json from django.test import TestCase from io import BytesIO from rest_framework_json_api.parsers import JSONParser class TestJSONParser(TestCase): def setUp(self): class MockRequest(object): def __init__(self): self.method = 'GET' request = MockRequest() ...
import json from io import BytesIO from django.test import TestCase from rest_framework.exceptions import ParseError from rest_framework_json_api.parsers import JSONParser class TestJSONParser(TestCase): def setUp(self): class MockRequest(object): def __init__(self): self.m...
Test case for parsing invalid data.
Test case for parsing invalid data.
Python
bsd-2-clause
django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api
d2b4ec50442a00df85ef525cc82aca971b72eb86
erpnext/patches/v11_0/rename_field_max_days_allowed.py
erpnext/patches/v11_0/rename_field_max_days_allowed.py
import frappe from frappe.model.utils.rename_field import rename_field def execute(): frappe.reload_doc("hr", "doctype", "leave_type") frappe.db.sql_ddl("""ALTER table `tabLeave Type` modify max_days_allowed int(8) NOT NULL""") rename_field("Leave Type", "max_days_allowed", "max_continuous_days_allowed")
import frappe def execute(): frappe.db.sql(""" UPDATE `tabLeave Type` SET max_days_allowed = '0' WHERE trim(coalesce(max_days_allowed, '')) = '' """) frappe.db.sql_ddl("""ALTER table `tabLeave Type` modify max_days_allowed int(8) NOT NULL""")
Set null values to '0' before changing column type
[fix] Set null values to '0' before changing column type
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
d3a2e344caa34f763f7e46710db5b9ddefe73c55
doc/mkapidoc.py
doc/mkapidoc.py
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Gen...
#!/usr/bin/env python # Generates the *public* API documentation. # Remember to hide your private parts, people! import os, re, sys project = 'Exscript' base_dir = os.path.join('..', 'src', project) doc_dir = 'api' # Create the documentation directory. if not os.path.exists(doc_dir): os.makedirs(doc_dir) # Gen...
Hide StreamAnalyzer and OsGuesser from the API docs.
Hide StreamAnalyzer and OsGuesser from the API docs.
Python
mit
maximumG/exscript,knipknap/exscript,knipknap/exscript,maximumG/exscript
91229ab93609f66af866f7ef87b576a84546aeab
api/base/parsers.py
api/base/parsers.py
from rest_framework.parsers import JSONParser from api.base.renderers import JSONAPIRenderer from api.base.exceptions import JSONAPIException class JSONAPIParser(JSONParser): """ Parses JSON-serialized data. Overrides media_type. """ media_type = 'application/vnd.api+json' renderer_class = JSONAPI...
from rest_framework.parsers import JSONParser from rest_framework.exceptions import ParseError from api.base.renderers import JSONAPIRenderer from api.base.exceptions import JSONAPIException class JSONAPIParser(JSONParser): """ Parses JSON-serialized data. Overrides media_type. """ media_type = 'appli...
Raise Parse Error if request data is not a dictionary
Raise Parse Error if request data is not a dictionary
Python
apache-2.0
mluo613/osf.io,adlius/osf.io,alexschiller/osf.io,samanehsan/osf.io,doublebits/osf.io,Ghalko/osf.io,rdhyee/osf.io,GageGaskins/osf.io,erinspace/osf.io,samanehsan/osf.io,caneruguz/osf.io,HalcyonChimera/osf.io,amyshi188/osf.io,doublebits/osf.io,caseyrygt/osf.io,adlius/osf.io,caneruguz/osf.io,kwierman/osf.io,erinspace/osf.i...
bdbff5ea5548067713951a85b05f3818e537c8d4
streamparse/bootstrap/project/src/bolts/wordcount.py
streamparse/bootstrap/project/src/bolts/wordcount.py
from __future__ import absolute_import, print_function, unicode_literals from collections import Counter from streamparse.bolt import Bolt class WordCounter(Bolt): def initialize(self, conf, ctx): self.counts = Counter() def process(self, tup): word = tup.values[0] self.counts[word] ...
from __future__ import absolute_import, print_function, unicode_literals from collections import Counter from streamparse.bolt import Bolt class WordCounter(Bolt): AUTO_ACK = True # automatically acknowledge tuples after process() AUTO_ANCHOR = True # automatically anchor tuples to current tuple AUTO_...
Update quickstart project to use AUTO_*
Update quickstart project to use AUTO_*
Python
apache-2.0
crohling/streamparse,petchat/streamparse,petchat/streamparse,eric7j/streamparse,msmakhlouf/streamparse,codywilbourn/streamparse,Parsely/streamparse,codywilbourn/streamparse,msmakhlouf/streamparse,scrapinghub/streamparse,Parsely/streamparse,petchat/streamparse,phanib4u/streamparse,petchat/streamparse,scrapinghub/streamp...
95988fc4e5d7b5b5fa3235000ad9680c168c485c
aiospamc/__init__.py
aiospamc/__init__.py
#!/usr/bin/env python3 '''aiospamc package. An asyncio-based library to communicate with SpamAssassin's SPAMD service.''' from aiospamc.client import Client __all__ = ('Client', 'MessageClassOption', 'ActionOption') __author__ = 'Michael Caley' __copyright__ = 'Copyright 2016, 2017 Michael Ca...
#!/usr/bin/env python3 '''aiospamc package. An asyncio-based library to communicate with SpamAssassin's SPAMD service.''' from aiospamc.client import Client from aiospamc.options import ActionOption, MessageClassOption __all__ = ('Client', 'MessageClassOption', 'ActionOption') __author__ = 'M...
Add import ActionOption and MessageClassOption to __all__
Add import ActionOption and MessageClassOption to __all__
Python
mit
mjcaley/aiospamc
f1793ed8a494701271b4a4baff8616e9c6202e80
message_view.py
message_view.py
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""...
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""...
Append messages if message view is currently open
Append messages if message view is currently open
Python
mit
SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3
4803578ebb306e2e142b629d98cb82899c0b0270
authorize/__init__.py
authorize/__init__.py
import xml.etree.ElementTree as E from authorize.configuration import Configuration from authorize.address import Address from authorize.bank_account import BankAccount from authorize.batch import Batch from authorize.credit_card import CreditCard from authorize.customer import Customer from authorize.environment impo...
import xml.etree.ElementTree as E from authorize.configuration import Configuration from authorize.address import Address from authorize.bank_account import BankAccount from authorize.batch import Batch from authorize.credit_card import CreditCard from authorize.customer import Customer from authorize.environment impo...
Fix monkey patching to pass kwargs required by Python 3.4
Fix monkey patching to pass kwargs required by Python 3.4
Python
mit
aryeh/py-authorize,uglycitrus/py-authorize,vcatalano/py-authorize
e8dd4ca8bd51b84d5d7d5a6a1c4144475e066bf1
zabbix.py
zabbix.py
import requests class Api(object): def __init__(self, server='http://localhost/zabbix'): self.session = requests.Session() self.session.headers.update({ 'Content-Type': 'application/json' }) self.url = server + '/api_jsonrpc.php' self.auth = '' self.id = ...
import requests class ZabbixError(Exception): pass class Api(object): def __init__(self, server='http://localhost/zabbix'): self.session = requests.Session() self.session.headers.update({ 'Content-Type': 'application/json' }) self.url = server + '/api_jsonrpc.php' ...
Create do_requestion function to be used by other methods.
Create do_requestion function to be used by other methods.
Python
apache-2.0
supasate/PythonZabbixApi
1b20116059b21905688b7fd6153ecd7c42bdc4a1
parseSAMOutput.py
parseSAMOutput.py
#!python # Load libraries import sys, getopt import pysam import libPipeline # Set constants helpMsg =''' SYNOPSIS parseSAMOutput parseSAMOutput [OPTIONS] SAMFILE # DESCRIPTION parseSAMOutput.py Parses SAM alignments into paired-end read summaries. Prints results to stdout. OPTIONS --rmdup Rem...
#!python # Load libraries import sys, getopt import pysam import libPipeline # Set constants helpMsg =''' SYNOPSIS parseSAMOutput parseSAMOutput [OPTIONS] SAMFILE # DESCRIPTION parseSAMOutput.py Parses SAM alignments into paired-end read summaries. Prints results to stdout. OPTIONS --rmdup Rem...
Fix rmdup handling in wrapper script.
Fix rmdup handling in wrapper script.
Python
apache-2.0
awblocker/paired-end-pipeline,awblocker/paired-end-pipeline
613a6f7947b46b9a6c4c679b638d1c4d946b644d
neutron/conf/policies/network_ip_availability.py
neutron/conf/policies/network_ip_availability.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 u...
# 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 u...
Implement secure RBAC for the network IP availability
Implement secure RBAC for the network IP availability This commit updates the network IP availability policies to understand scope checking and account for a read-only role. This is part of a broader series of changes across OpenStack to provide a consistent RBAC experience and improve security. Change-Id: Ia965e549e...
Python
apache-2.0
openstack/neutron,mahak/neutron,mahak/neutron,mahak/neutron,openstack/neutron,openstack/neutron
3f9623766b58c02b21abb967315bfe30a2b3974f
tests/TestTransaction.py
tests/TestTransaction.py
import Transaction import unittest class TestTransaction(unittest.TestCase) : def setUp(self) : self.test_object = Transaction.Transaction() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_can_assign_data(self) : s...
import Transaction import unittest class TestTransaction(unittest.TestCase) : def setUp(self) : self.test_object = Transaction.Transaction() def tearDown(self) : pass def test_not_None(self) : self.assertIsNotNone(self.test_object) def test_can_assign_data(self) : s...
Add test to clarify equality/is behavior
Add test to clarify equality/is behavior
Python
apache-2.0
mattdeckard/wherewithal
2728f33a0c8477d75b3716ea39fe2e3c8db9378d
tests/test_OrderedSet.py
tests/test_OrderedSet.py
from twisted.trial import unittest from better_od import OrderedSet class TestOrderedSet(unittest.TestCase): def setUp(self): self.values = 'abcddefg' self.s = OrderedSet(self.values) def test_order(self): expected = list(enumerate('abcdefg')) self.assertEquals(list(enumerate...
from twisted.trial import unittest from better_od import OrderedSet class TestOrderedSet(unittest.TestCase): def setUp(self): self.s = OrderedSet('abcdefg') def test_order(self): expected = list(enumerate('abcdefg')) self.assertEquals(list(enumerate(self.s)), expected) def test_...
Add OrderedSet mutation tests. Refactor tests.
Add OrderedSet mutation tests. Refactor tests. Refactored the tests to rely less on setUp because I've got to test mutating the objects.
Python
mit
JustusW/BetterOrderedDict,therealfakemoot/collections2
756860e325edd06eb98bed7c6fd5fa6c4a78243e
tests/test_migrations.py
tests/test_migrations.py
""" Tests that migrations are not missing """ try: from io import StringIO except ImportError: from StringIO import StringIO import pytest from django.core.management import call_command def test_no_missing_migrations(): """Check no model changes have been made since the last `./manage.py makemigration...
""" Tests that migrations are not missing """ try: from io import StringIO except ImportError: from StringIO import StringIO import pytest from django.core.management import call_command @pytest.mark.django_db def test_no_missing_migrations(): """Check no model changes have been made since the last `./...
Add missing pytest DB marker
Add missing pytest DB marker
Python
bsd-2-clause
bennylope/django-organizations,bennylope/django-organizations
d4003a3b07e4ead9bccbc6a9c8ff835970ad99a3
pymatgen/core/design_patterns.py
pymatgen/core/design_patterns.py
# coding: utf-8 from __future__ import division, unicode_literals """ This module defines some useful design patterns. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Producti...
# coding: utf-8 from __future__ import division, unicode_literals """ This module defines some useful design patterns. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "1.0" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __status__ = "Producti...
Move NullFile and NullStream to monty
Move NullFile and NullStream to monty Former-commit-id: 5492c3519fdfc444fd8cbb92cbf4b9c67c8a0883 [formerly 4aa6714284cb45a2747cea8e0f38e8fbcd8ec0bc] Former-commit-id: e6119512027c605a8277d0a99f37a6ab0d73b6c7
Python
mit
xhqu1981/pymatgen,tallakahath/pymatgen,fraricci/pymatgen,aykol/pymatgen,mbkumar/pymatgen,ndardenne/pymatgen,czhengsci/pymatgen,blondegeek/pymatgen,czhengsci/pymatgen,czhengsci/pymatgen,gVallverdu/pymatgen,nisse3000/pymatgen,dongsenfo/pymatgen,aykol/pymatgen,johnson1228/pymatgen,montoyjh/pymatgen,gpetretto/pymatgen,Bism...
c4903f5b631bba21e17be1b7deb118c0c9571432
Lab3/PalindromeExercise.py
Lab3/PalindromeExercise.py
# Asks the user for input of the word and makes it lower case. normStr = raw_input("Enter the word:\n").lower(); # Inverts the string so it can compare it with the original input. invertStr = normStr[::-1];
# Asks the user for input of the word and makes it lower case. normStr = raw_input("Enter the word:\n").lower(); # Inverts the string so it can compare it with the original input. invertStr = normStr[::-1]; # Tests if the string is a palindrome. If so, it prints True. Else, prints False. if normStr == invertStr: pri...
Test added. Program should be complete.
Test added. Program should be complete.
Python
mit
lgomie/dt228-3B-cloud-repo
98eead2549f4a2793011ffe8107e64530ddbf782
runtests.py
runtests.py
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.ses...
#!/usr/bin/env python import sys from os.path import abspath, dirname import django from django.conf import settings sys.path.insert(0, abspath(dirname(__file__))) if not settings.configured: settings.configure( INSTALLED_APPS=( 'django.contrib.contenttypes', 'django.contrib.ses...
Add missing auth middleware for 1.7 tests
Add missing auth middleware for 1.7 tests
Python
mit
treyhunner/django-relatives,treyhunner/django-relatives
de02f354e406e5b9a3f742697d3979d54b9ee581
fvserver/urls.py
fvserver/urls.py
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^macnamer/', include('macnamer.foo.urls')), url(r'^login/$', 'django.contrib.auth.views.login'),...
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^macnamer/', include('macnamer.foo.urls')), url(r'^login/$', 'django.contrib.auth.views.login'), ...
Update password functions for Django 1.8
Update password functions for Django 1.8
Python
apache-2.0
grahamgilbert/Crypt-Server,squarit/Crypt-Server,arubdesu/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,arubdesu/Crypt-Server,squarit/Crypt-Server,arubdesu/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,grahamgilbert/Crypt-Server
cc8f0760aa5497d2285dc85c6f3c17c6ce327c35
core/__init__.py
core/__init__.py
# Offer forward compatible imports of datastore_rpc and datastore_query. import logging try: from google.appengine.datastore import datastore_rpc from google.appengine.datastore import datastore_query logging.info('Imported official google datastore_{rpc,query}') except ImportError: logging.warning('Importing...
# Offer forward compatible imports of datastore_rpc and datastore_query. import logging import sys try: from google.appengine.datastore import datastore_rpc from google.appengine.datastore import datastore_query sys.modules['core.datastore_rpc'] = datastore_rpc sys.modules['core.datastore_query'] = datastore_...
Make official google imports actually work.
Make official google imports actually work.
Python
apache-2.0
GoogleCloudPlatform/datastore-ndb-python,GoogleCloudPlatform/datastore-ndb-python
c566fa8f49ea826b29937c9c128350494eb10bf6
rrd/__init__.py
rrd/__init__.py
#-*- coding:utf-8 -*- import os from flask import Flask #-- create app -- app = Flask(__name__) app.config.from_object("rrd.config") @app.errorhandler(Exception) def all_exception_handler(error): print "exception: %s" %error return u'dashboard 暂时无法访问,请联系管理员', 500 from view import api, chart, screen, index
#-*- coding:utf-8 -*- import os from flask import Flask from flask import request from flask import redirect #-- create app -- app = Flask(__name__) app.config.from_object("rrd.config") @app.errorhandler(Exception) def all_exception_handler(error): print "exception: %s" %error return u'dashboard 暂时无法访问,请联系管理员...
Add before_request and it works for this bug
Add before_request and it works for this bug Check if the signature exists. Redirect to the login page if it doesn't. I took `rrd/view/index.py` as the reference
Python
apache-2.0
Cepave/dashboard,Cepave/dashboard,Cepave/dashboard,Cepave/dashboard
4735804f4951835e4e3c7d116628344bddf45aa3
atomicpress/admin.py
atomicpress/admin.py
# -*- coding: utf-8 -*- from flask import current_app from flask_admin.contrib.fileadmin import FileAdmin from flask_admin import AdminIndexView, expose, Admin from flask_admin.contrib.sqla import ModelView from atomicpress import models from atomicpress.app import db class HomeView(AdminIndexView): @expose("/")...
# -*- coding: utf-8 -*- from flask import current_app from flask_admin.contrib.fileadmin import FileAdmin from flask_admin import AdminIndexView, expose, Admin from flask_admin.contrib.sqla import ModelView from atomicpress import models from atomicpress.app import db class HomeView(AdminIndexView): @expose("/")...
Update post view sorting (so latest comes first)
Update post view sorting (so latest comes first)
Python
mit
marteinn/AtomicPress,marteinn/AtomicPress,marteinn/AtomicPress,marteinn/AtomicPress
3a204de33589de943ff09525895812530baac0b2
saylua/modules/pets/models/db.py
saylua/modules/pets/models/db.py
from google.appengine.ext import ndb # This is to store alternate linart versions of the same pets class SpeciesVersion(ndb.Model): name = ndb.StringProperty() base_image = ndb.StringProperty() base_psd = ndb.StringProperty() default_image = ndb.StringProperty() # Pets are divided into species and spe...
from google.appengine.ext import ndb # This is to store alternate linart versions of the same pets class SpeciesVersion(ndb.Model): name = ndb.StringProperty() base_image = ndb.StringProperty() base_psd = ndb.StringProperty() default_image = ndb.StringProperty() # Pets are divided into species and spe...
Update to pet model for provisioner
Update to pet model for provisioner
Python
agpl-3.0
saylua/SayluaV2,saylua/SayluaV2,LikeMyBread/Saylua,LikeMyBread/Saylua,saylua/SayluaV2,LikeMyBread/Saylua,LikeMyBread/Saylua
4aeb2e57a05491973c761eb169a42cb5e1e32737
gtr/__init__.py
gtr/__init__.py
__all__ = [ "gtr.services.funds.Funds" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr.services.organisations import Organisations from gtr.services.persons import Persons from gtr.services.projects import Projects
__all__ = [ "gtr.services.funds.Funds", "gtr.services.organisations.Organisations", "gtr.services.persons.Persons", "gtr.services.projects.Projects" ] __version__ = "0.1.0" from gtr.services.base import _Service from gtr.services.funds import Funds from gtr.services.organisations import Organisations f...
Add all service Classes to import
Add all service Classes to import
Python
apache-2.0
nestauk/gtr
1d84a3b58aa752834aed31123dd16e3bfa723609
tests/storage_adapter_tests/test_storage_adapter.py
tests/storage_adapter_tests/test_storage_adapter.py
from unittest import TestCase from chatterbot.storage import StorageAdapter class StorageAdapterTestCase(TestCase): """ This test case is for the StorageAdapter base class. Although this class is not intended for direct use, this test case ensures that exceptions requiring basic functionality are ...
from unittest import TestCase from chatterbot.storage import StorageAdapter class StorageAdapterTestCase(TestCase): """ This test case is for the StorageAdapter base class. Although this class is not intended for direct use, this test case ensures that exceptions requiring basic functionality are ...
Remove tests for storage adapter methods being removed.
Remove tests for storage adapter methods being removed.
Python
bsd-3-clause
vkosuri/ChatterBot,gunthercox/ChatterBot
2d95f8fe9c9e9edf5b1a0b5dee2992187b0d89ed
src/pytest_django_lite/plugin.py
src/pytest_django_lite/plugin.py
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_...
import os import pytest try: from django.conf import settings except ImportError: settings = None # NOQA def is_configured(): if settings is None: return False return settings.configured or os.environ.get('DJANGO_SETTINGS_MODULE') @pytest.fixture(autouse=True, scope='session') def _django_...
Deal with the Django app refactoring.
Deal with the Django app refactoring.
Python
apache-2.0
pombredanne/pytest-django-lite,dcramer/pytest-django-lite
2f152c5036d32a780741edd8fb6ce75684728824
singleuser/user-config.py
singleuser/user-config.py
import os mylang = 'test' family = 'wikipedia' # Not defining any extra variables here at all since that causes pywikibot # to issue a warning about potential misspellings if os.path.exists(os.path.expanduser('~/user-config.py')): with open(os.path.expanduser('~/user-config.py'), 'r') as f: exec( ...
import os mylang = 'test' family = 'wikipedia' custom_path = os.path.expanduser('~/user-config.py') if os.path.exists(custom_path): with open(custom_path, 'r') as f: exec(compile(f.read(), custom_path, 'exec'), globals()) # Things that should be non-easily-overridable usernames['*']['*'] = os.environ['J...
Revert "Do not introduce extra variables"
Revert "Do not introduce extra variables" Since the 'f' is considered an extra variable and introduces a warning anyway :( Let's fix this the right way This reverts commit a03de68fb772d859098327d0e54a219fe4507072.
Python
mit
yuvipanda/paws,yuvipanda/paws
2d4016d8e4245a6e85c2bbea012d13471718b1b0
journal/views.py
journal/views.py
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from django.http import JsonResponse from rest_framework.parsers import JSONParser from .models import Entry from .serializers import EntrySerializer @method_decorator(csrf...
from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from django.http import JsonResponse from rest_framework.parsers import JSONParser from .models import Entry from .serializers import EntrySerializer @method_decorator(csrf...
Add a way to specific tag.
Add a way to specific tag.
Python
agpl-3.0
etesync/journal-manager
a4c9dd451062b83b907a350ea30f2d36badb6522
parsers/__init__.py
parsers/__init__.py
import importlib parsers = """ singtao.STParser apple.AppleParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module), class_name) ...
import importlib parsers = """ singtao.STParser apple.AppleParser tvb.TVBParser """.split() parser_dict = {} # Import the parser and fill in parser_dict: domain -> parser for parser_name in parsers: module, class_name = parser_name.rsplit('.', 1) parser = getattr(importlib.import_module('parsers.' + module),...
Add tvb Parser to the init
Add tvb Parser to the init
Python
mit
code4hk/hk-news-scrapper
a90889b773010d2fe2ed1dff133f951c0b5baea4
demo/__init__.py
demo/__init__.py
"""Package for PythonTemplateDemo.""" __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = __project__ + '-' + __version__ PYTHON_VERSION = 2, 7 import sys if not sys.version_info >= PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
"""Package for PythonTemplateDemo.""" import sys __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = __project__ + '-' + __version__ PYTHON_VERSION = 2, 7 if not sys.version_info >= PYTHON_VERSION: # pragma: no cover (manual test) exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
Deploy Travis CI build 387 to GitHub
Deploy Travis CI build 387 to GitHub
Python
mit
jacebrowning/template-python-demo
7e738ddbc1a4585f92e605369f8d6dc1d986dbec
scripts/get_cuda_version.py
scripts/get_cuda_version.py
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] ...
import os nvcc_version_cmd = 'nvcc -V > output.txt' os.system(nvcc_version_cmd) with open('output.txt') as f: lines = f.readlines() for line in lines: if ", release" in line: start = line.index(', release') + 10 end = line.index('.', start) result = line[start:end] ...
Remove output.txt file after done
Remove output.txt file after done After we are done detecting nvcc version, let's delete the temporary output.txt file.
Python
mit
GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC,GOMC-WSU/GOMC
a6f0b0db3e32c71e89d73db8997308e67aae294f
setup_cython.py
setup_cython.py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext core = Extension( 'geopy.core', ["geopy/core.pyx"], language='c++', libraries=['stdc++'], ) setup( cmdclass = {'build_ext': build_ext}, include_dirs ...
import os from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext core = Extension( 'geometry.core', [os.path.join("geometry", "core.pyx")], language='c++', libraries=['stdc++'], include_dirs = ['.'], ) setu...
Make module path OS independent by using os.path.join
Make module path OS independent by using os.path.join
Python
bsd-3-clause
FRidh/python-geometry
0571864eb2d99b746386ace721b8e218f127c6ac
email_obfuscator/templatetags/email_obfuscator.py
email_obfuscator/templatetags/email_obfuscator.py
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#%s;'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value): ...
from django import template from django.template.defaultfilters import stringfilter from django.utils.safestring import mark_safe register = template.Library() def obfuscate_string(value): return ''.join(['&#{0:s};'.format(str(ord(char))) for char in value]) @register.filter @stringfilter def obfuscate(value):...
Fix mixup of old and new-style string formatting
Fix mixup of old and new-style string formatting
Python
mit
morninj/django-email-obfuscator
41ac7e2d85126c2fe5dd16230ed678d72a8d048f
jax/__init__.py
jax/__init__.py
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Use a regular import to add jax.__version__ rather than exec() trickery.
Use a regular import to add jax.__version__ rather than exec() trickery. (The exec() trickery is needed for setup.py, but not for jax/__init__.py.)
Python
apache-2.0
tensorflow/probability,google/jax,google/jax,google/jax,google/jax,tensorflow/probability
e1c6b7c369395208b467fcf169b6e3d0eb8c8dd9
src/rlib/string_stream.py
src/rlib/string_stream.py
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, si...
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, ...
Fix StringStream to conform to latest pypy
Fix StringStream to conform to latest pypy Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
SOM-st/RPySOM,smarr/RTruffleSOM,smarr/RTruffleSOM,smarr/PySOM,SOM-st/RPySOM,SOM-st/RTruffleSOM,SOM-st/PySOM,SOM-st/RTruffleSOM,SOM-st/PySOM,smarr/PySOM
98925a82dfb45a4c76496cd11af8d1483a678e6e
sigh/views/api.py
sigh/views/api.py
import json from functools import wraps from flask import Blueprint from flask import Response from ..models import Tag api_views = Blueprint('api', __name__, url_prefix='/api/') def jsonify(func): @wraps(func) def _(*args, **kwargs): result = func(*args, **kwargs) return Response(json.dum...
import json from functools import wraps from flask import Blueprint from flask import Response from ..models import Tag from ..models import User api_views = Blueprint('api', __name__, url_prefix='/api/') def jsonify(func): @wraps(func) def _(*args, **kwargs): result = func(*args, **kwargs) ...
Create a new API for User autocompletion
Create a new API for User autocompletion
Python
mit
kxxoling/Programmer-Sign,kxxoling/Programmer-Sign,kxxoling/Programmer-Sign
83cc9a5304e41e4ce517cfc739238a37f13f626a
matchzoo/data_pack/build_unit_from_data_pack.py
matchzoo/data_pack/build_unit_from_data_pack.py
from tqdm import tqdm from .data_pack import DataPack from matchzoo import processor_units def build_unit_from_data_pack( unit: processor_units.StatefulProcessorUnit, data_pack: DataPack, flatten: bool = True, verbose: int = 1 ) -> processor_units.StatefulProcessorUnit: """ Build a :class:`Statef...
"""Build unit from data pack.""" from tqdm import tqdm from matchzoo import processor_units from .data_pack import DataPack def build_unit_from_data_pack( unit: processor_units.StatefulProcessorUnit, data_pack: DataPack, flatten: bool = True, verbose: int = 1 ) -> processor_units.StatefulProcessorUnit: ...
Update docs for build unit.
Update docs for build unit.
Python
apache-2.0
faneshion/MatchZoo,faneshion/MatchZoo
880b5257d549c2150d8888a2f062acd9cc948480
array/is-crypt-solution.py
array/is-crypt-solution.py
# You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm # Write a solution wh...
# You have an array of strings crypt, the cryptarithm, and an an array containing the mapping of letters and digits, solution. The array crypt will contain three non-empty strings that follow the structure: [word1, word2, word3], which should be interpreted as the word1 + word2 = word3 cryptarithm # Write a solution wh...
Check if sum of decoded numbers of first and second strings equal to decoded number of third string
Check if sum of decoded numbers of first and second strings equal to decoded number of third string
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
fef260c3731408592fd88e73817fe0f0cd7fe769
telemetry/telemetry/core/chrome/inspector_memory_unittest.py
telemetry/telemetry/core/chrome/inspector_memory_unittest.py
# Copyright (c) 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. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_...
# Copyright (c) 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. import os from telemetry.test import tab_test_case class InspectorMemoryTest(tab_test_case.TabTestCase): def testGetDOMStats(self): unittest_data_...
Fix InspectorMemoryTest.testGetDOMStats to have consistent behaviour on CrOS and desktop versions of Chrome. Starting the browser in CrOS requires navigating through an initial setup that does not leave us with a tab at "chrome://newtab". This workaround runs the test in a new tab on all platforms for consistency.
Fix InspectorMemoryTest.testGetDOMStats to have consistent behaviour on CrOS and desktop versions of Chrome. Starting the browser in CrOS requires navigating through an initial setup that does not leave us with a tab at "chrome://newtab". This workaround runs the test in a new tab on all platforms for consistency. BUG...
Python
bsd-3-clause
benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult-csm,sahiljain/catapult,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,benschmaus/catapult,SummerLW/Perf-Insight-Report,catapult-project/catapult,catapult-project/catapult,sahiljain/catap...
3a0c7caadb46a69fb29fe34bd64de28c9b263fd6
restconverter.py
restconverter.py
# -*- coding: utf-8 -*- """ flaskjk.restconverter ~~~~~~~~~~~~~~~~~~~~~ Helper functions for converting RestructuredText This class heavily depends on the functionality provided by the docutils package. :copyright: (c) 2010 by Jochem Kossen. :license: BSD, see LICENSE for more details. "...
# -*- coding: utf-8 -*- """ flaskjk.restconverter ~~~~~~~~~~~~~~~~~~~~~ Helper functions for converting RestructuredText This class heavily depends on the functionality provided by the docutils package. See http://wiki.python.org/moin/ReStructuredText for more information :copyright: (...
Add rest_to_html_fragment to be able to convert just the body part
Add rest_to_html_fragment to be able to convert just the body part
Python
bsd-2-clause
jkossen/flaskjk
17db9de51b816210728db7f58685b7d8e5545c65
src/__init__.py
src/__init__.py
from pkg_resources import get_distribution import codecs import json __version__ = get_distribution('rasa_nlu').version class Interpreter(object): def parse(self, text): raise NotImplementedError() @staticmethod def load_synonyms(entity_synonyms): if entity_synonyms: with cod...
from pkg_resources import get_distribution import codecs import json __version__ = get_distribution('rasa_nlu').version class Interpreter(object): def parse(self, text): raise NotImplementedError() @staticmethod def load_synonyms(entity_synonyms): if entity_synonyms: with cod...
Fix entity dict access key
Fix entity dict access key
Python
apache-2.0
RasaHQ/rasa_nlu,beeva-fernandocerezal/rasa_nlu,beeva-fernandocerezal/rasa_nlu,verloop/rasa_nlu,PHLF/rasa_nlu,verloop/rasa_nlu,PHLF/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu
2a950c91416d3b92a91f4f245a37a95b418b4bab
custom/uth/tasks.py
custom/uth/tasks.py
from custom.uth.utils import create_case, match_case, attach_images_to_case, submit_error_case from custom.uth.models import SonositeUpload, VscanUpload from celery.task import task import io def get_files_from_doc(doc): files = {} for f in doc._attachments.keys(): files[f] = io.BytesIO(doc.fetch_atta...
from custom.uth.utils import create_case, match_case, attach_images_to_case, submit_error_case from custom.uth.models import SonositeUpload, VscanUpload from celery.task import task import io def get_files_from_doc(doc): files = {} for f in doc._attachments.keys(): files[f] = io.BytesIO(doc.fetch_atta...
Delete docs on task completion
Delete docs on task completion
Python
bsd-3-clause
puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,SEL...
5bb84d5eac353cd4bbe1843fccaca64161830591
savu/__init__.py
savu/__init__.py
# Copyright 2014 Diamond Light Source 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 applicable law or agreed t...
# Copyright 2014 Diamond Light Source 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 applicable law or agreed t...
Update to make import of savu a little more useful
Update to make import of savu a little more useful
Python
apache-2.0
mjn19172/Savu,swtp1v07/Savu,swtp1v07/Savu,swtp1v07/Savu,mjn19172/Savu,swtp1v07/Savu,mjn19172/Savu,mjn19172/Savu,mjn19172/Savu
43ae9bdec900081d6ff91fc3847a4d8d9a42eaeb
contrib/plugins/w3cdate.py
contrib/plugins/w3cdate.py
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ ...
""" Add a 'w3cdate' key to every entry -- this contains the date in ISO8601 format WARNING: you must have PyXML installed as part of your python installation in order for this plugin to work Place this plugin early in your load_plugins list, so that the w3cdate will be available to subsequent plugins """ __author__ ...
Fix daylight savings time bug
Fix daylight savings time bug
Python
mit
daitangio/pyblosxom,daitangio/pyblosxom,willkg/douglas,willkg/douglas
e0a6ea3d48691bedfb39a0a92d569ea4aaf61810
pavement.py
pavement.py
import paver.doctools import paver.setuputils from schevo.release import setup_meta options( setup=setup_meta, sphinx=Bunch( docroot='doc', builddir='build', sourcedir='source', ), ) @task @needs('paver.doctools.html') def openhtml(): index_file = path('doc/build/html/index....
from schevo.release import setup_meta options( setup=setup_meta, sphinx=Bunch( docroot='doc', builddir='build', sourcedir='source', ), ) try: import paver.doctools except ImportError: pass else: @task @needs('paver.doctools.html') def openhtml(): index...
Make paver.doctools optional, to allow for downloading of ==dev eggs
Make paver.doctools optional, to allow for downloading of ==dev eggs Signed-off-by: Matthew R. Scott <878b2bb7d7b44067d87275810e479f4abd7737ae@gmail.com>
Python
mit
Schevo/schevo,Schevo/schevo
f408d7e61753ecdeb280e59ecb35485385ec3f6a
Tools/compiler/compile.py
Tools/compiler/compile.py
import sys import getopt from compiler import compile, visitor ##import profile def main(): VERBOSE = 0 DISPLAY = 0 CONTINUE = 0 opts, args = getopt.getopt(sys.argv[1:], 'vqdc') for k, v in opts: if k == '-v': VERBOSE = 1 visitor.ASTVisitor.VERBOSE = visitor.ASTVis...
import sys import getopt from compiler import compile, visitor import profile def main(): VERBOSE = 0 DISPLAY = 0 PROFILE = 0 CONTINUE = 0 opts, args = getopt.getopt(sys.argv[1:], 'vqdcp') for k, v in opts: if k == '-v': VERBOSE = 1 visitor.ASTVisitor.VERBOSE =...
Add -p option to invoke Python profiler
Add -p option to invoke Python profiler
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
a67176ba0ba06d1a7cfff5d8e21446bb78a30518
subscription/api.py
subscription/api.py
from tastypie import fields from tastypie.resources import ModelResource, ALL from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from subscription.models import Subscription, MessageSet from djcelery.models import PeriodicTask class PeriodicTaskResource(ModelResou...
from tastypie import fields from tastypie.resources import ModelResource, ALL from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import Authorization from subscription.models import Subscription, MessageSet from djcelery.models import PeriodicTask class PeriodicTaskResource(ModelResou...
Update tastypie methods allowed for subscriptions
Update tastypie methods allowed for subscriptions
Python
bsd-3-clause
praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control
dfb6d41be3acf5fc4d4d0f3d8a7fb9d3507e9ae7
labware/microplates.py
labware/microplates.py
from .grid import GridContainer, GridItem from .liquids import LiquidWell class Microplate(GridContainer): rows = 12 cols = 8 volume = 100 min_vol = 50 max_vol = 90 height = 14.45 length = 127.76 width = 85.47 diameter = 7.15 depth = 3.25 a1...
from .grid import GridContainer, GridItem from .liquids import LiquidWell class Microplate(GridContainer): rows = 12 cols = 8 volume = 100 min_vol = 50 max_vol = 90 height = 14.45 length = 127.76 width = 85.47 diameter = 7.15 depth = 3.25 a1...
Revert of af99d4483acb36eda65b; Microplate subsets are special and important.
Revert of af99d4483acb36eda65b; Microplate subsets are special and important.
Python
apache-2.0
OpenTrons/opentrons-api,OpenTrons/opentrons-api,Opentrons/labware,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons_sdk,OpenTrons/opentrons-api
abd4859f8bac46fd6d114352ffad4ee9af28aa5f
common/lib/xmodule/xmodule/tests/test_mongo_utils.py
common/lib/xmodule/xmodule/tests/test_mongo_utils.py
"""Tests for methods defined in mongo_utils.py""" import os from unittest import TestCase from uuid import uuid4 from pymongo import ReadPreference from django.conf import settings from xmodule.mongo_utils import connect_to_mongodb class MongoUtilsTests(TestCase): """ Tests for methods exposed in mongo_uti...
""" Tests for methods defined in mongo_utils.py """ import ddt import os from unittest import TestCase from uuid import uuid4 from pymongo import ReadPreference from django.conf import settings from xmodule.mongo_utils import connect_to_mongodb @ddt.ddt class MongoUtilsTests(TestCase): """ Tests for method...
Convert test to DDT and test for primary, nearest modes.
Convert test to DDT and test for primary, nearest modes.
Python
agpl-3.0
teltek/edx-platform,arbrandes/edx-platform,kmoocdev2/edx-platform,CredoReference/edx-platform,Stanford-Online/edx-platform,eduNEXT/edx-platform,EDUlib/edx-platform,appsembler/edx-platform,ahmedaljazzar/edx-platform,appsembler/edx-platform,gsehub/edx-platform,gymnasium/edx-platform,jolyonb/edx-platform,a-parhom/edx-plat...
956cb919554c8103149fa6442254bdfed0ce32d1
lms/djangoapps/experiments/factories.py
lms/djangoapps/experiments/factories.py
import factory from experiments.models import ExperimentData, ExperimentKeyValue from student.tests.factories import UserFactory class ExperimentDataFactory(factory.DjangoModelFactory): class Meta(object): model = ExperimentData user = factory.SubFactory(UserFactory) experiment_id = factory.fuzz...
import factory import factory.fuzzy from experiments.models import ExperimentData, ExperimentKeyValue from student.tests.factories import UserFactory class ExperimentDataFactory(factory.DjangoModelFactory): class Meta(object): model = ExperimentData user = factory.SubFactory(UserFactory) experim...
Add an import of a submodule to make pytest less complainy
Add an import of a submodule to make pytest less complainy
Python
agpl-3.0
angelapper/edx-platform,TeachAtTUM/edx-platform,a-parhom/edx-platform,CredoReference/edx-platform,gsehub/edx-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,stvstnfrd/edx-platform,eduNEXT/edx-platform,TeachAtTUM/edx-platform,Stanford-Online/edx-platform,a-parhom/edx-platform,eduNEXT/edx-platform,ahmedaljazzar/ed...
ea3e9270788b251440b5f6fab1605361e0dc2ade
inonemonth/challenges/tests/test_forms.py
inonemonth/challenges/tests/test_forms.py
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms ...
import unittest import django.test from django.core.exceptions import ValidationError from core.tests.setups import RobrechtSocialUserFactory from ..validators import RepoExistanceValidator ############################################################################### # Forms ...
Add Comment to RepoExistanceValidator test and correct test name
Add Comment to RepoExistanceValidator test and correct test name
Python
mit
robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth,robrechtdr/inonemonth
0bdcb1c36432cfa0506c6dd667e4e1910edcd371
ixprofile_client/management/commands/createsuperuser.py
ixprofile_client/management/commands/createsuperuser.py
""" A management command to create a user with a given email. """ from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from ixprofile_client.webservice import UserWebService from optparse import make_option class Command(BaseCommand): """ The command...
""" A management command to create a user with a given email. """ from django.contrib.auth.models import User from django.core.management.base import BaseCommand, CommandError from django.db import transaction from ixprofile_client.webservice import UserWebService from optparse import make_option class Command(Bas...
Handle the case where the user may already exist in the database
Handle the case where the user may already exist in the database
Python
mit
infoxchange/ixprofile-client,infoxchange/ixprofile-client
1cd3096322b5d4b4c4df0f1fba6891e29c911c53
spaces/utils.py
spaces/utils.py
import re import os def normalize_path(path): """ Normalizes a path: * Removes extra and trailing slashes * Converts special characters to underscore """ path = re.sub(r'/+', '/', path) # repeated slash path = re.sub(r'/*$', '', path) # trailing slash path = [to_slug(p)...
import re import os def normalize_path(path): """ Normalizes a path: * Removes extra and trailing slashes * Converts special characters to underscore """ if path is None: return "" path = re.sub(r'/+', '/', path) # repeated slash path = re.sub(r'/*$', '', path) # tr...
Convert path to lowercase when normalizing
Convert path to lowercase when normalizing
Python
mit
jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces,jgillick/Spaces
33c03c8d50524dca3b9c5990958a0b44e9fe399e
isserviceup/services/models/statuspage.py
isserviceup/services/models/statuspage.py
import requests from bs4 import BeautifulSoup from isserviceup.services.models.service import Service, Status class StatusPagePlugin(Service): def get_status(self): r = requests.get(self.status_url) if r.status_code != 200: return Status.unavailable b = BeautifulSoup(r.conte...
import requests from bs4 import BeautifulSoup from isserviceup.services.models.service import Service, Status class StatusPagePlugin(Service): def get_status(self): r = requests.get(self.status_url) if r.status_code != 200: return Status.unavailable b = BeautifulSoup(r.conte...
Use unresolved-incidents when page-status is empty
Use unresolved-incidents when page-status is empty
Python
apache-2.0
marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up
e49ac8daeabf82708f2ba7bb623d7db73e1fcaff
readthedocs/core/subdomain_urls.py
readthedocs/core/subdomain_urls.py
from django.conf.urls.defaults import url, patterns from urls import urlpatterns as main_patterns urlpatterns = patterns('', url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$', 'core.views.subproject_serve_docs', name='subproject_docs_detail...
from django.conf.urls.defaults import url, patterns from urls import urlpatterns as main_patterns urlpatterns = patterns('', url(r'^projects/(?P<project_slug>[\w.-]+)/(?P<lang_slug>\w{2})/(?P<version_slug>[\w.-]+)/(?P<filename>.*)$', 'core.views.subproject_serve_docs', name='subproject_docs_detail...
Add verison_slug redirection back in for now.
Add verison_slug redirection back in for now.
Python
mit
agjohnson/readthedocs.org,kdkeyser/readthedocs.org,istresearch/readthedocs.org,davidfischer/readthedocs.org,KamranMackey/readthedocs.org,espdev/readthedocs.org,ojii/readthedocs.org,singingwolfboy/readthedocs.org,michaelmcandrew/readthedocs.org,SteveViss/readthedocs.org,hach-que/readthedocs.org,raven47git/readthedocs.or...
0484d3f14f29aa489bc848f1d83a9fb20183532e
plaidml/keras/tile_sandbox.py
plaidml/keras/tile_sandbox.py
from collections import OrderedDict import numpy as np import plaidml import plaidml.keras plaidml.keras.install_backend() import keras.backend as K def main(code, tensor_A, tensor_B, output_shape): print(K.backend()) op = K._Op('sandbox_op', A.dtype, output_shape, code, OrderedDict([('A', tens...
from collections import OrderedDict import numpy as np import plaidml import plaidml.tile as tile import plaidml.keras plaidml.keras.install_backend() import keras.backend as K class SandboxOp(tile.Operation): def __init__(self, code, a, b, output_shape): super(SandboxOp, self).__init__(code, [('A', a), ...
Update Tile sandbox for op lib
Update Tile sandbox for op lib
Python
apache-2.0
plaidml/plaidml,plaidml/plaidml,plaidml/plaidml,plaidml/plaidml
583c946061f8af815c32254655f4aed8f0c18dc9
watcher/tests/api/test_config.py
watcher/tests/api/test_config.py
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in...
Use importlib to take place of im module
Use importlib to take place of im module The imp module is deprecated[1] since version 3.4, use importlib to instead 1: https://docs.python.org/3/library/imp.html#imp.reload Change-Id: Ic126bc8e0936e5d7a2c7a910b54b7348026fedcb
Python
apache-2.0
openstack/watcher,openstack/watcher
ed5a151942ff6aeddeaab0fb2e23428821f89fc4
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.Software.Python.grovepi import ultrasonicRead except ImportError: 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 grovepi import in sensor driver
Fix grovepi import in sensor driver
Python
apache-2.0
aninternetof/rover-code,aninternetof/rover-code,aninternetof/rover-code
95788f09949e83cf39588444b44eda55e13c6071
wluopensource/accounts/models.py
wluopensource/accounts/models.py
from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, blank=True, unique=True) url = models.URLField("Website", blank=True, verify_exists=False) def __unicode__(self): ...
from django.contrib.auth.models import User from django.db import models from django.db.models.signals import post_save class UserProfile(models.Model): user = models.ForeignKey(User, blank=True, unique=True) url = models.URLField("Website", blank=True) def __unicode__(self): return self.user....
Remove verify false from user URL to match up with comment URL
Remove verify false from user URL to match up with comment URL
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
d3bc714478c3f7a665b39dfb1b8d65e7bc59ccd0
utuputki-webui/utuputki/handlers/logout.py
utuputki-webui/utuputki/handlers/logout.py
# -*- coding: utf-8 -*- from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.clo...
# -*- coding: utf-8 -*- from handlers.handlerbase import HandlerBase from db import db_session, Session class LogoutHandler(HandlerBase): def handle(self, packet_msg): # Remove session s = db_session() s.query(Session).filter_by(key=self.sock.sid).delete() s.commit() s.clo...
Clear all session data from websocket obj
Clear all session data from websocket obj
Python
mit
katajakasa/utuputki2,katajakasa/utuputki2,katajakasa/utuputki2,katajakasa/utuputki2
5d5b59bde655fbeb2d07bd5539c2ff9b29879d1d
pythontutorials/books/AutomateTheBoringStuff/Ch14/P2_writeCSV.py
pythontutorials/books/AutomateTheBoringStuff/Ch14/P2_writeCSV.py
# This program uses the csv module to manipulate .csv files import csv # Writer Objects outputFile = open("output.csv", "w", newline='') outputWriter = csv.writer(outputFile) print(outputWriter.writerow(['spam', 'eggs', 'bacon', 'ham'])) print(outputWriter.writerow(['Hello, world!', 'eggs', 'bacon', 'ham'])) print(ou...
"""Write CSV This program uses :py:mod:`csv` to write .csv files. Note: Creates 'output.csv' and 'example.tsv' files. """ def main(): import csv # Writer Objects outputFile = open("output.csv", "w", newline='') outputWriter = csv.writer(outputFile) print(outputWriter.writerow(['spam', 'egg...
Update P1_writeCSV.py added docstring and wrapped in main function
Update P1_writeCSV.py added docstring and wrapped in main function
Python
mit
JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials
20d94336b163c1e98458f14ab44651e2df8ed659
web/social/management/commands/stream_twitter.py
web/social/management/commands/stream_twitter.py
import logging from django.core.management.base import BaseCommand, CommandError from django.conf import settings from social.models import * from social.utils import * from tweetstream import FilterStream class Command(BaseCommand): help = "Start Twitter streaming" def handle(self, *args, **options): ...
import logging import time from django.core.management.base import BaseCommand, CommandError from django.conf import settings from social.models import * from social.utils import * from tweetstream import FilterStream, ConnectionError class Command(BaseCommand): help = "Start Twitter streaming" def handle(sel...
Add ConnectionError handling and reconnection to Twitter streamer
Add ConnectionError handling and reconnection to Twitter streamer
Python
agpl-3.0
kansanmuisti/datavaalit,kansanmuisti/datavaalit
6bf762b7aeabcb47571fe4d23fe13ae8e4b3ebc3
editorsnotes/main/views.py
editorsnotes/main/views.py
from django.conf import settings from django.http import HttpResponse from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from models import Term, Reference @login_required def index(request): o = {} o['term_list'] = Term.objects.all() return render_to_...
from django.conf import settings from django.http import HttpResponse from django.shortcuts import render_to_response, get_object_or_404 from django.contrib.auth.decorators import login_required from models import Term, Reference @login_required def index(request): o = {} o['term_list'] = Term.objects.all() ...
Throw 404 for non-existent terms.
Throw 404 for non-existent terms.
Python
agpl-3.0
editorsnotes/editorsnotes,editorsnotes/editorsnotes
1fa22ca68394d4ce55a4e10aa7c23f7bcfa02f79
zc_common/remote_resource/mixins.py
zc_common/remote_resource/mixins.py
""" Class Mixins. """ from django.db import IntegrityError from django.http import Http404 class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ if hasattr(self.request, 'quer...
""" Class Mixins. """ from django.db import IntegrityError from django.http import Http404 class MultipleIDMixin(object): """ Override get_queryset for multiple id support """ def get_queryset(self): """ Override :meth:``get_queryset`` """ if hasattr(self.request, 'quer...
Update query param for mixin
Update query param for mixin
Python
mit
ZeroCater/zc_common,ZeroCater/zc_common
c5f6a9632b6d996fc988bfc9317915208ff69a42
domain/companies.py
domain/companies.py
# -*- coding: utf-8 -*- """ 'companies' resource and schema settings. :copyright: (c) 2014 by Nicola Iarocci and CIR2000. :license: BSD, see LICENSE for more details. """ from common import required_string _schema = { # company id ('id') 'n': required_string, # name 'p': ...
# -*- coding: utf-8 -*- """ 'companies' resource and schema settings. :copyright: (c) 2014 by Nicola Iarocci and CIR2000. :license: BSD, see LICENSE for more details. """ from common import required_string _schema = { # company id ('id') 'name': required_string, 'password': {'type': 'string', ...
Add a snake_cased field to the test document.
Add a snake_cased field to the test document.
Python
bsd-3-clause
nicolaiarocci/Eve.NET-testbed
9502de0e6be30e4592f4f0cf141abc27db64ccf4
dependencies.py
dependencies.py
import os import pkgutil import site if pkgutil.find_loader("gi"): try: import gi print('Found gi:', os.path.abspath(gi.__file__)) gi.require_version('Gst', '1.0') # from gi.repository import GLib, Gst except ValueError: print('Couldn\'t find Gst') print('Please ...
import os import pkgutil import site from sys import exit if pkgutil.find_loader('gi'): try: import gi print("Found gi at:", os.path.abspath(gi.__file__)) gi.require_version('Gst', '1.0') # from gi.repository import Gst except ValueError: print("Couldn\'t find Gst", ...
Clean up of text Proper exit when exception has been raised
Clean up of text Proper exit when exception has been raised
Python
mit
Kane610/axis
08cbb4ebd44b5dca26d55a0e177c03930a2beb57
stopspam/forms/widgets.py
stopspam/forms/widgets.py
from django import forms from django.utils.translation import ugettext as _, get_language from django.utils.safestring import mark_safe # RECAPTCHA widgets class RecaptchaResponse(forms.Widget): def render(self, *args, **kwargs): from recaptcha.client import captcha as recaptcha recaptcha_options...
from django import forms from django.utils.translation import ugettext as _, get_language from django.utils.safestring import mark_safe # RECAPTCHA widgets class RecaptchaResponse(forms.Widget): is_hidden = True def render(self, *args, **kwargs): from recaptcha.client import captcha as recaptcha ...
Fix skipping of recaptcha field widget HTML by marking it is_hidden
Fix skipping of recaptcha field widget HTML by marking it is_hidden
Python
bsd-3-clause
pombredanne/glamkit-stopspam
3d385898592b07249b478b37854d179d27a27bbb
OmniMarkupLib/Renderers/MarkdownRenderer.py
OmniMarkupLib/Renderers/MarkdownRenderer.py
from base_renderer import * import re import markdown @renderer class MarkdownRenderer(MarkupRenderer): FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown)$') def load_settings(self, renderer_options, global_setting): super(MarkdownRenderer, self).load_settings(renderer_options, globa...
from base_renderer import * import re import markdown @renderer class MarkdownRenderer(MarkupRenderer): FILENAME_PATTERN_RE = re.compile(r'\.(md|mkdn?|mdwn|mdown|markdown|litcoffee)$') def load_settings(self, renderer_options, global_setting): super(MarkdownRenderer, self).load_settings(renderer_opti...
Add litcoffee to Markdown extensions
Add litcoffee to Markdown extensions
Python
mit
timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,timonwong/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer,Lyleo/OmniMarkupPreviewer
2216caf836c1f2864103e8930f60713c226a8464
src/sql/parse.py
src/sql/parse.py
from ConfigParser import ConfigParser from sqlalchemy.engine.url import URL def parse(cell, config): parts = [part.strip() for part in cell.split(None, 1)] if not parts: return {'connection': '', 'sql': ''} if parts[0].startswith('[') and parts[0].endswith(']'): parser = ConfigParser() ...
from ConfigParser import ConfigParser from sqlalchemy.engine.url import URL def parse(cell, config): parts = [part.strip() for part in cell.split(None, 1)] if not parts: return {'connection': '', 'sql': ''} if parts[0].startswith('[') and parts[0].endswith(']'): section = parts[0].lstrip('...
Allow DNS file to be less specific
Allow DNS file to be less specific
Python
mit
catherinedevlin/ipython-sql,catherinedevlin/ipython-sql
4522de348aab4cc99904b0bc210c223b2477b4b7
tests/config.py
tests/config.py
# our constants. import os local_path = os.path.dirname(__file__) xml_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.xml')) csv_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.csv')) bathy_raster = os.path.abspath(os.path.join(local_path, 'data', 'bathy5m_cl...
# our constants. import os local_path = os.path.dirname(__file__) xml_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.xml')) csv_doc = os.path.abspath(os.path.join(local_path, 'data', 'fagatelebay_zone.csv')) bathy_raster = os.path.abspath(os.path.join(local_path, 'data', 'bathy5m_cl...
Use pyt file instead of stand-alone tbx for testing.
Use pyt file instead of stand-alone tbx for testing.
Python
mpl-2.0
EsriOceans/btm