commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
8e0d28d23c7ceb6a200773dde035b85965273ac6 | inbox/events/actions/base.py | inbox/events/actions/base.py | from inbox.models.account import Account
from inbox.models.event import Event
from inbox.events.actions.backends import module_registry
def create_event(account_id, event_id, db_session):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_create_event... | from inbox.models.account import Account
from inbox.models.event import Event
from inbox.events.actions.backends import module_registry
def create_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
remote_creat... | Add args flexibility to event create to match EAS requirements | Add args flexibility to event create to match EAS requirements
| Python | agpl-3.0 | PriviPK/privipk-sync-engine,ErinCall/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,closeio/nylas,nylas/sync-engine,jobscore/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,closeio/nylas... | ---
+++
@@ -3,7 +3,7 @@
from inbox.events.actions.backends import module_registry
-def create_event(account_id, event_id, db_session):
+def create_event(account_id, event_id, db_session, *args):
account = db_session.query(Account).get(account_id)
event = db_session.query(Event).get(event_id)
@@ -12,7... |
ea22f4bf62204805e698965300b6d8dfa637a662 | pybossa_discourse/globals.py | pybossa_discourse/globals.py | # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
app.jinja_env.globals.update(disco... | # -*- coding: utf8 -*-
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
from . import discourse_client
class DiscourseGlobals(object):
"""A class to implement Discourse Global variables."""
def __init__(self, app):
self.url = app.config['DISCOURSE_URL']
app... | Add notifications count to global envar | Add notifications count to global envar
| Python | bsd-3-clause | alexandermendes/pybossa-discourse | ---
+++
@@ -2,6 +2,7 @@
"""Jinja globals module for pybossa-discourse."""
from flask import Markup, request
+from . import discourse_client
class DiscourseGlobals(object):
@@ -32,3 +33,11 @@
}}
</script>
""").format(self.url, request.base_url)
+
+ def notifications(s... |
1d292feebd2999eb042da1f606c0fdc33103225f | api/models.py | api/models.py | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_categ... | class MessageModel:
def __init__(self, message, duration, creation_date, message_category):
# We will automatically generate the new id
self.id = 0
self.message = message
self.duration = duration
self.creation_date = creation_date
self.message_category = message_categ... | Update model script to support task database schema | Update model script to support task database schema
| Python | mit | candidate48661/BEA | ---
+++
@@ -8,3 +8,18 @@
self.message_category = message_category
self.printed_times = 0
self.printed_once = False
+
+
+class AccountModel:
+ def __init__(self, account_type, account_number, name, first_name, address, birthdate):
+ # We will automatically generate the new id
+ ... |
e0d8099e57fb890649490b9e9bb201b98b041212 | libcloud/__init__.py | libcloud/__init__.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not... | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# libcloud.org licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not... | Add version string to libcloud | Add version string to libcloud
git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@895867 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | cloudkick/libcloud,cloudkick/libcloud | ---
+++
@@ -16,3 +16,5 @@
"""
libcloud provides a unified interface to the cloud computing resources.
"""
+
+__version__ = "0.1.1-dev" |
46a0caa1bc162d11b26a996379170b2fc49f2940 | mcbench/client.py | mcbench/client.py | import collections
import redis
BENCHMARK_FIELDS = [
'author', 'author_url', 'date_submitted', 'date_updated',
'name', 'summary', 'tags', 'title', 'url'
]
Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS))
class McBenchClient(object):
def __init__(self, redis):
self.red... | import redis
class Benchmark(object):
def __init__(self, author, author_url, date_submitted, date_updated,
name, summary, tags, title, url):
self.author = author
self.author_url = author_url
self.date_submitted = date_submitted
self.date_updated = date_updated
... | Make Benchmark a class, not a namedtuple. | Make Benchmark a class, not a namedtuple.
| Python | mit | isbadawi/mcbench,isbadawi/mcbench | ---
+++
@@ -1,13 +1,29 @@
-import collections
-
import redis
-BENCHMARK_FIELDS = [
- 'author', 'author_url', 'date_submitted', 'date_updated',
- 'name', 'summary', 'tags', 'title', 'url'
-]
-Benchmark = collections.namedtuple('Benchmark', ' '.join(BENCHMARK_FIELDS))
+class Benchmark(object):
+ def __ini... |
1b9c4935b2edf6601c2d75d8a2d318266de2d456 | circuits/tools/__init__.py | circuits/tools/__init__.py | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportE... | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportE... | Store the depth (d) on the stack and restore when backtracking | tools: Store the depth (d) on the stack and restore when backtracking
| Python | mit | treemo/circuits,treemo/circuits,eriol/circuits,treemo/circuits,eriol/circuits,nizox/circuits,eriol/circuits | ---
+++
@@ -39,13 +39,12 @@
x = children[i]
i += 1
if x.components:
- stack.append((i, children))
+ stack.append((i, d, children))
children = list(x.components)
i = 0
else:
if stack:
- ... |
7ba2299e2d429bd873539507b3edbe3cdd3de9d6 | linkatos/firebase.py | linkatos/firebase.py | import pyrebase
def initialise(FB_API_KEY, project_name):
config = {
"apiKey": FB_API_KEY,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyr... | import pyrebase
def initialise(api_key, project_name):
config = {
"apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".format(project_name),
"storageBucket": "{}.appspot.com".format(project_name),
}
return pyrebase.... | Change variables to lower case | style: Change variables to lower case
| Python | mit | iwi/linkatos,iwi/linkatos | ---
+++
@@ -1,9 +1,9 @@
import pyrebase
-def initialise(FB_API_KEY, project_name):
+def initialise(api_key, project_name):
config = {
- "apiKey": FB_API_KEY,
+ "apiKey": api_key,
"authDomain": "{}.firebaseapp.com".format(project_name),
"databaseURL": "https://{}.firebaseio.com".forma... |
d320de7a66472036f2504f8b935747ff4a1e4e49 | barf/setup.py | barf/setup.py | #! /usr/bin/env python
from setuptools import setup
from setuptools import find_packages
setup(
author = 'Christian Heitman',
author_email = 'cnheitman@fundacionsadosky.org.ar',
description = 'A multiplatform open source Binary Analysis and Reverse engineering Framework',
install_re... | #! /usr/bin/env python
from setuptools import setup
from setuptools import find_packages
# https://github.com/aquynh/capstone/issues/583
def fix_setuptools():
"""Work around bugs in setuptools.
Some versions of setuptools are broken and raise SandboxViolation for normal
operations in a virtualenv. We th... | Fix Capstone installation error on virtualenvs | Fix Capstone installation error on virtualenvs
| Python | bsd-2-clause | chubbymaggie/barf-project,programa-stic/barf-project,cnheitman/barf-project,cnheitman/barf-project,chubbymaggie/barf-project,chubbymaggie/barf-project,programa-stic/barf-project,cnheitman/barf-project | ---
+++
@@ -2,6 +2,28 @@
from setuptools import setup
from setuptools import find_packages
+
+
+# https://github.com/aquynh/capstone/issues/583
+def fix_setuptools():
+ """Work around bugs in setuptools.
+
+ Some versions of setuptools are broken and raise SandboxViolation for normal
+ operations in a vi... |
56edfe1bacff53eec22b05d43f32063f83f43ea5 | studies/helpers.py | studies/helpers.py | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
"""
... | from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL
@app.task
def send_mail(template_name, subject, to_addresses, cc=None, bcc=None, from_email=None, **context):
... | Add OSF_URL to send_email helper. | Add OSF_URL to send_email helper.
| Python | apache-2.0 | CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api | ---
+++
@@ -1,7 +1,7 @@
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import get_template
from project.celery import app
-from project.settings import EMAIL_FROM_ADDRESS, BASE_URL
+from project.settings import EMAIL_FROM_ADDRESS, BASE_URL, OSF_URL
@app.task
@@ -19,6 +... |
6fcf03532dcc549a3a95390b7c999482a64fc6c6 | tests/unit/utils/test_pycrypto.py | tests/unit/utils/test_pycrypto.py | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
# Import Salt Libs
import salt.utils.pycrypto
import salt.utils.platform
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
log = logging.getLogger(_... | # -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import re
# Import Salt Libs
import salt.utils.pycrypto
import salt.utils.platform
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
log = logging.getLogger(_... | Make the skip apply to any system missing crypt | Make the skip apply to any system missing crypt
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -20,7 +20,9 @@
TestCase for salt.utils.pycrypto module
'''
- @skipIf(salt.utils.platform.is_windows(), 'No crypto module for Windows')
+ # The crypt module is only available on Unix systems
+ # https://docs.python.org/dev/library/crypt.html
+ @skipIf(not salt.utils.pycrypto.HAS_CRYP... |
edebe37458da391723e3206c63102cbb69606c5b | ideascube/conf/idb_irq_bardarash.py | ideascube/conf/idb_irq_bardarash.py | """Bardarash in Kurdistan, Iraq"""
from .idb_jor_azraq import * # pragma: no flakes
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_o... | """Bardarash in Kurdistan, Iraq"""
from .idb_jor_azraq import * # pragma: no flakes
from django.utils.translation import ugettext_lazy as _
USER_FORM_FIELDS = (
('Ideasbox', ['serial', 'box_awareness']),
(_('Personal informations'), ['short_name', 'full_name', 'latin_name', 'birth_year', 'gender', 'country_o... | Remove Kalite until Arabic language is available | Remove Kalite until Arabic language is available
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -14,3 +14,16 @@
ENTRY_ACTIVITY_CHOICES = []
+
+HOME_CARDS = STAFF_HOME_CARDS + [
+ {
+ 'id': 'blog',
+ },
+ {
+ 'id': 'mediacenter',
+ },
+ {
+ 'id': 'library',
+ }
+]
+ |
066833caebddb9a6e0735e635ff214448e078405 | check_env.py | check_env.py | """ Run this file to check your python installation.
"""
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
assert version_found > (0, 15)
def test_import_numpy()... | """ Run this file to check your python installation.
"""
from os.path import dirname, join
HERE = dirname(__file__)
def test_import_pandas():
import pandas
def test_pandas_version():
import pandas
version_found = pandas.__version__.split(".")
version_found = tuple(int(num) for num in version_found)
... | Add some more content in tests including with statsmodels. | Add some more content in tests including with statsmodels.
| Python | mit | wateryhcho/pandas_tutorial,linan7788626/pandas_tutorial,jonathanrocher/pandas_tutorial,wateryhcho/pandas_tutorial,Sandor-PRA/pandas_tutorial,Sandor-PRA/pandas_tutorial,ajaykliyara/pandas_tutorial,ajaykliyara/pandas_tutorial,jonathanrocher/pandas_tutorial,jonathanrocher/pandas_tutorial,ajaykliyara/pandas_tutorial,linan7... | ---
+++
@@ -1,5 +1,8 @@
""" Run this file to check your python installation.
"""
+from os.path import dirname, join
+
+HERE = dirname(__file__)
def test_import_pandas():
import pandas
@@ -17,7 +20,23 @@
def test_import_matplotlib():
- import matplotlib
+ import matplotlib.pyplot as plt
+ plt.f... |
5301f5a641426cd223cb528696495ee1df70258a | prefixlist/api.py | prefixlist/api.py | from flask import Flask
from flask_restful import abort, Api, Resource
app = Flask("pre-fixlist")
api = Api(app)
class PrefixListList(Resource):
def get(self):
# Return a list of all prefix lists we know about
return None
class PrefixList(Resource):
def get(self, listid):
# Return a... | from flask import Flask
from flask_restful import abort, Api, Resource
from flask_cors import CORS
app = Flask("pre-fixlist")
api = Api(app)
CORS(app)
class PrefixListList(Resource):
def get(self):
# Return a list of all prefix lists we know about
return None
class PrefixList(Resource):
def... | Add CORS header to API responses | Add CORS header to API responses
| Python | bsd-2-clause | emjemj/pre-fixlist | ---
+++
@@ -1,8 +1,10 @@
from flask import Flask
from flask_restful import abort, Api, Resource
+from flask_cors import CORS
app = Flask("pre-fixlist")
api = Api(app)
+CORS(app)
class PrefixListList(Resource):
|
9b5b6514ace9d08d2dca563b71c8b6a1ca3f4f70 | wordcloud.py | wordcloud.py | import falcon, json, pymongo
MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user'
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
user_name = mongo_db_user_config.split(':')[0]
password = mongo_db_user_config.split(':')[1]
mongo_db_client = pymongo.MongoClient('wordcloud-mongo.hom... | import falcon, json, pymongo
MONGO_DB_USER_FILE = '/home/frank/word_cloud-backend/config/mongodb-user'
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
user_name = mongo_db_user_config.rstrip('\n').split(':')[0]
password = mongo_db_user_config.rstrip('\n').split(':')[1]
mongo_db_client = pymongo.MongoC... | Read mongo user and passwd from config file | Read mongo user and passwd from config file
| Python | apache-2.0 | Frank-Krick/word_cloud-backend | ---
+++
@@ -5,8 +5,8 @@
mongo_db_user_config = open(MONGO_DB_USER_FILE, 'r').read()
-user_name = mongo_db_user_config.split(':')[0]
-password = mongo_db_user_config.split(':')[1]
+user_name = mongo_db_user_config.rstrip('\n').split(':')[0]
+password = mongo_db_user_config.rstrip('\n').split(':')[1]
mongo_db... |
2b0edbadec80300d20a280db0f06281040e00e25 | radar/radar/validation/consultants.py | radar/radar/validation/consultants.py | from radar.validation.core import Field, Validation, ListField, ValidationError
from radar.validation.meta import MetaValidationMixin
from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower
from radar.validation.number_validators import gmc_number
... | from radar.validation.core import Field, Validation, ListField, ValidationError
from radar.validation.meta import MetaValidationMixin
from radar.validation.validators import not_empty, none_if_blank, optional, email_address, max_length, required, upper, lower
from radar.validation.number_validators import gmc_number
... | Check consultant groups aren't duplicated | Check consultant groups aren't duplicated
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | ---
+++
@@ -14,10 +14,30 @@
return group
+class GroupConsultantListField(ListField):
+ def __init__(self, chain=None):
+ super(GroupConsultantListField, self).__init__(GroupConsultantValidation(), chain=chain)
+
+ def validate(self, group_consultants):
+ print 'hello!'
+
+ grou... |
b8359e6b04d13f550aec308308f2e91e194bc372 | uberlogs/handlers/kill_process.py | uberlogs/handlers/kill_process.py | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | import sys
import os
from logging import Handler as LoggingHandler
class KillProcessHandler(LoggingHandler):
@profile
def emit(self, record):
if record.levelno != self.level:
return
# flush text before exiting
for fd in [sys.stdout, sys.stderr]:
fd.flush()
... | Remove repetitive getMessage calls in KillProcesshandler | Remove repetitive getMessage calls in KillProcesshandler
| Python | mit | odedlaz/uberlogs,odedlaz/uberlogs | ---
+++
@@ -14,9 +14,10 @@
for fd in [sys.stdout, sys.stderr]:
fd.flush()
+ msg = record.getMessage()
# Twisted writes unhandled errors in different calls
# If we exit on the first call, we'd lose the actual error
for log_to_ignore in ["Unhandled error in Defe... |
be5eecf2a043abf7585022f1dda3b79572eba192 | tests/test__pycompat.py | tests/test__pycompat.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask_ndmeasure._pycompat
def test_irange():
r = dask_ndmeasure._pycompat.irange(5)
assert not isinstance(r, list)
assert list(r) == [0, 1, 2, 3, 4]
| Add a basic test for irange | Add a basic test for irange
Make sure `irange` is there, it doesn't return a list, and it acts like
`range` on some test arguments.
| Python | bsd-3-clause | dask-image/dask-ndmeasure | ---
+++
@@ -1,2 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+
+
+from __future__ import absolute_import
+
+import dask_ndmeasure._pycompat
+
+
+def test_irange():
+ r = dask_ndmeasure._pycompat.irange(5)
+
+ assert not isinstance(r, list)
+
+ assert list(r) == [0, 1, 2, 3, 4] |
e90a60b1da00a6c6a5e1b4235c4009d7477986ca | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.0.2"
class CPPCheckTargetCMakeConan(ConanFile):
name = "cppcheck-target-cmake"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
requires = ("cmake-include-guard/master@smspilla... | Copy find modules to root of module path | conan: Copy find modules to root of module path
| Python | mit | polysquare/cppcheck-target-cmake | ---
+++
@@ -26,6 +26,10 @@
os.unlink(zip_name)
def package(self):
+ self.copy(pattern="Find*.cmake",
+ dst="",
+ src="cppcheck-target-cmake-" + VERSION,
+ keep_path=True)
self.copy(pattern="*.cmake",
dst="cmake/cppch... |
59afb96f2211983ee2a2786c60791074b13c3e7f | ni/__main__.py | ni/__main__.py | """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records:... | """Implement a server to check if a contribution is covered by a CLA(s)."""
from aiohttp import web
from . import abc
from . import ContribHost
from . import ServerHost
from . import CLAHost
class Handler:
"""Handle requests from the contribution host."""
def __init__(self, server: ServerHost, cla_records:... | Tweak comment about 202 response | Tweak comment about 202 response
| Python | apache-2.0 | python/the-knights-who-say-ni,python/the-knights-who-say-ni | ---
+++
@@ -21,8 +21,8 @@
contribution = ContribHost.process(request)
usernames = await contribution.usernames() # XXX not implemented
cla_status = await self.cla_records.check(usernames) # XXX not implemented
- # With a background queue, one could add the update as... |
9681b2f31163e24e72121afc6195262376891220 | marketpulse/main/__init__.py | marketpulse/main/__init__.py | import moneyed
FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price'
def get_currency_choices():
return sorted(((currency, data.name) for currency, data in moneyed.CURRENCIES.items()))
| import moneyed
FFXOS_ACTIVITY_NAME = 'Submit FirefoxOS device price'
def get_currency_choices():
return sorted(((currency, data.code) for currency, data in moneyed.CURRENCIES.items()))
| Replace currency full name with currency code. | Replace currency full name with currency code.
| Python | mpl-2.0 | akatsoulas/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,mozilla/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,akatsoulas/marketpulse,johngian/marketpulse,mozilla/marketpulse,mozilla/marketpulse,johngian/marketpulse,mozilla/marketpulse | ---
+++
@@ -5,4 +5,4 @@
def get_currency_choices():
- return sorted(((currency, data.name) for currency, data in moneyed.CURRENCIES.items()))
+ return sorted(((currency, data.code) for currency, data in moneyed.CURRENCIES.items())) |
9cfe03ab06f126406a51c0945e990fc849d8dfb9 | scripts/crontab/gen-crons.py | scripts/crontab/gen-crons.py | #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
... | #!/usr/bin/env python
import os
from optparse import OptionParser
from jinja2 import Template
TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read()
def main():
parser = OptionParser()
parser.add_option("-k", "--kitsune",
help="Location of kitsune (required)")
... | Add local site-packages to PYTHONPATH. | Add local site-packages to PYTHONPATH.
To pick up the local version of PyOpenSSL.
| Python | bsd-3-clause | philipp-sumo/kitsune,iDTLabssl/kitsune,orvi2014/kitsune,silentbob73/kitsune,NewPresident1/kitsune,MziRintu/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,YOTOV-LIMITED/kitsune,safwanrahman/kitsune,silentbob73/kitsune,safwanrahman/linuxdesh,mythmon/kitsune,YOTOV-LIMITED/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune... | ---
+++
@@ -23,7 +23,11 @@
if not opts.kitsune:
parser.error("-k must be defined")
- ctx = {'django': 'cd %s; %s manage.py' % (opts.kitsune, opts.python),}
+ # To pick up the right PyOpenSSL:
+ python_path = 'PYTHONPATH=/usr/local/lib64/python2.6/site-packages'
+
+ ctx = {'django': 'cd %s;... |
49493f11e20e4cb033ae17d29bfa14fa8473d145 | qutebrowser/.qutebrowser/config.py | qutebrowser/.qutebrowser/config.py | c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info = "16pt monosp... | # Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
c.fonts.downloads = "16pt monospace"
c.fonts.hints = "16pt monospace"
c.fonts.keyhint = "16pt monospace"
c.fonts.messages.error = "16pt monospace"
c.fonts.messages.info ... | Add mpv spawning to qutebrowser | Add mpv spawning to qutebrowser
Signed-off-by: Tomas <5fad2aa041dd6f0fec7c9125f282be028fd2d7b0@Tomass-MacBook-Pro.local>
| Python | mit | deathbeam/dotfiles,deathbeam/dotfiles,deathbeam/awesomedotrc,deathbeam/dotfiles,deathbeam/dotfiles | ---
+++
@@ -1,3 +1,4 @@
+# Adjust font
c.fonts.completion.category = "bold 16pt monospace"
c.fonts.completion.entry = "16pt monospace"
c.fonts.debug_console = "16pt monospace"
@@ -11,3 +12,7 @@
c.fonts.prompts = "16pt sans-serif"
c.fonts.statusbar = "16pt monospace"
c.fonts.tabs = "16pt monospace"
+
+# Play vid... |
cac3099b9ab07d5ac2180e0b2796f55668ddda1e | generate_keyczart.py | generate_keyczart.py | import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.listdir(directory):
os.makedirs(directory)
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczart.main(['addkey','--location=keyset'... | import keyczar
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
if not os.path.exists(directory):
os.makedirs(directory)
if not os.listdir(directory):
keyczart.main(['create','--location=keyset','--purpose=crypt','--name=crypt'])
keyczar... | Make the directory if it doesn't exist | Make the directory if it doesn't exist
| Python | apache-2.0 | arubdesu/Crypt-Server,arubdesu/Crypt-Server,arubdesu/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server,squarit/Crypt-Server,grahamgilbert/Crypt-Server | ---
+++
@@ -2,8 +2,11 @@
from keyczar import keyczart
import os
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keyset')
+
+if not os.path.exists(directory):
+ os.makedirs(directory)
+
if not os.listdir(directory):
- os.makedirs(directory)
keyczart.main(['create','--location=keyse... |
62d5682fa3be9dfbae80b2acae9839cd1278dcb6 | whatismyip.py | whatismyip.py | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text)
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__':
ma... | #! /usr/bin/python
import requests
from bs4 import BeautifulSoup
def main():
r = requests.get('http://www.whatismyip.com')
soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'):
ip_address += span.text
print(ip_address)
if __name__ == '__main__'... | Use lxml as a parsing engine for bs4 | Use lxml as a parsing engine for bs4
| Python | apache-2.0 | MichaelAquilina/whatismyip | ---
+++
@@ -8,7 +8,7 @@
def main():
r = requests.get('http://www.whatismyip.com')
- soup = BeautifulSoup(r.text)
+ soup = BeautifulSoup(r.text, 'lxml')
ip_address = ''
for span in soup.find('div', 'the-ip'): |
c485876017c92ac01af733945f04d36a21da8a6d | newsroom/settings.py | newsroom/settings.py | from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 12)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZ... | from django.conf import settings
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 16)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PARSER',
"lxml")
ARTICLE_SUMMARY_IMAGE_SIZ... | Set default number of articles on page to 16, up from 12. | Set default number of articles on page to 16, up from 12.
| Python | bsd-3-clause | groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu,groundupnews/gu | ---
+++
@@ -2,7 +2,7 @@
ARTICLE_COPYRIGHT = getattr(settings, 'NEWSROOM_ARTICLE_COPYRIGHT', "")
-ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 12)
+ARTICLES_PER_PAGE = getattr(settings, 'NEWSROOM_ARTICLES_PER_PAGE', 16)
BEAUTIFUL_SOUP_PARSER = getattr(settings, 'NEWSROOM_BEAUTIFUL_SOUP_PAR... |
9d0798904160f86d7f580dde3bfba8cc28b5a23f | troposphere/ram.py | troposphere/ram.py | # Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare(AWSObject):
resource_type = "AWS::RAM::ResourceShare"
props = {
"AllowExternalP... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 39.3.0
from troposphere import Tags
from . import AWSObject
from .validators import boolean
class ResourceShare... | Update RAM per 2021-06-10 changes | Update RAM per 2021-06-10 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -1,7 +1,11 @@
-# Copyright (c) 2012-2019, Mark Peek <mark@peek.org>
+# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
+#
+# *** Do not modify - this file is autogenerated ***
+# Resource specification version: 39.3.0
+
from troposphere... |
eb4456b752313383a573bacfc102db9149ee1854 | django_transfer/urls.py | django_transfer/urls.py | from __future__ import unicode_literals
try:
from django.conf.urls import patterns, url
except ImportError:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
'',
url(r'^download/.*$', 'django_transfer.views.download', name='download'),
url(r'^upload/$', 'django_transfer.... | from __future__ import unicode_literals
try:
from django.conf.urls import url
def patterns(*args):
return args
except ImportError:
from django.conf.urls.defaults import patterns, url
from django_transfer.views import download, upload
urlpatterns = patterns(
url(r'^download/.*$', download, ... | Fix URL patterns for different Django versions. | Fix URL patterns for different Django versions.
| Python | mit | smartfile/django-transfer | ---
+++
@@ -1,13 +1,18 @@
from __future__ import unicode_literals
try:
- from django.conf.urls import patterns, url
+ from django.conf.urls import url
+
+ def patterns(*args):
+ return args
+
except ImportError:
from django.conf.urls.defaults import patterns, url
+from django_transfer.view... |
4cff7dd08fdb345b6e091570a2ca5500ef871318 | flask_authorization_panda/basic_auth.py | flask_authorization_panda/basic_auth.py | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, Response, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
di... | """
Functions related to HTTP Basic Authorization
"""
from functools import wraps
from flask import request, jsonify, current_app
def basic_auth(original_function):
"""
Wrapper. Verify that request.authorization exists and that its
contents match the application's config.basic_auth_credentials
dic... | Remove use of assert statements since this does not conform to general best practice. | Remove use of assert statements since this does not conform to general best practice.
This is unfortunate, because the code is much more verbose than before and NOT as clear.
| Python | mit | eikonomega/flask-authorization-panda | ---
+++
@@ -5,7 +5,7 @@
from functools import wraps
-from flask import request, Response, current_app
+from flask import request, jsonify, current_app
def basic_auth(original_function):
@@ -22,22 +22,28 @@
original_function (function): The original function.
"""
+
@wraps(original_functi... |
e33a2879fbafe36c8c29d48042dad8277b068e91 | umap/tests/test_plot.py | umap/tests/test_plot.py | from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at... | from nose.tools import assert_less
from nose.tools import assert_greater_equal
import os.path
import numpy as np
from nose import SkipTest
from sklearn import datasets
import umap
import umap.plot
np.random.seed(42)
iris = datasets.load_iris()
mapper = umap.UMAP(n_epochs=100).fit(iris.data)
def test_plot_runs_at... | Add more basic plotting tests | Add more basic plotting tests
| Python | bsd-3-clause | lmcinnes/umap,lmcinnes/umap | ---
+++
@@ -17,7 +17,15 @@
def test_plot_runs_at_all():
+ umap.plot.points(mapper)
umap.plot.points(mapper, labels=iris.target)
umap.plot.points(mapper, values=iris.data[:, 0])
- umap.plot.diagnostic(mapper, diagnostic_type="all")
+ umap.plot.points(mapper, theme='fire')
+ umap.plot.diagnos... |
bf23c87c7606cbcf8afcd2c5120c25ede92675c0 | irc/functools.py | irc/functools.py | from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, we save the args and
kwargs with which it was called.
>>> class MyClass(object):
... @save_method_args
... | from __future__ import absolute_import, print_function, unicode_literals
import functools
import collections
def save_method_args(method):
"""
Wrap a method such that when it is called, the args and kwargs are
saved on the method.
>>> class MyClass(object):
... @save_method_args
... d... | Update docstring and expand doctests. | Update docstring and expand doctests.
| Python | mit | jaraco/irc | ---
+++
@@ -5,8 +5,8 @@
def save_method_args(method):
"""
- Wrap a method such that when it is called, we save the args and
- kwargs with which it was called.
+ Wrap a method such that when it is called, the args and kwargs are
+ saved on the method.
>>> class MyClass(object):
... ... |
dfc7d629956f708cf5b69e464fe3a7298ffb6cfa | BotHandler.py | BotHandler.py | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_w... | from twisted.internet import reactor
from Hubbot import Hubbot, HubbotFactory
import GlobalVars
class BotHandler:
botfactories = {}
def __init__(self):
for (server_with_port,channels) in GlobalVars.connections.items():
server = server_with_port.split(":")[0]
port = int(server_w... | Print a quit message when shutting down a bot | Print a quit message when shutting down a bot
| Python | mit | HubbeKing/Hubbot_Twisted | ---
+++
@@ -29,6 +29,7 @@
if server not in self.botfactories:
print "ERROR: Bot for '{}' does not exist yet was asked to stop.".format(server)
else:
+ print "Shutting down bot for server '{}'".format(server)
self.botfactories[server].protocol.quit(quitmessage)
... |
982f4af638e83ee49c87a0dffad2b47daf872749 | workers/data_refinery_workers/downloaders/test_utils.py | workers/data_refinery_workers/downloaders/test_utils.py | import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an ... | import os
from django.test import TestCase, tag
from typing import List
from unittest.mock import patch, call
from urllib.error import URLError
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
@tag('downloaders')
def test_no_jobs_to_create(self):
"""Make sure this fu... | Add tag to downloaders test so it is actually run. | Add tag to downloaders test so it is actually run.
| Python | bsd-3-clause | data-refinery/data_refinery,data-refinery/data_refinery,data-refinery/data_refinery | ---
+++
@@ -8,6 +8,7 @@
from data_refinery_workers.downloaders import utils
class UtilsTestCase(TestCase):
+ @tag('downloaders')
def test_no_jobs_to_create(self):
"""Make sure this function doesn't raise an exception with no files."""
create_processor_job_for_original_files([]) |
813970150109450e53be44715913e5fb3c680c77 | uscampgrounds/models.py | uscampgrounds/models.py | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... | from django.conf import settings
from django.contrib.gis.db import models
class Campground(models.Model):
campground_code = models.CharField(max_length=64)
name = models.CharField(max_length=128)
campground_type = models.CharField(max_length=128)
phone = models.CharField(max_length=128)
comments = ... | Include an override to the default manager to allow geospatial querying. | Include an override to the default manager to allow geospatial querying.
| Python | bsd-3-clause | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds | ---
+++
@@ -13,6 +13,8 @@
amenities = models.TextField()
point = models.PointField(srid=4326)
+ objects = models.GeoManager()
+
def locator_point(self):
return self.point
|
f0dd6411458a19985408404d511584f7c7e26e38 | useful/tests/tasks/call_management_command.py | useful/tests/tasks/call_management_command.py | from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_management_command(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'S... | from django.test import TestCase
from useful.tasks import call_management_command
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
def test_success(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
... | Add failed management command test | Add failed management command test
| Python | isc | yprez/django-useful,yprez/django-useful | ---
+++
@@ -5,6 +5,10 @@
class ManagementCommandTestCase(TestCase):
"""Test calling a management command as a Celery task"""
- def test_management_command(self):
+ def test_success(self):
t = call_management_command.delay('validate')
self.assertEquals(t.status, 'SUCCESS')
+
+ def te... |
bfa98f350a3da827da8359a4e6e7373fc11626cd | changeling/models.py | changeling/models.py | import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
},
'additionalProperties': False,
}
def __init__(self, id=None, nam... | import uuid
import jsonschema
import changeling.exception
class Change(object):
schema = {
'name': 'change',
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
'description': {'type': 'string'},
},
'additionalProperties': Fa... | Add description attr to Change | Add description attr to Change
| Python | apache-2.0 | bcwaldon/changeling,bcwaldon/changeling | ---
+++
@@ -12,13 +12,15 @@
'properties': {
'id': {'type': 'string'},
'name': {'type': 'string'},
+ 'description': {'type': 'string'},
},
'additionalProperties': False,
}
- def __init__(self, id=None, name=None):
+ def __init__(self, id=None... |
0165e350a8b49e11b119c6393de93b28f9523dca | fedoracommunity/mokshaapps/packages/controllers/bugs.py | fedoracommunity/mokshaapps/packages/controllers/bugs.py | from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import ContextAwareWidget
from tg import expose, tmpl_context, require, request
class BugsDashboard(Dashboard... | from tw.api import Widget as TWWidget
from pylons import cache
from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
from moksha.lib.helpers import Widget
from moksha.api.widgets.containers import DashboardContainer
from moksha.api.widgets import Con... | Add BugStats and BugsGrid widgets | Add BugStats and BugsGrid widgets
| Python | agpl-3.0 | Fale/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages,fedora-infra/fedora-packages,Fale/fedora-packages | ---
+++
@@ -1,18 +1,61 @@
+from tw.api import Widget as TWWidget
+from pylons import cache
from moksha.lib.base import Controller
from moksha.lib.helpers import Category, MokshaApp, Not, not_anonymous, MokshaWidget
+from moksha.lib.helpers import Widget
from moksha.api.widgets.containers import DashboardContainer
... |
0ff8c816d739deb19352b6e49cab86ddbde948fb | openelex/tasks/__init__.py | openelex/tasks/__init__.py | from invoke import Collection
from mongoengine import ConnectionError
from openelex.settings import init_db
from fetch import fetch
import archive, cache, datasource, load, load_metadata, transform, validate, bake
# Build tasks namespace
ns = Collection()
ns.add_task(fetch)
ns.add_collection(archive)
ns.add_collect... | from invoke import Collection
from mongoengine import ConnectionError
from openelex.settings import init_db
from fetch import fetch
import archive, cache, datasource, load, load_metadata, transform, validate
# TODO: Add bake task back in
# import bake
# Build tasks namespace
ns = Collection()
ns.add_task(fetch)
ns.... | Disable bake for now because it doesn't match rawresult models | Disable bake for now because it doesn't match rawresult models
| Python | mit | cathydeng/openelections-core,datamade/openelections-core,openelections/openelections-core,cathydeng/openelections-core,openelections/openelections-core,datamade/openelections-core | ---
+++
@@ -4,7 +4,9 @@
from openelex.settings import init_db
from fetch import fetch
-import archive, cache, datasource, load, load_metadata, transform, validate, bake
+import archive, cache, datasource, load, load_metadata, transform, validate
+# TODO: Add bake task back in
+# import bake
# Build tasks nam... |
46ab04db26f6330e732abdf4284242bd83179684 | lametro/management/commands/refresh_guid.py | lametro/management/commands/refresh_guid.py | from django.core.management.base import BaseCommand
from django.conf import settings
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = LegistarAPIBillScraper()
scraper.BASE_UR... | from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.utils import IntegrityError
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
class Command(BaseCommand):
def handle(self, *args, **options):
scraper = Legi... | Update API path, handle updated SubjectGuid | Update API path, handle updated SubjectGuid
| Python | mit | datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic,datamade/la-metro-councilmatic | ---
+++
@@ -1,5 +1,7 @@
from django.core.management.base import BaseCommand
from django.conf import settings
+from django.db.utils import IntegrityError
+
from legistar.bills import LegistarAPIBillScraper
from lametro.models import SubjectGuid, Subject
@@ -8,7 +10,7 @@
def handle(self, *args, **options):
... |
7798d5d8c625a4cbdb689cb7ffa38c2f90c0dc02 | dduplicated/fileManager.py | dduplicated/fileManager.py | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | import os
from threading import Thread
def _delete(path: str, src: str, link: bool):
os.remove(path)
if link:
os.symlink(src, path)
def manager_files(paths, link):
# The first file is preserved to not delete all files in directories.
first = True
src = ""
deleted_files = []
linked_files = []
errors = []
... | Fix in error when analyze directories without duplicates | Fix in error when analyze directories without duplicates
| Python | mit | messiasthi/dduplicated-cli | ---
+++
@@ -37,8 +37,9 @@
# Try The Voight-Kampff if you not recognize if is a replicant or not, all is suspect
def manager(duplicates, create_link=False):
if len(duplicates) == 0:
- return None
-
+ # Return empty list object
+ return []
+
processed_files = []
for files_by_hash in duplicates.values():
... |
bfea504373593bbfbe08ad423a8e98ecbd77565e | mule/utils/multithreading.py | mule/utils/multithreading.py | from collections import defaultdict
from Queue import Queue
from threading import Thread
import thread
_results = defaultdict(list)
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemo... | from collections import defaultdict
from Queue import Queue
from threading import Thread
import thread
_results = defaultdict(list)
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemo... | Add needs to block so the queue doesnt end up full | Add needs to block so the queue doesnt end up full
| Python | apache-2.0 | disqus/mule | ---
+++
@@ -35,7 +35,7 @@
def add(self, func, *args, **kwargs):
"""Add a task to the queue"""
- self.tasks.put((func, args, kwargs, id(self)), False)
+ self.tasks.put((func, args, kwargs, id(self)))
def join(self):
"""Wait for completion of all the tasks in the queue"... |
63935d3c62dad19d2668d0e0633ebd4ce6e6ed26 | actions/kvstore.py | actions/kvstore.py | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | from st2actions.runners.pythonrunner import Action
from st2client.client import Client
from st2client.models.datastore import KeyValuePair
class KVPAction(Action):
def run(self, key, action, st2host='localhost', value=""):
st2_endpoints = {
'action': "http://%s:9101" % st2host,
'r... | Fix create action for key value pair | Fix create action for key value pair
| Python | apache-2.0 | StackStorm/st2cd,StackStorm/st2cd | ---
+++
@@ -25,16 +25,12 @@
return kvp.value
else:
- instance = KeyValuePair()
- instance.id = client.keys.get_by_name(key).name
+ instance = client.keys.get_by_name(key) or KeyValuePair()
+ instance.id = key
instance.name = key
... |
c18f21995ff76681fdfa7e511019f5f27bfea749 | playserver/trackchecker.py | playserver/trackchecker.py | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | from threading import Timer
from . import track
_listeners = []
class TrackChecker():
def __init__(self, interval = 5):
self.listeners = []
self.CHECK_INTERVAL = interval
self.currentSong = ""
self.currentArtist = ""
self.currentAlbum = ""
self.timer = None
def checkSong(self):
song = track.getCurren... | Send data in trackChecker callbacks | Send data in trackChecker callbacks
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver | ---
+++
@@ -31,8 +31,14 @@
_listeners.append(function)
def _callListeners(self):
+ data = {
+ "song": track.getCurrentSong(),
+ "artist": track.getCurrentArtist(),
+ "album": track.getCurrentAlbum()
+ }
+
for listener in _listeners:
- listener()
+ listener(data)
def startTimer(self):
self... |
51080ad6e8ad38ea8c22593b07d70b27965545bd | api/views/users.py | api/views/users.py | from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset =... | from rest_framework import viewsets, status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from api.models import User
from api.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset =... | Make signup not require token in API | Make signup not require token in API
| Python | mit | frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq,frostblooded/kanq | ---
+++
@@ -10,6 +10,8 @@
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
+
+ permission_classes_by_action = {'create': []}
@detail_route(methods=['put'])
def follow(self, request, pk=None): # follows a given user
@@ -28,3 +30,10 @@
... |
6d7c1172ff156f376c61476bccf9912598059d19 | rabbitpy/__init__.py | rabbitpy/__init__.py | __version__ = '0.10.0'
version = __version__
from rabbitpy.connection import Connection
from rabbitpy.exchange import Exchange
from rabbitpy.message import Message
from rabbitpy.amqp_queue import Queue
from rabbitpy.tx import Tx
from rabbitpy.simple import consume
from rabbitpy.simple import get
from rabbitpy.simple ... | __version__ = '0.10.0'
version = __version__
DEBUG = False
import logging
try:
from logging import NullHandler
except ImportError:
# Python 2.6 does not have a NullHandler
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger('rabbitpy').addHandler(NullHa... | Fix order of operations issues | Fix order of operations issues
| Python | bsd-3-clause | jonahbull/rabbitpy,gmr/rabbitpy,gmr/rabbitpy | ---
+++
@@ -1,5 +1,19 @@
__version__ = '0.10.0'
version = __version__
+
+DEBUG = False
+
+import logging
+
+try:
+ from logging import NullHandler
+except ImportError:
+ # Python 2.6 does not have a NullHandler
+ class NullHandler(logging.Handler):
+ def emit(self, record):
+ pass
+
+logg... |
7c60024684024b604eb19a02d119adab547ed0d1 | ovp_organizations/migrations/0023_auto_20170627_0236.py | ovp_organizations/migrations/0023_auto_20170627_0236.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
]
... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-06-27 02:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
('o... | Add ovp_core_0011 migration as dependency for ovp_organizations_0023 | Add ovp_core_0011 migration as dependency for ovp_organizations_0023
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations | ---
+++
@@ -10,6 +10,7 @@
dependencies = [
('ovp_organizations', '0022_auto_20170613_1424'),
+ ('ovp_core', '0011_simpleaddress'),
]
operations = [ |
b2f40d9b1ed9d78a4fdc1f73e64575a26d117d0c | nuitka/tools/release/msi_create/__main__.py | nuitka/tools/release/msi_create/__main__.py | # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | # Copyright 2017, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | Copy created MSI to dedicated folder. | Release: Copy created MSI to dedicated folder.
* The "dist" folder is erased each time and we determine the result
name from being the only MSI file.
| Python | apache-2.0 | kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka | ---
+++
@@ -19,11 +19,23 @@
"""
+import os
+import shutil
+
+from nuitka.tools.Basics import goHome
from nuitka.tools.release.MSI import createMSIPackage
def main():
- createMSIPackage()
+ goHome()
+
+ msi_filename = createMSIPackage()
+
+ if not os.path.exists("msi"):
+ os.makedirs("msi... |
41a8d7e1e762133fb24608524e229b882fabda22 | packages/pegasus-python/src/Pegasus/service/defaults.py | packages/pegasus-python/src/Pegasus/service/defaults.py | import os
import tempfile
# SERVER CONFIGURATION
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5000
# SSL config: path to certificate and private key files
CERTIFICATE = None
PRIVATE_KEY = None
# Max number of processes to fork when handling requests
MAX_PROCESSES = 10
# Enable debugging
DEBUG = False
# The secret key ... | import os
import tempfile
# SERVER CONFIGURATION
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5000
# SSL config: path to certificate and private key files
CERTIFICATE = None
PRIVATE_KEY = None
# Max number of processes to fork when handling requests
MAX_PROCESSES = 10
# Enable debugging
DEBUG = False
# The secret key ... | Use SimpleCache instead of Filesystemcache as it can cause errors due to use of different pickle versions. | Use SimpleCache instead of Filesystemcache as it can cause errors due to use of different pickle versions.
| Python | apache-2.0 | pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus,pegasus-isi/pegasus | ---
+++
@@ -24,8 +24,7 @@
PROCESS_SWITCHING = True
# Flask cache configuration
-CACHE_TYPE = "filesystem"
-CACHE_DIR = os.path.join(tempfile.gettempdir(), "pegasus-service")
+CACHE_TYPE = "flask_caching.backends.SimpleCache"
#
# Authorization - |
dda88345334985796dac2095f6e78bb106bc19b3 | pullpush/pullpush.py | pullpush/pullpush.py | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(se... | #!/usr/bin/env python3
import git
class PullPush:
def __init__(self, repo_dir):
self.repo_dir = repo_dir
self.repo = None
def pull(self, source_repo):
"""
Pulls the remote source_repo and stores it in the repo_dir directory.
"""
self.repo = git.Repo.init(se... | Check of repo was pulled | Check of repo was pulled
| Python | mit | martialblog/git-pullpush | ---
+++
@@ -35,6 +35,10 @@
Pushes the previously pulled repo to the target_repo.
"""
+ if self.repo is None:
+ # TODO Better handling
+ return
+
origin = self.repo.remotes.origin
self.set_target_repo(target_repo)
self.repo.create_head('master... |
beb8f12e4a8290d4107cdb91a321a6618a038ef9 | rose_trellis/util.py | rose_trellis/util.py | from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.... | from urllib.parse import urljoin
import time
import asyncio
from typing import Any
from typing import Callable
TRELLO_URL_BASE = 'https://api.trello.com/1/'
def join_url(part: str) -> str:
"""
Adds `part` to API base url. Always returns url without trailing slash.
:param part:
:return: url
"""
part = part.... | Make easy_run better by taking the generator from coroutines | Make easy_run better by taking the generator from coroutines
| Python | mit | dmwyatt/rose_trellis | ---
+++
@@ -24,6 +24,6 @@
return newpath
-def easy_run(func: Callable[Any], *args, **kwargs) -> Any:
+def easy_run(gen) -> Any:
el = asyncio.get_event_loop()
- return el.run_until_complete(func(*args, **kwargs))
+ return el.run_until_complete(gen) |
2c15d96a7d77269fbe41e5b2940873fc849d411a | random_projection.py | random_projection.py | """
Random projection, Assignment 1c
"""
| """
Random projection, Assignment 1c
"""
import numpy as np
import matplotlib.pylab as plt
import random, mnist_dataloader
from numpy import dtype
"""
Generate random projection matrix R
@param: k, the reduced number of dimensions
@param: d, the original number of dimensions
@return: R, the generated random projection... | Add random projection matrix generation and random projection. | Add random projection matrix generation and random projection.
| Python | mit | lidalei/DataMining | ---
+++
@@ -1,3 +1,59 @@
"""
Random projection, Assignment 1c
"""
+import numpy as np
+import matplotlib.pylab as plt
+import random, mnist_dataloader
+from numpy import dtype
+
+"""
+Generate random projection matrix R
+@param: k, the reduced number of dimensions
+@param: d, the original number of dimensions
+@re... |
5596f599287d36126b3a6e30e7579eb00ed07d73 | downstream_farmer/utils.py | downstream_farmer/utils.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote_plus
except ImportError:
from urllib.parse import quote_plus
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to k... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
def urlify(string):
""" You might be wondering: why is this here at all, since it's basically
doing exactly what the quote_plus function in urllib does. Well, to keep
th... | Fix method to use quote, not quote_plus | Fix method to use quote, not quote_plus
| Python | mit | Storj/downstream-farmer | ---
+++
@@ -3,9 +3,9 @@
try:
- from urllib import quote_plus
+ from urllib import quote
except ImportError:
- from urllib.parse import quote_plus
+ from urllib.parse import quote
def urlify(string):
@@ -20,4 +20,4 @@
:param string: String to URLify
:return: URLified string
"""
- ... |
f842cf7605018e85b13f27f3a0886122e4cbb80c | expert_tourist/views.py | expert_tourist/views.py | from collections import namedtuple
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected... | from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from .models import User
from .errors import APIException
from .schemas import UserSchema
api = Blueprint('api', __name__)
@api.route('/whoami')
@jwt_required
def protected():
return jsonify(token=get_jwt... | Return the whole user in successful login | Return the whole user in successful login
| Python | mit | richin13/expert-tourist | ---
+++
@@ -1,5 +1,3 @@
-from collections import namedtuple
-
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
@@ -41,7 +39,6 @@
user = User.validate_login(conditions[0], conditions[1])
if user:
- print(user.token)
- return jsoni... |
01a9b6457d78dd583637bf8174edda40e2bd3276 | django_website/blog/feeds.py | django_website/blog/feeds.py | from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self)... | from __future__ import absolute_import
from django.contrib.syndication.views import Feed
from .models import Entry
class WeblogEntryFeed(Feed):
title = "The Django weblog"
link = "http://www.djangoproject.com/weblog/"
description = "Latest news about Django, the Python Web framework."
def items(self)... | Add author name and body to the weblog RSS feed. | Add author name and body to the weblog RSS feed.
| Python | bsd-3-clause | alawnchen/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,khkaminska/djangoproject.com,khkaminska/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,rmoorman/djangoproject.com,django/djangoproject.com,nanuxbe/django,django/djangoproject.com,xavierdutreilh/djangoproj... | ---
+++
@@ -13,3 +13,9 @@
def item_pubdate(self, item):
return item.pub_date
+
+ def item_author_name(self, item):
+ return item.author
+
+ def item_description(self, item):
+ return item.body_html |
5adb6de6b926a54dc9a6dd334a34d42dd2044481 | src/pushover_complete/pushover_api.py | src/pushover_complete/pushover_api.py | import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound... | import requests
from .error import PushoverCompleteError
class PushoverAPI(object):
def __init__(self, token):
self.token = token
def send_message(self, user, message, device=None, title=None, url=None, url_title=None,
priority=None, retry=None, expire=None, timestamp=None, sound... | Split send_message out in to _send_message to reuse functionality later | Split send_message out in to _send_message to reuse functionality later
| Python | mit | scolby33/pushover_complete | ---
+++
@@ -31,5 +31,16 @@
'https://api.pushover.net/1/messages.json',
data=payload,
headers=headers
+ def get_sounds(self):
+ resp = requests.get(
+ urljoin(PUSHOVER_API_URL, 'sounds.json'),
+ data={'token': self.token}
)
- return... |
f87b8c5b94e3e163f19ea0414d1fb2c42f09c166 | test/test_genmidi.py | test/test_genmidi.py | import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInst... | import unittest
import tempfile
from pyknon.MidiFile import MIDIFile
from pyknon.genmidi import Midi, MidiError
from pyknon.music import NoteSeq, Note
class TestMidi(unittest.TestCase):
def test_init(self):
midi = Midi(1, tempo=120)
self.assertEqual(midi.number_tracks, 1)
self.assertIsInst... | Test for sequence of chords | Test for sequence of chords
| Python | mit | palmerev/pyknon,kroger/pyknon | ---
+++
@@ -22,6 +22,11 @@
midi.seq_notes(NoteSeq("C D"), track=0)
midi.seq_notes(NoteSeq("D E"), track=1)
+ def test_seq_chords(self):
+ chords = [NoteSeq("C E G"), NoteSeq("G B D")]
+ midi = Midi()
+ midi.seq_chords(chords)
+
class TestWriteMidi(unittest.TestCa... |
86cf16611fe4126f4345477b24da5c15fed4c1e8 | eval_kernel/eval_kernel.py | eval_kernel/eval_kernel.py | from __future__ import print_function
from jupyter_kernel import MagicKernel
import os
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
... | from __future__ import print_function
from jupyter_kernel import MagicKernel
class EvalKernel(MagicKernel):
implementation = 'Eval'
implementation_version = '1.0'
language = 'python'
language_version = '0.1'
banner = "Eval kernel - evaluates simple Python statements and expressions"
env = {}
... | Update eval kernel to use python magic. | Update eval kernel to use python magic.
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -1,7 +1,7 @@
from __future__ import print_function
from jupyter_kernel import MagicKernel
-import os
+
class EvalKernel(MagicKernel):
implementation = 'Eval'
@@ -20,17 +20,25 @@
"""
self.env[name] = value
- def get_kernel_help_on(self, expr, level):
- return "Sorry... |
b0b4bad0ca68ebd1927229e85e7116fb63126c65 | src/olympia/zadmin/helpers.py | src/olympia/zadmin/helpers.py | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
... | from jingo import register
from olympia.amo.urlresolvers import reverse
@register.function
def admin_site_links():
return {
'addons': [
('Search for add-ons by name or id',
reverse('zadmin.addon-search')),
('Featured add-ons', reverse('zadmin.features')),
... | Remove generate error page from admin site | Remove generate error page from admin site
| Python | bsd-3-clause | bqbn/addons-server,wagnerand/olympia,harry-7/addons-server,wagnerand/addons-server,harikishen/addons-server,psiinon/addons-server,lavish205/olympia,mstriemer/addons-server,kumar303/addons-server,Prashant-Surya/addons-server,mstriemer/olympia,mozilla/addons-server,harikishen/addons-server,Revanth47/addons-server,mstriem... | ---
+++
@@ -32,7 +32,6 @@
('Purge data from memcache', reverse('zadmin.memcache')),
('View event log', reverse('admin:editors_eventlog_changelist')),
('View addon log', reverse('admin:devhub_activitylog_changelist')),
- ('Generate error', reverse('zadmin.generate-erro... |
be964b02036159567efcaecce5b5d905f23985af | deduper/scanfiles.py | deduper/scanfiles.py | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to... | # This file is part of the File Deduper project. It is subject to
# the the revised 3-clause BSD license terms as set out in the LICENSE
# file found in the top-level directory of this distribution. No part of this
# project, including this file, may be copied, modified, propagated, or
# distributed except according to... | Check that fullpath is a regular file before continuing | Check that fullpath is a regular file before continuing
| Python | bsd-3-clause | cgspeck/filededuper | ---
+++
@@ -24,6 +24,9 @@
fullpath = os.path.join(root, filename)
+ if not os.path.isfile(fullpath):
+ continue
+
if Util.file_record_exists(session, fullpath):
print('{count} of {length}: Skipping {filename}'.format(
count=... |
a95e891b637f0182031f229465bcded966100889 | readthedocs/core/models.py | readthedocs/core/models.py | from django.db import models
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(User, unique=True, related_name='profile')
whitelisted = models.BooleanField()
... | from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
class UserProfile (models.Model):
"""Additional information about a User.
"""
user = models.ForeignKey(U... | Add post save signal for user creation | Add post save signal for user creation
| Python | mit | safwanrahman/readthedocs.org,raven47git/readthedocs.org,sunnyzwh/readthedocs.org,agjohnson/readthedocs.org,d0ugal/readthedocs.org,GovReady/readthedocs.org,kenshinthebattosai/readthedocs.org,jerel/readthedocs.org,jerel/readthedocs.org,dirn/readthedocs.org,gjtorikian/readthedocs.org,titiushko/readthedocs.org,wijerasa/rea... | ---
+++
@@ -1,4 +1,6 @@
from django.db import models
+from django.db.models.signals import post_save
+from django.dispatch import receiver
from django.contrib.auth.models import User
STANDARD_EMAIL = "anonymous@readthedocs.org"
@@ -33,3 +35,9 @@
else:
email = STANDARD_EMAIL
return ... |
bf6565d3bf3c2345a7187d07585bdbf08db06f61 | reddit_adzerk/adzerkads.py | reddit_adzerk/adzerkads.py | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
si... | from urllib import quote
from pylons import c, g
from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR
FRONTPAGE_NAME = "-reddit.com"
class Ads(BaseAds):
def __init__(self):
BaseAds.__init__(self)
url_key = "adzerk_https_url" if c.secure else "adzerk_url"
si... | Add loggedin keyword to adzerk Ads. | Add loggedin keyword to adzerk Ads.
| Python | bsd-3-clause | madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk,madbook/reddit-plugin-adzerk | ---
+++
@@ -22,5 +22,6 @@
self.ad_url = g.config[url_key].format(
subreddit=quote(site_name.lower()),
origin=c.request_origin,
+ loggedin="loggedin" if c.user_is_loggedin else "loggedout",
)
self.frame_id = "ad_main" |
fe22a0f9ca92ef0e76bb2f730a2b22da500db5dd | addons/website_sale_management/__manifest__.py | addons/website_sale_management/__manifest__.py | # -*- encoding: utf-8 -*-
{
'name': 'Website Sale - Sale Management',
'version': '1.0',
'category': 'Website',
'description': """
Display orders to invoice in website dashboard.
""",
'depends': [
'sale_management',
'website_sale',
],
'installable': True,
'autoinstall': Tr... | # -*- encoding: utf-8 -*-
{
'name': 'Website Sale - Sale Management',
'version': '1.0',
'category': 'Website',
'description': """
Display orders to invoice in website dashboard.
""",
'depends': [
'sale_management',
'website_sale',
],
'installable': True,
'auto_install': T... | Fix auto_install typo in manifest | [FIX] website_sale_management: Fix auto_install typo in manifest
| Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -11,7 +11,7 @@
'website_sale',
],
'installable': True,
- 'autoinstall': True,
+ 'auto_install': True,
'data': [
],
'demo': [ |
ad17f4a48bdee7ca57e8fe66e4658821b3c8789e | corehq/apps/userreports/migrations/0018_ucrexpression.py | corehq/apps/userreports/migrations/0018_ucrexpression.py | # Generated by Django 2.2.27 on 2022-04-12 10:28
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name=... | # Generated by Django 3.2.12 on 2022-04-12 15:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userreports', '0017_index_cleanup'),
]
operations = [
migrations.CreateModel(
name='UCRExpression',
fields=[
... | Use django 3 to make migration | Use django 3 to make migration
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,6 +1,5 @@
-# Generated by Django 2.2.27 on 2022-04-12 10:28
+# Generated by Django 3.2.12 on 2022-04-12 15:07
-import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
@@ -19,7 +18,7 @@
('domain', models.CharField(db_index=True, max_length=255)),
... |
7ee5692a98a6dfc714a05f1add8e72b09c52929e | students/psbriant/final_project/clean_data.py | students/psbriant/final_project/clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
# print(data["Date Text"].head(... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Code for Final Project
"""
import pandas
from datetime import datetime
# Change source to smaller file.
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
parse_dat... | Add code to split month and year into new columns. | Add code to split month and year into new columns.
| Python | unlicense | UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -12,18 +12,24 @@
from datetime import datetime
# Change source to smaller file.
-data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
+data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv",
+ parse_dates=[0], infer_datetime_format=True)
+t... |
f334c9770dd7d9fb38fd5c118df806dbf532d17a | wsgi.py | wsgi.py | # -*- coding: utf-8 -*-
"""
wsgi
~~~~
ieee wsgi module
"""
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from myip.factory import create_app
if __name__ == "__main__":
run_simple('localhost', 5000, create_app(), use_reloader=True,
use_debugger... | # -*- coding: utf-8 -*-
"""
wsgi
~~~~
ieee wsgi module
"""
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from myip.factory import create_app
application = create_app()
if __name__ == "__main__":
run_simple('localhost', 5000, application, use_reloader=True,
... | Add application variable for the procfile. | Add application variable for the procfile.
| Python | mit | brotatos/myip,brotatos/myip | ---
+++
@@ -11,7 +11,9 @@
from myip.factory import create_app
+application = create_app()
+
if __name__ == "__main__":
- run_simple('localhost', 5000, create_app(), use_reloader=True,
+ run_simple('localhost', 5000, application, use_reloader=True,
use_debugger=True, use_evalex=True) |
d52a7b19f7b5596e88d7233dfea35a70b2645385 | osmaxx-py/excerptconverter/converter_manager.py | osmaxx-py/excerptconverter/converter_manager.py | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
export_options = {}
for Converter in BaseExcerptConverter.available_converters:
export_options[Converter.__name__] = Converter.converter_confi... | from excerptconverter.baseexcerptconverter import BaseExcerptConverter
class ConverterManager:
@staticmethod
def converter_configuration():
return {Converter.__name__: Converter.converter_configuration()
for Converter in BaseExcerptConverter.available_converters}
def __init__(self... | Replace loop by dictionary comprehension | Refactoring: Replace loop by dictionary comprehension
| Python | mit | geometalab/osmaxx,geometalab/drf-utm-zone-info,geometalab/drf-utm-zone-info,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx-frontend,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx,geometalab/osmaxx-frontend | ---
+++
@@ -4,10 +4,8 @@
class ConverterManager:
@staticmethod
def converter_configuration():
- export_options = {}
- for Converter in BaseExcerptConverter.available_converters:
- export_options[Converter.__name__] = Converter.converter_configuration()
- return export_option... |
d9da661c9493c0d1b54eeda8bb416ad98ca07a33 | acapi/resources/environmentlist.py | acapi/resources/environmentlist.py | """ Acquia Cloud API server list resource. """
from .acquialist import AcquiaList
class EnvironmentList(AcquiaList):
"""Dict of Acquia Cloud API Server resources keyed by hostname."""
def set_base_uri(self, base_uri):
""" Set the base URI for server resources.
Parameters
----------... | """ Acquia Cloud API server list resource. """
from .acquialist import AcquiaList
class EnvironmentList(AcquiaList):
"""Dict of Acquia Cloud API Server resources keyed by hostname."""
def set_base_uri(self, base_uri):
""" Set the base URI for server resources.
Parameters
----------... | Use correct URI for looking up environment resources | Use correct URI for looking up environment resources
| Python | mit | skwashd/python-acquia-cloud | ---
+++
@@ -15,5 +15,5 @@
base_uri : str
The base URI to use for generating the new URI.
"""
- uri = '{}/servers'.format(base_uri)
+ uri = '{}/envs'.format(base_uri)
self.uri = uri |
f5d864c2a5c9b4d2ea1ff95e59d60adf2ebd176e | recipes/sos-bash/run_test.py | recipes/sos-bash/run_test.py | import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
@unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32')
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as k... | import unittest
import sys
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel() as kc:
execute(kc=kc, code='a = 1')
stdout, stderr = a... | Test does not have to fail under windows | Test does not have to fail under windows
| Python | bsd-3-clause | birdsarah/staged-recipes,synapticarbors/staged-recipes,SylvainCorlay/staged-recipes,kwilcox/staged-recipes,johanneskoester/staged-recipes,synapticarbors/staged-recipes,asmeurer/staged-recipes,SylvainCorlay/staged-recipes,scopatz/staged-recipes,patricksnape/staged-recipes,goanpeca/staged-recipes,hadim/staged-recipes,had... | ---
+++
@@ -4,7 +4,6 @@
from sos_notebook.test_utils import sos_kernel
from ipykernel.tests.utils import execute, wait_for_idle, assemble_output
-@unittest.skipIf(sys.platform == 'win32', 'bash does not exist on win32')
class TestSoSKernel(unittest.TestCase):
def testKernel(self):
with sos_kernel()... |
c7bc130efaaba1e079bc8a0f39f37ef3c2534413 | Yank/tests/test_utils.py | Yank/tests/test_utils.py | #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#====... | #!/usr/local/bin/env python
"""
Test various utility functions.
"""
#=============================================================================================
# GLOBAL IMPORTS
#=============================================================================================
from yank.utils import YankOptions
#====... | Add more informative error message for yank options assertion test. | Add more informative error message for yank options assertion test.
| Python | mit | andrrizzi/yank,andrrizzi/yank,choderalab/yank,andrrizzi/yank,choderalab/yank | ---
+++
@@ -24,7 +24,7 @@
assert yank_opt['option2'] == 'test'
assert yank_opt['option1'] == 1 # command line > yaml
- assert len(yank_opt) == 2
+ assert len(yank_opt) == 2, "Excepted two options, found: %s" % str([x for x in yank_opt])
# runtime > command line
yank_opt['option1'] = 0 |
81dc92b3c2875b6775d33321b1bcd9f994be8a10 | txircd/modules/extra/snotice_remoteconnect.py | txircd/modules/extra/snotice_remoteconnect.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
re... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class SnoRemoteConnect(ModuleData):
implements(IPlugin, IModuleData)
name = "ServerNoticeRemoteConnect"
def __init__(self):
self.burstingServer = None
def actions(self):
re... | Fix checking a name against an object | Fix checking a name against an object
| Python | bsd-3-clause | Heufneutje/txircd | ---
+++
@@ -17,9 +17,10 @@
("endburstcommand", 1, self.markEndBurst) ]
def sendRemoteConnectNotice(self, user, *params):
- server = self.ircd.servers[user.uuid[:3]].name
+ server = self.ircd.servers[user.uuid[:3]]
if server == self.burstingServer:
return
+ server = server.name
message = ... |
8ecf97b338dd37eaf5a4e2672e33e27cc40d215d | sacred/observers/__init__.py | sacred/observers/__init__.py | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observer... | #!/usr/bin/env python
# coding=utf-8
from __future__ import division, print_function, unicode_literals
from sacred.commandline_options import CommandLineOption
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
from sacred.observer... | Add TinyDbReader to observers init | Add TinyDbReader to observers init
| Python | mit | IDSIA/sacred,IDSIA/sacred | ---
+++
@@ -7,7 +7,7 @@
from sacred.observers.base import RunObserver
from sacred.observers.file_storage import FileStorageObserver
import sacred.optional as opt
-from sacred.observers.tinydb_hashfs import TinyDbObserver
+from sacred.observers.tinydb_hashfs import TinyDbObserver, TinyDbReader
if opt.has_pymongo... |
04fec1c50ac81c1b80c22f37bd43845a0e08c1a3 | fancypages/assets/models.py | fancypages/assets/models.py | from django.db import models
from django.utils.translation import ugettext as _
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=255)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
date_modified = models.DateTimeField(_("Date modified"), auto_now... | from django.db import models
from django.utils.translation import ugettext as _
try:
from django.contrib.auth import get_user_model
User = get_user_model()
except ImportError:
from django.contrib.auth.models import User
class AbstractAsset(models.Model):
name = models.CharField(_("Name"), max_length=... | Add support for custom user model (Django 1.5+) | Add support for custom user model (Django 1.5+)
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages | ---
+++
@@ -1,5 +1,11 @@
from django.db import models
from django.utils.translation import ugettext as _
+
+try:
+ from django.contrib.auth import get_user_model
+ User = get_user_model()
+except ImportError:
+ from django.contrib.auth.models import User
class AbstractAsset(models.Model):
@@ -9,7 +15,... |
7629afde2627457b4f4b19e1542a87e695c1837d | tests/events/test_models.py | tests/events/test_models.py | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | """Unit tests for events models."""
import datetime
from app.events.factories import EventFactory
from app.events.models import Event
def test_event_factory(db): # noqa: D103
# GIVEN an empty database
assert Event.objects.count() == 0
# WHEN saving a new event instance to the database
EventFactory.... | Make sure slug gets updated on date change | Make sure slug gets updated on date change
| Python | mit | FlowFX/reggae-cdmx,FlowFX/reggae-cdmx | ---
+++
@@ -42,3 +42,19 @@
# THEN it gets a slug generated from its date and title
assert e.slug == '2018-01-01-one-happy-family'
+
+
+def test_event_slug_gets_updated_on_date_change(db): # noqa: D103
+ # GIVEN an event
+ e = EventFactory.create(
+ date=datetime.date(2018, 1, 1),
+ ve... |
8209b77a16c899436418dbc85dc891f671949bfc | bot/logger/message_sender/asynchronous.py | bot/logger/message_sender/asynchronous.py | from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sende... | from bot.logger.message_sender import IntermediateMessageSender, MessageSender
from bot.multithreading.work import Work
from bot.multithreading.worker import Worker
class AsynchronousMessageSender(IntermediateMessageSender):
def __init__(self, sender: MessageSender, worker: Worker):
super().__init__(sende... | Clarify work action in AsynchronousMessageSender | Clarify work action in AsynchronousMessageSender
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -9,4 +9,4 @@
self.worker = worker
def send(self, text):
- self.worker.post(Work(lambda: self.sender.send(text), "async_message_send"))
+ self.worker.post(Work(lambda: self.sender.send(text), "asynchronous_message_sender:send")) |
ccf3c508bd6750073ea3bbaefff567b92880df73 | rest_framework/authtoken/serializers.py | rest_framework/authtoken/serializers.py | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... | from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
username... | Fix missing message in ValidationError | Fix missing message in ValidationError | Python | bsd-2-clause | jtiai/django-rest-framework,sbellem/django-rest-framework,kylefox/django-rest-framework,jerryhebert/django-rest-framework,zeldalink0515/django-rest-framework,adambain-vokal/django-rest-framework,tcroiset/django-rest-framework,alacritythief/django-rest-framework,johnraz/django-rest-framework,rhblind/django-rest-framewor... | ---
+++
@@ -18,7 +18,7 @@
if user:
if not user.is_active:
msg = _('User account is disabled.')
- raise serializers.ValidationError()
+ raise serializers.ValidationError(msg)
attrs['user'] = user
... |
ac1a2191b7923a21b621c5e2ea6465e79a36e579 | doc2dash/__init__.py | doc2dash/__init__.py | """
Convert docs to Dash.app's docset format.
"""
from __future__ import absolute_import, division, print_function
__author__ = 'Hynek Schlawack'
__version__ = '2.0.0'
__license__ = 'MIT'
| """
Convert docs to Dash.app's docset format.
"""
from __future__ import absolute_import, division, print_function
__author__ = 'Hynek Schlawack'
__version__ = '2.0.0-dev'
__license__ = 'MIT'
| Use -dev tag for in-dev versions | Use -dev tag for in-dev versions
| Python | mit | hynek/doc2dash,hynek/doc2dash | ---
+++
@@ -6,5 +6,5 @@
__author__ = 'Hynek Schlawack'
-__version__ = '2.0.0'
+__version__ = '2.0.0-dev'
__license__ = 'MIT' |
5f6fb5866ca74793b05308ac27c4698033068cfe | tvtk/tests/test_garbage_collection.py | tvtk/tests/test_garbage_collection.py | """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from t... | """ Tests for the garbage collection of objects in tvtk package.
"""
# Authors: Deepak Surti, Ioannis Tziakos
# Copyright (c) 2015, Enthought, Inc.
# License: BSD Style.
import unittest
from traits.etsconfig.api import ETSConfig
from tvtk.pyface.tvtk_scene import TVTKScene
from tvtk.pyface.scene import Scene
from tvt... | Test TVTKScene garbage collection and renaming | Test TVTKScene garbage collection and renaming
| Python | bsd-3-clause | alexandreleroux/mayavi,alexandreleroux/mayavi,liulion/mayavi,liulion/mayavi,dmsurti/mayavi,dmsurti/mayavi | ---
+++
@@ -7,6 +7,7 @@
import unittest
from traits.etsconfig.api import ETSConfig
+from tvtk.pyface.tvtk_scene import TVTKScene
from tvtk.pyface.scene import Scene
from tvtk.pyface.scene_model import SceneModel
from tvtk.tests.common import TestGarbageCollection
@@ -14,18 +15,27 @@
class TestTVTKGarbageColle... |
6af828b3f541adf0c42e73d76d7998bc21a072cb | sample_proj/polls/filters.py | sample_proj/polls/filters.py | from datafilters.filterform import FilterForm
from datafilters.specs import (GenericSpec, DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = GenericSpec('choice__votes')
has_choice_with_votes = GreaterThanZero... | from datafilters.filterform import FilterForm
from datafilters.filterspec import FilterSpec
from datafilters.specs import (DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)
class PollsFilterForm(FilterForm):
has_exact_votes = FilterSpec('choice__votes')
has_cho... | Use FilterSpec instead of GenericSpec in sample_proj | Use FilterSpec instead of GenericSpec in sample_proj
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters | ---
+++
@@ -1,11 +1,12 @@
from datafilters.filterform import FilterForm
-from datafilters.specs import (GenericSpec, DateFieldFilterSpec,
+from datafilters.filterspec import FilterSpec
+from datafilters.specs import (DateFieldFilterSpec,
GreaterThanFilterSpec, ContainsFilterSpec,
GreaterThanZeroFilterSpec)... |
d611eb18b234c7d85371d38d8c875aaae447c231 | testing/urls.py | testing/urls.py | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.views.generic import View
urlpatterns = patterns('',
url(r'foo$', View.as_view(), name="foo"),
)
| # -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import View
urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
]
| Fix tests remove unneccessary imports | Fix tests remove unneccessary imports
| Python | bsd-3-clause | niwinz/django-sites,niwinz/django-sites | ---
+++
@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*-
-from django.conf.urls import patterns, include, url
+from django.conf.urls import url
from django.views.generic import View
-urlpatterns = patterns('',
+urlpatterns = [
url(r'foo$', View.as_view(), name="foo"),
-)
+] |
69ce0c86e2eb5be9b4977cc6033c5aa330c88122 | tfx/utils/dsl_utils_test.py | tfx/utils/dsl_utils_test.py | # Copyright 2019 Google LLC. 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 a... | # Copyright 2019 Google LLC. 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 a... | Change a test name to CamelCase instead of snake, to conform with TFX convention. | Change a test name to CamelCase instead of snake, to conform with TFX convention.
PiperOrigin-RevId: 246340014
| Python | apache-2.0 | tensorflow/tfx,tensorflow/tfx | ---
+++
@@ -25,7 +25,7 @@
class DslUtilsTest(tf.test.TestCase):
- def csv_input(self):
+ def testCsvInput(self):
[csv] = dsl_utils.csv_input(uri='path')
self.assertEqual('ExternalPath', csv.type_name)
self.assertEqual('path', csv.uri) |
72dd3f7245f07f7c596da707dffbb67ae6aa7cd0 | tohu/custom_generator_v2.py | tohu/custom_generator_v2.py | import logging
logger = logging.getLogger('tohu')
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
logger.debug('[DDD] CustomGeneratorMetaV2.__new__')
logger.debug(f' - metacls={metacls}')
logger.debug(f' - cg_name={cg_name}')
logg... | import logging
logger = logging.getLogger('tohu')
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
logger.debug('[DDD]')
logger.debug('CustomGeneratorMetaV2.__new__')
logger.debug(f' - metacls={metacls}')
logger.debug(f' - cg_name={cg_name}')
... | Tweak debugging messages, add comments | Tweak debugging messages, add comments
| Python | mit | maxalbert/tohu | ---
+++
@@ -6,14 +6,22 @@
class CustomGeneratorMetaV2(type):
def __new__(metacls, cg_name, bases, clsdict):
- logger.debug('[DDD] CustomGeneratorMetaV2.__new__')
- logger.debug(f' - metacls={metacls}')
- logger.debug(f' - cg_name={cg_name}')
- logger.debug(f' ... |
af2b561cd1a25fc4abd7c7948e5ff8ceb507a497 | tests/cli/test_rasa_shell.py | tests/cli/test_rasa_shell.py | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
[--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN... | from typing import Callable
from _pytest.pytester import RunResult
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet]
[--conversation-id CONVERSATION_ID] [-m MODEL]
[--log-file LOG_... | Adjust rasa shell help test to changes. | Adjust rasa shell help test to changes.
| Python | apache-2.0 | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | ---
+++
@@ -5,9 +5,10 @@
def test_shell_help(run: Callable[..., RunResult]):
output = run("shell", "--help")
- help_text = """usage: rasa shell [-h] [-v] [-vv] [--quiet] [-m MODEL] [--log-file LOG_FILE]
- [--endpoints ENDPOINTS] [-p PORT] [-t AUTH_TOKEN]
- [--cors [CORS [C... |
43ca4bf6a9c30055385519bb4c4472a530cce4dd | site_scons/site_tools/build_and_compress.py | site_scons/site_tools/build_and_compress.py | def build_and_compress(env, source, target):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
d... | def build_and_compress(env, target, source):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact(
target = target,
source = uncompressed,
)
return compressed
def generate(env):
env.AddMethod(build_and_compress, 'BuildAndCompress')
d... | Fix argument order in BuildAndCompress pseudo-builder | Fix argument order in BuildAndCompress pseudo-builder
| Python | mit | robobrobro/terminus | ---
+++
@@ -1,4 +1,4 @@
-def build_and_compress(env, source, target):
+def build_and_compress(env, target, source):
env.Tool('compactor')
uncompressed = env.Program('uncompressed', source)
compressed = env.Compact( |
fb7c10fd96747285e13f89a5415da8e09c8beae6 | setup.py | setup.py | from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :... | from setuptools import find_packages, setup
setup(
name='incuna-pigeon',
version='0.0.0',
description='Notification management',
url='https://github.com/incuna/incuna-pigeon',
author='Incuna',
author_email='admin@incuna.com',
license='BSD',
classifiers=[
'Development Status :... | Update Development Status from Planning to Alpha | Update Development Status from Planning to Alpha
| Python | bsd-2-clause | incuna/incuna-pigeon | ---
+++
@@ -12,7 +12,7 @@
author_email='admin@incuna.com',
license='BSD',
classifiers=[
- 'Development Status :: 1 - Planning',
+ 'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Topic :: Communications',
'License :: OSI Approved :: BSD Lic... |
cc7da0c83a27e42619f0d800b11ef7bf7f82e4bb | setup.py | setup.py | from distutils.core import setup
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = '0.3.0',
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'https://github.com/... | from distutils.core import setup
VERSION='0.3.1'
setup(
name = 'sdnotify',
packages = ['sdnotify'],
version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett Bethke',
author_email = 'bbethke@gmail.com',
url = 'h... | Include LICENSE.txt in the package tarball | Include LICENSE.txt in the package tarball
| Python | mit | bb4242/sdnotify | ---
+++
@@ -1,13 +1,16 @@
from distutils.core import setup
+
+VERSION='0.3.1'
+
setup(
name = 'sdnotify',
packages = ['sdnotify'],
- version = '0.3.0',
+ version = VERSION,
description = 'A pure Python implementation of systemd\'s service notification protocol (sd_notify)',
author = 'Brett... |
9c9a461cf85d123a249460aa306d8300c515ac81 | setup.py | setup.py | from setuptools import setup
setup(name='tfr',
version='0.1',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=Fals... | from setuptools import setup
setup(name='tfr',
version='0.1',
description='Time-frequency reassigned spectrograms',
url='http://github.com/bzamecnik/tfr',
author='Bohumir Zamecnik',
author_email='bohumir.zamecnik@gmail.com',
license='MIT',
packages=['tfr'],
zip_safe=Fals... | Add the markdown readme to the pip package. | Add the markdown readme to the pip package.
| Python | mit | bzamecnik/tfr,bzamecnik/tfr | ---
+++
@@ -15,6 +15,8 @@
'scipy',
'soundfile',
],
+ setup_requires=['setuptools-markdown'],
+ long_description_markdown_filename='README.md',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common ... |
935c1bfa6fedea6ee3f1d4329c3632fecb7a4bdc | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging ... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-sentry',
version='.'.join(map(str, __import__('sentry').__version__)),
author='David Cramer',
author_email='dcramer@gmail.com',
url='http://github.com/dcramer/django-sentry',
description = 'Exception Logging ... | Remove all info pertaining to pygooglechart | Remove all info pertaining to pygooglechart
| Python | bsd-3-clause | primepix/django-sentry,kevinlondon/sentry,JTCunning/sentry,Goldmund-Wyldebeast-Wunderliebe/raven-python,imankulov/sentry,zenefits/sentry,arthurlogilab/raven-python,johansteffner/raven-python,Kryz/sentry,smarkets/raven-python,ewdurbin/raven-python,kevinastone/sentry,songyi199111/sentry,rdio/sentry,mvaled/sentry,beniwohl... | ---
+++
@@ -12,7 +12,6 @@
packages=find_packages(),
zip_safe=False,
install_requires=[
- # Optional
'django-paging>=0.2.2',
'django-indexer==0.2',
], |
c486d44cbb6007d5a89f36746822e68ea8cb0afa | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="cumulus",
version="0.1.0",
description="Girder API endpoints for interacting with cloud providers.",
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
packages=find_packages(),
... | from setuptools import setup, find_packages
setup(
name="cumulus",
version="0.1.0",
description="Girder API endpoints for interacting with cloud providers.",
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
packages=find_packages(exclu... | Exclude unit tests from install | Exclude unit tests from install
| Python | apache-2.0 | Kitware/cumulus,Kitware/cumulus,cjh1/cumulus,cjh1/cumulus | ---
+++
@@ -7,8 +7,9 @@
author="Chris Haris",
author_email="chris.harris@kitware.com",
url="https://github.com/Kitware/cumulus",
- packages=find_packages(),
+ packages=find_packages(exclude=["*.tests", "*.tests.*",
+ "tests.*", "tests"]),
package_data={
- ... |
208f31883a42bc1407f2f911f627b44fd23bf8b1 | setup.py | setup.py | #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_d... | #!/usr/bin/env python
import io
from setuptools import find_packages, setup, Extension
with io.open('README.rst', encoding='utf8') as readme:
long_description = readme.read()
setup(
name="pyspamsum",
version="1.0.5",
description="A Python wrapper for Andrew Tridgell's spamsum algorithm",
long_d... | Remove support for deprecated Python versions. | Remove support for deprecated Python versions.
| Python | bsd-3-clause | freakboy3742/pyspamsum,freakboy3742/pyspamsum | ---
+++
@@ -21,11 +21,7 @@
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Pytho... |
1fd8ea9c746bc1c3fa0dc95a3b00244f97373976 | setup.py | setup.py | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | from distutils.core import setup
setup(
name='django-robots',
version=__import__('robots').__version__,
description='Robots exclusion application for Django, complementing Sitemaps.',
long_description=open('docs/overview.txt').read(),
author='Jannis Leidel',
author_email='jannis@leidel.info',
... | Remove download URL since Github doesn't get his act together. Damnit | Remove download URL since Github doesn't get his act together. Damnit
git-svn-id: https://django-robots.googlecode.com/svn/trunk@36 12edf5ea-513a-0410-8a8c-37067077e60f
committer: leidel <48255722c72bb2e7f7bec0fff5f60dc7fb5357fb@12edf5ea-513a-0410-8a8c-37067077e60f>
| Python | bsd-3-clause | Jythoner/django-robots,Jythoner/django-robots | ---
+++
@@ -8,7 +8,6 @@
author='Jannis Leidel',
author_email='jannis@leidel.info',
url='http://code.google.com/p/django-robots/',
- download_url='http://github.com/jezdez/django-dbtemplates/zipball/0.5.4',
packages=['robots'],
package_dir={'dbtemplates': 'dbtemplates'},
classifiers=[ |
743fcf5266235b47cfec7f9e12b7df0378f4f9c4 | solar/solar/extensions/modules/discovery.py | solar/solar/extensions/modules/discovery.py | import io
import os
import yaml
from solar.extensions import base
class Discovery(base.BaseExtension):
VERSION = '1.0.0'
ID = 'discovery'
PROVIDES = ['nodes_resources']
COLLECTION_NAME = 'nodes'
FILE_PATH = os.path.join(
# TODO(pkaminski): no way we need '..' here...
os.path.d... | import io
import os
import yaml
from solar.extensions import base
class Discovery(base.BaseExtension):
VERSION = '1.0.0'
ID = 'discovery'
PROVIDES = ['nodes_resources']
COLLECTION_NAME = 'nodes'
FILE_PATH = os.path.join(
# TODO(pkaminski): no way we need '..' here...
os.path.d... | Add node specific tag generation | Add node specific tag generation
| Python | apache-2.0 | pigmej/solar,pigmej/solar,torgartor21/solar,torgartor21/solar,zen/solar,loles/solar,Mirantis/solar,CGenie/solar,pigmej/solar,zen/solar,dshulyak/solar,openstack/solar,Mirantis/solar,loles/solar,openstack/solar,Mirantis/solar,dshulyak/solar,Mirantis/solar,CGenie/solar,loles/solar,loles/solar,openstack/solar,zen/solar,zen... | ---
+++
@@ -24,7 +24,7 @@
nodes = yaml.load(f)
for node in nodes:
- node['tags'] = []
+ node['tags'] = ['node/{0}'.format(node['id'])]
self.db.store_list(self.COLLECTION_NAME, nodes)
|
d5e05aa44998e6f2cebc41b0c945d234eeb6317d | gcloud/search/connection.py | gcloud/search/connection.py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | Fix scope used for Cloud Search. | Fix scope used for Cloud Search.
| Python | apache-2.0 | googleapis/google-cloud-python,VitalLabs/gcloud-python,jgeewax/gcloud-python,waprin/google-cloud-python,tseaver/gcloud-python,jgeewax/gcloud-python,jonparrott/google-cloud-python,tswast/google-cloud-python,dhermes/google-cloud-python,tseaver/google-cloud-python,jonparrott/gcloud-python,dhermes/google-cloud-python,jonpa... | ---
+++
@@ -29,5 +29,5 @@
API_URL_TEMPLATE = '{api_base_url}/{api_version}{path}'
"""A template for the URL of a particular API call."""
- SCOPE = ('https://www.googleapis.com/auth/ndev.cloudsearch',)
+ SCOPE = ('https://www.googleapis.com/auth/cloudsearch',)
"""The scopes required for authenti... |
f4fb4e90725cec378634c22ee8803eeb29ccf143 | conveyor/processor.py | conveyor/processor.py | from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(sel... | from __future__ import absolute_import
from __future__ import division
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client = xmlrpc2.Client(sel... | Switch from returning a set to returning a list | Switch from returning a set to returning a list
| Python | bsd-2-clause | crateio/carrier | ---
+++
@@ -18,9 +18,9 @@
def get_releases(self, name, version=None):
if version is None:
- return set(self.client.package_releases(name, True))
+ return self.client.package_releases(name, True)
else:
- return set([version])
+ return [version]
... |
22ab7f94c3b8b04a50cd11e73b2963bddb0470a5 | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | poradnia/contrib/sites/migrations/0002_set_site_domain_and_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.db import models, migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(
id=settings... | Fix migrations - drop old domain | Fix migrations - drop old domain
| Python | mit | rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia | ---
+++
@@ -11,7 +11,7 @@
Site.objects.update_or_create(
id=settings.SITE_ID,
defaults={
- "domain": "poradnia.informacjapubliczna.org.pl",
+ "domain": "porady.siecobywatelska.pl",
"name": "poradnia"
}
) |
73feddb22ad3a2543ad4f8047061d909c64fd75d | server/system/CommonMySQL.py | server/system/CommonMySQL.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCfg('MYSQL', 'idF... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from system.DBMysql import connect
from system.ConfigLoader import getCfg
import logging
def loginUser(login, password):
''' Try to login a user regarding login/password '''
userContent = None
table = getCfg('MYSQL', 'table')
tableId = getCf... | Remove some bug on mysql elements. | Remove some bug on mysql elements.
| Python | mit | Deisss/webservice-notification,Deisss/webservice-notification | ---
+++
@@ -3,6 +3,7 @@
from system.DBMysql import connect
from system.ConfigLoader import getCfg
+import logging
def loginUser(login, password):
''' Try to login a user regarding login/password '''
@@ -13,6 +14,7 @@
tableLogin = getCfg('MYSQL', 'loginField')
tablePassword = getCfg('MYSQL', '... |
9ffb43c969288bdb06de20aded660bd7e4e5c337 | plugins/witai.py | plugins/witai.py | import os
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
@respond_to('')
def wit(message):
message.react('+1')
message.reply('You... | import os
import random
import string
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from wit import Wit
from wit_actions import actions
wit_client = Wit(
access_token=os.environ['WIT_API_TOKEN'],
actions=actions
)
wit_context = {}
def random_word(length):
return... | Create new session on restart | Create new session on restart
| Python | mit | sanjaybv/netbot | ---
+++
@@ -1,4 +1,6 @@
import os
+import random
+import string
from slackbot.bot import respond_to
from slackbot.bot import listen_to
@@ -11,9 +13,18 @@
actions=actions
)
+wit_context = {}
+
+def random_word(length):
+ return ''.join(random.choice(string.lowercase) for i in range(length))
... |
667fbe85d0e0ce60a696e63aa705dcb6b59c1214 | geokey_wegovnow/__init__.py | geokey_wegovnow/__init__.py | """Main initialization for the WeGovNow extension."""
VERSION = (3, 1, 1)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
... | """Main initialization for the WeGovNow extension."""
VERSION = (3, 1, 2)
__version__ = '.'.join(map(str, VERSION))
try:
from geokey.extensions.base import register
register(
'geokey_wegovnow',
'WeGovNow',
display_admin=False,
superuser=False,
version=__version__
... | Increment patch number following bugfix. | Increment patch number following bugfix. | Python | mit | ExCiteS/geokey-wegovnow,ExCiteS/geokey-wegovnow | ---
+++
@@ -1,6 +1,6 @@
"""Main initialization for the WeGovNow extension."""
-VERSION = (3, 1, 1)
+VERSION = (3, 1, 2)
__version__ = '.'.join(map(str, VERSION))
|
25351cd6b9119ea27123a2fddbbcc274c3620886 | examples/examples.py | examples/examples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Usage examples
"""
from __future__ import print_function, division
import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
from multidensity import MultiDensity
from skewstudent import SkewStudent
def estimate_bivariate_mle():
ndim = 2
size =... | Add plot legend in the example | Add plot legend in the example
| Python | mit | khrapovs/multidensity | ---
+++
@@ -29,14 +29,15 @@
fig, axes = plt.subplots(nrows=size[1], ncols=1)
for innov, ax in zip(data.T, axes):
- sns.kdeplot(innov, ax=ax)
+ sns.kdeplot(innov, ax=ax, label='data')
lines = [ax.get_lines()[0].get_xdata() for ax in axes]
lines = np.vstack(lines).T
marginals ... |
cde9dd479b2974f26f2e50b3611bfd0756f86c2b | game_of_thrones/__init__.py | game_of_thrones/__init__.py | class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
return [pair for pair in zip(text[0::1], text[1::1])]
| class MarkovChain:
"""
Entity which contains a chunk of text and a Markov chain generated from it.
"""
def __init__(self, text):
self.text = text
def pair_symbols(self, text):
"""
Takes an string and returns a list of tuples. For example:
>>> pair_symbols('Arya'... | Add docstring to the `pair_symbols` method | Add docstring to the `pair_symbols` method
| Python | mit | Matt-Deacalion/Name-of-Thrones | ---
+++
@@ -6,4 +6,10 @@
self.text = text
def pair_symbols(self, text):
+ """
+ Takes an string and returns a list of tuples. For example:
+
+ >>> pair_symbols('Arya')
+ [('A', 'r'), ('r', 'y'), ('y', 'a')]
+ """
return [pair for pair in zip(text[0::... |
c8cbd2c660a2e10cc021bdc0a2fead872f77967d | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | ynr/apps/uk_results/migrations/0054_update_is_winner_to_elected.py | # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyErro... | # Generated by Django 2.2.18 on 2021-05-13 11:27
from django.db import migrations
def update_versions(versions, current_key, new_key):
for version in versions:
for result in version["candidate_results"]:
try:
result[new_key] = result.pop(current_key)
except KeyErro... | Use iterator in resultset data migration | Use iterator in resultset data migration
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -14,7 +14,7 @@
def forwards(apps, schema_editor):
ResultSet = apps.get_model("uk_results", "ResultSet")
- for result in ResultSet.objects.all():
+ for result in ResultSet.objects.all().iterator():
update_versions(
versions=result.versions, current_key="is_winner", new_ke... |
32d2d6069191cd2f7e98d1dedce13ddc1a6b1f32 | config.py | config.py | dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://sixpak.org/finance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
banks = [ "bankofamerica", "citicards", "wellsfargo", "chase", "paypal", "gap", "fecu", "csvurl" ]
| Use example.com for API URL. | Use example.com for API URL. | Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash | ---
+++
@@ -1,6 +1,6 @@
dbdir = "/usr/local/finance/db"
imgdir = "/usr/local/finance/img"
-apiurl = "https://sixpak.org/finance/api.py"
+apiurl = "https://example.com/pywebfinance/api.py"
sessiondir = "/usr/local/finance/session"
sessiontimeout = (60*15) # 15 minutes
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.