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
cebf3fa5cf428659960a547780e53a247a2322e8
lib/custom_data/settings_manager.py
lib/custom_data/settings_manager.py
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH (String): The file path for the settings file. SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ from lib.custom_data.xml_ops import load_xml_doc_as_object...
"""This module provides functions for saving to and loading data from the settings XML file. Attributes: SETTINGS_PATH (String): The file path for the settings file. SETTINGS_SCHEMA_PATH (String): The file path for the settings' XML Schema. """ from lib.custom_data.settings_data import SettingsData fro...
Use default settings in case of file read errors
Use default settings in case of file read errors
Python
unlicense
MarquisLP/Sidewalk-Champion
7015766b70bf56f9338713c4302aa3cba75510c5
app/tests/test_views.py
app/tests/test_views.py
from django.test import TestCase from django.core.urlresolvers import reverse class IndexViewCase(TestCase): """Index view case""" def setUp(self): self.url = reverse('home') def test_get_ok(self): """Test status=200""" response = self.client.get(self.url) self.assertEqua...
import sure from django.test import TestCase from django.core.urlresolvers import reverse class IndexViewCase(TestCase): """Index view case""" def setUp(self): self.url = reverse('home') def test_get_ok(self): """Test status=200""" response = self.client.get(self.url) res...
Use sure in app tests
Use sure in app tests
Python
mit
nvbn/coviolations_web,nvbn/coviolations_web
d8e054df4810ad2c32cd61c41391e0ee1b542a66
ipython_widgets/__init__.py
ipython_widgets/__init__.py
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None: ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
from .widgets import * # Register a comm target for Javascript initialized widgets.. from IPython import get_ipython ip = get_ipython() if ip is not None and hasattr(ip, 'kernel') and hasattr(ip.kernel, 'comm_manager'): ip.kernel.comm_manager.register_target('ipython.widget', Widget.handle_comm_opened)
Make it possible to import ipython_widgets without having a kernel or comm manager
Make it possible to import ipython_widgets without having a kernel or comm manager
Python
bsd-3-clause
ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,...
03491b6c11964f18f7c1867ef9f2612761a006ae
test/config/nsuserdefaults_config.py
test/config/nsuserdefaults_config.py
import unittest if sys.platform.startswith('darwin'): from nativeconfig.config import NSUserDefaultsConfig from test.config import TestConfigMixin class MyNSUserDefaultsConfig(NSUserDefaultsConfig): pass class TestMemoryConfig(unittest.TestCase, TestConfigMixin): CONFIG_TYPE = MyNSU...
import sys import unittest if sys.platform.startswith('darwin'): from nativeconfig.config import NSUserDefaultsConfig from test.config import TestConfigMixin class MyNSUserDefaultsConfig(NSUserDefaultsConfig): pass class TestMemoryConfig(unittest.TestCase, TestConfigMixin): CONFIG_T...
Add missing import of sys.
Add missing import of sys.
Python
mit
GreatFruitOmsk/nativeconfig
3f5a73f39451e73b2f32fe3a05888f118952e591
ppp_datamodel/utils.py
ppp_datamodel/utils.py
"""Utilities for using the PPP datamodel.""" from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort def contains_missing(tree): def predicate(node, childs): if isinstance(node, Missing): return True else: return any(childs.val...
"""Utilities for using the PPP datamodel.""" from . import Resource, Triple, Missing, Intersection, List, Union, And, Or, Exists, First, Last, Sort def contains_missing(tree): def predicate(node, childs): if isinstance(node, Missing): return True else: return any(childs.val...
Fix isincluded for List operators.
Fix isincluded for List operators.
Python
agpl-3.0
ProjetPP/PPP-datamodel-Python,ProjetPP/PPP-datamodel-Python
c37cafb9c83e9f9bcc806cdb979f127fe924fa00
tools/get_binary.py
tools/get_binary.py
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: pars...
#!/usr/bin/env python import os import sys import shutil from version import full_version from optparse import OptionParser import pkgutils def main(): usage = "usage: %prog [destination path]" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() if len(args) != 1: pars...
Revert "remove the dest tree and recreate it"
Revert "remove the dest tree and recreate it" This reverts commit becc4657acea505594836e62c49de2b4cb0160a9.
Python
apache-2.0
christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-m...
db580bc3a433f15b31c21fbeac39fc2e40e85cdd
km3pipe/io/tests/test_ch.py
km3pipe/io/tests/test_ch.py
# Filename: test_ch.py # pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212 from km3pipe.testing import TestCase, patch, Mock from km3pipe.io.ch import CHPump __author__ = "Tamas Gal" __copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer...
# Filename: test_ch.py # pylint: disable=locally-disabled,C0111,R0904,C0301,C0103,W0212 from km3pipe.testing import TestCase, patch, Mock from km3pipe.io.ch import CHPump __author__ = "Tamas Gal" __copyright__ = "Copyright 2018, Tamas Gal and the KM3NeT collaboration." __credits__ = [] __license__ = "MIT" __maintainer...
Add a test for CHPump
Add a test for CHPump
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
072944268a5932875532d53237f9fdfd26406c2d
thrive_refugee/urls.py
thrive_refugee/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'thrive_refugee.views.home', name='home'), # url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')), # Uncomment the admin/doc line below...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'thrive_refugee.views.home', name='home'), # url(r'^thrive_refugee/', include('thrive_refugee.foo.urls')), # Uncomment the admin/doc line below...
Set root route to point to admin
Set root route to point to admin
Python
mit
thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee,thrive-refugee/thrive-refugee
6ff07265feaf40e20fe0fbd23df2747660dd0483
trex/serializers.py
trex/serializers.py
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import ( HyperlinkedModelSerializer, HyperlinkedIdentityField, ) from trex.models.project import Project, Entry class ProjectSerializer(Hype...
# -*- coding: utf-8 -*- # # (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com> # # See LICENSE comming with the source of 'trex' for details. # from rest_framework.serializers import ( HyperlinkedModelSerializer, HyperlinkedIdentityField, ) from trex.models.project import Project, Entry class ProjectSerializer(Hype...
Add url, id and trags to the EntriesSerializer
Add url, id and trags to the EntriesSerializer
Python
mit
bjoernricks/trex,bjoernricks/trex
aac11d0d9805559000635b24227a8d13314feaa1
booksforcha/booksforcha.py
booksforcha/booksforcha.py
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
# -*- coding: utf-8 -*- import schedule from feed import load_feed from twitter import send_queued_tweet import time import os RSS_FEED_LIST = os.environ['RSS_FEED_LIST'] LOAD_FEED_SECONDS = int(os.environ['LOAD_FEED_SECONDS']) SEND_QUEUED_TWEET_SECONDS = int(os.environ['SEND_QUEUED_TWEET_SECONDS']) def parse_feed...
Move process scheduling out of main.
Move process scheduling out of main.
Python
mit
ChattanoogaPublicLibrary/booksforcha
017b01a1df6e7095aac78d2c859125bf7107095a
plugins/random/plugin.py
plugins/random/plugin.py
import random import re from cardinal.decorators import command def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$', arg)...
import random import re from cardinal.decorators import command, help def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$'...
Add help text for roll command
Add help text for roll command
Python
mit
JohnMaguire/Cardinal
948e5b89db6056cd6a5065f8a5411113f6b320a7
zc-list.py
zc-list.py
#!/usr/bin/env python import client_wrap def main(): client = client_wrap.ClientWrap("get_test.log", "ipc:///var/run/zero-cache/0", 0) key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: return print keys if __name__ == "__main__": main()
#!/usr/bin/env python import sys import client_wrap def get_keys(client): key_str = client.GetKeys() keys = key_str.split (';') del keys[-1] if len(keys) == 0: sys.exit() return keys def print_keys(client, keys): for key in keys: value = client.ReadLong(key) print "%...
Implement formatted list of keys and values in output
Implement formatted list of keys and values in output
Python
agpl-3.0
ellysh/zero-cache-utils,ellysh/zero-cache-utils
4987275ab868aa98359d6583c7817c4adf09000b
zipeggs.py
zipeggs.py
import logging, os, zc.buildout, sys, shutil class ZipEggs: def __init__(self, buildout, name, options): self.name, self.options = name, options if options['target'] is None: raise zc.buildout.UserError('Invalid Target') if options['source'] is None: raise zc.buildou...
import logging, os, zc.buildout, sys, shutil class ZipEggs: def __init__(self, buildout, name, options): self.name, self.options = name, options if options['target'] is None: raise zc.buildout.UserError('Invalid Target') if options['source'] is None: raise zc.buildou...
Improve variable names for clarity
Improve variable names for clarity
Python
apache-2.0
tamizhgeek/zipeggs
7396b20c3ee1b037580463c9a653e782c197e536
xdocker/run_worker.py
xdocker/run_worker.py
from rq import Connection, Queue, Worker def worker_exc_handler(job, exc_type, exc_value, traceback): job.meta['exc_code'] = exc_type.code job.meta['exc_message'] = exc_type.message return True def main(): with Connection(): q = Queue() worker = Worker([q]) worker.push_exc_ha...
from rq import Connection, Queue, Worker from worker.exceptions import WorkerException def worker_exc_handler(job, exc_type, exc_value, traceback): if isinstance(exc_type, WorkerException): job.meta['exc_code'] = exc_type.code job.meta['exc_message'] = exc_type.message return True def main()...
Fix worker exception handler for non workerexceptions
Fix worker exception handler for non workerexceptions
Python
apache-2.0
XDocker/Engine,XDocker/Engine
260cb862f5324387d796826d76ff224c01ca5036
localore/localore_admin/migrations/0003_auto_20160316_1646.py
localore/localore_admin/migrations/0003_auto_20160316_1646.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('localore_admin', '0002_auto_20160316_1444'), ] operations = [ migrations.RenameField( model_name='localoreimage'...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('localore_admin', '0002_auto_20160316_1444'), ] run_before = [ ('home', '0002_create_homepage'), ] operations = [ ...
Fix migrations dependency issue caused by 990563e.
Fix migrations dependency issue caused by 990563e.
Python
mpl-2.0
ghostwords/localore,ghostwords/localore,ghostwords/localore
3d5902b341e15a6d5f8ba1599902b6f9327a021b
typedjsonrpc/errors.py
typedjsonrpc/errors.py
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__() self.data = data def as_error_object(self): """Turns the...
"""This module defines error classes for typedjsonrpc.""" class Error(Exception): """Base class for all errors.""" code = 0 message = None data = None def __init__(self, data=None): super(Error, self).__init__(self.code, self.message, data) self.data = data def as_error_objec...
Make exception messages more descriptive
Make exception messages more descriptive
Python
apache-2.0
palantir/typedjsonrpc,palantir/typedjsonrpc
489129bd26f72967fbbc279ab488fe047714a250
qual/tests/test_iso.py
qual/tests/test_iso.py
import unittest from hypothesis import given from hypothesis.extra.datetime import datetimes import qual from datetime import date class TestIsoUtils(unittest.TestCase): @given(datetimes()) def test_round_trip_date(self, dt): d = dt.date() self.assertEqual(qual.iso_to_gregorian(*d.isocalendar...
import unittest from hypothesis import given from hypothesis.extra.datetime import datetimes import qual from datetime import date class TestIsoUtils(unittest.TestCase): @given(datetimes(timezones=[])) def test_round_trip_date(self, dt): d = dt.date() self.assertEqual(qual.iso_to_gregorian(*d...
Use timezones=[] to underline that we only care about dates.
Use timezones=[] to underline that we only care about dates.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
b72f0ed25750a29b5dc1cdd2790102d8351606f9
pronto_feedback/feedback/views.py
pronto_feedback/feedback/views.py
import csv from datetime import datetime from django.shortcuts import render from django.utils import timezone from django.views.generic import TemplateView from .forms import FeedbackUploadForm from .models import Feedback class FeedbackView(TemplateView): template_name = 'index.html' def get(self, reques...
import csv from datetime import datetime from django.shortcuts import render from django.utils import timezone from django.views.generic import TemplateView from .forms import FeedbackUploadForm from .models import Feedback class FeedbackView(TemplateView): template_name = 'index.html' def get(self, reques...
Use next method of reader object
Use next method of reader object
Python
mit
zkan/pronto-feedback,zkan/pronto-feedback
8780d2eb3d7782e7f1e6c23e2e428a72e6bd3dad
server/kcaa/manipulator_util_test.py
server/kcaa/manipulator_util_test.py
#!/usr/bin/env python import pytest import manipulator_util class TestManipulatorManager(object): def pytest_funcarg__manager(self, request): return manipulator_util.ManipulatorManager(None, {}, 0) def test_in_schedule_fragment(self): in_schedule_fragment = ( manipulator_util.M...
#!/usr/bin/env python import pytest import manipulator_util class TestManipulatorManager(object): def pytest_funcarg__manager(self, request): return manipulator_util.ManipulatorManager(None, {}, 0) def test_in_schedule_fragment(self): in_schedule_fragment = ( manipulator_util.M...
Add a test for one schedule fragment.
Add a test for one schedule fragment.
Python
apache-2.0
kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa
3987f059632c64058862425407cdc165d4f3182b
python/qisrc/test/test_qisrc_list.py
python/qisrc/test/test_qisrc_list.py
from qisys import ui def test_list_tips_when_empty(qisrc_action, record_messages): qisrc_action("init") qisrc_action("list") assert ui.find_message("Tips")
from qisys import ui def test_list_tips_when_empty(qisrc_action, record_messages): qisrc_action("init") qisrc_action("list") assert ui.find_message("Tips") def test_list_with_pattern(qisrc_action, record_messages): qisrc_action.git_worktree.create_git_project("foo") qisrc_action.git_worktree.creat...
Add test for qisrc list
Add test for qisrc list Change-Id: I04c08f60044ffb0ba2ff63141d085e4dc2545455
Python
bsd-3-clause
dmerejkowsky/qibuild,aldebaran/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild
06dc49becd393e07086e368b26ab1aea3a9bc149
pyelasticsearch/tests/__init__.py
pyelasticsearch/tests/__init__.py
""" Unit tests for pyelasticsearch These require an elasticsearch server running on the default port (localhost:9200). """ import unittest from nose.tools import eq_ # Test that __all__ is sufficient: from pyelasticsearch import * class ElasticSearchTestCase(unittest.TestCase): def setUp(self): self.co...
""" Unit tests for pyelasticsearch These require a local elasticsearch server running on the default port (localhost:9200). """ from time import sleep from unittest import TestCase from nose import SkipTest from nose.tools import eq_ from six.moves import xrange # Test that __all__ is sufficient: from pyelasticsearc...
Add a wait to see if we can get Travis passing again.
Add a wait to see if we can get Travis passing again.
Python
bsd-3-clause
erikrose/pyelasticsearch
fbb0abe3bdb62ec64bfdd03f9b45ded4def9613a
wsgi_intercept/test/test_mechanize.py
wsgi_intercept/test/test_mechanize.py
from nose.tools import with_setup, raises from urllib2 import URLError from wsgi_intercept.mechanize_intercept import Browser import wsgi_intercept from wsgi_intercept import test_wsgi_app from mechanize import Browser as MechanizeBrowser ### _saved_debuglevel = None def add_intercept(): # _saved_debuglevel, ws...
from urllib2 import URLError from wsgi_intercept import testing from wsgi_intercept.testing import unittest from wsgi_intercept.test import base try: import mechanize has_mechanize = True except ImportError: has_mechanize = False _skip_message = "mechanize is not installed" @unittest.skipUnless(has_mecha...
Use unittest in the mechanize related tests.
Use unittest in the mechanize related tests.
Python
mit
pumazi/wsgi_intercept2
697c590bf60c261280e55f8580b33423dbe800c6
splinter/driver/webdriver/firefox.py
splinter/driver/webdriver/firefox.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from selenium.webdriver import Firefox from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement from splinter.driver.webdriver.cookie_manager import...
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from selenium.webdriver import Firefox from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement from splinter.driver.webdriver.cookie_manager import...
Fix error on Firefox 6 where pages are not open if this preference is True (default).
Fix error on Firefox 6 where pages are not open if this preference is True (default).
Python
bsd-3-clause
bmcculley/splinter,cobrateam/splinter,bmcculley/splinter,nikolas/splinter,drptbl/splinter,objarni/splinter,nikolas/splinter,cobrateam/splinter,drptbl/splinter,underdogio/splinter,underdogio/splinter,bubenkoff/splinter,lrowe/splinter,bubenkoff/splinter,lrowe/splinter,objarni/splinter,gjvis/splinter,bmcculley/splinter,un...
0e3952c0648375810b479d093e970d072db0fe6d
app/resources/forms.py
app/resources/forms.py
from flask.ext.wtf import Form from wtforms.fields import ( StringField, IntegerField, SubmitField ) from wtforms.validators import InputRequired, Length class ResourceForm(Form): autocomplete = StringField('Enter the address') name = StringField('Name', validators=[ InputRequired(), ...
from flask.ext.wtf import Form from wtforms.fields import ( StringField, IntegerField, SubmitField ) from wtforms.validators import InputRequired, Length class ResourceForm(Form): autocomplete = StringField('Enter the address') name = StringField('Name', validators=[ InputRequired(), ...
Comment about form field names for Google Autocomplete
Comment about form field names for Google Autocomplete
Python
mit
hack4impact/women-veterans-rock,hack4impact/women-veterans-rock,hack4impact/women-veterans-rock
992b3302c4cb690e86436c54c43d0bb2aa406b0d
scrapi/harvesters/hacettepe_U_DIM.py
scrapi/harvesters/hacettepe_U_DIM.py
''' Harvester for the DSpace on LibLiveCD for the SHARE project Example API call: http://bbytezarsivi.hacettepe.edu.tr/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import OAIHarvester class Hacettepe_u_dimHarvester(OAIHarvester): short_name = 'h...
''' Harvester for the DSpace on LibLiveCD for the SHARE project Example API call: http://bbytezarsivi.hacettepe.edu.tr/oai/request?verb=ListRecords&metadataPrefix=oai_dc ''' from __future__ import unicode_literals from scrapi.base import OAIHarvester class HacettepeHarvester(OAIHarvester): short_name = 'hacette...
Change shortname and class name
Change shortname and class name
Python
apache-2.0
alexgarciac/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,ostwald/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,jeffreyliu3230/scrapi,mehanig/scrapi,erinspace/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi
312c0d463940257cb1f777d3720778550b5bdb2d
bluebottle/organizations/serializers.py
bluebottle/organizations/serializers.py
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_l...
from rest_framework import serializers from bluebottle.organizations.models import Organization from bluebottle.utils.serializers import URLField class OrganizationSerializer(serializers.ModelSerializer): class Meta: model = Organization fields = ('id', 'name', 'slug', 'address_line1', 'address_l...
Revert "Make the name of an organization required"
Revert "Make the name of an organization required" This reverts commit 02140561a29a2b7fe50f7bf2402da566e60be641.
Python
bsd-3-clause
jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
80fa2f3c47ddc845d4dc9e549df38f68267873d6
corehq/ex-submodules/pillow_retry/tasks.py
corehq/ex-submodules/pillow_retry/tasks.py
from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db.models import Count from corehq.util.datadog.gauges import datadog_gauge from pillow_retry.models import PillowError @periodic_task( run_every=crontab(minute="*/15"), queue=settings.CELE...
from celery.schedules import crontab from celery.task import periodic_task from django.conf import settings from django.db.models import Count from corehq.util.datadog.gauges import datadog_gauge from pillow_retry.models import PillowError @periodic_task( run_every=crontab(minute="*/15"), queue=settings.CELE...
Send error-type info to pillow error DD metrics
Send error-type info to pillow error DD metrics
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
3c64002217795e5d8d3eebb7b06f8ad72f342564
thinglang/parser/tokens/functions.py
thinglang/parser/tokens/functions.py
from thinglang.lexer.symbols.base import LexicalAccess from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thinglang.utils.type_descriptors import ValueType class Access(BaseToken): def __init__(self...
from thinglang.lexer.symbols.base import LexicalAccess, LexicalIdentifier from thinglang.lexer.symbols.functions import LexicalClassInitialization from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thingl...
Add proper support for constructor calls to MethodCall
Add proper support for constructor calls to MethodCall
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
acd84f19d8d8820aecdba62bf4d0c97a2d4bdf34
src/source_weather/source_weather.py
src/source_weather/source_weather.py
""" Definition of a source than add dumb data """ from src.source import Source class SourceMock(Source): """Add a funny key with a funny value in the given dict""" def __init__(self, funny_message="Java.OutOfMemoryError" funny_key="Who's there ?"): self.funny_message = funny_message...
""" Definition of a source than add dumb data """ from src.source import Source from . import weather class SourceWeaver(Source): """ Throught Open Weather Map generates today weather and expected weather for next days, if possible """ def enrichment(self, data_dict): if default.FIELD_CO...
Access to actual or predicted weather done
Access to actual or predicted weather done
Python
unlicense
Aluriak/24hducode2016,Aluriak/24hducode2016
d8e876fc60d96f0d635862e845ae565ef3e2afb9
openpnm/models/geometry/__init__.py
openpnm/models/geometry/__init__.py
r""" **openpnm.models.geometry** ---- This submodule contains pore-scale models that calculate geometrical properties """ from . import pore_size from . import pore_seed from . import pore_volume from . import pore_surface_area from . import pore_area from . import throat_area from . import throat_equivalent_area ...
r""" **openpnm.models.geometry** ---- This submodule contains pore-scale models that calculate geometrical properties """ from . import pore_size from . import pore_seed from . import pore_volume from . import pore_surface_area from . import pore_area from . import throat_centroid from . import throat_area from . ...
Update init file in models.geometry
Update init file in models.geometry
Python
mit
TomTranter/OpenPNM,PMEAL/OpenPNM
41221b36a596b1253445f1e49b10bff1fc44be42
tests/test_it.py
tests/test_it.py
import requests def test_notifications_admin_index(): response = requests.request("GET", "http://notifications-admin.herokuapp.com/index") assert response.status_code == 200 # assert response.content == 'Hello from notifications-admin'
import requests def test_notifications_admin_index(): # response = requests.request("GET", "http://localhost:6012") response = requests.request("GET", "http://notifications-admin.herokuapp.com/") assert response.status_code == 200 assert 'GOV.UK Notify' in response.content
Fix test for initial registration page flow
Fix test for initial registration page flow
Python
mit
alphagov/notifications-functional-tests,alphagov/notifications-functional-tests
15cb312fd7acbb7fae67cb3953537a95274f9d40
saleor/search/forms.py
saleor/search/forms.py
from __future__ import unicode_literals from django import forms from django.utils.translation import pgettext from .backends import elasticsearch class SearchForm(forms.Form): q = forms.CharField( label=pgettext('Search form label', 'Query'), required=True) def search(self): return elastics...
from __future__ import unicode_literals from django import forms from django.utils.translation import pgettext from .backends import picker class SearchForm(forms.Form): q = forms.CharField( label=pgettext('Search form label', 'Query'), required=True) def search(self): search = picker.pick_b...
Use backend picker in storefront search form
Use backend picker in storefront search form
Python
bsd-3-clause
UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,maferelo/saleor
422a75e4b85345bd517c73760430ae773d49dc00
var/spack/packages/arpack/package.py
var/spack/packages/arpack/package.py
from spack import * class Arpack(Package): """FIXME: put a proper description of your package here.""" homepage = "http://www.caam.rice.edu/software/ARPACK/" url = "http://www.caam.rice.edu/software/ARPACK/SRC/arpack96.tar.gz" version('96', 'fffaa970198b285676f4156cebc8626e') depends_on('bla...
from spack import * class Arpack(Package): """A collection of Fortran77 subroutines designed to solve large scale eigenvalue problems. """ homepage = "http://www.caam.rice.edu/software/ARPACK/" url = "http://www.caam.rice.edu/software/ARPACK/SRC/arpack96.tar.gz" version('96', 'fffaa970...
Clean up arpack build, use the Spack f77 compiler.
Clean up arpack build, use the Spack f77 compiler.
Python
lgpl-2.1
TheTimmy/spack,tmerrick1/spack,mfherbst/spack,lgarren/spack,iulian787/spack,lgarren/spack,skosukhin/spack,krafczyk/spack,iulian787/spack,EmreAtes/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,matthiasdiener/spack,mfherbst/spack,skosukhin/spack,matthiasdiener/spack,LLNL/spack,krafczyk/spack,EmreAtes/spack,EmreAte...
e8ca2582404d44a6bc97f455187523713c49d90f
test/test_random_seed.py
test/test_random_seed.py
from nose.tools import assert_equal import genson def test_gaussian_random_seed(): gson = \ """ { "gaussian_random_seed" : gaussian(0, 1, draws=1, random_seed=42) } """ val = genson.loads(gson).next()['gaussian_random_seed'] assert_equal(val, 0.4967141530112327) def test_gaussian...
from nose.tools import assert_equal import genson def test_gaussian_random_seed(): gson = \ """ { "gaussian_random_seed" : gaussian(0, 1, draws=2, random_seed=42) } """ vals = [val['gaussian_random_seed'] for val in genson.loads(gson)] assert_equal(vals[0], 0.4967141530112327) ...
Add RandomState to help generate different values, with test
Add RandomState to help generate different values, with test
Python
mit
davidcox/genson
1bb86e33c8862b5423d292ccc1bd74c560af2e44
vinotes/apps/api/models.py
vinotes/apps/api/models.py
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Winery) def __str__(sel...
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Winery) def __str__(sel...
Update to include vintage in string representation for Wine.
Update to include vintage in string representation for Wine.
Python
unlicense
rcutmore/vinotes-api,rcutmore/vinotes-api
10a0d12f39760d2c2d57f66bc445f0cb87cde69f
django_website/aggregator/management/commands/mark_defunct_feeds.py
django_website/aggregator/management/commands/mark_defunct_feeds.py
import urllib2 from django.core.management.base import BaseCommand from django_website.apps.aggregator.models import Feed class Command(BaseCommand): """ Mark people with 404'ing feeds as defunct. """ def handle(self, *args, **kwargs): verbose = kwargs.get('verbosity') for f in Feed.obj...
import urllib2 from django.core.management.base import BaseCommand from django_website.apps.aggregator.models import Feed class Command(BaseCommand): """ Mark people with 404'ing feeds as defunct. """ def handle(self, *args, **kwargs): verbose = kwargs.get('verbosity') for f in Feed.obj...
Set feed update timeouts in a more modern way.
Set feed update timeouts in a more modern way.
Python
bsd-3-clause
vxvinh1511/djangoproject.com,gnarf/djangoproject.com,hassanabidpk/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,nanuxbe/django,django/djangoproject.com,hassanabidpk/djangoproject.com,django/djangoproject.com,xavierdutreilh/djangoproject.com,gnarf/djangoprojec...
450cb155d87b49a718e465d582bd2ccafb3244dd
tests/test_calculator.py
tests/test_calculator.py
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, resu...
import unittest from app.calculator import Calculator class TestCalculator(unittest.TestCase): def setUp(self): self.calc = Calculator() def test_calculator_addition_method_returns_correct_result(self): calc = Calculator() result = calc.addition(2,2) self.assertEqual(4, resu...
Add new test for division
Add new test for division
Python
apache-2.0
kamaxeon/fap
472110a92d15358aee6aeb6dd007f4d237a6fad6
compile/06-switch.dg.py
compile/06-switch.dg.py
..compile = import ..parse.syntax = import compile.r.builtins !! 'else' = (self, cond, otherwise) -> ''' a if b else c a unless b else c Ternary conditional. ''' is_if, (then, cond) = parse.syntax.else_: cond ptr = self.opcode: 'POP_JUMP_IF_TRUE' cond delta: 0 if is_if ptr = self.op...
..compile = import ..parse.syntax = import compile.r.builtins !! 'else' = (self, cond, otherwise) -> ''' a if b else c a unless b else c Ternary conditional. ''' is_if, (then, cond) = parse.syntax.else_: cond ptr = self.opcode: 'POP_JUMP_IF_FALSE' cond delta: 0 if is_if ptr = self.op...
Swap opcodes for if-else and unless-else.
Swap opcodes for if-else and unless-else. Oops.
Python
mit
pyos/dg
0c3bbe815275b06729cdb52668b38f3a83e7fbac
datacommons/crawlers/zz/icij_dump.py
datacommons/crawlers/zz/icij_dump.py
from normality import slugify, stringify from csv import DictReader from zipfile import ZipFile def load_file(context, zip, name): fh = zip.open(name) _, section, _ = name.rsplit(".", 2) table_name = "%s_%s" % (context.crawler.name, section) table = context.datastore[table_name] table.drop() r...
import io from csv import DictReader from zipfile import ZipFile from normality import slugify, stringify from dataset.chunked import ChunkedInsert def load_file(context, zip, name): fh = zip.open(name) _, section, _ = name.rsplit(".", 2) table_name = "%s_%s" % (context.crawler.name, section) table = ...
Fix up ICIJ loader as-is
Fix up ICIJ loader as-is
Python
mit
pudo/flexicadastre
8f4c376a57c68636188880cd92c64b4640b1c8cc
sheared/web/entwine.py
sheared/web/entwine.py
import warnings from dtml import tal, metal, tales, context from sheared.python import io class Entwiner: def __init__(self): self.builtins = context.BuiltIns({}) #self.context = context.Context() #self.context.setDefaults(self.builtins) def handle(self, request, reply, subpath): ...
import warnings from dtml import tal, metal, tales from sheared.python import io class Entwiner: def handle(self, request, reply, subpath): self.context = {} self.entwine(request, reply, subpath) r = self.execute(self.page_path, throwaway=0) reply.send(r) def execute(self, pa...
Remove the builtins arguments to the {tal,metal}.execute calls.
Remove the builtins arguments to the {tal,metal}.execute calls. git-svn-id: 8b0eea19d26e20ec80f5c0ea247ec202fbcc1090@107 5646265b-94b7-0310-9681-9501d24b2df7
Python
mit
kirkeby/sheared
a463fe25f21194744e9979840b7535f6cd765e36
core/plugins/command.py
core/plugins/command.py
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os from ..quokka import ExternalProcess, PluginException class ConsoleApplication(ExternalProce...
# coding: utf-8 # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os import shlex from ..quokka import ExternalProcess, PluginException class ConsoleApplication(...
Use shlex to split parameters
Use shlex to split parameters
Python
mpl-2.0
MozillaSecurity/quokka,drptbl/quokka
a1db577312a31f73a0f1c9f04cc65871f2ef1c95
dbaas/maintenance/admin/maintenance.py
dbaas/maintenance/admin/maintenance.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.utils.translation import ugettext_lazy as _ from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService class MaintenanceAdmin(admin.DjangoServicesAdmin): servi...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.utils.translation import ugettext_lazy as _ from django_services import admin from ..models import Maintenance from ..service.maintenance import MaintenanceService class MaintenanceAdmin(admin.DjangoServicesAdmin): servi...
Change field order and customize Maintenance add_view
Change field order and customize Maintenance add_view
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
2d0a96403d58c4a939b17e67f8f93190839ff340
txircd/modules/cmd_ping.py
txircd/modules/cmd_ping.py
from twisted.words.protocols import irc from txircd.modbase import Command class PingCommand(Command): def onUse(self, user, data): if data["params"]: user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"], prefix=None) else: user.sendMessage(irc.ERR_NOORIGIN, ":No ...
from twisted.words.protocols import irc from txircd.modbase import Command class PingCommand(Command): def onUse(self, user, data): if data["params"]: user.sendMessage("PONG", ":{}".format(data["params"][0]), to=self.ircd.servconfig["server_name"]) else: user.sendMessage(irc.ERR_NOORIGIN, ":No origin specif...
Send the server prefix on the line when the client sends PING
Send the server prefix on the line when the client sends PING
Python
bsd-3-clause
Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd
8fd62b820cb03b1dcfc3945f612ca43f916b86a2
prettyplotlib/_eventplot.py
prettyplotlib/_eventplot.py
__author__ = 'jgosmann' from prettyplotlib.utils import remove_chartjunk, maybe_get_ax from prettyplotlib.colors import set2 def eventplot(*args, **kwargs): ax, args, kwargs = maybe_get_ax(*args, **kwargs) show_ticks = kwargs.pop('show_ticks', False) # FIXME 1d positions if len(args) > 0: po...
__author__ = 'jgosmann' from matplotlib.cbook import iterable from prettyplotlib.utils import remove_chartjunk, maybe_get_ax from prettyplotlib.colors import set2 def eventplot(*args, **kwargs): ax, args, kwargs = maybe_get_ax(*args, **kwargs) show_ticks = kwargs.pop('show_ticks', False) if len(args) >...
Fix eventplot for 1d arguments.
Fix eventplot for 1d arguments.
Python
mit
olgabot/prettyplotlib,olgabot/prettyplotlib
21cf7d8dddad631975760ea71ef4f530acecf393
hello.py
hello.py
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello(): return render_template('hello.html')
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def hello(): return render_template('hello.html') if __name__ == '__main__': app.run()
Allow running the app from cli
Allow running the app from cli
Python
mit
siavashg/tictail-heroku-flask-app,siavashg/tictail-heroku-flask-app
f64f0b42f2d1163b2d85194e0979def539f5dca3
Lib/fontTools/misc/intTools.py
Lib/fontTools/misc/intTools.py
__all__ = ['popCount'] def popCount(v): """Return number of 1 bits (population count) of an integer. If the integer is negative, the number of 1 bits in the twos-complement representation of the integer is returned. i.e. ``popCount(-30) == 28`` because -30 is:: 1111 1111 1111 1111 1111 1111 ...
__all__ = ['popCount'] try: bit_count = int.bit_count except AttributeError: def bit_count(v): return bin(v).count('1') """Return number of 1 bits (population count) of the absolute value of an integer. See https://docs.python.org/3.10/library/stdtypes.html#int.bit_count """ popCount = bit_count
Consolidate bit_count / popCount methods
Consolidate bit_count / popCount methods Fixes https://github.com/fonttools/fonttools/issues/2331
Python
mit
googlefonts/fonttools,fonttools/fonttools
5cb2d684ac3a0f99153cf88649b1f9d5274e4c76
seo/escaped_fragment/app.py
seo/escaped_fragment/app.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): ...
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. from subprocess import check_output from urllib import unquote def application(env, start_response): status = "200 OK" response = "" qs = env.get("QUERY_STRING", None) if not qs or not qs.startswith("_escaped_fragment_="): ...
Enable disk cache for PhJS
Enable disk cache for PhJS
Python
apache-2.0
orgkhnargh/platformio-web,platformio/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web,orgkhnargh/platformio-web
ea887d44f7e66d48036ffa81d678311de3857271
jsonpickle/handlers.py
jsonpickle/handlers.py
class BaseHandler(object): """ Abstract base class for handlers. """ def __init__(self, base): """ Initialize a new handler to handle `type`. :Parameters: - `base`: reference to pickler/unpickler """ self._base = base def flatten(self, obj, data):...
class BaseHandler(object): """ Abstract base class for handlers. """ def __init__(self, base): """ Initialize a new handler to handle `type`. :Parameters: - `base`: reference to pickler/unpickler """ self._base = base def flatten(self, obj, data):...
Remove usage of built-in 'type' name
jsonpickle.handler: Remove usage of built-in 'type' name 'type' is a built-in function so use 'cls' instead of 'type'. Signed-off-by: David Aguilar <9de348c050f7cd1ca590883733c4e531ce610bf4@gmail.com>
Python
bsd-3-clause
dongguangming/jsonpickle,eoghanmurray/jsonpickle_prev,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,eoghanmurray/jsonpickle_prev
adfaff320066422734c28759688f75e3f127078c
icekit/plugins/contact_person/models.py
icekit/plugins/contact_person/models.py
import os from django.core.urlresolvers import NoReverseMatch from fluent_contents.models import ContentItem from fluent_pages.urlresolvers import app_reverse, PageTypeNotMounted from icekit.publishing.models import PublishingModel from timezone import timezone from django.db import models from django.utils.encoding im...
from fluent_contents.models import ContentItem from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class ContactPerson(models.Model): name = models.CharField(max_length=255) title = mode...
Repair 500 viewing contact person
Repair 500 viewing contact person
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
92676c0e84df0e1c0d14766b339410d09c60b5fb
froide/helper/forms.py
froide/helper/forms.py
from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib.admin.widgets import ForeignKeyRawIdWidget from taggit.forms import TagField from taggit.utils import edit_string_for_tags from .widgets import TagAutocompleteWidget class TagObjectForm(forms.Form): def __init__...
from django.utils.translation import ugettext_lazy as _ from django import forms from django.contrib.admin.widgets import ForeignKeyRawIdWidget from taggit.forms import TagField from taggit.utils import edit_string_for_tags from .widgets import TagAutocompleteWidget class TagObjectForm(forms.Form): def __init__...
Make empty tag form valid
Make empty tag form valid
Python
mit
stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
ea20f912696974a2543a8fa15f63f0a3b64d7263
froide/helper/utils.py
froide/helper/utils.py
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): retu...
from django.shortcuts import render def get_next(request): # This is not a view return request.GET.get("next", request.META.get("HTTP_REFERER", "/")) def render_code(code, request, context={}): return render(request, "%d.html" % code, context, status=code) def render_400(request): retu...
Add utility function to get client IP from request
Add utility function to get client IP from request
Python
mit
ryankanno/froide,fin/froide,CodeforHawaii/froide,fin/froide,catcosmo/froide,LilithWittmann/froide,okfse/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,stefanw/froide,fin/froide,stefanw/froide,catcosmo/froide,okfse/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,catcosmo/froide,LilithWittmann/fro...
486156f344af66fa762e6321d52e26b40c734e38
login.py
login.py
''' The user login module for SaltBot ''' import requests import os from dotenv import load_dotenv, find_dotenv URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1' def saltbot_login(): # Default the return values to None session = None request = None # Start a session so we can have persist...
''' The user login module for SaltBot ''' import requests import os from dotenv import load_dotenv, find_dotenv URL_SIGNIN = 'https://www.saltybet.com/authenticate?signin=1' def saltbot_login(): # Default the return values to None session = None request = None # Start a session so we can have persist...
Add check for Heroku before .env import
Add check for Heroku before .env import Heroku was rightfully breaking when loadenv() was called as it already had the proper environment variables. Add a check for Heroku before loading the variables.
Python
mit
Jacobinski/SaltBot
638e9761a6a42a8ab9d8eb7996b0a19d394ad3ea
precision/accounts/urls.py
precision/accounts/urls.py
from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), url( regex=r'^logout/$', ...
from django.conf.urls import url from django.contrib.auth.views import login, logout, logout_then_login, password_change, password_change_done from .views import SignInView urlpatterns = [ # Authentication # ============== url( regex=r'^login/$', view=login, name='login' ), ...
Add password change url patterns
Add password change url patterns
Python
mit
FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management
e15029d051bbfa12dd8c01709e94e6b731b243e1
djangopress/tests/test_templatetags.py
djangopress/tests/test_templatetags.py
"""Test djangopress templatetags.""" from django.template import Template, Context def test_archive_list_tag(): """Test the archive_list tag.""" template_snippet = '{% load djangopress %}{% archive_list %}' Template(template_snippet).render(Context({}))
"""Test djangopress templatetags.""" from django.template import Template, Context from djangopress.templatetags.djangopress import archive_list def test_archive_list_tag(): """Test the archive_list tag.""" template_snippet = '{% load djangopress %}{% archive_list %}' Template(template_snippet).render(Co...
Test archive_list returns a dictionary
Test archive_list returns a dictionary
Python
mit
gilmrjc/djangopress,gilmrjc/djangopress,gilmrjc/djangopress
30fa7e0137b2afae8a4b1de01fcde14bc9e7e910
iktomi/web/shortcuts.py
iktomi/web/shortcuts.py
# -*- coding: utf-8 -*- import json from webob.exc import status_map from webob import Response from .core import cases from . import filters __all__ = ['redirect_to', 'http_error', 'to_json', 'Rule'] def redirect_to(endpoint, _code=303, qs=None, **kwargs): def handle(env, data): url = env.root.build_url(...
# -*- coding: utf-8 -*- import json from webob.exc import status_map from webob import Response from .core import cases from . import filters __all__ = ['redirect_to', 'http_error', 'to_json', 'Rule'] def redirect_to(endpoint, _code=303, qs=None, **kwargs): def handle(env, data): url = env.root.build_url(...
Fix Rule: pass convs argument to match
Fix Rule: pass convs argument to match
Python
mit
boltnev/iktomi,oas89/iktomi,Lehych/iktomi,SmartTeleMax/iktomi,boltnev/iktomi,SlivTime/iktomi,SlivTime/iktomi,Lehych/iktomi,oas89/iktomi,oas89/iktomi,SlivTime/iktomi,Lehych/iktomi,SmartTeleMax/iktomi,boltnev/iktomi,SmartTeleMax/iktomi
c7e65db27da59ddf221d1720362434581ef30311
test/unit/locale/test_locale.py
test/unit/locale/test_locale.py
#!/usr/bin/env python #-*- coding:utf-8 -*- import os import unittest try: from subprocess import check_output except ImportError: from subprocess import Popen, PIPE, CalledProcessError def check_output(*popenargs, **kwargs): """Lifted from python 2.7 stdlib.""" if 'stdout' in kwargs: ...
#!/usr/bin/env python #-*- coding:utf-8 -*- import os import unittest import string import sys try: from subprocess import check_output except ImportError: from subprocess import Popen, PIPE, CalledProcessError def check_output(*popenargs, **kwargs): """Lifted from python 2.7 stdlib.""" i...
Make test_translations test our tree
Make test_translations test our tree In order to run the correct classes, Python test framework adjusts sys.path. However, these changes are not propagated to subprocesses. Therefore, the test actually tries to test installed Swift, not the one in which it is running. The usual suggestion is to run "python setup.py d...
Python
apache-2.0
swiftstack/swift,rackerlabs/swift,zackmdavis/swift,williamthegrey/swift,eatbyte/Swift,matthewoliver/swift,Seagate/swift,anishnarang/gswift,clayg/swift,shibaniahegde/OpenStak_swift,openstack/swift,prashanthpai/swift,matthewoliver/swift,psachin/swift,nadeemsyed/swift,AfonsoFGarcia/swift,prashanthpai/swift,smerritt/swift,...
858c61a5d23685b62e590d28c896002291817bb1
pygotham/admin/schedule.py
pygotham/admin/schedule.py
"""Admin for schedule-related models.""" from pygotham.admin.utils import model_view from pygotham.schedule import models # This line is really long because pep257 needs it to be on one line. __all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView') CATEGORY = 'Schedule' DayModelView = ...
"""Admin for schedule-related models.""" from pygotham.admin.utils import model_view from pygotham.schedule import models # This line is really long because pep257 needs it to be on one line. __all__ = ('DayModelView', 'RoomModelView', 'SlotModelView', 'PresentationModelView') CATEGORY = 'Schedule' DayModelView = ...
Change admin columns for slots
Change admin columns for slots
Python
bsd-3-clause
pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,djds23/pygotham-1,djds23/pygotham-1,pathunstrom/pygotham,PyGotham/pygotham,djds23/pygotham-1,PyGotham/pygotham,PyGotham/pygotham,pathunstrom/pygotham,pathunstrom/pygotham
b1a15ffe1c5f916076ac107735baf76e1da23bea
aiopg/__init__.py
aiopg/__init__.py
import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool') __version__ = '0.3.0' version = __version__ + ' , Python ' + sys.version VersionI...
import re import sys from collections import namedtuple from .connection import connect, Connection from .cursor import Cursor from .pool import create_pool, Pool __all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool', 'version', 'version_info') __version__ = '0.3.0' version = __version__ +...
Add version and version_info to exported public API
Add version and version_info to exported public API
Python
bsd-2-clause
eirnym/aiopg,nerandell/aiopg,hyzhak/aiopg,aio-libs/aiopg,luhn/aiopg,graingert/aiopg
39b5378b0d52e226c410671a47934a02d18f678e
scripts/extract_pivots_from_model.py
scripts/extract_pivots_from_model.py
#!/usr/bin/env python import sys import numpy as np import torch from learn_pivots_tm import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(args) > 1:...
#!/usr/bin/env python import sys import numpy as np import torch from learn_pivots_dual_domain import PivotLearnerModel, StraightThroughLayer def main(args): if len(args) < 1: sys.stderr.write("Required arguments: <model file> [num pivots (100)]\n") sys.exit(-1) num_pivots = 100 if len(a...
Fix import for new script location.
Fix import for new script location.
Python
apache-2.0
tmills/uda,tmills/uda
0173d18e2c88f4b944b3b12df2259fb0d26fee1d
drogher/shippers/dhl.py
drogher/shippers/dhl.py
from .base import Shipper class DHL(Shipper): barcode_pattern = r'^\d{10}$' shipper = 'DHL'
from .base import Shipper class DHL(Shipper): barcode_pattern = r'^\d{10}$' shipper = 'DHL' @property def valid_checksum(self): sequence, check_digit = self.tracking_number[:-1], self.tracking_number[-1] return int(sequence) % 7 == int(check_digit)
Add DHL waybill checksum validation
Add DHL waybill checksum validation
Python
bsd-3-clause
jbittel/drogher
3ecc978421e1bcceb30635e875333e52272e07a3
tests/providers/test_ovh.py
tests/providers/test_ovh.py
# Test for one implementation of the interface from unittest import TestCase from lexicon.providers.ovh import Provider from lexicon.common.options_handler import env_auth_options from integration_tests import IntegrationTests # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *e...
# Test for one implementation of the interface from unittest import TestCase from lexicon.providers.ovh import Provider from lexicon.common.options_handler import env_auth_options from integration_tests import IntegrationTests # Hook into testing framework by inheriting unittest.TestCase and reuse # the tests which *e...
Select ovh-eu entrypoint for test integration
Select ovh-eu entrypoint for test integration
Python
mit
tnwhitwell/lexicon,AnalogJ/lexicon,AnalogJ/lexicon,tnwhitwell/lexicon
42a6421fedadaea5f583dbccb8908b9b2df97231
spacq/devices/lakeshore/mock/mock_tc335.py
spacq/devices/lakeshore/mock/mock_tc335.py
import random from ...mock.mock_abstract_device import MockAbstractDevice from ..tc335 import TC335 """ Mock Lakeshore 335 Temperature Controller """ class MockTC335(MockAbstractDevice, TC335): """ Mock interface for Lakeshore 335 Temperature Controller. """ def __init__(self, *args, **kwargs): self.mocking =...
import random from ...mock.mock_abstract_device import MockAbstractDevice from ..tc335 import TC335 """ Mock Lakeshore 335 Temperature Controller """ class MockTC335(MockAbstractDevice, TC335): """ Mock interface for Lakeshore 335 Temperature Controller. """ def __init__(self, *args, **kwargs): self.mocking =...
Fix a bug involving how mock_state is set
Fix a bug involving how mock_state is set
Python
bsd-2-clause
ghwatson/SpanishAcquisitionIQC,ghwatson/SpanishAcquisitionIQC
2c54a9eb78a1cb88ef03db97e21e376ae764a33e
errata/admin_actions.py
errata/admin_actions.py
import unicodecsv from django.http import HttpResponse from django.utils.encoding import smart_str def export_as_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True): """ This function returns an export csv action 'fields' and 'excl...
import unicodecsv from django.http import StreamingHttpResponse class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def export_as_csv_...
Make use of Django's StreamingHttpResponse for large CSV exports
Make use of Django's StreamingHttpResponse for large CSV exports
Python
agpl-3.0
Connexions/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms
d3c7ae5389f2fd90ae35d87f87e4f7dd01572f4a
numpy/f2py/__init__.py
numpy/f2py/__init__.py
#!/usr/bin/env python __all__ = ['run_main','compile','f2py_testing'] import os import sys import commands from info import __doc__ import f2py2e run_main = f2py2e.run_main main = f2py2e.main import f2py_testing def compile(source, modulename = 'untitled', extra_args = '', verbo...
#!/usr/bin/env python __all__ = ['run_main','compile','f2py_testing'] import os import sys import commands import f2py2e import f2py_testing import diagnose from info import __doc__ run_main = f2py2e.run_main main = f2py2e.main def compile(source, modulename = 'untitled', extra_args = '', ...
Add diagnose to f2py package. This makes the tests a bit easier to fix.
ENH: Add diagnose to f2py package. This makes the tests a bit easier to fix.
Python
bsd-3-clause
ChristopherHogan/numpy,ChristopherHogan/numpy,seberg/numpy,bmorris3/numpy,njase/numpy,BabeNovelty/numpy,mhvk/numpy,tdsmith/numpy,cowlicks/numpy,MaPePeR/numpy,rmcgibbo/numpy,utke1/numpy,simongibbons/numpy,GrimDerp/numpy,shoyer/numpy,numpy/numpy-refactor,has2k1/numpy,ESSS/numpy,githubmlai/numpy,rgommers/numpy,Srisai85/nu...
bcc6d199186953b5ae05f7e93bf61c169ac89c77
opps/archives/admin.py
opps/archives/admin.py
from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File @apply_opps_rul...
# coding: utf-8 from django.contrib import admin from django.contrib.auth import get_user_model from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from opps.core.admin import apply_opps_rules from opps.contrib.multisite.admin import AdminViewPermission from .models import File ...
Add list_display on FileAdmin and download_link def
Add list_display on FileAdmin and download_link def
Python
mit
YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps
71241579d678185eb315ba2658f1c7eb9ec75603
example/django/tests.py
example/django/tests.py
from __future__ import absolute_import from django.contrib.auth.models import User from noseperf.testcases import DjangoPerformanceTest class DjangoSampleTest(DjangoPerformanceTest): def test_create_a_bunch_of_users(self): for n in xrange(2 ** 8): User.objects.create(username='test-%d' % n, e...
from __future__ import absolute_import from django.core.cache import cache from django.contrib.auth.models import User from noseperf.testcases import DjangoPerformanceTest class DjangoSampleTest(DjangoPerformanceTest): def test_create_a_bunch_of_users(self): for n in xrange(2 ** 8): User.obje...
Add basic cache test example
Add basic cache test example
Python
apache-2.0
disqus/nose-performance,disqus/nose-performance
2cf5041ff923fbecdcd31595d8340d12bb4d6283
build/copy_sources.py
build/copy_sources.py
#!/usr/bin/python # Copyright (c) 2012 The Native Client 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 import shutil import sys """Copy Sources Copy from a source file or directory to a new file or directory. This suppor...
#!/usr/bin/python # Copyright (c) 2012 The Native Client 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 import shutil import sys """Copy Sources Copy from a source file or directory to a new file or directory. This suppor...
Add information on Copy command.
Add information on Copy command. Adding extra information to track down mysterious mac build failures. tbr=bradnelson@google.com git-svn-id: 721b910a23eff8a86f00c8fd261a7587cddf18f8@9679 fcba33aa-ac0c-11dd-b9e7-8d5594d729c2
Python
bsd-3-clause
sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,nacl-webkit/native_client,sbc100/native_client,nacl-webkit/native_client,sbc100/native_client,sbc100/native_client,sbc100/native_client,nacl-webkit/native_client
efabe61cec636d5104a639b8d5cfef23eb840dd7
apps/live/urls.py
apps/live/urls.py
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from .views import (AwayView, DiscussionView, EpilogueView, GameView, NotifierView, PrologueView, StatusView) urlpatterns = patterns('', # Because sooner ...
# -*- coding: utf-8 -*- from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import RedirectView from .views import StatusView urlpatterns = patterns('', # Because sooner or later, avalonstar.tv/ will be a welcome page. url(r'^$', name='site-home', vi...
Remove the missing view references.
Remove the missing view references.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
f64cb48d51e1bcc3879a40d308452c4e65d13439
src/pymfony/component/system/serializer.py
src/pymfony/component/system/serializer.py
# -*- coding: utf-8 -*- # This file is part of the pymfony package. # # (c) Alexandre Quercia <alquerci@email.com> # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. from __future__ import absolute_import; from pickle import dumps; from pickl...
# -*- coding: utf-8 -*- # This file is part of the pymfony package. # # (c) Alexandre Quercia <alquerci@email.com> # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. from __future__ import absolute_import; from pickle import dumps; from pickl...
Use pickle protocole 2 to BC for Python2*
[System][Serializer] Use pickle protocole 2 to BC for Python2*
Python
mit
pymfony/pymfony
be89b2d9617fd5b837695e4322a2c98e4d4346cc
semillas_backend/users/serializers.py
semillas_backend/users/serializers.py
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
#from phonenumber_field.serializerfields import PhoneNumberField from rest_framework import serializers from drf_extra_fields.geo_fields import PointField from .models import User class UserSerializer(serializers.ModelSerializer): """ Usage: from rest_framework.renderers import JSONRenderer from ...
Add phone and email to user serializer
Add phone and email to user serializer
Python
mit
Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform
4cdf5be2a3c01e1b16a5e49bdf770f9d8573e16e
icekit/utils/testing.py
icekit/utils/testing.py
# USEFUL FUNCTIONS DESIGNED FOR TESTS ############################################################## import glob import os import uuid from django.core.files.base import ContentFile from PIL import Image from StringIO import StringIO def new_test_image(): """ Creates an automatically generated test image. ...
# USEFUL FUNCTIONS DESIGNED FOR TESTS ############################################################## import glob import os import uuid from PIL import Image from django.core.files.base import ContentFile from django.utils import six def new_test_image(): """ Creates an automatically generated test image. ...
Update StringIO import for Python3 compat
Update StringIO import for Python3 compat
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
b6e393271971426506557a208be93d8b79d55cc3
examples/image_captioning/download.py
examples/image_captioning/download.py
import argparse import os from six.moves.urllib import request import zipfile """Download the MSCOCO dataset (images and captions).""" urls = [ 'http://images.cocodataset.org/zips/train2014.zip', 'http://images.cocodataset.org/zips/val2014.zip', 'http://images.cocodataset.org/annotations/annotations_tra...
import argparse import os from six.moves.urllib import request import zipfile """Download the MSCOCO dataset (images and captions).""" urls = [ 'http://images.cocodataset.org/zips/train2014.zip', 'http://images.cocodataset.org/zips/val2014.zip', 'http://images.cocodataset.org/annotations/annotations_tra...
Fix error type for Python 2
Fix error type for Python 2
Python
mit
chainer/chainer,ktnyt/chainer,hvy/chainer,aonotas/chainer,wkentaro/chainer,tkerola/chainer,chainer/chainer,keisuke-umezawa/chainer,niboshi/chainer,okuta/chainer,niboshi/chainer,ktnyt/chainer,rezoo/chainer,jnishi/chainer,okuta/chainer,hvy/chainer,jnishi/chainer,wkentaro/chainer,hvy/chainer,wkentaro/chainer,jnishi/chaine...
9eec48753b2643d25d3ce1e143125b29351e0804
features/environment.py
features/environment.py
import os import tempfile from flask import json import tsserver # If set to True, each time the test is run, new database is created as a # temporary file. If the value is equal to False, tests will be using SQLite # in-memory database. USE_DB_TEMP_FILE = False def before_scenario(context, scenario): if USE_...
import os import tempfile from flask import json import tsserver # If set to True, each time the test is run, new database is created as a # temporary file. If the value is equal to False, tests will be using SQLite # in-memory database. USE_DB_TEMP_FILE = False def before_scenario(context, scenario): if USE_...
Add support for arguments in request() in tests
Add support for arguments in request() in tests
Python
mit
m4tx/techswarm-server
2d15ff38abb68335daa8bb2b94aaeff91ed829a2
photoshell/__main__.py
photoshell/__main__.py
import os import sys import yaml from photoshell import ui config_path = os.path.join(os.environ['HOME'], '.photoshell.yaml') with open(config_path, 'r') as config_file: config = yaml.load(config_file) print('Libray path is {0}'.format(config['library'])) # Open photo viewer ui.render(config['library'])
import os import sys import yaml from photoshell import ui config_path = os.path.join(os.environ['HOME'], '.photoshell.yaml') config = dict( { 'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell') } ) if os.path.isfile(config_path): with open(config_path, 'r') as config_file: ...
Create default config if one doesn't exist
Create default config if one doesn't exist Fixes #20
Python
mit
photoshell/photoshell,SamWhited/photoshell,campaul/photoshell
20a801255ab505641e1ec0d449a4b36411c673bc
indra/tests/test_tas.py
indra/tests/test_tas.py
from nose.plugins.attrib import attr from indra.sources.tas import process_from_web @attr('slow') def test_processor(): tp = process_from_web(affinity_class_limit=10) assert tp assert tp.statements num_stmts = len(tp.statements) # This is the total number of statements about human genes assert...
from nose.plugins.attrib import attr from indra.sources.tas import process_from_web @attr('slow') def test_processor(): tp = process_from_web(affinity_class_limit=10) assert tp assert tp.statements num_stmts = len(tp.statements) # This is the total number of statements about human genes assert...
Update test for current evidence aggregation
Update test for current evidence aggregation
Python
bsd-2-clause
sorgerlab/indra,sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,johnbachman/indra,bgyori/indra
5c7c2f87330aae72e4b30be7f4a9867e51793cf6
foosball/games/forms.py
foosball/games/forms.py
from django import forms from django_select2.forms import ModelSelect2MultipleWidget from django_superform import ModelFormField, SuperForm from .models import Team, Game from .utils import clean_team_forms from foosball.users.models import User class MultiPlayerWidget(ModelSelect2MultipleWidget): model = User ...
from django import forms from django_select2.forms import ModelSelect2MultipleWidget from django_superform import ModelFormField, SuperForm from .models import Team, Game from .utils import clean_team_forms from foosball.users.models import User class MultiPlayerWidget(ModelSelect2MultipleWidget): model = User ...
Change Game form score input to select
Change Game form score input to select
Python
mit
andersinno/foosball,andersinno/foosball,andersinno/foosball,andersinno/foosball
f0e71bdeca1a553c05228b57366a46c25db3d632
threema/gateway/util.py
threema/gateway/util.py
""" Utility functions. """ from threema.gateway.key import Key __all__ = ('read_key_or_key_file',) def read_key_or_key_file(key, expected_type): # Read key file (if any) try: with open(key) as file: key = file.readline().strip() except IOError: pass # Convert to key insta...
""" Utility functions. """ from threema.gateway.key import Key __all__ = ('read_key_or_key_file',) def read_key_or_key_file(key, expected_type): """ Decode a hex-encoded key or read it from a file. Arguments: - `key`: A hex-encoded key or the name of a file which contains a key. ...
Add missing docstring for read_key_or_key_file
Add missing docstring for read_key_or_key_file
Python
mit
lgrahl/threema-msgapi-sdk-python,threema-ch/threema-msgapi-sdk-python
fcb86792af4738ade1422f996397d8b96f0c54c5
scripts/mc_add_observation.py
scripts/mc_add_observation.py
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. import os import numpy as np from astropy.time import Time from pyuvdata import UVData from hera_mc import mc a = mc.get_mc_argument_parser() a.description = """Read the ob...
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2017 the HERA Collaboration # Licensed under the 2-clause BSD license. import numpy as np from astropy.time import Time from pyuvdata import UVData from hera_mc import mc a = mc.get_mc_argument_parser() a.description = """Read the obsid from a...
Fix flake8 issue and fix up documentation
Fix flake8 issue and fix up documentation
Python
bsd-2-clause
HERA-Team/hera_mc,HERA-Team/hera_mc,HERA-Team/Monitor_and_Control
70441c75eacd3e71c5e3a0f4db1cc0712729e50f
Python/pizza/pizza_roulette.py
Python/pizza/pizza_roulette.py
#!/usr/bin/env python import codecs import random import os dirname = os.path.dirname(os.path.realpath(__file__)) MIN_INGRED = 2 MAX_INGRED = 8 filename = dirname + "/vegetarian" with open(filename) as ingredients: content = ingredients.read().splitlines() roulette_result = [] roulette_tries = random.randin...
#!/usr/bin/env python import codecs import random import os import sys dirname = os.path.dirname(os.path.realpath(__file__)) MIN_INGRED = 2 MAX_INGRED = 8 filename = dirname + "/vegetarian" with open(filename) as ingredients: content = ingredients.read().splitlines() if "meat" in sys.argv : filename = d...
Add option to get meat
Add option to get meat
Python
mit
hjorthjort/scripts,hjorthjort/scripts
70a997c2991ea306a40054be8e2e93361ef9c702
src/globus_sdk/services/gcs/errors.py
src/globus_sdk/services/gcs/errors.py
from typing import Any, List, Optional, Union import requests from globus_sdk import exc class GCSAPIError(exc.GlobusAPIError): """ Error class for the GCS Manager API client """ def __init__(self, r: requests.Response) -> None: self.detail_data_type: Optional[str] = None self.detai...
from typing import Any, List, Optional, Union import requests from globus_sdk import exc class GCSAPIError(exc.GlobusAPIError): """ Error class for the GCS Manager API client """ def __init__(self, r: requests.Response) -> None: self.detail_data_type: Optional[str] = None self.detai...
Add a missing isinstance check to pacify pyright
Add a missing isinstance check to pacify pyright pyright (correctly) complains that we use `detail["DATA_TYPE"]` in GCS error parsing without knowing that `detail` is a type which supports strings in `__getitem__`. Check if `detail` is a dict before indexing into it.
Python
apache-2.0
globus/globus-sdk-python,globus/globus-sdk-python,sirosen/globus-sdk-python
13ffdb0cb455bf32a10d055e6e972c0ca725557a
src/mmw/apps/home/views.py
src/mmw/apps/home/views.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models import User from django.shortcuts import render_to_response from rest_framework import serializers, viewsets # Serializers define the API representatio...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.contrib.auth.models import User from django.shortcuts import render_to_response from django.template.context_processors import csrf from rest_framework import serializers, v...
Return a csrf token on the homepage.
Return a csrf token on the homepage. We were not setting a CSRF token on the homepage. This meant that requests to API endpoints did not have a token available. This change sets the token immediatley as part of the cookie. Ajax calls can then use this value.
Python
apache-2.0
WikiWatershed/model-my-watershed,kdeloach/model-my-watershed,kdeloach/model-my-watershed,mmcfarland/model-my-watershed-1,lewfish/model-my-watershed,WikiWatershed/model-my-watershed,lliss/model-my-watershed,lewfish/model-my-watershed,mmcfarland/model-my-watershed-1,lewfish/model-my-watershed,WikiWatershed/model-my-water...
276f22927890051f66976468585d8351c0ccf5b9
sum-of-multiples/sum_of_multiples.py
sum-of-multiples/sum_of_multiples.py
def sum_of_multiples(limit, factors): return sum(filter(lambda n: n < limit, {f*i for i in range(1, limit) for f in factors}))
def sum_of_multiples(limit, factors): return sum({n for f in factors for n in range(f, limit, f)})
Use more optimal method of getting multiples
Use more optimal method of getting multiples
Python
agpl-3.0
CubicComet/exercism-python-solutions
74f07511d810447f8c357aadebb810f6cb67ef55
algoliasearch/__init__.py
algoliasearch/__init__.py
# -*- coding: utf-8 -*- """ Copyright (c) 2013 Algolia http://www.algolia.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, ...
# -*- coding: utf-8 -*- """ Copyright (c) 2013 Algolia http://www.algolia.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, ...
Make VERSION easier to access
Make VERSION easier to access Until now `algoliasearch.version.VERSION` was needed to obtain the current version. Only `algoliasearch.VERSION` is now needed. The change is backward compatible: it is still possible to do `algoliasearch.version.VERSION`.
Python
mit
algolia/algoliasearch-client-python
e09d2a22bd91b114d291f05131ed7a487370e438
short.py
short.py
def ok(n): s = n + 3 print 's = %d' % (s,) return s def ident(val): return val def main(): while False: inside = 1 a = 1 + 2 ok(a) if True: print 'ok' elif False: print 'what' else: print 'no' assert True, 'WHAT' t = (1, 2) c = None ...
def ok(n): s = n + 3 print 's = %d' % (s,) return s def ident(val): return val Pair = DT('Pair', ('first', int), ('second', int)) Maybe, Just, Nothing = ADT('Maybe', 'Just', ('just', 'a'), 'Nothing') def main(): while False: inside = 1 a = 1 + 2 ok(a) if True: print 'ok' ...
Move data structures out of main
Move data structures out of main
Python
mit
pshc/archipelago,pshc/archipelago,pshc/archipelago
d0bcfebd2f85ec0ba17812ad4e98ef738dae1163
menpo/shape/groupops.py
menpo/shape/groupops.py
from .pointcloud import PointCloud import numpy as np def mean_pointcloud(pointclouds): r""" Compute the mean of a `list` of :map:`PointCloud` objects. Parameters ---------- pointclouds: `list` of :map:`PointCloud` List of point cloud objects from which we want to compute the mean. R...
from __future__ import division from .pointcloud import PointCloud def mean_pointcloud(pointclouds): r""" Compute the mean of a `list` of :map:`PointCloud` objects. Parameters ---------- pointclouds: `list` of :map:`PointCloud` List of point cloud objects from which we want to compute the...
Update mean_pointcloud to be faster
Update mean_pointcloud to be faster This is actually faster than using numpy. It is also MUCH faster if it gets jitted by something like pypy or numba.
Python
bsd-3-clause
mozata/menpo,mozata/menpo,patricksnape/menpo,menpo/menpo,grigorisg9gr/menpo,mozata/menpo,yuxiang-zhou/menpo,menpo/menpo,mozata/menpo,grigorisg9gr/menpo,yuxiang-zhou/menpo,grigorisg9gr/menpo,patricksnape/menpo,menpo/menpo,patricksnape/menpo,yuxiang-zhou/menpo
8ea6176719cd0c167420e3a7332efc7ece947a0d
genderjobcheck/views.py
genderjobcheck/views.py
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render import assess def home(request): if request.method == 'GET': return render(request, 'home.html', {}) @csrf_exempt def assessJobAd(request): if request.method == 'POST': ad_text = request.POST["adtext"] ...
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.shortcuts import redirect import assess def home(request): if request.method == 'GET': return render(request, 'home.html', {}) @csrf_exempt def assessJobAd(request): if request.method == 'POST': ...
Handle form submits without ad text
Handle form submits without ad text
Python
mit
lovedaybrooke/gender-decoder,lovedaybrooke/gender-decoder
d666c5c818fbfc00f642cfeb24cb90aab94035cd
keyring/devpi_client.py
keyring/devpi_client.py
import contextlib import functools import pluggy import keyring from keyring.errors import KeyringError hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}...
import contextlib import functools import pluggy import keyring.errors hookimpl = pluggy.HookimplMarker("devpiclient") # https://github.com/jaraco/jaraco.context/blob/c3a9b739/jaraco/context.py#L205 suppress = type('suppress', (contextlib.suppress, contextlib.ContextDecorator), {}) def restore_signature(func): ...
Remove superfluous import by using the exception from the namespace.
Remove superfluous import by using the exception from the namespace.
Python
mit
jaraco/keyring
142de9e809a9bc82bca6d12eaf492c1ce12a618d
geotrek/authent/migrations/0002_auto_20181107_1620.py
geotrek/authent/migrations/0002_auto_20181107_1620.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations import django.apps from django.core.management import call_command def add_permissions(): call_command('update_geotrek_permissions', verbosity=0) UserModel = django.apps.apps.get_model('auth', 'User') Permiss...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.core.management import call_command def add_permissions(apps, schema_editor): call_command('update_geotrek_permissions', verbosity=0) UserModel = apps.get_model('auth', 'User') PermissionModel = a...
Change migrations lack of apps, schema_editor
Change migrations lack of apps, schema_editor
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
1d4aea091883ad464d1c7fcdf734b1916337b25e
zeus/utils/revisions.py
zeus/utils/revisions.py
from zeus.exceptions import UnknownRepositoryBackend from zeus.models import Repository, Revision from zeus.vcs.base import UnknownRevision def identify_revision(repository: Repository, treeish: str): """ Attempt to transform a a commit-like reference into a valid revision. """ # try to find it from t...
from zeus.config import redis from zeus.exceptions import UnknownRepositoryBackend from zeus.models import Repository, Revision from zeus.vcs.base import UnknownRevision def identify_revision(repository: Repository, treeish: str): """ Attempt to transform a a commit-like reference into a valid revision. "...
Add lock on identify_revision when revision is missing
ref: Add lock on identify_revision when revision is missing
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
d5a3285b05d96ffc99049867256cdba87a5b420a
packages/mono_crypto.py
packages/mono_crypto.py
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): ...
from mono_master import MonoMasterPackage from bockbuild.util.util import * class MonoMasterEncryptedPackage (MonoMasterPackage): def __init__(self): MonoMasterPackage.__init__ (self) self.configure_flags.extend(['--enable-extension-module=crypto --enable-native-types']) def prep(self): ...
Fix mono-extensions checkout for PR branches ('origin/pull/N/merge')
Fix mono-extensions checkout for PR branches ('origin/pull/N/merge')
Python
mit
mono/bockbuild,mono/bockbuild
75bc100fb49588c057a6049975ce7c5803aa9145
zvm/zcpu.py
zvm/zcpu.py
# # A class which represents the CPU itself, the brain of the virtual # machine. It ties all the systems together and runs the story. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZCpuError(Exception): "General exception for Zcpu class" ...
# # A class which represents the CPU itself, the brain of the virtual # machine. It ties all the systems together and runs the story. # # For the license of this file, please consult the LICENSE file in the # root directory of this distribution. # class ZCpuError(Exception): "General exception for Zcpu class" ...
Make the CPU use lovely decorator syntax for registering opcode implementations.
Make the CPU use lovely decorator syntax for registering opcode implementations.
Python
bsd-3-clause
BGCX262/zvm-hg-to-git,BGCX262/zvm-hg-to-git
80a4c503675026c1274e2f1c20de6e3363cfb0f6
utils.py
utils.py
import datetime import time def datetime_to_sec_since_epoch(dt): '''Take a python datetime object and convert it to seconds since the unix epoch. Not timezone aware''' return time.mktime(dt.timetuple()) def sec_since_epoch_to_datetime(sec_since_epoch): '''Take some number seconds since the epoch and conver...
import datetime import time def datetime_to_sec_since_epoch(dt): '''Take a python datetime object and convert it to seconds since the unix epoch. Not timezone aware''' return int(time.mktime(dt.timetuple())) def sec_since_epoch_to_datetime(sec_since_epoch): '''Take some number seconds since the epoch and c...
Make datetime_to_sec_since_epoch return an int and fix epoch_sec_to_minutes_since_epoch
Make datetime_to_sec_since_epoch return an int and fix epoch_sec_to_minutes_since_epoch
Python
bsd-2-clause
tofu702/varz_python_client
33fcaf9b7a54dfb3cf065455eba75ee74fbb313b
pep8speaks/constants.py
pep8speaks/constants.py
import os # HEADERS is deprecated, use AUTH only HEADERS = {"Authorization": "token " + os.environ.setdefault("GITHUB_TOKEN", "")} AUTH = (os.environ.setdefault("BOT_USERNAME", ""), os.environ.setdefault("BOT_PASSWORD", "")) BASE_URL = 'https://api.github.com'
import os # HEADERS is deprecated, use AUTH only HEADERS = {"Authorization": "token " + os.environ.setdefault("GITHUB_TOKEN", "")} AUTH = (os.environ.setdefault("BOT_USERNAME", ""), os.environ.setdefault("GITHUB_TOKEN", "")) BASE_URL = 'https://api.github.com'
Use GITHUB_TOKEN instead of BOT_PASSWORD
Use GITHUB_TOKEN instead of BOT_PASSWORD When using BOT_PASSWORD, the bot cannot have two factor authentication enabled as GitHub expects an additional header parameter that is the one time 2FA password: https://developer.github.com/v3/auth/#working-with-two-factor-authentication GITHUB_TOKEN can be used in place of ...
Python
mit
OrkoHunter/pep8speaks
4267ef9e8fc555a460b53fcfdee0f048bbdb84cf
accounts/tests/test_views.py
accounts/tests/test_views.py
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. ...
"""accounts app unittests for views """ from django.test import TestCase from django.urls import reverse class WelcomePageTest(TestCase): """Tests relating to the welcome_page view. """ def test_uses_welcome_template(self): """The root url should respond with the welcome page template. ...
Add test for denying get requests
Add test for denying get requests
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
8b7df2f297fde16525821a14755c870c290850af
salt/thorium/runner.py
salt/thorium/runner.py
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
# -*- coding: utf-8 -*- ''' React by calling async runners ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals # import salt libs import salt.runner def cmd( name, func=None, arg=(), **kwargs): ''' Execute a runner asynchronous: ...
Fix local opts from CLI
Fix local opts from CLI
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
945195071418762de447dfdb8a73c386f3796e96
backend/unichat/models/user.py
backend/unichat/models/user.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class User(models.Model): MALE = -1 UNDEFINED = 0 FEMALE = 1 GENDER_CHOICES = ( (MALE, 'Male'), (UNDEFINED, 'Undefined'), (FEMALE, 'Female') ) school = models.ForeignKey('unich...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class User(models.Model): MALE = -1 UNDEFINED = 0 FEMALE = 1 GENDER_CHOICES = ( (MALE, 'Male'), (UNDEFINED, 'Undefined'), (FEMALE, 'Female') ) school = models.ForeignKey('unich...
Add password field to User model
Add password field to User model
Python
mit
dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet
f8ea4266082fba1210be270d6ae7607717591978
skimage/io/__init__.py
skimage/io/__init__.py
"""Utilities to read and write images in various formats. The following plug-ins are available: """ from ._plugins import * from .sift import * from .collection import * from ._io import * from ._image_stack import * from .video import * reset_plugins() def _update_doc(doc): """Add a list of plugins to the ...
"""Utilities to read and write images in various formats. The following plug-ins are available: """ from ._plugins import * from .sift import * from .collection import * from ._io import * from ._image_stack import * from .video import * reset_plugins() WRAP_LEN = 73 def _separator(char, lengths): return [...
Refactor io doc building code
Refactor io doc building code
Python
bsd-3-clause
youprofit/scikit-image,ofgulban/scikit-image,Hiyorimi/scikit-image,ofgulban/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,WarrenWeckesser/scikits-image,blink1073/scikit-image,SamHames/scikit-image,bsipocz/scikit-image,chriscrosscutler/scikit-image,vighneshbirodkar/scikit-image,dpshelio/scikit-image,Midaf...
e31790412c9e869841b448f3e7f8bb4a965da81d
mygpo/web/templatetags/devices.py
mygpo/web/templatetags/devices.py
from django import template from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from mygpo.api.models import DEVICE_TYPES register = template.Library() # Create a dictionary of device_type -> caption mappings DEVICE_TYPES_DICT = dict(DEVICE_TYPES) # This dictionary maps ...
from django import template from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from mygpo.api.models import DEVICE_TYPES register = template.Library() # Create a dictionary of device_type -> caption mappings DEVICE_TYPES_DICT = dict(DEVICE_TYPES) # This dictionary maps ...
Fix problem with device icons
Fix problem with device icons
Python
agpl-3.0
gpodder/mygpo,gpodder/mygpo,gpodder/mygpo,gpodder/mygpo
362d60b4ab982efa96a0ef255f5de97b80c0b569
skan/test/test_pipe.py
skan/test/test_pipe.py
import os import pytest import pandas from skan import pipe @pytest.fixture def image_filename(): rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') return os.path.join(datadir, 'retic.tif') def test_pipe(image_filename): data = pipe.process_images([image_file...
import os import pytest import tempfile import pandas from skan import pipe @pytest.fixture def image_filename(): rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') return os.path.join(datadir, 'retic.tif') def test_pipe(image_filename): data = pipe.process_im...
Add test for saving skeleton image
Add test for saving skeleton image
Python
bsd-3-clause
jni/skan
ada3d309541daaa8591a6bcb6ec42a2a2ff468db
catsnap/worker/tasks.py
catsnap/worker/tasks.py
from __future__ import unicode_literals, absolute_import from boto.cloudfront.exception import CloudFrontServerError from catsnap.worker import worker from catsnap import Client class Invalidate(worker.Task): def run(self, filename): config = Client().config() try: distro_id = config['...
from __future__ import unicode_literals, absolute_import from boto.cloudfront.exception import CloudFrontServerError from catsnap.worker import worker from catsnap import Client class Invalidate(worker.Task): def run(self, filename): config = Client().config() try: distro_id = config['...
Remove a line of debug output
Remove a line of debug output
Python
mit
ErinCall/catsnap,ErinCall/catsnap,ErinCall/catsnap