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 |
|---|---|---|---|---|---|---|---|---|---|---|
77db2b0b01cda0565312430f84b35c901ad44c31 | ktbs_bench/benchable_store.py | ktbs_bench/benchable_store.py | from rdflib import Graph
from ktbs_bench.bnsparqlstore import SPARQLStore
class BenchableStore:
"""Allows to use a store/graph for benchmarks.
Contains a rdflib.Graph with setup and teardown.
"""
def __init__(self, store, graph_id, store_config, store_create=False):
self.graph = Graph(store=... | from rdflib import Graph
from ktbs_bench.bnsparqlstore import SPARQLStore
class BenchableStore:
"""Allows to use a store/graph for benchmarks.
Contains a rdflib.Graph with setup and teardown.
"""
def __init__(self, store, graph_id, store_config, store_create=False):
self.graph = Graph(store=... | Simplify ux code for creating notsparqlstore tables | Simplify ux code for creating notsparqlstore tables
| Python | mit | ktbs/ktbs-bench,ktbs/ktbs-bench | ---
+++
@@ -13,12 +13,8 @@
self._store_config = store_config
self._store_create = store_create
- def connect(self, store_create=None):
- if store_create:
- do_create = store_create
- else:
- do_create = self._store_create
- self.graph.open(self._store_... |
04f36fab2168fb9cd34d3c6fc7f31533c90b9149 | app/clients/statsd/statsd_client.py | app/clients/statsd/statsd_client.py | from statsd import StatsClient
class StatsdClient(StatsClient):
def init_app(self, app, *args, **kwargs):
self.active = app.config.get('STATSD_ENABLED')
self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api."
if self.active:
StatsClient.__init__(
... | from statsd import StatsClient
class StatsdClient(StatsClient):
def init_app(self, app, *args, **kwargs):
self.active = app.config.get('STATSD_ENABLED')
self.namespace = app.config.get('NOTIFY_ENVIRONMENT') + ".notifications.api."
if self.active:
StatsClient.__init__(
... | Format the stat name with environmenbt | Format the stat name with environmenbt
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -28,4 +28,4 @@
def timing_with_dates(self, stat, start, end, rate=1):
if self.active:
delta = (start - end).total_seconds()
- super(StatsClient, self).timing(stat, delta, rate)
+ super(StatsClient, self).timing(self.format_stat_name(stat), delta, rate) |
da03ad3386d45d310514f2b5ef3145fbcf5b773d | dashboard/ratings/tests/factories.py | dashboard/ratings/tests/factories.py | """
Contains factory classes for quickly generating test data.
It uses the factory_boy package.
Please see https://github.com/rbarrois/factory_boy for more info
"""
import datetime
import factory
import random
from django.utils import timezone
from ratings import models
class SubmissionFactory(factory.DjangoModelFa... | """
Contains factory classes for quickly generating test data.
It uses the factory_boy package.
Please see https://github.com/rbarrois/factory_boy for more info
"""
import datetime
import factory
import factory.fuzzy
import random
from django.utils import timezone
from ratings import models
class SubmissionFactory(... | Make sure seeder creates random values | Make sure seeder creates random values
| Python | mit | daltonamitchell/rating-dashboard,daltonamitchell/rating-dashboard,daltonamitchell/rating-dashboard | ---
+++
@@ -8,6 +8,7 @@
import datetime
import factory
+import factory.fuzzy
import random
from django.utils import timezone
from ratings import models
@@ -15,8 +16,8 @@
class SubmissionFactory(factory.DjangoModelFactory):
class Meta:
model = models.Submission
- application_date = timezone.no... |
79b0584887075eb1732770d1732ae07147ec21b6 | tests/mpd/protocol/test_status.py | tests/mpd/protocol/test_status.py | from __future__ import absolute_import, unicode_literals
from mopidy.models import Track
from tests.mpd import protocol
class StatusHandlerTest(protocol.BaseTestCase):
def test_clearerror(self):
self.send_request('clearerror')
self.assertEqualResponse('ACK [0@0] {clearerror} Not implemented')
... | from __future__ import absolute_import, unicode_literals
from mopidy.models import Track
from tests.mpd import protocol
class StatusHandlerTest(protocol.BaseTestCase):
def test_clearerror(self):
self.send_request('clearerror')
self.assertEqualResponse('ACK [0@0] {clearerror} Not implemented')
... | Stop using tracklist add tracks in mpd status test | tests: Stop using tracklist add tracks in mpd status test
| Python | apache-2.0 | ZenithDK/mopidy,quartz55/mopidy,tkem/mopidy,dbrgn/mopidy,rawdlite/mopidy,ali/mopidy,glogiotatidis/mopidy,quartz55/mopidy,bacontext/mopidy,bencevans/mopidy,kingosticks/mopidy,ZenithDK/mopidy,tkem/mopidy,dbrgn/mopidy,tkem/mopidy,jmarsik/mopidy,glogiotatidis/mopidy,adamcik/mopidy,bacontext/mopidy,bacontext/mopidy,pacificI... | ---
+++
@@ -11,11 +11,13 @@
self.assertEqualResponse('ACK [0@0] {clearerror} Not implemented')
def test_currentsong(self):
- track = Track()
- self.core.tracklist.add([track])
+ track = Track(uri='dummy:/a')
+ self.backend.library.dummy_library = [track]
+ self.core.... |
8f60ea444d2732b5e0f1b73a24cd8e753f160e79 | corehq/apps/userreports/specs.py | corehq/apps/userreports/specs.py | from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to the type.
"""
return StringProperty(required=Tr... | from jsonobject import StringProperty
def TypeProperty(value):
"""
Shortcut for making a required property and restricting it to a single specified
value. This adds additional validation that the objects are being wrapped as expected
according to the type.
"""
return StringProperty(required=Tr... | Set default iteration on EvaluationContext initializer | Set default iteration on EvaluationContext initializer
| Python | bsd-3-clause | dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq | ---
+++
@@ -15,6 +15,6 @@
An evaluation context. Necessary for repeats to pass both the row of the repeat as well
as the root document and the iteration number.
"""
- def __init__(self, root_doc, iteration):
+ def __init__(self, root_doc, iteration=0):
self.root_doc = root_doc
s... |
31dd9f5ec73db577bf00d7411ecffeba30691d0c | django_lean/lean_analytics/models.py | django_lean/lean_analytics/models.py | from django_lean.experiments.models import GoalRecord
from django_lean.experiments.signals import goal_recorded, user_enrolled
from django_lean.lean_analytics import get_all_analytics
def analytics_goalrecord(sender, goal_record, experiment_user, *args, **kwargs):
for analytics in get_all_analytics():
ana... | from django.conf import settings
from django_lean.experiments.models import GoalRecord
from django_lean.experiments.signals import goal_recorded, user_enrolled
from django_lean.lean_analytics import get_all_analytics
def analytics_goalrecord(sender, goal_record, experiment_user, *args, **kwargs):
if getattr(sett... | Make it possible to disable enrollment and goal record analytics. | Make it possible to disable enrollment and goal record analytics.
| Python | bsd-3-clause | e-loue/django-lean,e-loue/django-lean | ---
+++
@@ -1,20 +1,24 @@
+from django.conf import settings
+
from django_lean.experiments.models import GoalRecord
from django_lean.experiments.signals import goal_recorded, user_enrolled
from django_lean.lean_analytics import get_all_analytics
def analytics_goalrecord(sender, goal_record, experiment_user, *... |
7da561d7bf3affecce8b10b50818591ccebe0ba2 | dog/core/cog.py | dog/core/cog.py | class Cog:
""" The Cog baseclass that all cogs should inherit from. """
def __init__(self, bot):
self.bot = bot
| import logging
class Cog:
""" The Cog baseclass that all cogs should inherit from. """
def __init__(self, bot):
self.bot = bot
self.logger = logging.getLogger('cog.' + type(self).__name__.lower())
| Add logger attribute in Cog baseclass | Add logger attribute in Cog baseclass
I don't feel like refactoring all of my cog code to use this attribute at the moment, so I'll just leave this here for now.
| Python | mit | sliceofcode/dogbot,slice/dogbot,slice/dogbot,sliceofcode/dogbot,slice/dogbot | ---
+++
@@ -1,4 +1,8 @@
+import logging
+
+
class Cog:
""" The Cog baseclass that all cogs should inherit from. """
def __init__(self, bot):
self.bot = bot
+ self.logger = logging.getLogger('cog.' + type(self).__name__.lower()) |
eafafd3d90024c552a6a607871c1441e358eb927 | Bar.py | Bar.py | import pylab
from matplotlib import pyplot
from PlotInfo import *
class Bar(PlotInfo):
"""
A bar chart consisting of a single series of bars.
"""
def __init__(self):
PlotInfo.__init__(self, "bar")
self.width=0.8
self.color="black"
self.edgeColor=None
self.hatch=... | import pylab
from matplotlib import pyplot
from PlotInfo import *
class Bar(PlotInfo):
"""
A bar chart consisting of a single series of bars.
"""
def __init__(self):
PlotInfo.__init__(self, "bar")
self.width=0.8
self.color="black"
self.edgeColor=None
self.hatch=... | Fix bar graph x-axis centering. | Fix bar graph x-axis centering.
| Python | bsd-3-clause | alexras/boomslang | ---
+++
@@ -15,6 +15,13 @@
self.hatch=None
def draw(self, axis):
+ if self.xTickLabelPoints is None:
+ self.xTickLabelPoints = \
+ [x + (self.width / 2.0) for x in self.xValues]
+
+ if self.xTickLabels is None:
+ self.xTickLabe... |
320214ca1636415bc4d677ba9e3b40f0bf24c8f9 | openprescribing/frontend/migrations/0008_create_searchbookmark.py | openprescribing/frontend/migrations/0008_create_searchbookmark.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-07-07 11:58
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-07-07 11:58
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependen... | Fix multiple leaf nodes in migrations | Fix multiple leaf nodes in migrations
| Python | mit | ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc | ---
+++
@@ -11,7 +11,7 @@
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
- ('frontend', '0007_auto_20160908_0811'),
+ ('frontend', '0007_add_cost_per_fields'),
]
operations = [ |
106eaf7d22bf4039756c0ae32c125d475eb4c109 | utils/html.py | utils/html.py | #coding=UTF-8
__author__ = 'Gareth Coles'
from HTMLParser import HTMLParser
import htmlentitydefs
class HTMLTextExtractor(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.result = []
def handle_data(self, d):
self.result.append(d)
def handle_charref(self, number):... | #coding=UTF-8
__author__ = 'Gareth Coles'
from HTMLParser import HTMLParser
import htmlentitydefs
class HTMLTextExtractor(HTMLParser):
def __init__(self, newlines=True):
HTMLParser.__init__(self)
self.result = []
self.newlines = newlines
def handle_starttag(self, tag, attrs):
... | Add new-line support to HTML text extractor | Add new-line support to HTML text extractor
| Python | artistic-2.0 | UltrosBot/Ultros,UltrosBot/Ultros | ---
+++
@@ -6,9 +6,22 @@
class HTMLTextExtractor(HTMLParser):
- def __init__(self):
+ def __init__(self, newlines=True):
HTMLParser.__init__(self)
self.result = []
+ self.newlines = newlines
+
+ def handle_starttag(self, tag, attrs):
+ if self.newlines:
+ if ta... |
45bd76bbaafdeaeab28bb86ae719bdeefabbf95b | tests/test_rubymine.py | tests/test_rubymine.py | import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
'.molecule/ansible_inventory').get_hosts('all')
desktop_file_location = "/root/.local/share/applications/rubymine-2017.2.desktop"
def test_desktop_file_exists(File):
f = File(desktop_file_location)
as... | import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
'.molecule/ansible_inventory').get_hosts('all')
desktop_file_location = "/root/.local/share/applications/rubymine-2017.2.desktop"
def test_desktop_file_exists(File):
f = File(desktop_file_location)
as... | Update testcases with proper casing | Update testcases with proper casing
| Python | mit | henriklynggaard/ansible-role-rubymine | ---
+++
@@ -24,7 +24,7 @@
def test_desktop_file_contains_right_name(File):
f = File(desktop_file_location)
- assert f.contains("rubymine 2017.2")
+ assert f.contains("RubyMine 2017.2")
def test_start_file_exists(File): |
d48fd8b11fe2d9edef0ca7044df8659244a13821 | Telegram/Telegram_Harmonbot.py | Telegram/Telegram_Harmonbot.py |
import telegram
import telegram.ext
import os
import dotenv
version = "0.1.4"
# Load credentials from .env
dotenv.load_dotenv()
token = os.getenv("TELEGRAM_BOT_API_TOKEN")
bot = telegram.Bot(token = token)
updater = telegram.ext.Updater(token = token)
def test(bot, update):
bot.sendMessage(chat_id = update.mess... |
import telegram
import telegram.ext
import os
import dotenv
version = "0.2.0"
# Load credentials from .env
dotenv.load_dotenv()
token = os.getenv("TELEGRAM_BOT_API_TOKEN")
bot = telegram.Bot(token = token)
updater = telegram.ext.Updater(token = token, use_context = True)
def test(update, context):
context.bot.s... | Update to context based callbacks | [Telegram] Update to context based callbacks
| Python | mit | Harmon758/Harmonbot,Harmon758/Harmonbot | ---
+++
@@ -6,20 +6,20 @@
import dotenv
-version = "0.1.4"
+version = "0.2.0"
# Load credentials from .env
dotenv.load_dotenv()
token = os.getenv("TELEGRAM_BOT_API_TOKEN")
bot = telegram.Bot(token = token)
-updater = telegram.ext.Updater(token = token)
+updater = telegram.ext.Updater(token = token, use_c... |
a174b827b36293d90babfcdf557bdbb9c9d0b655 | ibei/__init__.py | ibei/__init__.py | # -*- coding: utf-8 -*-
"""
=========================
Base Library (:mod:`ibei`)
=========================
.. currentmodule:: ibei
"""
from main import uibei, SQSolarcell, DeVosSolarcell
| # -*- coding: utf-8 -*-
"""
=========================
Base Library (:mod:`ibei`)
=========================
.. currentmodule:: ibei
"""
from main import uibei, SQSolarcell, DeVosSolarcell
__version__ = "0.0.2"
| Add version information in module | Add version information in module
| Python | mit | jrsmith3/tec,jrsmith3/ibei,jrsmith3/tec | ---
+++
@@ -8,3 +8,5 @@
"""
from main import uibei, SQSolarcell, DeVosSolarcell
+
+__version__ = "0.0.2" |
aeb3ce72205051039e6339f83a2b7dec37f8b8c9 | idlk/__init__.py | idlk/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import sys
import idlk.base41
if sys.version_info[0] == 3:
_get_byte = lambda c: c
else:
_get_byte = ord
def hash_macroman(data):
h = 0
for c in data:
h = ((h << 8) + h) + ... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
import sys
import unicodedata
import idlk.base41
if sys.version_info[0] == 3:
_get_byte = lambda c: c
else:
_get_byte = ord
def hash_macroman(data):
h = 0
for c in data:
h ... | Normalize filename to NFC before computing the hash | Normalize filename to NFC before computing the hash
| Python | mit | znerol/py-idlk | ---
+++
@@ -4,6 +4,7 @@
import os
import sys
+import unicodedata
import idlk.base41
if sys.version_info[0] == 3:
@@ -19,6 +20,9 @@
return h % 0xFFFEECED
def idlk(filename):
+ # Normalize to NFC.
+ filename = unicodedata.normalize('NFC', filename)
+
# Convert to lowercase first.
filenam... |
9fb8b0a72740ba155c76a5812706612b656980f4 | openprocurement/auctions/flash/constants.py | openprocurement/auctions/flash/constants.py | # -*- coding: utf-8 -*-
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
"openprocurement.auctions.core.plugins",
]
| # -*- coding: utf-8 -*-
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
]
| Add view_locations for plugins in core | Add view_locations for plugins in core
| Python | apache-2.0 | openprocurement/openprocurement.auctions.flash | ---
+++
@@ -2,6 +2,5 @@
VIEW_LOCATIONS = [
"openprocurement.auctions.flash.views",
- "openprocurement.auctions.core.plugins",
]
|
b66b9a2e329bf7a68c41bf07a1444c9d49a0b6c8 | app.py | app.py | # coding: utf-8
import os
import time
from twython import Twython
import requests
APP_KEY = os.environ.get('APP_KEY')
APP_SECRET = os.environ.get('APP_SECRET')
OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA... | # coding: utf-8
import os
import time
from twython import Twython
import requests
APP_KEY = os.environ.get('APP_KEY')
APP_SECRET = os.environ.get('APP_SECRET')
OAUTH_TOKEN = os.environ.get('OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = os.environ.get('OAUTH_TOKEN_SECRET')
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OA... | Fix error with string rank value | Fix error with string rank value
| Python | mit | erickgnavar/coinstats | ---
+++
@@ -30,7 +30,7 @@
def main():
response = requests.get('https://api.coinmarketcap.com/v1/ticker/')
- for currency in sorted(response.json(), key=lambda x: x['rank'])[:10]:
+ for currency in sorted(response.json(), key=lambda x: int(x['rank']))[:10]:
post_tweet(currency)
time.sle... |
8d9f3214cc5663dc29f7dcf3a03bc373a51d010b | core/admin/start.py | core/admin/start.py | #!/usr/bin/python3
import os
import logging as log
import sys
log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
os.system("flask mailu advertise")
os.system("flask db upgrade")
account = os.environ.get("INITIAL_ADMIN_ACCOUNT")
domain = os.environ.get("INITIAL_ADMIN_DOMAIN")
password = os... | #!/usr/bin/python3
import os
import logging as log
import sys
log.basicConfig(stream=sys.stderr, level=os.environ.get("LOG_LEVEL", "INFO"))
os.system("flask mailu advertise")
os.system("flask db upgrade")
account = os.environ.get("INITIAL_ADMIN_ACCOUNT")
domain = os.environ.get("INITIAL_ADMIN_DOMAIN")
password = os... | Use threads in gunicorn rather than processes | Use threads in gunicorn rather than processes
This ensures that we share the auth-cache... will enable memory savings
and may improve performances when a higher number of cores is available
"smarter default"
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io | ---
+++
@@ -19,7 +19,8 @@
os.system("flask mailu admin %s %s '%s' --mode %s" % (account, domain, password, mode))
start_command="".join([
- "gunicorn -w 4 -b :80 ",
+ "gunicorn --threads ", str(os.cpu_count()),
+ " -b :80 ",
"--access-logfile - " if (log.root.level<=log.INFO) else "",
"--er... |
e8ac68b33b3b7bf54baa36b89ac90e9e5a666599 | magnum/conf/services.py | magnum/conf/services.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Use HostAddressOpt for opts that accept IP and hostnames | Use HostAddressOpt for opts that accept IP and hostnames
Some configuration options were accepting both IP addresses
and hostnames. Since there was no specific OSLO opt type to
support this, we were using ``StrOpt``. The change [1] that
added support for ``HostAddressOpt`` type was merged in Ocata
and became available... | Python | apache-2.0 | openstack/magnum,ArchiFleKs/magnum,ArchiFleKs/magnum,openstack/magnum | ---
+++
@@ -15,12 +15,13 @@
from magnum.i18n import _
service_opts = [
- cfg.StrOpt('host',
- help=_('Name of this node. This can be an opaque identifier. '
- 'It is not necessarily a hostname, FQDN, or IP address. '
- 'However, the node name must be vali... |
381cf72695185fda93d0d9685fad887d445b4a72 | mesonwrap/inventory.py | mesonwrap/inventory.py | RESTRICTED_PROJECTS = [
'dubtestproject',
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
ISSUE_TRACKER = 'wrapdb'
class Inventory:
def __init__(self, organization):
self.organization = organization
self.restricted_p... | RESTRICTED_PROJECTS = [
'cidata',
'dubtestproject',
'meson',
'meson-ci',
'mesonbuild.github.io',
'mesonwrap',
'wrapdb',
'wrapdevtools',
'wrapweb',
]
ISSUE_TRACKER = 'wrapdb'
class Inventory:
def __init__(self, organization):
self.organization = organization
sel... | Add cidata to the list of restricted projects | Add cidata to the list of restricted projects
| Python | apache-2.0 | mesonbuild/wrapweb,mesonbuild/wrapweb,mesonbuild/wrapweb | ---
+++
@@ -1,4 +1,5 @@
RESTRICTED_PROJECTS = [
+ 'cidata',
'dubtestproject',
'meson',
'meson-ci', |
71b8ee305e70d3822bc5efe13de4eede7f13b65e | __init__.py | __init__.py | from __future__ import absolute_import, division, print_function
import sys
# Hack to disable any DIALS banner showing up.
# To work properly this requires *this* file here to be essentially empty.
# Load *this* file here as dials.util.banner, so any future import
# will do exactly nothing.
sys.modules['dials.util.ba... | Hide DIALS banner during xia2 execution | Hide DIALS banner during xia2 execution
There probably should be a neater way to achieve this.
| Python | bsd-3-clause | xia2/xia2,xia2/xia2 | ---
+++
@@ -0,0 +1,9 @@
+from __future__ import absolute_import, division, print_function
+
+import sys
+
+# Hack to disable any DIALS banner showing up.
+# To work properly this requires *this* file here to be essentially empty.
+# Load *this* file here as dials.util.banner, so any future import
+# will do exactly n... | |
8ffd6ffecd7ce713446385b6cd108e50fb041403 | __main__.py | __main__.py | from . import *
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def g... | from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
... | Add readline support for the REPL | Add readline support for the REPL
| Python | isc | gvx/isle | ---
+++
@@ -1,4 +1,6 @@
from . import *
+
+import readline
ps1 = '\n% '
ps2 = '| ' |
c654bc1fdacdb355b7e03c853ebcdc919ac5f91d | tests/capture/test_capture.py | tests/capture/test_capture.py | from pyshark.capture.capture import Capture
def test_capture_gets_decoding_parameters():
c = Capture(decode_as={'tcp.port==8888': 'http'})
params = c.get_parameters()
decode_index = params.index('-d')
assert params[decode_index + 1] == 'tcp.port==8888,http'
def test_capture_gets_multiple_decoding_pa... | from pyshark.capture.capture import Capture
def test_capture_gets_decoding_parameters():
c = Capture(decode_as={'tcp.port==8888': 'http'})
params = c.get_parameters()
decode_index = params.index('-d')
assert params[decode_index + 1] == 'tcp.port==8888,http'
def test_capture_gets_multiple_decoding_pa... | Fix tests to avoid dict ordering problem | Fix tests to avoid dict ordering problem
| Python | mit | KimiNewt/pyshark,eaufavor/pyshark-ssl | ---
+++
@@ -12,6 +12,8 @@
c = Capture(decode_as={'tcp.port==8888': 'http', 'tcp.port==6666': 'dns'})
params = c.get_parameters()
decode_index = params.index('-d')
- assert params[decode_index + 1] == 'tcp.port==8888,http'
+ possible_results = ['tcp.port==8888,http', 'tcp.port==6666,dns']
+ ass... |
3e9a4f27ad05b3ecd2a4c013ff0f3b04e5fe44aa | tests/test_list_generators.py | tests/test_list_generators.py | import unittest
import craft_ai
from . import settings
from .utils import generate_entity_id
from .data import valid_data
class TestListGenerators(unittest.TestCase):
"""Checks that the client succeeds when getting an agent with OK input"""
@classmethod
def setUpClass(cls):
cls.client = craft_a... | import unittest
import craft_ai
from . import settings
from .utils import generate_entity_id
from .data import valid_data
class TestListGenerators(unittest.TestCase):
"""Checks that the client succeeds when getting an agent with OK input"""
@classmethod
def setUpClass(cls):
cls.client = craft_a... | Fix agent creation configuration to make tests great again | Fix agent creation configuration to make tests great again
lint
| Python | bsd-3-clause | craft-ai/craft-ai-client-python,craft-ai/craft-ai-client-python | ---
+++
@@ -21,9 +21,7 @@
def setUp(self):
self.client.delete_agent(self.agent_id)
- self.client.create_agent(
- valid_data.VALID_GENERATOR_CONFIGURATION, self.agent_id
- )
+ self.client.create_agent(valid_data.VALID_CONFIGURATION, self.agent_id)
for generators... |
4420eb020d96004c5373584781c7b130de7b90e9 | reg/__init__.py | reg/__init__.py | # flake8: noqa
from .implicit import implicit, NoImplicitLookupError
from .registry import ClassRegistry, Registry, IRegistry, IClassLookup
from .lookup import Lookup, ComponentLookupError, Matcher
from .predicate import (PredicateRegistry, Predicate, KeyIndex,
PredicateRegistryError)
from .comp... | # flake8: noqa
from .implicit import implicit, NoImplicitLookupError
from .registry import ClassRegistry, Registry, IRegistry, IClassLookup
from .lookup import Lookup, ComponentLookupError, Matcher
from .predicate import (PredicateRegistry, Predicate, KeyIndex,
PredicateRegistryError)
from .comp... | Make sentinel available to outside. | Make sentinel available to outside.
| Python | bsd-3-clause | taschini/reg,morepath/reg | ---
+++
@@ -7,3 +7,4 @@
from .compose import ListClassLookup, ChainClassLookup, CachingClassLookup
from .generic import generic
from .mapply import mapply
+from .sentinel import Sentinel |
268c4458161ce754a82e3986787f6703f9122e3e | trackmybmi/users/factories.py | trackmybmi/users/factories.py | import factory
from django.contrib.auth.hashers import make_password
from .models import Friendship, User
class UserFactory(factory.django.DjangoModelFactory):
"""Create users with default attributes."""
class Meta:
model = User
email = factory.Sequence(lambda n: 'user.{}@test.test'.format(n))... | import factory
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from .models import Friendship
User = get_user_model()
class UserFactory(factory.django.DjangoModelFactory):
"""Create users with default attributes."""
class Meta:
model = User
... | Replace User import with call to get_user_model() | Replace User import with call to get_user_model()
| Python | mit | ojh/trackmybmi | ---
+++
@@ -1,8 +1,12 @@
import factory
+from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
-from .models import Friendship, User
+from .models import Friendship
+
+
+User = get_user_model()
class UserFactory(factory.django.DjangoModelFactory): |
b9ccbb2addd8dcaeb100bb5e95768caa2a97c280 | srttools/core/__init__.py | srttools/core/__init__.py | import warnings
try:
import matplotlib
# matplotlib.use('TkAgg')
HAS_MPL = True
except ImportError:
HAS_MPL = False
try:
import statsmodels.api as sm
HAS_STATSM = True
except ImportError:
HAS_STATSM = False
try:
from numba import jit, vectorize
except ImportError:
warnings.warn("N... | import warnings
DEFAULT_MPL_BACKEND = 'TkAgg'
try:
import matplotlib
# This is necessary. Random backends might respond incorrectly.
matplotlib.use(DEFAULT_MPL_BACKEND)
HAS_MPL = True
except ImportError:
HAS_MPL = False
try:
import statsmodels.api as sm
version = [int(i) for i in sm.versio... | Set default backend, and minimum statsmodels version | Set default backend, and minimum statsmodels version
| Python | bsd-3-clause | matteobachetti/srt-single-dish-tools | ---
+++
@@ -1,14 +1,23 @@
import warnings
+DEFAULT_MPL_BACKEND = 'TkAgg'
try:
import matplotlib
- # matplotlib.use('TkAgg')
+ # This is necessary. Random backends might respond incorrectly.
+ matplotlib.use(DEFAULT_MPL_BACKEND)
HAS_MPL = True
except ImportError:
HAS_MPL = False
try:
... |
ab02c54cc713cc10c60f09dde3cae2fca3c2a9a4 | conference/management/commands/make_speaker_profiles_public.py | conference/management/commands/make_speaker_profiles_public.py |
from django.core.management.base import BaseCommand
from conference import models as cmodels
def make_speaker_profiles_public_for_conference(conference):
# Get speaker records
speakers = set()
talks = cmodels.Talk.objects.accepted(conference)
for t in talks:
speakers |= set(t.get_all_speake... |
from django.core.management.base import BaseCommand
from conference import models as cmodels
def make_speaker_profiles_public_for_conference(conference):
# Get speaker records
speakers = set()
talks = cmodels.Talk.objects.accepted(conference)
for t in talks:
speakers |= set(t.get_all_speake... | Fix script to make speaker profiles public. | Fix script to make speaker profiles public.
| Python | bsd-2-clause | EuroPython/epcon,EuroPython/epcon,EuroPython/epcon,EuroPython/epcon | ---
+++
@@ -28,11 +28,15 @@
Argument: <conference year>
"""
- args = '<conference>'
+
+ def add_arguments(self, parser):
+
+ # Positional arguments
+ parser.add_argument('conference')
def handle(self, *args, **options):
try:
- conference = args[0]
- excep... |
6ce05a55b2318f1ad567c8e4345fb286777b53e6 | ndohyep/settings/production.py | ndohyep/settings/production.py | from .base import *
# Disable debug mode
DEBUG = False
TEMPLATE_DEBUG = False
# Compress static files offline
# http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True
# Send notification emails as a background task using Celery,
# to prevent th... | from .base import *
# Disable debug mode
DEBUG = True
TEMPLATE_DEBUG = True
# Compress static files offline
# http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE = True
# Send notification emails as a background task using Celery,
# to prevent this... | Set debug to true for template debugging | Set debug to true for template debugging
| Python | bsd-2-clause | praekelt/molo-ndoh-yep,praekelt/molo-ndoh-yep,praekelt/molo-ndoh-yep,praekelt/molo-ndoh-yep | ---
+++
@@ -3,8 +3,8 @@
# Disable debug mode
-DEBUG = False
-TEMPLATE_DEBUG = False
+DEBUG = True
+TEMPLATE_DEBUG = True
# Compress static files offline |
b875f457d7a4926f5028428ead4cecc75af90c2e | examples/launch_cloud_harness.py | examples/launch_cloud_harness.py | import json
import os
from osgeo import gdal
from gbdxtools import Interface
from gbdx_task_template import TaskTemplate, Task, InputPort, OutputPort
gbdx = Interface()
# data = "s3://receiving-dgcs-tdgplatform-com/054813633050_01_003" # WV02 Image over San Francisco
# aoptask = gbdx.Task("AOP_Strip_Processor", da... | from gbdxtools import Interface
gbdx = Interface()
# Create a cloud-harness gbdxtools Task
from ch_tasks.cp_task import CopyTask
cp_task = gbdx.Task(CopyTask)
from ch_tasks.raster_meta import RasterMetaTask
ch_task = gbdx.Task(RasterMetaTask)
# NOTE: This will override the value in the class definition.
ch_task.inp... | Remove the cloud-harness task and add second cloud-harness task for chaining. | Remove the cloud-harness task and add second cloud-harness task for chaining.
| Python | mit | michaelconnor00/gbdxtools,michaelconnor00/gbdxtools | ---
+++
@@ -1,54 +1,22 @@
-import json
-import os
-from osgeo import gdal
+from gbdxtools import Interface
+gbdx = Interface()
-from gbdxtools import Interface
-from gbdx_task_template import TaskTemplate, Task, InputPort, OutputPort
+# Create a cloud-harness gbdxtools Task
+
+from ch_tasks.cp_task import CopyTask
... |
4f46fe7abf5efcd93bc161f2cfccc58df4ab1ee4 | whats_fresh/whats_fresh_api/tests/views/entry/test_list_preparations.py | whats_fresh/whats_fresh_api/tests/views/entry/test_list_preparations.py | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListPreparationTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-preparat... | from django.test import TestCase
from django.core.urlresolvers import reverse
from whats_fresh_api.models import *
from django.contrib.gis.db import models
import json
class ListPreparationTestCase(TestCase):
fixtures = ['test_fixtures']
def test_url_endpoint(self):
url = reverse('entry-list-preparat... | Rewrite preparations list test to get ID from URL | Rewrite preparations list test to get ID from URL
| Python | apache-2.0 | iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api | ---
+++
@@ -22,9 +22,14 @@
for preparation in Preparation.objects.all():
self.assertEqual(
- items[preparation.id-1]['description'], preparation.description)
+ items[preparation.id-1]['description'],
+ preparation.description)
self.asse... |
8d014f6bc3994fabf3c0658e6884648ad9a8f2c2 | quizalicious.py | quizalicious.py | from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app.debug = config.DEBUG
db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
return render_template('tem... | from flask import Flask, render_template
from redis import StrictRedis
import random
import config
app = Flask(__name__)
app.debug = config.DEBUG
db = StrictRedis(host=config.REDIS_HOST, port=config.REDIS_PORT)
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
return render_template('mai... | Change key lookups and fix typos | Change key lookups and fix typos
Revamped the way URLs were handled from Redis by differentiating the URL
friendly name from the actual name. Fixed bad paths in render_template
for all routes.
| Python | bsd-2-clause | estreeper/quizalicious,estreeper/quizalicious,estreeper/quizalicious | ---
+++
@@ -11,18 +11,28 @@
@app.route('/')
def main():
available_quizzes = db.smembers('quizzes')
- return render_template('templates/main.html', quizzes=available_quizzes)
+ return render_template('main.html', quizzes=available_quizzes)
-@app.route('/quiz/start/<quiz_name>')
-def start_quiz(quiz_name... |
7b10375eaae7c79a4d90b8f3835e8a1fe06c5f31 | hermes/feeds.py | hermes/feeds.py | from django.contrib.syndication.views import Feed
from .models import Post
from .settings import (
SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK,
SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE
)
class LatestPostFeed(Feed):
title = SYNDICATION_FEED_TITLE
link = SYNDICATION_FEED_LINK
descripti... | from django.contrib.syndication.views import Feed
from .models import Post
from .settings import (
SYNDICATION_FEED_TITLE, SYNDICATION_FEED_LINK,
SYNDICATION_FEED_DESCRIPTION, SYNDICATION_FEED_TYPE
)
class LatestPostFeed(Feed):
title = SYNDICATION_FEED_TITLE
link = SYNDICATION_FEED_LINK
descripti... | Use actual path to template | Use actual path to template | Python | mit | DemocracyClub/django-hermes,DemocracyClub/django-hermes | ---
+++
@@ -12,7 +12,7 @@
link = SYNDICATION_FEED_LINK
description = SYNDICATION_FEED_DESCRIPTION
feed_type = SYNDICATION_FEED_TYPE
- description_template = 'feed_post_description.html
+ description_template = 'hermes/feed_post_description.html
def items(self):
return Post.objects... |
f9a59247155b5d8f356ae09d25573fb703d58e52 | hijack/views.py | hijack/views.py | from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from hijack.helpers import login_user
from hijack.helpers import rel... | from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponseRedirect
from hijack.helpers import login_user
from hijack.helpers import releas... | Remove extra whitespace from imports | Remove extra whitespace from imports
| Python | mit | arteria/django-hijack,arteria/django-hijack,arteria/django-hijack | ---
+++
@@ -1,12 +1,9 @@
from django.contrib.admin.views.decorators import staff_member_required
-
from django.contrib.auth.decorators import login_required
-
from django.shortcuts import get_object_or_404
from django.http import HttpResponseBadRequest, HttpResponseRedirect
-
from hijack.helpers import log... |
e0d0c9726766dc3281411e265c4d16ff66ecc595 | regression/pages/studio/terms_of_service.py | regression/pages/studio/terms_of_service.py | """
Terms of Service page
"""
from bok_choy.page_object import PageObject
from regression.pages.studio import LOGIN_BASE_URL
class TermsOfService(PageObject):
"""
Terms of Service page
"""
url = LOGIN_BASE_URL + '/edx-terms-service'
def is_browser_on_page(self):
return "Please read these ... | """
Terms of Service page
"""
from bok_choy.page_object import PageObject
from regression.pages.studio import LOGIN_BASE_URL
class TermsOfService(PageObject):
"""
Terms of Service page
"""
url = LOGIN_BASE_URL + '/edx-terms-service'
def is_browser_on_page(self):
return "Please read these ... | Fix target css for TOS page | Fix target css for TOS page
| Python | agpl-3.0 | edx/edx-e2e-tests,edx/edx-e2e-tests | ---
+++
@@ -13,5 +13,5 @@
def is_browser_on_page(self):
return "Please read these Terms of Service" in self.q(
- css='.field-page-body'
+ css='.content-section'
).text[0] |
649c70527ae602512cfa6ea62b60ebc43fc69797 | lab/run_trace.py | lab/run_trace.py | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Run a simple trace function on a file of Python code."""
import os, sys
nest = 0
def trace(frame, event, arg):
global nest
if nest is None:
#... | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Run a simple trace function on a file of Python code."""
import os, sys
nest = 0
def trace(frame, event, arg):
global nest
if nest is None:
#... | Make this useful for py3 also | Make this useful for py3 also
| Python | apache-2.0 | hugovk/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,hugovk/coveragepy,nedbat/coveragepy,nedbat/coveragepy,nedbat/coveragepy,nedbat/coveragepy,hugovk/coveragepy | ---
+++
@@ -31,5 +31,6 @@
the_program = sys.argv[1]
+code = open(the_program).read()
sys.settrace(trace)
-execfile(the_program)
+exec(code) |
89bbc555ecf520ee34a9b1292a2bdb5c937b18e2 | addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py | addons/hw_drivers/iot_handlers/interfaces/PrinterInterface.py | from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_de... | from cups import Connection as cups_connection
from re import sub
from threading import Lock
from odoo.addons.hw_drivers.controllers.driver import Interface
conn = cups_connection()
PPDs = conn.getPPDs()
cups_lock = Lock() # We can only make one call to Cups at a time
class PrinterInterface(Interface):
_loop_de... | Fix issue with printer device-id | [FIX] hw_drivers: Fix issue with printer device-id
When we print a ticket status with a thermal printer we need printer's device-id
But if we add manually a printer this device-id doesn't exist
So now we update de devices list with a supported = True if
printer are manually added
closes odoo/odoo#53043
Signed-off-by... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo | ---
+++
@@ -16,16 +16,11 @@
printer_devices = {}
with cups_lock:
printers = conn.getPrinters()
+ devices = conn.getDevices()
for printer in printers:
- printers[printer]['supported'] = True # these printers are automatically supported
- ... |
460ed562a64b7aacbd690a2e62f39b11bfcb092f | src/MCPClient/lib/clientScripts/examineContents.py | src/MCPClient/lib/clientScripts/examineContents.py | #!/usr/bin/env python2
import os
import subprocess
import sys
def main(target, output):
args = [
'bulk_extractor', target, '-o', output,
'-M', '250', '-q', '-1'
]
try:
os.makedirs(output)
subprocess.call(args)
return 0
except Exception as e:
return e
if... | #!/usr/bin/env python2
import os
import subprocess
import sys
def main(target, output):
args = [
'bulk_extractor', target, '-o', output,
'-M', '250', '-q', '-1'
]
try:
os.makedirs(output)
subprocess.call(args)
# remove empty BulkExtractor logs
for filename i... | Remove empty bulk extractor logs | Remove empty bulk extractor logs
Squashed commit of the following:
commit c923667809bb5d828144b09d03bd53554229a9bd
Author: Aaron Elkiss <aelkiss@umich.edu>
Date: Thu Dec 8 09:34:47 2016 -0500
fix spacing & variable name
commit df597f69e19c3a3b4210c1131a79550eb147e412
Author: Aaron Daniel Elkiss <aelkiss@umich... | Python | agpl-3.0 | artefactual/archivematica,artefactual/archivematica,artefactual/archivematica,artefactual/archivematica | ---
+++
@@ -12,6 +12,11 @@
try:
os.makedirs(output)
subprocess.call(args)
+ # remove empty BulkExtractor logs
+ for filename in os.listdir(output):
+ filepath = os.path.join(output,filename)
+ if os.path.getsize(filepath) == 0:
+ os.remove(file... |
5a15ca8b790dda7b2ea11af5d1c179f9e7d9f2ac | pages/search_indexes.py | pages/search_indexes.py | """Django haystack `SearchIndex` module."""
from pages.models import Page
from django.conf import settings
from haystack.indexes import SearchIndex, CharField, DateTimeField, RealTimeSearchIndex
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(doc... | """Django haystack `SearchIndex` module."""
from pages.models import Page
from gerbi import settings
from haystack.indexes import SearchIndex, CharField, DateTimeField, RealTimeSearchIndex
from haystack import site
class PageIndex(SearchIndex):
"""Search index for pages content."""
text = CharField(document=... | Use gerbi setting not global settings | Use gerbi setting not global settings
| Python | bsd-3-clause | pombredanne/django-page-cms-1,akaihola/django-page-cms,remik/django-page-cms,akaihola/django-page-cms,batiste/django-page-cms,remik/django-page-cms,remik/django-page-cms,pombredanne/django-page-cms-1,batiste/django-page-cms,batiste/django-page-cms,pombredanne/django-page-cms-1,remik/django-page-cms,akaihola/django-page... | ---
+++
@@ -1,6 +1,6 @@
"""Django haystack `SearchIndex` module."""
from pages.models import Page
-from django.conf import settings
+from gerbi import settings
from haystack.indexes import SearchIndex, CharField, DateTimeField, RealTimeSearchIndex
from haystack import site
@@ -33,4 +33,4 @@
site.register(P... |
6c4c3ac1dde0519d08ab461ab60ccc1d8b9d3d38 | CodeFights/createDie.py | CodeFights/createDie.py | #!/usr/local/bin/python
# Code Fights Create Die Problem
import random
def createDie(seed, n):
class Die(object):
pass
class Game(object):
die = Die(seed, n)
return Game.die
def main():
tests = [
[37237, 5, 3],
[36706, 12, 9],
[21498, 10, 10],
[2998... | #!/usr/local/bin/python
# Code Fights Create Die Problem
import random
def createDie(seed, n):
class Die(object):
def __new__(self, seed, n):
random.seed(seed)
return int(random.random() * n) + 1
class Game(object):
die = Die(seed, n)
return Game.die
def main()... | Solve Code Fights create die problem | Solve Code Fights create die problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -6,7 +6,9 @@
def createDie(seed, n):
class Die(object):
- pass
+ def __new__(self, seed, n):
+ random.seed(seed)
+ return int(random.random() * n) + 1
class Game(object):
die = Die(seed, n) |
b57a599640c6fa8bf23f081c914b7437e3f04dcd | course_discovery/apps/courses/management/commands/refresh_all_courses.py | course_discovery/apps/courses/management/commands/refresh_all_courses.py | import logging
from optparse import make_option
from django.core.management import BaseCommand, CommandError
from course_discovery.apps.courses.models import Course
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Refresh course data from external sources.'
option_list = BaseComman... | import logging
from django.core.management import BaseCommand, CommandError
from course_discovery.apps.courses.models import Course
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = 'Refresh course data from external sources.'
def add_arguments(self, parser):
parser.add_argum... | Switch to argparse for management command argument parsing | Switch to argparse for management command argument parsing
| Python | agpl-3.0 | edx/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery | ---
+++
@@ -1,5 +1,4 @@
import logging
-from optparse import make_option
from django.core.management import BaseCommand, CommandError
@@ -11,13 +10,14 @@
class Command(BaseCommand):
help = 'Refresh course data from external sources.'
- option_list = BaseCommand.option_list + (
- make_option('-... |
e321b47a5ee2252ce71fabb992e50e5f455a217f | blaze/tests/test_blfuncs.py | blaze/tests/test_blfuncs.py | from blaze.blfuncs import BlazeFunc
from blaze.datashape import double, complex128 as c128
from blaze.blaze_kernels import BlazeElementKernel
import blaze
def _add(a,b):
return a + b
def _mul(a,b):
return a * b
add = BlazeFunc('add',[(_add, 'f8(f8,f8)'),
(_add, 'c16(c16,c16)')])
mul =... | from blaze.blfuncs import BlazeFunc
from blaze.datashape import double, complex128 as c128
from blaze.blaze_kernels import BlazeElementKernel
import blaze
def _add(a,b):
return a + b
def _mul(a,b):
return a * b
add = BlazeFunc('add',[('f8(f8,f8)', _add),
('c16(c16,c16)', _add)])
mul =... | Fix usage of urlparse. and re-order list of key, value dict specification. | Fix usage of urlparse. and re-order list of key, value dict specification.
| Python | bsd-3-clause | ContinuumIO/blaze,dwillmer/blaze,dwillmer/blaze,ContinuumIO/blaze,mwiebe/blaze,markflorisson/blaze-core,AbhiAgarwal/blaze,LiaoPan/blaze,ChinaQuants/blaze,markflorisson/blaze-core,FrancescAlted/blaze,caseyclements/blaze,FrancescAlted/blaze,caseyclements/blaze,jcrist/blaze,mwiebe/blaze,AbhiAgarwal/blaze,jcrist/blaze,cpcl... | ---
+++
@@ -9,8 +9,8 @@
def _mul(a,b):
return a * b
-add = BlazeFunc('add',[(_add, 'f8(f8,f8)'),
- (_add, 'c16(c16,c16)')])
+add = BlazeFunc('add',[('f8(f8,f8)', _add),
+ ('c16(c16,c16)', _add)])
mul = BlazeFunc('mul', {(double,)*3: _mul})
|
54be27f1c2e6c288465f2b59e41f5a4deed00fe7 | atompos/atompos/main/views.py | atompos/atompos/main/views.py | import json as simplejson
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from atompos.main import settings
from util import get_atom_pos, get_positions_atb
def index(request):
return render(request, 'index.html')
def _get_positi... | import json as simplejson
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from atompos.main import settings
from util import get_atom_pos, get_positions_atb
def index(request):
return render(request, 'index.html')
def _get_positi... | Fix django-1.7 deprecated mimetype keyword argument | Fix django-1.7 deprecated mimetype keyword argument
Source: https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.HttpResponse.__init__
| Python | mit | bertrand-caron/OAPoC,bertrand-caron/OAPoC | ---
+++
@@ -27,7 +27,7 @@
}
return HttpResponse(
simplejson.dumps(res, indent=2),
- mimetype="application/json"
+ content_type="application/json"
)
@csrf_exempt |
9581334db472c8ad8dbff0766ec74ed6dfa20d6f | tests/test_api_request.py | tests/test_api_request.py | #!/usr/bin/env python
# coding=utf-8
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceRequestException
import pytest
import requests_mock
client = Client('api_key', 'api_secret')
def test_invalid_json():
"""Test Invalid response Exception"""
with pytest.raises(B... | #!/usr/bin/env python
# coding=utf-8
from binance.client import Client
from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException
import pytest
import requests_mock
client = Client('api_key', 'api_secret')
def test_invalid_json():
"""Test Invalid response Exception"""... | Add test for withdraw exception response | Add test for withdraw exception response
| Python | mit | sammchardy/python-binance | ---
+++
@@ -2,7 +2,7 @@
# coding=utf-8
from binance.client import Client
-from binance.exceptions import BinanceAPIException, BinanceRequestException
+from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException
import pytest
import requests_mock
@@ -27,3 +27,14 @@
... |
c73572f2a9b63d35daf8b5935c4a1e6a0422c122 | pinax/documents/receivers.py | pinax/documents/receivers.py | from django.db.models.signals import post_save
from django.dispatch import receiver
from .conf import settings
from .models import UserStorage
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def ensure_userstorage(sender, **kwargs):
if kwargs["created"]:
user = kwargs["instance"]
UserStorag... | from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from .conf import settings
from .models import UserStorage, Document
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def ensure_userstorage(sender, **kwargs):
if kwargs["created"]:
user = kwargs["instanc... | Implement deletion of file object via Document model pre_save signal. | Implement deletion of file object via Document model pre_save signal.
| Python | mit | pinax/pinax-documents | ---
+++
@@ -1,8 +1,8 @@
-from django.db.models.signals import post_save
+from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from .conf import settings
-from .models import UserStorage
+from .models import UserStorage, Document
@receiver(post_save, sender=settings.... |
9c48cd08ee0805cfd9a8115d77da139e8c09d7a9 | plyer/platforms/linux/cpu.py | plyer/platforms/linux/cpu.py | from subprocess import Popen, PIPE
from plyer.facades import CPU
from plyer.utils import whereis_exe
from os import environ
class LinuxProcessors(CPU):
def _cpus(self):
old_lang = environ.get('LANG', '')
environ['LANG'] = 'C'
cpus = {
'physical': None, # cores
'l... | from subprocess import Popen, PIPE
from plyer.facades import CPU
from plyer.utils import whereis_exe
from os import environ
class LinuxProcessors(CPU):
def _cpus(self):
old_lang = environ.get('LANG', '')
environ['LANG'] = 'C'
cpus = {
'physical': None, # cores
'l... | Add CPU count for GNU/Linux | Add CPU count for GNU/Linux
| Python | mit | kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer | ---
+++
@@ -15,15 +15,32 @@
'logical': None # cores * threads
}
+ physical = [] # list of CPU ids from kernel
+ # open Linux kernel data file for CPU
+ with open('/proc/cpuinfo', 'rb') as fle:
+ lines = fle.readlines()
+ # go through the lines and obt... |
4c7336fbe1e82bd3d7d091429feda40932d73e67 | bin/pear.py | bin/pear.py | """
PEAR task
A task to detect whether a specific PEAR package is installed or not
"""
import os
from fabric.api import *
from fabric.colors import red, green
def pear_detect(package):
"""
Detect if a pear package is installed.
"""
if which('pear'):
pear_out = local('pear list -a', True)
... | """
PEAR task
A task to detect whether a specific PEAR package is installed or not
"""
import os
from fabric.api import *
from fabric.colors import red, green
import shell
def pear_detect(package):
"""
Detect if a pear package is installed.
"""
if shell.which('pear'):
pear_out = local('pear l... | Add missing import for shell module | Add missing import for shell module
| Python | mit | hglattergotz/sfdeploy | ---
+++
@@ -7,12 +7,13 @@
import os
from fabric.api import *
from fabric.colors import red, green
+import shell
def pear_detect(package):
"""
Detect if a pear package is installed.
"""
- if which('pear'):
+ if shell.which('pear'):
pear_out = local('pear list -a', True)
if ... |
ccd681ab4cb840461d5cdc8197242af16e0c12d0 | app.py | app.py | from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello world!"
if __name__ == "__main__":
app.run()
| from flask import Flask
app = Flask(__name__)
app.debug = True
@app.route("/")
def home():
return "Skill Camp!"
@app.route("/create")
def create():
return "Make a new thing!"
@app.route("/<int:uid>/view")
def view(uid):
return "Look at %d" % (uid,)
@app.route("/<int:uid>/edit")
def edit(uid):
return... | Add all of our routes | Add all of our routes
| Python | mit | codeforamerica/skillcamp,codeforamerica/skillcamp,codeforamerica/skillcamp,codeforamerica/skillcamp | ---
+++
@@ -1,9 +1,22 @@
from flask import Flask
app = Flask(__name__)
+app.debug = True
@app.route("/")
-def hello():
- return "Hello world!"
+def home():
+ return "Skill Camp!"
+
+@app.route("/create")
+def create():
+ return "Make a new thing!"
+
+@app.route("/<int:uid>/view")
+def view(uid):
+ re... |
60f101e4fc3ac6822c7cf254afa9e98004eb07a1 | bot.py | bot.py | #!/usr/bin/python3
import tweepy
import random
import os
from secrets import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
twitter = tweepy.API(auth)
photo_file = os.path.join("polaroids", os.listdir("polaroids")[0])
comment = random.choice([
... | #!/usr/bin/python3
"""
Copyright (c) 2017 Finn Ellis.
Free to use and modify under the terms of the MIT license.
See included LICENSE file for details.
"""
import tweepy
import random
import os
from secrets import *
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access... | Add copyright and license information. | Add copyright and license information. | Python | mit | relsqui/awkward_polaroid,relsqui/awkward_polaroid | ---
+++
@@ -1,4 +1,10 @@
#!/usr/bin/python3
+
+"""
+Copyright (c) 2017 Finn Ellis.
+Free to use and modify under the terms of the MIT license.
+See included LICENSE file for details.
+"""
import tweepy
import random |
cd611cee6843ff9056d98d26d08091188cd20172 | app/rest.py | app/rest.py | from flask import Blueprint, jsonify, current_app
from app import db
from app.errors import register_errors
base_blueprint = Blueprint('', __name__)
register_errors(base_blueprint)
@base_blueprint.route('/')
def get_info():
current_app.logger.info('get_info')
query = 'SELECT version_num FROM alembic_version... | from flask import Blueprint, jsonify, current_app
from app import db
from app.errors import register_errors
base_blueprint = Blueprint('', __name__)
register_errors(base_blueprint)
@base_blueprint.route('/')
def get_info():
current_app.logger.info('get_info')
query = 'SELECT version_num FROM alembic_version... | Handle db exceptions when getting api info | Handle db exceptions when getting api info
| Python | mit | NewAcropolis/api,NewAcropolis/api,NewAcropolis/api | ---
+++
@@ -11,7 +11,11 @@
def get_info():
current_app.logger.info('get_info')
query = 'SELECT version_num FROM alembic_version'
- full_name = db.session.execute(query).fetchone()[0]
+ try:
+ full_name = db.session.execute(query).fetchone()[0]
+ except Exception as e:
+ current_app.l... |
f779905c1b7a48a8f49da6ad061ae7d67e677052 | cartoframes/viz/legend_list.py | cartoframes/viz/legend_list.py | from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, de... | from .legend import Legend
from .constants import SINGLE_LEGEND
class LegendList:
"""LegendList
Args:
legends (list, Legend): List of legends for a layer.
"""
def __init__(self, legends=None, default_legend=None, geom_type=None):
self._legends = self._init_legends(legends, de... | Fix default legend type detection | Fix default legend type detection
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | ---
+++
@@ -17,9 +17,10 @@
legend_list = []
for legend in legends:
if isinstance(legend, Legend):
- if legend._type == 'default' or legend._type == 'basic':
+ if legend._type == 'basic':
legend._type = _get_simpl... |
4b3ec77a6e1639dc156135fd42ca215c58c082a3 | pyecore/notification.py | pyecore/notification.py | """
This module gives the "listener" classes for the PyEcore notification layer.
The main class to create a new listener is "EObserver" which is triggered
each time a modification is perfomed on an observed element.
"""
class ENotifer(object):
def notify(self, notification):
notification.notifier = notifi... | """
This module gives the "listener" classes for the PyEcore notification layer.
The main class to create a new listener is "EObserver" which is triggered
each time a modification is perfomed on an observed element.
"""
try:
from enum34 import unique, Enum
except ImportError:
from enum import unique, Enum
cla... | Add conditional import of the enum34 library | Add conditional import of the enum34 library
This lib is used to bing enumerations to Python <= 3.3.
| Python | bsd-3-clause | aranega/pyecore,pyecore/pyecore | ---
+++
@@ -3,6 +3,10 @@
The main class to create a new listener is "EObserver" which is triggered
each time a modification is perfomed on an observed element.
"""
+try:
+ from enum34 import unique, Enum
+except ImportError:
+ from enum import unique, Enum
class ENotifer(object): |
f18ea85f3599e16c60cfc2b652c30ff64997e95b | pytablereader/loadermanager/_base.py | pytablereader/loadermanager/_base.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def format... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import
from ..interface import TableLoaderInterface
class TableLoaderManager(TableLoaderInterface):
def __init__(self, loader):
self.__loader = loader
@property
def loader... | Add an interface to get the loader | Add an interface to get the loader
| Python | mit | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader | ---
+++
@@ -13,6 +13,10 @@
def __init__(self, loader):
self.__loader = loader
+
+ @property
+ def loader(self):
+ return self.__loader
@property
def format_name(self): |
ddb12a892d42e8a6ffdd8146149ec306dea48a12 | pydmrs/pydelphin_interface.py | pydmrs/pydelphin_interface.py | from delphin.interfaces import ace
from delphin.mrs import simplemrs, dmrx
from pydmrs.core import ListDmrs
from pydmrs.utils import load_config, get_config_option
DEFAULT_CONFIG_FILE = 'default_interface.conf'
config = load_config(DEFAULT_CONFIG_FILE)
DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG')
... | from delphin.interfaces import ace
from delphin.mrs import simplemrs, dmrx
from pydmrs.core import ListDmrs
from pydmrs.utils import load_config, get_config_option
DEFAULT_CONFIG_FILE = 'default_interface.conf'
config = load_config(DEFAULT_CONFIG_FILE)
DEFAULT_ERG_FILE = get_config_option(config, 'Grammar', 'ERG')
... | Update PyDelphin interface to recent version | Update PyDelphin interface to recent version
| Python | mit | delph-in/pydmrs,delph-in/pydmrs,delph-in/pydmrs | ---
+++
@@ -12,9 +12,8 @@
def parse(sentence, cls=ListDmrs, erg_file=DEFAULT_ERG_FILE):
results = []
- for result in ace.parse(erg_file, sentence)['RESULTS']: # cmdargs=['-r', 'root_informal']
- mrs = result['MRS']
- xmrs = simplemrs.loads_one(mrs)
+ for result in ace.parse(erg_file, sent... |
c26a7f83b1e9689496b5cf3b5e42fb85611c1ded | ideascube/conf/idb_aus_queensland.py | ideascube/conf/idb_aus_queensland.py | # -*- coding: utf-8 -*-
"""Queensland box in Australia"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Queensland"
IDEASCUBE_PLACE_NAME = _("the community")
COUNTRIES_FIRST = ['AU']
TIME_ZONE = 'Australia/Darwin'
LANGUAGE_CODE = 'en'
LOAN_DURATION = 14
MONITORIN... | # -*- coding: utf-8 -*-
"""Queensland box in Australia"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Queensland"
IDEASCUBE_PLACE_NAME = _("the community")
COUNTRIES_FIRST = ['AU']
TIME_ZONE = 'Australia/Darwin'
LANGUAGE_CODE = 'en'
LOAN_DURATION = 14
MONITORIN... | Change cards for the new version | Change cards for the new version
We setup a new version of the server and installed the ZIM file with the
catalog, so the cards has to change from the old version to the new
version to match with the ideascube catalog policy
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -17,3 +17,33 @@
(_('In the town'), ['current_occupation', 'school_level']),
(_('Language skills'), ['en_level']),
)
+
+STAFF_HOME_CARDS = [c for c in STAFF_HOME_CARDS
+ if c['url'] not in ['server:battery']]
+
+HOME_CARDS = STAFF_HOME_CARDS + [
+ {
+ 'id': 'blog',
+ ... |
6894bd3cfc010c371478e7ae9e5e0b3ba108e165 | plugins/configuration/configurationtype/configuration_registrar.py | plugins/configuration/configurationtype/configuration_registrar.py | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... | #!/usr/bin/env python
#-*- coding: utf-8 -*-
#This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software.
#The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif... | Implement unregistration of configuration plug-ins | Implement unregistration of configuration plug-ins
Perhaps we should not give a warning, but instead an exception, when registering or unregistering fails?
| Python | cc0-1.0 | Ghostkeeper/Luna | ---
+++
@@ -28,7 +28,18 @@
_configurations[identity] = metadata["configuration"]["class"]
def unregister(identity):
- raise Exception("Not implemented yet.")
+ """
+ Undoes the registration of a configuration plug-in.
+
+ The configuration plug-in will no longer keep track of any configuration.
+ Existing config... |
7b83e8fbe8e6a249ab82db38e358774ba78b4ea8 | pyflation/analysis/__init__.py | pyflation/analysis/__init__.py | """ analysis package - Provides modules to analyse results from cosmomodels runs.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
"""
from adiabatic import Pr, Pzeta, scaled_Pr
from nonadiabatic import deltaPspectrum, deltaPnadspectrum, deltarhospectrum | """ analysis package - Provides modules to analyse results from cosmomodels runs.
Author: Ian Huston
For license and copyright information see LICENSE.txt which was distributed with this file.
"""
from adiabatic import Pr, Pzeta, scaled_Pr, scaled_Pzeta
from nonadiabatic import deltaPspectrum, deltaPnadspectrum, delt... | Add new S spectrum functions into package initializer. | Add new S spectrum functions into package initializer.
| Python | bsd-3-clause | ihuston/pyflation,ihuston/pyflation | ---
+++
@@ -4,5 +4,7 @@
For license and copyright information see LICENSE.txt which was distributed with this file.
"""
-from adiabatic import Pr, Pzeta, scaled_Pr
-from nonadiabatic import deltaPspectrum, deltaPnadspectrum, deltarhospectrum
+from adiabatic import Pr, Pzeta, scaled_Pr, scaled_Pzeta
+from nonadiab... |
6212f78597dff977a7e7348544d09c7a649aa470 | bitbots_transform/src/bitbots_transform/transform_ball.py | bitbots_transform/src/bitbots_transform/transform_ball.py | #!/usr/bin/env python2.7
import rospy
from bitbots_transform.transform_helper import transf
from humanoid_league_msgs.msg import BallRelative, BallInImage
from sensor_msgs.msg import CameraInfo
class TransformLines(object):
def __init__(self):
rospy.Subscriber("ball_in_image", BallInImage, self._callback_... | #!/usr/bin/env python2.7
import rospy
from bitbots_transform.transform_helper import transf
from humanoid_league_msgs.msg import BallRelative, BallInImage
from sensor_msgs.msg import CameraInfo
class TransformBall(object):
def __init__(self):
rospy.Subscriber("ball_in_image", BallInImage, self._callback_b... | Transform Ball: Fixed wrong names | Transform Ball: Fixed wrong names
| Python | mit | bit-bots/bitbots_misc,bit-bots/bitbots_misc,bit-bots/bitbots_misc | ---
+++
@@ -5,11 +5,11 @@
from sensor_msgs.msg import CameraInfo
-class TransformLines(object):
+class TransformBall(object):
def __init__(self):
rospy.Subscriber("ball_in_image", BallInImage, self._callback_ball, queue_size=1)
- rospy.Subscriber("camera/camera_info", CameraInfo, self._callb... |
b28b4bb834d8ab70e8820c43ed8cf11242c1b5b6 | keystoneclient/v2_0/endpoints.py | keystoneclient/v2_0/endpoints.py | # Copyright 2012 Canonical Ltd.
# 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 b... | # Copyright 2012 Canonical Ltd.
# 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 b... | Make parameters in EndpointManager optional | Make parameters in EndpointManager optional
Change adminurl and internalurl parameters in EndpointManager create()
to optional parameters.
Change-Id: I490e35b89f7ae7c6cdbced6ba8d3b82d5132c19d
Closes-Bug: #1318436
| Python | apache-2.0 | magic0704/python-keystoneclient,jamielennox/python-keystoneclient,klmitch/python-keystoneclient,ging/python-keystoneclient,alexpilotti/python-keystoneclient,klmitch/python-keystoneclient,darren-wang/ksc,alexpilotti/python-keystoneclient,magic0704/python-keystoneclient,Mercador/python-keystoneclient,ging/python-keystone... | ---
+++
@@ -31,7 +31,8 @@
"""List all available endpoints."""
return self._list('/endpoints', 'endpoints')
- def create(self, region, service_id, publicurl, adminurl, internalurl):
+ def create(self, region, service_id, publicurl, adminurl=None,
+ internalurl=None):
""... |
1005a41bd6fb3f854f75bd9d4d6ab69290778ba9 | kolibri/core/lessons/viewsets.py | kolibri/core/lessons/viewsets.py | from rest_framework.viewsets import ModelViewSet
from .serializers import LessonSerializer
from kolibri.core.lessons.models import Lesson
class LessonViewset(ModelViewSet):
serializer_class = LessonSerializer
def get_queryset(self):
return Lesson.objects.filter(is_archived=False)
| from rest_framework.viewsets import ModelViewSet
from .serializers import LessonSerializer
from kolibri.core.lessons.models import Lesson
class LessonViewset(ModelViewSet):
serializer_class = LessonSerializer
def get_queryset(self):
queryset = Lesson.objects.filter(is_archived=False)
classid ... | Add classid filter for Lessons | Add classid filter for Lessons
| Python | mit | learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,lyw07/kolibri,christianmemije/kolibri,christianmemije/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,jonboiser/kolibri,benjaoming/kolibri,lyw07/kolibri,jonboiser/kolibri,learningequality/kolibri,christianmemije/kolibri,jonboiser/kolibri,DXCanas/kolibri,mrpau/kol... | ---
+++
@@ -6,4 +6,11 @@
serializer_class = LessonSerializer
def get_queryset(self):
- return Lesson.objects.filter(is_archived=False)
+ queryset = Lesson.objects.filter(is_archived=False)
+
+ classid = self.request.query_params.get('classid', None)
+
+ if classid is not None:
... |
bd5844aa6c59c8d34df12e358e5e06eefcb55f9d | qiita_pet/handlers/download.py | qiita_pet/handlers/download.py | from tornado.web import authenticated
from os.path import split
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@aut... | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@... | Use basename instead of os.path.split(...)[-1] | Use basename instead of os.path.split(...)[-1]
| Python | bsd-3-clause | ElDeveloper/qiita,josenavas/QiiTa,RNAer/qiita,squirrelo/qiita,RNAer/qiita,ElDeveloper/qiita,antgonza/qiita,adamrp/qiita,wasade/qiita,antgonza/qiita,squirrelo/qiita,biocore/qiita,adamrp/qiita,josenavas/QiiTa,biocore/qiita,ElDeveloper/qiita,adamrp/qiita,antgonza/qiita,RNAer/qiita,squirrelo/qiita,ElDeveloper/qiita,wasade/... | ---
+++
@@ -1,6 +1,6 @@
from tornado.web import authenticated
-from os.path import split
+from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
@@ -20,7 +20,7 @@
self.current_user, 'filepath id %d' % filepath_id)
... |
d20e1a1fba39b688a21bfbf02fe32a2039232949 | lib/speedway.py | lib/speedway.py | #!/usr/bin/python2.4
#
# Copyright 2011 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 b... | #!/usr/bin/python2.4
#
# Copyright 2011 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 b... | Append newline after 'COMMIT' in iptables policies. Without newline, the iptables-restore command complains. | Append newline after 'COMMIT' in iptables policies.
Without newline, the iptables-restore command complains.
| Python | apache-2.0 | FlorianHeigl/capirca,haykeh/capirca,FlorianHeigl/capirca,haykeh/capirca | ---
+++
@@ -39,7 +39,7 @@
_SUFFIX = '.ipt'
_RENDER_PREFIX = '*filter'
- _RENDER_SUFFIX = 'COMMIT'
+ _RENDER_SUFFIX = 'COMMIT\n'
_DEFAULTACTION_FORMAT = ':%s %s'
_TERM = Term |
23a3f80d44592d4a86878f29eaa873d727ad31ee | london_commute_alert.py | london_commute_alert.py | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription']
for el in resp}
def email(lines):
with open... | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | Correct for problem on webfaction | Correct for problem on webfaction
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -7,8 +7,7 @@
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
- return {el['id']: el['lineStatuses'][0]['statusSeverityDescription']
- for el in resp}
+ return {el['id']: el['lineStatuses'][0]['statusSeverity... |
3504baa66ada0bde545ed2b111b71335f23d1838 | PyTestStub/Templates.py | PyTestStub/Templates.py |
functionTest = '''
def test_%s(self):
raise NotImplementedError() #TODO: test %s'''
classTest = '''class %sTest(unittest.TestCase):
"""
%s
"""
@staticmethod
def setUpClass(cls):
pass #TODO
@staticmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TO... |
functionTest = '''
def test_%s(self):
raise NotImplementedError() #TODO: test %s'''
classTest = '''class %sTest(unittest.TestCase):
"""
%s
"""
@classmethod
def setUpClass(cls):
pass #TODO
@classmethod
def tearDownClass(cls):
pass #TODO
def setUp(self):
pass #TODO
def tearDown(self):
pass #TODO... | Fix error in unit test template | Fix error in unit test template
| Python | mit | AgalmicVentures/PyTestStub | ---
+++
@@ -8,11 +8,11 @@
%s
"""
- @staticmethod
+ @classmethod
def setUpClass(cls):
pass #TODO
- @staticmethod
+ @classmethod
def tearDownClass(cls):
pass #TODO
|
816ceb19e224f23bf3ba2fd06f7f3e2296ee5622 | asp/__init__.py | asp/__init__.py | # From http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
# Author: James Antill (http://stackoverflow.com/users/10314/james-antill)
__version__ = '0.1.3.0'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])
class SpecializationError(Exception):
"""
... | # From http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
# Author: James Antill (http://stackoverflow.com/users/10314/james-antill)
__version__ = '0.1.3.1'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])
class SpecializationError(Exception):
"""
... | Bump version number for avro fix. | Bump version number for avro fix. | Python | bsd-3-clause | shoaibkamil/asp,shoaibkamil/asp,shoaibkamil/asp | ---
+++
@@ -1,6 +1,6 @@
# From http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package
# Author: James Antill (http://stackoverflow.com/users/10314/james-antill)
-__version__ = '0.1.3.0'
+__version__ = '0.1.3.1'
__version_info__ = tuple([ int(num) for num in __version__.split('.... |
598e21a7c397c0c429a78f008a36e5800c1b23e3 | conftest.py | conftest.py | import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.grap... | import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.grap... | Fix picking invalid env variable for tests | Fix picking invalid env variable for tests
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -22,6 +22,6 @@
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
- default=os.environ.get("PYTEST_DB_URL"), conn_max_age=600
+ env="PYTEST_DB_URL", conn_max_age=600
),
... |
3643c0c4959f5d27c5faab2533fa5c3a7952cbb8 | test_titanic.py | test_titanic.py | import titanic
buildername = 'Ubuntu HW 12.04 x64 mozilla-inbound pgo talos svgr'
branch = 'mozilla-inbound'
delta = 30
# NOTE: This API might take long to run.
# Usually takes around a minute to run, may take longer
revList, buildList = titanic.runAnalysis(
branch, buildername, '6ffcd2030ed8', delta)
# NOTE: ru... | import titanic
import sys
buildername = 'Windows 7 32-bit mozilla-central debug test mochitest-1'
branch = 'mozilla-central'
delta = 30
revision = 'cd2acc7ab2f8'
revList, buildList = titanic.runAnalysis(
branch, buildername, revision, delta)
for rev in buildList:
if not (titanic.isBuildPending(branch, builde... | Update Sample Code for Backfill | Update Sample Code for Backfill
Update Sample Code that could be used to automatically
trigger builds and jobs
| Python | mpl-2.0 | gakiwate/titanic | ---
+++
@@ -1,29 +1,31 @@
import titanic
+import sys
-buildername = 'Ubuntu HW 12.04 x64 mozilla-inbound pgo talos svgr'
-branch = 'mozilla-inbound'
+buildername = 'Windows 7 32-bit mozilla-central debug test mochitest-1'
+branch = 'mozilla-central'
delta = 30
+revision = 'cd2acc7ab2f8'
-# NOTE: This API might ... |
c265f3a24ba26800a15ddf54ad3aa7515695fb3f | app/__init__.py | app/__init__.py | from flask import Flask
from .extensions import db
from . import views
def create_app(config):
""" Create a Flask App base on a config obejct. """
app = Flask(__name__)
app.config.from_object(config)
register_extensions(app)
register_views(app)
# @app.route("/")
# def index():
# ... | from flask import Flask
from flask_user import UserManager
from . import views
from .extensions import db, mail, toolbar
from .models import DataStoreAdapter, UserModel
def create_app(config):
""" Create a Flask App base on a config obejct. """
app = Flask(__name__)
app.config.from_object(config)
reg... | Update app init to user flask user, mail and toolbar ext | Update app init to user flask user, mail and toolbar ext
| Python | mit | oldani/nanodegree-blog,oldani/nanodegree-blog,oldani/nanodegree-blog | ---
+++
@@ -1,6 +1,8 @@
from flask import Flask
-from .extensions import db
+from flask_user import UserManager
from . import views
+from .extensions import db, mail, toolbar
+from .models import DataStoreAdapter, UserModel
def create_app(config):
@@ -11,16 +13,19 @@
register_extensions(app)
register... |
e0bbdd0aac905aa0fc16837b63ce7545099e019f | controlcenter/app_settings.py | controlcenter/app_settings.py | import sys
from django.utils import six
# I know, it's ugly, but I just can't write:
# gettattr(settings, 'CONTROLCENTER_CHARTIST_COLORS', 'default')
# This is way better: app_settings.CHARTIST_COLORS
# TODO: move to separate project
def proxy(attr, default):
def wrapper(self):
# It has to be most rece... | import sys
from django.utils import six
# I know, it's ugly, but I just can't write:
# gettattr(settings, 'CONTROLCENTER_CHARTIST_COLORS', 'default')
# This is way better: app_settings.CHARTIST_COLORS
# TODO: move to separate project
def proxy(attr, default):
def wrapper(self):
# It has to be most rece... | Replace local variable with class attribute | Replace local variable with class attribute
| Python | bsd-3-clause | byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter | ---
+++
@@ -34,8 +34,8 @@
# http://mail.python.org/pipermail/python-ideas/2012-May/
# 014969.html
ins = cls()
- ins.__name__ = __name__
- sys.modules[__name__] = ins
+ ins.__name__ = ins.__module__
+ sys.modules[ins.__module__] = ins
... |
d00377ae301163debec253b9261ea41eeaa0e176 | src/dbbrankingparser/httpclient.py | src/dbbrankingparser/httpclient.py | """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Icewea... | """
dbbrankingparser.httpclient
~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP client utilities
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: MIT, see LICENSE for details.
"""
from urllib.request import Request, urlopen
USER_AGENT = (
'Mozilla/5.0 (X11; Linux x86_64; rv:38.0) '
'Gecko/20100101 Firefox/38.0 Icewea... | Use HTTPS to retrieve ranking from DBB | Use HTTPS to retrieve ranking from DBB
| Python | mit | homeworkprod/dbb-ranking-parser | ---
+++
@@ -20,7 +20,7 @@
def assemble_url(league_id: int) -> str:
"""Assemble the ranking HTML's URL for the league with that ID."""
template = (
- 'http://www.basketball-bund.net/public/tabelle.jsp'
+ 'https://www.basketball-bund.net/public/tabelle.jsp'
'?print=1'
'&viewDe... |
c109b41dc76c333bda1973fa2a543688f2fd5141 | braid/config.py | braid/config.py | """
Support for multiple environments based on python configuration files.
"""
from __future__ import print_function, absolute_import
import imp
import os
from twisted.python.filepath import FilePath
from fabric.api import env, task
CONFIG_DIRS = [
'~/.braid',
'./braidrc.local',
]
def loadEnvironmentCon... | """
Support for multiple environments based on python configuration files.
"""
from __future__ import print_function, absolute_import
import imp
import os
from twisted.python.filepath import FilePath
from fabric.api import env, task
CONFIG_DIRS = [
'~/.braid',
'./braidrc.local',
]
def loadEnvironmentCon... | Make docstrings more Fabric friendly | Make docstrings more Fabric friendly
| Python | mit | alex/braid,alex/braid | ---
+++
@@ -39,8 +39,8 @@
@task
def environment(env):
"""
- Loads the passed environment configuration. This task can be invoked before
- executing the desired Fabric action.
+ Load the passed environment configuration.
+ This task can be invoked before executing the desired Fabric action.
"""... |
97a1e627b682f9aec80134334277b63e81265ddd | tests/test_ircv3.py | tests/test_ircv3.py | import pytest
from pydle.features import ircv3
pytestmark = [pytest.mark.unit, pytest.mark.ircv3]
@pytest.mark.parametrize(
"payload, expected",
[
(
rb"@+example=raw+:=,escaped\:\s\\ :irc.example.com NOTICE #channel :Message",
{"+example": """raw+:=,escaped; \\"""}
... | import pytest
from pydle.features import ircv3
pytestmark = [pytest.mark.unit, pytest.mark.ircv3]
@pytest.mark.parametrize(
"payload, expected",
[
(
rb'@empty=;missing :irc.example.com NOTICE #channel :Message',
{'empty': True, 'missing': True}
),
(
... | Add test case for empty and missing IRCv3 tags | Add test case for empty and missing IRCv3 tags
| Python | bsd-3-clause | Shizmob/pydle | ---
+++
@@ -9,6 +9,10 @@
"payload, expected",
[
(
+ rb'@empty=;missing :irc.example.com NOTICE #channel :Message',
+ {'empty': True, 'missing': True}
+ ),
+ (
rb"@+example=raw+:=,escaped\:\s\\ :irc.example.com NOTICE #channel :Message",
... |
127a3da0d453785bd9c711d738e20dfdc1876df1 | tool/serial_dump.py | tool/serial_dump.py | #!/usr/bin/python
import serial
import string
import io
import time
import sys
if __name__ == '__main__':
port = "/dev/ttyUSB0"
baudrate = "57600"
second = 0.1
if (len(sys.argv) < 3):
print("Usage: serial_dump.py /dev/ttyUSB0 57600")
exit()
elif (len(sys.argv) == 3):
port = sys.argv[1]
baudrate = sys... | #!/usr/bin/python
import serial
import string
import io
import time
import sys
if __name__ == '__main__':
port = "/dev/ttyUSB0"
baudrate = "57600"
second = 0.001
if (len(sys.argv) < 4 ):
print("Usage: \n./serial_dump.py /dev/ttyUSB0 57600 file_name 0.01")
exit()
elif (len(sys.argv) == 4):
port = sys.a... | Change command option, need to specify file name now | Change command option, need to specify file name now
| Python | mit | ming6842/firmware-new,fboris/firmware,UrsusPilot/firmware,fboris/firmware,UrsusPilot/firmware,fboris/firmware,UrsusPilot/firmware,ming6842/firmware-new,ming6842/firmware-new | ---
+++
@@ -11,26 +11,28 @@
port = "/dev/ttyUSB0"
baudrate = "57600"
- second = 0.1
+ second = 0.001
- if (len(sys.argv) < 3):
- print("Usage: serial_dump.py /dev/ttyUSB0 57600")
+ if (len(sys.argv) < 4 ):
+ print("Usage: \n./serial_dump.py /dev/ttyUSB0 57600 file_name 0.01")
exit()
- elif (len(sys.ar... |
0655505b20c5fc88ba3b5de1d948538acc5c1b8a | normandy/health/urls.py | normandy/health/urls.py | from django.conf.urls import url
from normandy.health.api import views
urlpatterns = [
url(r'^__version__', views.version, name='normandy.version'),
url(r'^__heartbeat__', views.heartbeat, name='normandy.heartbeat'),
url(r'^__lbheartbeat__', views.heartbeat, name='normandy.lbheartbeat'),
]
| from django.conf.urls import url
from normandy.health.api import views
urlpatterns = [
url(r'^__version__', views.version, name='normandy.version'),
url(r'^__heartbeat__', views.heartbeat, name='normandy.heartbeat'),
url(r'^__lbheartbeat__', views.lbheartbeat, name='normandy.lbheartbeat'),
]
| Use the right view for the lbheartbeat check | Use the right view for the lbheartbeat check
| Python | mpl-2.0 | mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,Osmose/normandy,Osmose/normandy,mozilla/normandy,mozilla/normandy | ---
+++
@@ -5,5 +5,5 @@
urlpatterns = [
url(r'^__version__', views.version, name='normandy.version'),
url(r'^__heartbeat__', views.heartbeat, name='normandy.heartbeat'),
- url(r'^__lbheartbeat__', views.heartbeat, name='normandy.lbheartbeat'),
+ url(r'^__lbheartbeat__', views.lbheartbeat, name='norma... |
5fb17ccf0311500e5ce14a49e246d1a6cbc427a4 | mopidy/frontends/mpd/__init__.py | mopidy/frontends/mpd/__init__.py | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.process import MpdProcess
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
... | import logging
from mopidy.frontends.base import BaseFrontend
from mopidy.frontends.mpd.dispatcher import MpdDispatcher
from mopidy.frontends.mpd.process import MpdProcess
from mopidy.utils.process import unpickle_connection
logger = logging.getLogger('mopidy.frontends.mpd')
class MpdFrontend(BaseFrontend):
"""
... | Make MpdFrontend ignore unknown messages | Make MpdFrontend ignore unknown messages
| Python | apache-2.0 | diandiankan/mopidy,rawdlite/mopidy,adamcik/mopidy,ZenithDK/mopidy,SuperStarPL/mopidy,bencevans/mopidy,abarisain/mopidy,pacificIT/mopidy,bacontext/mopidy,jodal/mopidy,adamcik/mopidy,jcass77/mopidy,jmarsik/mopidy,quartz55/mopidy,quartz55/mopidy,kingosticks/mopidy,SuperStarPL/mopidy,ali/mopidy,bencevans/mopidy,adamcik/mop... | ---
+++
@@ -45,4 +45,4 @@
connection = unpickle_connection(message['reply_to'])
connection.send(response)
else:
- logger.warning(u'Cannot handle message: %s', message)
+ pass # Ignore messages for other frontends |
076ef01bd3334d2a1941df369286e4972223901e | PyramidSort.py | PyramidSort.py | import sublime, sublime_plugin
def pyramid_sort(txt):
txt = list(filter(lambda s: s.strip(), txt))
txt.sort(key = lambda s: len(s))
return txt
class PyramidSortCommand(sublime_plugin.TextCommand):
def run(self, edit):
regions = [s for s in self.view.sel() if not s.empty()]
if regions:
for r in regions:
... | #
# 123
# 12
# 1
import sublime, sublime_plugin
def pyramid_sort(txt):
txt = list(filter(lambda s: s.strip(), txt))
txt.sort(key = lambda s: len(s))
return txt
class PyramidSortCommand(sublime_plugin.TextCommand):
def run(self, edit):
regions = [s for s in self.view.sel() if not s.empty()]
if regions:
... | Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked" | Revert "removed grab line from region, gives some unexpected behaviour. Instead just replace exactly what is marked"
This reverts commit 9c944db3affc8181146fa27d8483a58d2731756b.
| Python | apache-2.0 | kenglxn/PyramidSortSublimeTextPlugin,kenglxn/PyramidSortSublimeTextPlugin | ---
+++
@@ -1,3 +1,8 @@
+#
+# 123
+# 12
+# 1
+
import sublime, sublime_plugin
def pyramid_sort(txt):
@@ -10,7 +15,8 @@
regions = [s for s in self.view.sel() if not s.empty()]
if regions:
for r in regions:
- txt = self.view.substr(r)
+ lr = self.view.line(r)
+ txt = self.view.substr(lr)
... |
44f2ea1a47ee8502580853aaf6ca98597d83446a | __openerp__.py | __openerp__.py | # -*- coding: utf-8 -*-
{
"name": "Alternate Ledger",
"version": "1.2.2",
"author": "XCG Consulting",
"category": 'Accounting',
"description": '''Allow the creation of new accounting ledgers that store
separate transactions.''',
'website': 'http://www.openerp-experts.com',
'init_xml'... | # -*- coding: utf-8 -*-
{
"name": "Alternate Ledger",
"version": "1.2.3",
"author": "XCG Consulting",
"category": 'Accounting',
"description": '''Allow the creation of new accounting ledgers that store
separate transactions.''',
'website': 'http://www.openerp-experts.com',
'init_xml'... | Change version to 1.2.3 (dev) | Change version to 1.2.3 (dev)
| Python | agpl-3.0 | xcgd/alternate_ledger,xcgd/alternate_ledger | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
{
"name": "Alternate Ledger",
- "version": "1.2.2",
+ "version": "1.2.3",
"author": "XCG Consulting",
"category": 'Accounting',
"description": '''Allow the creation of new accounting ledgers that store |
6f4b4a9e54e527292d04d0a0f50ce6e02e08750d | pymc/__init__.py | pymc/__init__.py | __version__ = "3.0"
import matplotlib
matplotlib.use('Agg')
from .core import *
from .distributions import *
from .math import *
from .trace import *
from .sample import *
from .step_methods import *
from .tuning import *
from .debug import *
from .diagnostics import *
from .plots import *
from .tests import test... | __version__ = "3.0"
from .core import *
from .distributions import *
from .math import *
from .trace import *
from .sample import *
from .step_methods import *
from .tuning import *
from .debug import *
from .diagnostics import *
from .plots import *
from .tests import test
from . import glm
from .data import *
| Revert "Experimenting with import order" | Revert "Experimenting with import order"
This reverts commit c407a00, which selected the Agg backend for
Matplotlib in pymc/__init__.py, overriding the effects of 40a8070. These
changes were unnecessary to fix the non-interative display errors in the
Travis tests and prevent interactive plotting unless the user has
se... | Python | apache-2.0 | MCGallaspy/pymc3,superbobry/pymc3,JesseLivezey/pymc3,wanderer2/pymc3,JesseLivezey/pymc3,kmather73/pymc3,MichielCottaar/pymc3,kmather73/pymc3,kyleam/pymc3,dhiapet/PyMC3,tyarkoni/pymc3,LoLab-VU/pymc,tyarkoni/pymc3,clk8908/pymc3,superbobry/pymc3,jameshensman/pymc3,arunlodhi/pymc3,Anjum48/pymc3,MCGallaspy/pymc3,wanderer2/p... | ---
+++
@@ -1,6 +1,4 @@
__version__ = "3.0"
-import matplotlib
-matplotlib.use('Agg')
from .core import *
from .distributions import * |
69b0e1c60eafff596ebb494a7e79a22c6bea374b | polling_stations/apps/data_collection/management/commands/import_hart.py | polling_stations/apps/data_collection/management/commands/import_hart.py | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000089'
addresses_name = 'parl.2017-06-08/Version 1/Hart DC General Election polling place 120517.TSV'
stations_name = 'parl.2017-06-08/Version 1/Hart DC Ge... | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = 'E07000089'
addresses_name = 'parl.2017-06-08/Version 1/Hart DC General Election polling place 120517.TSV'
stations_name = 'parl.2017-06-08/Version 1/Hart DC Ge... | Fix dodgy point in Hart | Fix dodgy point in Hart
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -6,3 +6,11 @@
stations_name = 'parl.2017-06-08/Version 1/Hart DC General Election polling place 120517.TSV'
elections = ['parl.2017-06-08']
csv_delimiter = '\t'
+
+ def station_record_to_dict(self, record):
+
+ if record.polling_place_id == '1914':
+ record = record._rep... |
c24ecf7387f962415fcb03cd0dca9a136d1eda4e | cesium/setup.py | cesium/setup.py | def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('cesium', parent_package, top_path)
config.add_subpackage('science_features')
config.add_data_files('cesium.yaml.example')
config.add_data_dir('data')
return config
... | def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('cesium', parent_package, top_path)
config.add_subpackage('science_features')
config.add_data_files('cesium.yaml.example')
config.add_data_dir('tests')
return config
... | Add test data to cesium package | Add test data to cesium package
| Python | bsd-3-clause | acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,bnaul/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,bnaul/mltsp,acrellin/mltsp | ---
+++
@@ -4,7 +4,7 @@
config = Configuration('cesium', parent_package, top_path)
config.add_subpackage('science_features')
config.add_data_files('cesium.yaml.example')
- config.add_data_dir('data')
+ config.add_data_dir('tests')
return config
|
1ac2e2b03048cf89c8df36c838130212f4ac63d3 | server/src/weblab/__init__.py | server/src/weblab/__init__.py | import os
import json
from .util import data_filename
version_filename = data_filename(os.path.join("weblab", "version.json"))
base_version = "5.0"
__version__ = base_version
if version_filename:
try:
git_version = json.loads(open(version_filename).read())
except:
git_version = None
if git_v... | import os
import json
from .util import data_filename
version_filename = data_filename(os.path.join("weblab", "version.json"))
base_version = "5.0"
__version__ = base_version
if version_filename:
try:
git_version = json.loads(open(version_filename).read())
except:
git_version = None
if git_v... | Add date to the version | Add date to the version
| Python | bsd-2-clause | morelab/weblabdeusto,porduna/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto,weblabdeusto/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto,porduna/weblabdeusto,porduna/weblabdeusto,porduna/weblabdeusto,morelab/weblabdeusto,weblabdeusto/weblabdeusto,pordun... | ---
+++
@@ -10,5 +10,5 @@
except:
git_version = None
if git_version and 'version' in git_version:
- __version__ = "{0} - {1}".format(base_version, git_version.get('version'))
+ __version__ = "{0} - {1} ({2})".format(base_version, git_version.get('version'), git_version.get('date'))
_... |
50ab2ed3d8e50e5106dc486e4d20c889d6b18e82 | spkg/base/package_database.py | spkg/base/package_database.py | """
Package database utilities for creating and modifying the database.
"""
from os.path import split, splitext
from json import load
f = open("packages.json")
data = load(f)
g = []
for p in data:
pkg = {
"name": p["name"],
"dependencies": p["dependencies"],
"version": p["versi... | """
Package database utilities for creating and modifying the database.
"""
from os.path import split, splitext
from json import load
f = open("packages.json")
data = load(f)
g = []
for p in data:
pkg = {
"name": p["name"],
"dependencies": p["dependencies"],
"version": p["versi... | Add a new line at the end of the file | Add a new line at the end of the file
| Python | bsd-3-clause | qsnake/qsnake,qsnake/qsnake | ---
+++
@@ -27,3 +27,4 @@
s = s.replace(" \n", "\n")
f = open("packages.json", "w")
f.write(s)
+f.write("\n") |
766ea05836544b808cd2c346873d9e4f60c858a1 | ping/tests/test_ping.py | ping/tests/test_ping.py | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 p... | import pytest
import mock
from datadog_checks.checks import AgentCheck
from datadog_checks.ping import PingCheck
from datadog_checks.errors import CheckException
def mock_exec_ping():
return """FAKEPING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.093 ms
--- 127.0.0.1 p... | Update test to assert metric | Update test to assert metric
| Python | bsd-3-clause | DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras,DataDog/integrations-extras | ---
+++
@@ -37,3 +37,4 @@
with mock.patch.object(c, "_exec_ping", return_value=mock_exec_ping()):
c.check(instance)
aggregator.assert_service_check('network.ping.can_connect', AgentCheck.OK)
+ aggregator.assert_metric('network.ping.can_connect', value=1) |
164fe2780554ddca5f66273e11efea37cfaf1368 | numba/tests/issues/test_issue_204.py | numba/tests/issues/test_issue_204.py | from numba import autojit, jit
@autojit
def closure_modulo(a, b):
@jit('int32()')
def foo():
return a % b
return foo()
print closure_modulo(100, 48)
| from numba import autojit, jit
@autojit
def closure_modulo(a, b):
@jit('int32()')
def foo():
return a % b
return foo()
def test_closure_modulo():
assert closure_modulo(100, 48) == 4
if __name__ == '__main__':
test_closure_modulo()
| Fix tests for python 3 | Fix tests for python 3
| Python | bsd-2-clause | GaZ3ll3/numba,pombredanne/numba,ssarangi/numba,stefanseefeld/numba,GaZ3ll3/numba,shiquanwang/numba,jriehl/numba,gdementen/numba,sklam/numba,jriehl/numba,ssarangi/numba,stonebig/numba,sklam/numba,GaZ3ll3/numba,seibert/numba,numba/numba,gmarkall/numba,sklam/numba,GaZ3ll3/numba,gmarkall/numba,stonebig/numba,seibert/numba,... | ---
+++
@@ -7,4 +7,8 @@
return a % b
return foo()
-print closure_modulo(100, 48)
+def test_closure_modulo():
+ assert closure_modulo(100, 48) == 4
+
+if __name__ == '__main__':
+ test_closure_modulo() |
422bf9860aacc3babbdd09ab1bd0941455b6ac7b | calaccess_campaign_browser/management/commands/dropcalaccesscampaignbrowser.py | calaccess_campaign_browser/management/commands/dropcalaccesscampaignbrowser.py | from django.db import connection
from calaccess_campaign_browser import models
from calaccess_campaign_browser.management.commands import CalAccessCommand
class Command(CalAccessCommand):
help = "Drops all CAL-ACCESS campaign browser database tables"
def handle(self, *args, **options):
self.header("D... | from django.db import connection
from calaccess_campaign_browser import models
from calaccess_campaign_browser.management.commands import CalAccessCommand
class Command(CalAccessCommand):
help = "Drops all CAL-ACCESS campaign browser database tables"
def handle(self, *args, **options):
self.header("D... | Add scraper models to drop command | Add scraper models to drop command
| Python | mit | california-civic-data-coalition/django-calaccess-campaign-browser,myersjustinc/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,dwillis/django-calaccess-campaign-browser,california-civic-data-coalition/django-calaccess-campaign-browser,myersjustinc/django-calaccess-campaign-browser | ---
+++
@@ -23,6 +23,11 @@
models.Committee,
models.Filer,
models.Cycle,
+ models.Election,
+ models.Office,
+ models.Candidate,
+ models.Proposition,
+ models.PropositionFiler,
]
sql = """DROP TABLE IF EXI... |
25429b016ccd979c95da329491e95e69a4a18308 | packages/pcl-reference-assemblies.py | packages/pcl-reference-assemblies.py | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies',
version='2014-04-14',
sources=['http://storage.bos.xamarin.com/bot-pro... | import glob
import os
import shutil
class PCLReferenceAssembliesPackage(Package):
def __init__(self):
Package.__init__(self,
name='PortableReferenceAssemblies',
version='2014-04-14',
sources=['http://storage.bos.xamarin.com/bot-pro... | Fix the directory structure inside the source. | Fix the directory structure inside the source.
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild | ---
+++
@@ -26,7 +26,7 @@
shutil.rmtree(dest, ignore_errors=True)
- pcldir = os.path.join(self.package_build_dir(), self.source_dir_name, ".NETPortable")
+ pcldir = os.path.join(self.package_build_dir(), self.source_dir_name)
self.sh("rsync -abv -q %s/* %s" % (pcldir, dest))
PCL... |
b5bf391ca0303f877b39bed4c3266441a9b78b2b | src/waldur_mastermind/common/serializers.py | src/waldur_mastermind/common/serializers.py | from rest_framework import serializers
def validate_options(options, attributes):
fields = {}
for name, option in options.items():
params = {}
field_type = option.get('type', '')
field_class = serializers.CharField
if field_type == 'integer':
field_class = seriali... | from rest_framework import serializers
class StringListSerializer(serializers.ListField):
child = serializers.CharField()
FIELD_CLASSES = {
'integer': serializers.IntegerField,
'date': serializers.DateField,
'time': serializers.TimeField,
'money': serializers.IntegerField,
'boolean': seriali... | Fix validation of OpenStack select fields in request-based item form | Fix validation of OpenStack select fields in request-based item form [WAL-4035]
| Python | mit | opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -1,4 +1,23 @@
from rest_framework import serializers
+
+
+class StringListSerializer(serializers.ListField):
+ child = serializers.CharField()
+
+
+FIELD_CLASSES = {
+ 'integer': serializers.IntegerField,
+ 'date': serializers.DateField,
+ 'time': serializers.TimeField,
+ 'money': serialize... |
1fb54fcb5236b8c5f33f3eb855c1085c00eeeb2c | src/__init__.py | src/__init__.py | from .pytesseract import ( # noqa: F401
Output,
TesseractError,
TesseractNotFoundError,
TSVNotSupported,
get_tesseract_version,
image_to_alto_xml,
image_to_boxes,
image_to_data,
image_to_osd,
image_to_pdf_or_hocr,
image_to_string,
run_and_get_output,
)
| from .pytesseract import ( # noqa: F401
Output,
TesseractError,
TesseractNotFoundError,
ALTONotSupported,
TSVNotSupported,
get_tesseract_version,
image_to_alto_xml,
image_to_boxes,
image_to_data,
image_to_osd,
image_to_pdf_or_hocr,
image_to_string,
run_and_get_output... | Make the ALTONotSupported exception available | Make the ALTONotSupported exception available | Python | apache-2.0 | madmaze/pytesseract | ---
+++
@@ -2,6 +2,7 @@
Output,
TesseractError,
TesseractNotFoundError,
+ ALTONotSupported,
TSVNotSupported,
get_tesseract_version,
image_to_alto_xml, |
f89dce3ff6d0858c5a29b96610fe4113d6200184 | gallery/storages.py | gallery/storages.py | # coding: utf-8
from __future__ import unicode_literals
import re
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage
from django.dispatch import receiver
from django.utils.lru_cache import lru_cache
from django.utils.module... | # coding: utf-8
from __future__ import unicode_literals
import re
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage
from django.dispatch import receiver
from django.test.signals import setting_changed
from django.utils.lru... | Remove backwards compatibility with Django < 1.8. | Remove backwards compatibility with Django < 1.8.
| Python | bsd-3-clause | aaugustin/myks-gallery,aaugustin/myks-gallery | ---
+++
@@ -8,13 +8,9 @@
from django.core.exceptions import ImproperlyConfigured
from django.core.files.storage import FileSystemStorage
from django.dispatch import receiver
+from django.test.signals import setting_changed
from django.utils.lru_cache import lru_cache
from django.utils.module_loading import impor... |
4121dc4b67d198b7aeea16a4c46d7fc85e359190 | presentation/models.py | presentation/models.py | from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = ... | from django.db import models
from model_utils.models import TimeStampedModel
from warp.users.models import User
class Presentation(TimeStampedModel):
subject = models.CharField(max_length=50)
author = models.ForeignKey(User, on_delete=models.CASCADE)
views = models.IntegerField(default=0)
markdown = ... | Add 'is_public' field for checking the whether or not presentation is public | Add 'is_public' field for checking the whether or not presentation is public
| Python | mit | SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp | ---
+++
@@ -10,3 +10,4 @@
views = models.IntegerField(default=0)
markdown = models.TextField()
html = models.TextField()
+ is_public = models.BooleanField(default=True) |
0b5f3dc674001c9abd1a7d7df18badfafdb825eb | equajson.py | equajson.py | #! /usr/bin/env python
from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "para... | #! /usr/bin/env python
from __future__ import print_function
import os
import sys
import json
def pretty_print(equation):
print(equation["description"]["terse"])
eqn_dict = equation["unicode-pretty-print"]
equation_text = eqn_dict["multiline"]
for line in equation_text:
print(line)
if "para... | Add visual separator between outputs. | Add visual separator between outputs.
| Python | mit | nbeaver/equajson | ---
+++
@@ -35,7 +35,7 @@
description = equation["description"]["verbose"]
if query.lower() in description.lower():
pretty_print(equation)
- print()
+ print('-'*80)
if __name__ == '__main__': |
6c61e1000f3f87501b6e45a2715bd26a3b83b407 | collector/absolutefrequency.py | collector/absolutefrequency.py | from collector import ItemCollector
class ItemNumericAbsoluteFrequencyCollector(ItemCollector):
def __init__(self, previous_collector_set = None):
ItemCollector.__init__(self, previous_collector_set)
self.absolute_frequencies = {}
def collect(self, item, collector_set=None):
current_absolute_freque... | import collections
from collector import ItemCollector
class ItemNumericAbsoluteFrequencyCollector(ItemCollector):
def __init__(self, previous_collector_set = None):
ItemCollector.__init__(self, previous_collector_set)
self.absolute_frequencies = collections.defaultdict(int)
def collect(self, item, col... | Use defaultdict for absolute frequency collector | Use defaultdict for absolute frequency collector
| Python | mit | davidfoerster/schema-matching | ---
+++
@@ -1,3 +1,4 @@
+import collections
from collector import ItemCollector
@@ -5,12 +6,12 @@
def __init__(self, previous_collector_set = None):
ItemCollector.__init__(self, previous_collector_set)
- self.absolute_frequencies = {}
+ self.absolute_frequencies = collections.defaultdict(int)
... |
8a6ba483e88b4f5ace6e9a6773f0ad681edf92b2 | packages/Python/lldbsuite/test/api/multiple-targets/TestMultipleTargets.py | packages/Python/lldbsuite/test/api/multiple-targets/TestMultipleTargets.py | """Test the lldb public C++ api when creating multiple targets simultaneously."""
from __future__ import print_function
import os
import re
import subprocess
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestMultipleSimultaneous... | """Test the lldb public C++ api when creating multiple targets simultaneously."""
from __future__ import print_function
import os
import re
import subprocess
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestMultipleTargets(Test... | Rename multiple target test so it is unique. | Rename multiple target test so it is unique.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@289222 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb | ---
+++
@@ -13,7 +13,7 @@
from lldbsuite.test import lldbutil
-class TestMultipleSimultaneousDebuggers(TestBase):
+class TestMultipleTargets(TestBase):
mydir = TestBase.compute_mydir(__file__)
NO_DEBUG_INFO_TESTCASE = True |
743198c5e94471cfa68bdb8335e1d75ce4580722 | components/archivist/archivist.py | components/archivist/archivist.py | #! /usr/bin/env python
from pika import BlockingConnection, ConnectionParameters
from psycopg2 import connect
RABBIT_MQ_HOST = '54.76.183.35'
RABBIT_MQ_PORT = 5672
POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com'
POSTGRES_DATABASE = 'micro'
POSTGRES_USER = 'microservices'
POSTGRES_PASSWORD = ... | #! /usr/bin/env python
from pika import BlockingConnection, ConnectionParameters
from psycopg2 import connect
RABBIT_MQ_HOST = '54.76.183.35'
RABBIT_MQ_PORT = 5672
POSTGRES_HOST = 'microservices.cc9uedlzx2lk.eu-west-1.rds.amazonaws.com'
POSTGRES_DATABASE = 'micro'
POSTGRES_USER = 'microservices'
POSTGRES_PASSWORD = ... | Fix silly close error, wrong connection | Fix silly close error, wrong connection
| Python | mit | douglassquirrel/combo,douglassquirrel/microservices-hackathon-july-2014,douglassquirrel/microservices-hackathon-july-2014,douglassquirrel/combo,douglassquirrel/microservices-hackathon-july-2014,douglassquirrel/microservices-hackathon-july-2014,douglassquirrel/combo | ---
+++
@@ -20,7 +20,7 @@
(topic, content))
conn.commit()
cursor.close()
- connection.close()
+ conn.close()
print 'Recorded topic %s, content %s' % (topic, content)
connection = BlockingConnection(ConnectionParameters(host=RABBIT_MQ_HOST, |
1318d0bc658d23d22452b27004c5d670f4c80d17 | spacy/tests/conftest.py | spacy/tests/conftest.py | import pytest
import os
import spacy
@pytest.fixture(scope="session")
def EN():
return spacy.load("en")
@pytest.fixture(scope="session")
def DE():
return spacy.load("de")
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help="include tests that require full model... | import pytest
import os
from ..en import English
from ..de import German
@pytest.fixture(scope="session")
def EN():
return English(path=None)
@pytest.fixture(scope="session")
def DE():
return German(path=None)
def pytest_addoption(parser):
parser.addoption("--models", action="store_true",
help... | Test with the non-loaded versions of the English and German pipelines. | Test with the non-loaded versions of the English and German pipelines.
| Python | mit | raphael0202/spaCy,honnibal/spaCy,banglakit/spaCy,aikramer2/spaCy,recognai/spaCy,raphael0202/spaCy,recognai/spaCy,explosion/spaCy,spacy-io/spaCy,explosion/spaCy,oroszgy/spaCy.hu,raphael0202/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,oroszgy/spaCy.hu,aikramer2/spaCy,explosion/spaCy,spacy-i... | ---
+++
@@ -1,16 +1,17 @@
import pytest
import os
-import spacy
+from ..en import English
+from ..de import German
@pytest.fixture(scope="session")
def EN():
- return spacy.load("en")
+ return English(path=None)
@pytest.fixture(scope="session")
def DE():
- return spacy.load("de")
+ return Ge... |
07bf035221667bdd80ed8570079163d1162d0dd2 | cartoframes/__init__.py | cartoframes/__init__.py | from ._version import __version__
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
__all__ = [
'__version__',
'Ca... | from ._version import __version__
from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy_table, create_table_from_query
... | Check critical dependencies versions on runtime | Check critical dependencies versions on runtime
| Python | bsd-3-clause | CartoDB/cartoframes,CartoDB/cartoframes | ---
+++
@@ -1,8 +1,15 @@
from ._version import __version__
+from .utils.utils import check_package
from .core.cartodataframe import CartoDataFrame
from .core.logger import set_log_level
from .io.carto import read_carto, to_carto, has_table, delete_table, describe_table, \
update_table, copy... |
39d47ed5c0e89f41648a9bdd412b6190d274a488 | tbapy/models.py | tbapy/models.py | class _base_model_class(dict):
def __init__(self, json={}):
self.update(json)
self.update(self.__dict__)
self.__dict__ = self
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.json())
def json(self):
return dict.__repr__(self)
def _model_class(c... | class _base_model_class(dict):
def __init__(self, json={}):
self.update(json)
self.update(self.__dict__)
self.__dict__ = self
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.json())
def json(self):
return dict.__repr__(self)
def _model_class(c... | Clear up Status naming confusion | Clear up Status naming confusion
| Python | mit | frc1418/tbapy | ---
+++
@@ -15,7 +15,7 @@
return type(class_name, (_base_model_class,), {})
-APIStatus = _model_class('Status')
+APIStatus = _model_class('APIStatus')
Team = _model_class('Team')
Event = _model_class('Event')
Match = _model_class('Match')
@@ -31,4 +31,4 @@
Prediction = _model_class('Prediction')
Ranking... |
f338c4ff0c1ff30a3fa44182b0ce0dcbe4ae9dca | Mariana/regularizations.py | Mariana/regularizations.py | __all__ = ["SingleLayerRegularizer_ABC", "L1", "L2"]
class SingleLayerRegularizer_ABC(object) :
"""An abstract regularization to be applied to a layer."""
def __init__(self, factor, *args, **kwargs) :
self.name = self.__class__.__name__
self.factor = factor
self.hyperparameters = ["factor"]
def getFormula(s... | __all__ = ["SingleLayerRegularizer_ABC", "L1", "L2"]
class SingleLayerRegularizer_ABC(object) :
"""An abstract regularization to be applied to a layer."""
def __init__(self, factor, *args, **kwargs) :
self.name = self.__class__.__name__
self.factor = factor
self.hyperparameters = ["factor"]
def getFormula(s... | Fix L2 formula that was mistakenly added as L1. | Fix L2 formula that was mistakenly added as L1.
| Python | apache-2.0 | tariqdaouda/Mariana,tariqdaouda/Mariana,tariqdaouda/Mariana,JonathanSeguin/Mariana | ---
+++
@@ -16,7 +16,7 @@
"""
Will add this to the cost
.. math::
-
+
factor * abs(Weights)
"""
@@ -27,9 +27,9 @@
"""
Will add this to the cost
.. math::
-
+
factor * (Weights)^2
"""
def getFormula(self, layer) :
- return self.factor * ( abs(layer.W).sum() )
+ return self.factor * ... |
49f61f7f47bbb69236ef319dfa861ea437a0aac4 | build_qrc.py | build_qrc.py | #!/usr/bin/env python
import os
import sys
import json
def read_conf(fname):
if not os.path.isfile(fname):
return {}
with open(fname, 'r') as conf:
return json.load(conf)
def build_qrc(resources):
yield '<RCC>'
yield '<qresource>'
for d in resources:
for root, dirs, fil... | #!/usr/bin/env python
import os
import sys
import json
def read_conf(fname):
if not os.path.isfile(fname):
return {}
with open(fname, 'r') as conf:
return json.load(conf)
def build_qrc(resources):
yield '<RCC>'
yield '<qresource>'
for d in resources:
for root, dirs, fil... | Sort qrc input file list | Sort qrc input file list
so that yubikey-manager-qt packages build in a reproducible way
in spite of indeterministic filesystem readdir order
See https://reproducible-builds.org/ for why this is good.
| Python | bsd-2-clause | Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt,Yubico/yubikey-manager-qt | ---
+++
@@ -18,6 +18,8 @@
yield '<qresource>'
for d in resources:
for root, dirs, files in os.walk(d):
+ dirs.sort()
+ files.sort()
for f in files:
yield '<file>{}</file>'.format(os.path.join(root, f))
yield '</qresource>' |
9209ce05cae66f99166101905f6981da04eef656 | wake/filters.py | wake/filters.py | from datetime import datetime
from twitter_text import TwitterText
def relative_time(timestamp):
delta = (datetime.now() - datetime.fromtimestamp(timestamp))
delta_s = delta.days * 86400 + delta.seconds
if delta_s < 60:
return "less than a minute ago"
elif delta_s < 120:
return "about a... | from datetime import datetime
from twitter_text import TwitterText
from flask import Markup
def relative_time(timestamp):
delta = (datetime.now() - datetime.fromtimestamp(timestamp))
delta_s = delta.days * 86400 + delta.seconds
if delta_s < 60:
return "less than a minute ago"
elif delta_s < 120... | Mark output of tweet filter as safe by default | Mark output of tweet filter as safe by default
| Python | bsd-3-clause | chromakode/wake | ---
+++
@@ -1,5 +1,6 @@
from datetime import datetime
from twitter_text import TwitterText
+from flask import Markup
def relative_time(timestamp):
delta = (datetime.now() - datetime.fromtimestamp(timestamp))
@@ -20,4 +21,4 @@
return str(delta_s / 86400) + " days ago"
def tweet(text):
- return... |
9f8d134585a423773a6122c7312c1d88c6203867 | fastats/_version.py | fastats/_version.py | # This is the authoritative version number which should be used everywhere,
# including setup, packaging, documentation generation etc.
#
# Normally, this should be available as fastats.__version__
VERSION = '2017.1.3rc0'
| # This is the authoritative version number which should be used everywhere,
# including setup, packaging, documentation generation etc.
#
# Normally, this should be available as fastats.__version__
VERSION = '2017.1rc0'
| Fix version to match the current milestone | Fix version to match the current milestone
| Python | mit | fastats/fastats,dwillmer/fastats | ---
+++
@@ -2,4 +2,5 @@
# including setup, packaging, documentation generation etc.
#
# Normally, this should be available as fastats.__version__
-VERSION = '2017.1.3rc0'
+VERSION = '2017.1rc0'
+ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.