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 |
|---|---|---|---|---|---|---|---|---|---|---|
167ca3f2a91cd20f38b32ab204855a1e86785c67 | st2common/st2common/constants/meta.py | st2common/st2common/constants/meta.py | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | Add a comment to custom yaml_safe_load() method. | Add a comment to custom yaml_safe_load() method.
| Python | apache-2.0 | StackStorm/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2 | ---
+++
@@ -26,6 +26,13 @@
# NOTE: We utilize CSafeLoader if available since it uses C extensions and is faster.
+#
+# SafeLoader / CSafeLoader are both safe to use and don't allow loading arbitrary Python objects.
+#
+# That's the actual class which is used internally by ``yaml.safe_load()``, but we can't use t... |
0661728da6f38f91d2afa145e0db523a91241e61 | plugins/noah_stuff.py | plugins/noah_stuff.py | from plugin import Plugin
from utils import create_logger
from config import OwnerID
class Jacob_Noah(Plugin):
is_global = True
log = create_logger('noah_stuff')
async def on_message(self, message, pfx):
if message.content.startswith('<@' + self.client.id + '> kish meh'):
await self.cl... | from plugin import Plugin
from utils import create_logger
from config import OwnerID
class Jacob_Noah(Plugin):
is_global = True
log = create_logger('noah_stuff')
async def on_message(self, message, pfx):
if message.content.startswith('<@' + self.client.user.id + '> kish meh'):
await se... | Fix for the noah thing | Fix for the noah thing
| Python | mpl-2.0 | mralext20/apex-sigma,mralext20/apex-sigma | ---
+++
@@ -7,7 +7,7 @@
log = create_logger('noah_stuff')
async def on_message(self, message, pfx):
- if message.content.startswith('<@' + self.client.id + '> kish meh'):
+ if message.content.startswith('<@' + self.client.user.id + '> kish meh'):
await self.client.send_typing(me... |
39b382770ecc1b4c4fc33273fac0467344ccadfc | relay_api/api/main.py | relay_api/api/main.py | from flask import Flask
import relay_api.api.server as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_re... | from flask import Flask
import relay_api.api.backend as backend
server = Flask(__name__)
backend.init_relays()
@server.route("/relay-api/relays/", methods=["GET"])
def get_all_relays():
js = backend.get_all_relays()
return js, 200
@server.route("/relay-api/relays/<relay_name>", methods=["GET"])
def get_r... | Fix issue with backend import | Fix issue with backend import
| Python | mit | pahumadad/raspi-relay-api | ---
+++
@@ -1,5 +1,5 @@
from flask import Flask
-import relay_api.api.server as backend
+import relay_api.api.backend as backend
server = Flask(__name__) |
1747fa822c6daf63d0875cf7b3da37423b0932dc | apps/api/paginators.py | apps/api/paginators.py | from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class QuotesResultsSetPagination(PageNumberPagination):
page_size = 10
page_size_query_param = 'page_size'
max_page_size = 10000
def get_paginated_response(self, data):
return Response({
... | from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class QuotesResultsSetPagination(PageNumberPagination):
page_size = 25
page_size_query_param = 'page_size'
max_page_size = 10000
def get_paginated_response(self, data):
return Response({
... | Change page size to 25 | Change page size to 25
| Python | bsd-3-clause | lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes,lucifurtun/myquotes | ---
+++
@@ -3,7 +3,7 @@
class QuotesResultsSetPagination(PageNumberPagination):
- page_size = 10
+ page_size = 25
page_size_query_param = 'page_size'
max_page_size = 10000
|
7a281be50ba1fc59281a76470776fa9c8efdfd54 | pijobs/scrolljob.py | pijobs/scrolljob.py | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness... | import scrollphat
from pijobs.scrollphatjob import ScrollphatJob
class ScrollJob(ScrollphatJob):
def default_options(self):
opts = {
'brightness': 2,
'interval': 0.1,
'sleep': 1.0,
}
return opts
def init(self):
self.set_brightness... | Add back rotatation for scroll job. | Add back rotatation for scroll job.
| Python | mit | ollej/piapi,ollej/piapi | ---
+++
@@ -12,6 +12,7 @@
def init(self):
self.set_brightness()
+ self.set_rotate()
self.write_message()
def write_message(self): |
592ffbcd7fbbc29bfd377b5abadb39aa29f1c88d | foyer/tests/conftest.py | foyer/tests/conftest.py | import pytest
@pytest.fixture(scope="session")
def initdir(tmpdir):
tmpdir.chdir()
| import pytest
@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| Switch from scope="session" to autouse=True | Switch from scope="session" to autouse=True
| Python | mit | iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer | ---
+++
@@ -1,5 +1,5 @@
import pytest
-@pytest.fixture(scope="session")
+@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir() |
ea633b9cf062e28525910f5659b6b8f2ddbb74e3 | accelerator/migrations/0099_update_program_model.py | accelerator/migrations/0099_update_program_model.py | # Generated by Django 2.2.28 on 2022-04-20 13:05
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
model_name='progr... | # Generated by Django 2.2.28 on 2022-04-20 13:05
import sorl.thumbnail.fields
from django.db import (
migrations,
models,
)
class Migration(migrations.Migration):
dependencies = [
('accelerator', '0098_update_startup_update_20220408_0441'),
]
operations = [
migrations.AddField(
... | Fix image field import and migration | [AC-9452] Fix image field import and migration
| Python | mit | masschallenge/django-accelerator,masschallenge/django-accelerator | ---
+++
@@ -1,5 +1,6 @@
# Generated by Django 2.2.28 on 2022-04-20 13:05
+import sorl.thumbnail.fields
from django.db import (
migrations,
models,
@@ -21,6 +22,8 @@
migrations.AddField(
model_name='program',
name='program_image',
- field=models.ImageField(nu... |
5c5e0c7809d8db77327dc259df0547579e515a54 | server-side/Judge.py | server-side/Judge.py | import sys
sys.path.append('../audio2tokens')
from audio2tokens import *
download_dir='/home/michele/Downloads'
from rhyme import get_score
import time
def retrieve_tokens(audiofile):
#time.sleep(3)
audio_path_raw = raw_audio(audiofile.replace(':','-'))
tokens = get_text(audio_path_raw)
print(tokens)
return token... | import sys
sys.path.append('../audio2tokens')
from audio2tokens import *
download_dir='/home/michele/Downloads'
from rhyme import get_score
import time
def remove_audiofiles(audio_path):
audio_path_16k = audio_path.replace('.wav','_16k.wav')
audio_path_raw = audio_path.replace('.wav','.raw')
os.remove(a... | Add some functions to remove wave files | Add some functions to remove wave files
| Python | mit | hajicj/HAMR_2016,hajicj/HAMR_2016,hajicj/HAMR_2016 | ---
+++
@@ -4,10 +4,22 @@
download_dir='/home/michele/Downloads'
from rhyme import get_score
import time
+
+
+def remove_audiofiles(audio_path):
+ audio_path_16k = audio_path.replace('.wav','_16k.wav')
+ audio_path_raw = audio_path.replace('.wav','.raw')
+
+ os.remove(audio_path)
+ os.remove(audio_path_1... |
693dc9d8448740e1a1c4543cc3a91e3769fa7a3e | pySPM/utils/plot.py | pySPM/utils/plot.py | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r',... | import numpy as np
import matplotlib.pyplot as plt
def plotMask(ax, mask, color, **kargs):
import copy
m = np.ma.masked_array(mask, ~mask)
palette = copy.copy(plt.cm.gray)
palette.set_over(color, 1.0)
ax.imshow(m, cmap=palette, vmin=0, vmax=0.5, **kargs)
def Xdist(ax,left, right, y, color='r',... | Add helper function to create a DualPlot | Add helper function to create a DualPlot
| Python | apache-2.0 | scholi/pySPM | ---
+++
@@ -14,3 +14,13 @@
s = "{:"+fmt+"}"+kargs.get('unit','')
ax.annotate(s.format(xtransf(right-left)),(.5*(left+right),y),(0,2),textcoords='offset pixels',va='bottom',ha='center')
ax.annotate("",(left,y),(right,y),arrowprops=dict(arrowstyle=kargs.get('arrowstyle','<->')))
+
+def DualPlot(ax, c... |
2bd551d7fa8da9d7641998a5515fba634d65bc56 | comics/feedback/views.py | comics/feedback/views.py | from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if reques... | from django.conf import settings
from django.core.mail import mail_admins
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from comics.feedback.forms import FeedbackForm
def feedback(request):
"""Mail feedback to ADMINS"""
if reques... | Add user information to feedback emails | Add user information to feedback emails
| Python | agpl-3.0 | jodal/comics,datagutten/comics,jodal/comics,datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics | ---
+++
@@ -14,6 +14,16 @@
if form.is_valid():
subject = 'Feedback from %s' % settings.COMICS_SITE_TITLE
message = form.cleaned_data['message']
+
+ metadata = 'Client IP address: %s\n' % request.META['REMOTE_ADDR']
+ metadata += 'User agent: %s\n' % request.MET... |
c7ab4bc8e0b3dbdd305a7a156ef58dddaa37296c | pystorm/__init__.py | pystorm/__init__.py | from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
__all__ = [
'BatchingBolt',
'Bolt',
'Component',
'Spout',
'TicklessBatchingBolt',
'Tuple',
]
| '''
pystorm is a production-tested Storm multi-lang implementation for Python
It is mostly intended to be used by other libraries (e.g., streamparse).
'''
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
from .version import __version__, VERSI... | Add VERSION and __version__ directly to pystorm namespace | Add VERSION and __version__ directly to pystorm namespace
| Python | apache-2.0 | pystorm/pystorm | ---
+++
@@ -1,6 +1,13 @@
+'''
+pystorm is a production-tested Storm multi-lang implementation for Python
+
+It is mostly intended to be used by other libraries (e.g., streamparse).
+'''
+
from .component import Component, Tuple
from .bolt import BatchingBolt, Bolt, TicklessBatchingBolt
from .spout import Spout
+fr... |
3a5c7cecbca59567a76be1264d15d45824e69199 | python/src/setup.py | python/src/setup.py | """Setup specs for packaging, distributing, and installing gcs lib."""
import distribute_setup
distribute_setup.use_setuptools()
import setuptools
setuptools.setup(
name="GoogleAppEngineCloudStorageClient",
version="1.9.5.0",
packages=setuptools.find_packages(),
author="Google App Engine",
auth... | """Setup specs for packaging, distributing, and installing gcs lib."""
import distribute_setup
distribute_setup.use_setuptools()
import setuptools
setuptools.setup(
name="GoogleAppEngineCloudStorageClient",
version="1.9.15.0",
packages=setuptools.find_packages(),
author="Google App Engine",
aut... | Increment GCS Client PyPi version to 1.9.15.0. - Just doing whatever the most recent GAE version is for the package version. | Increment GCS Client PyPi version to 1.9.15.0.
- Just doing whatever the most recent GAE version is for the package version.
R=tkaitchuck
DELTA=1 (0 added, 0 deleted, 1 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=7186
| Python | apache-2.0 | aozarov/appengine-gcs-client,aozarov/appengine-gcs-client,GoogleCloudPlatform/appengine-gcs-client,GoogleCloudPlatform/appengine-gcs-client,aozarov/appengine-gcs-client,GoogleCloudPlatform/appengine-gcs-client | ---
+++
@@ -9,7 +9,7 @@
setuptools.setup(
name="GoogleAppEngineCloudStorageClient",
- version="1.9.5.0",
+ version="1.9.15.0",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.com", |
eb0aeda225cc7c0aef85559857de4cca35b77efd | ratemyflight/urls.py | ratemyflight/urls.py |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flight/l... |
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
urlpatterns = patterns("ratemyflight.views",
url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),
url("^api/flig... | Clean up URLS for API and point final URLS to views. | Clean up URLS for API and point final URLS to views.
| Python | bsd-2-clause | stephenmcd/ratemyflight,stephenmcd/ratemyflight | ---
+++
@@ -4,10 +4,15 @@
urlpatterns = patterns("ratemyflight.views",
- url("^api/airport/list/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
+ url("^api/airport/boundary/(?P<south>.*)/(?P<west>.*)/(?P<north>.*)/(?P<east>.*)/$",
"airports_for_boundary", name="airports_for_boundary"),... |
1775782f100f9db9ad101a19887ba95fbc36a6e9 | backend/project_name/celerybeat_schedule.py | backend/project_name/celerybeat_schedule.py | from celery.schedules import crontab
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
| from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module
CELERYBEAT_SCHEDULE = {
# Internal tasks
"clearsessions": {"schedule": crontab(hour=3, minute=0), "task": "users.tasks.clearsessions"},
}
| Disable prospector on celery.schedules import | Disable prospector on celery.schedules import
| Python | mit | vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate,vintasoftware/django-react-boilerplate | ---
+++
@@ -1,4 +1,4 @@
-from celery.schedules import crontab
+from celery.schedules import crontab # pylint:disable=import-error,no-name-in-module
CELERYBEAT_SCHEDULE = { |
691e3581f1602714fba33f6dcb139f32e0507d23 | packages/syft/src/syft/core/node/common/node_table/setup.py | packages/syft/src/syft/core/node/common/node_table/setup.py | # third party
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="")
node_id =... | # third party
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Boolean
# relative
from . import Base
class SetupConfig(Base):
__tablename__ = "setup"
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(... | ADD description / contact / daa fields | ADD description / contact / daa fields
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -2,6 +2,7 @@
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
+from sqlalchemy import Boolean
# relative
from . import Base
@@ -12,6 +13,9 @@
id = Column(Integer(), primary_key=True, autoincrement=True)
domain_name = Column(String(255), default="... |
7fc81e93ea44e52ab7c29087a01eac65a145db09 | qiprofile_rest/server/settings.py | qiprofile_rest/server/settings.py | """This ``settings`` file specifies the Eve configuration."""
import os
# The run environment default is production.
# Modify this by setting the NODE_ENV environment variable.
env = os.getenv('NODE_ENV') or 'production'
# The MongoDB database.
if env == 'production':
MONGO_DBNAME = 'qiprofile'
else:
MONGO_DB... | """This ``settings`` file specifies the Eve configuration."""
import os
# The run environment default is production.
# Modify this by setting the NODE_ENV environment variable.
env = os.getenv('NODE_ENV') or 'production'
# The MongoDB database.
if env == 'production':
MONGO_DBNAME = 'qiprofile'
else:
MONGO_DB... | Add Mongo env var overrides. | Add Mongo env var overrides.
| Python | bsd-2-clause | ohsu-qin/qiprofile-rest,ohsu-qin/qirest | ---
+++
@@ -17,6 +17,21 @@
if host:
MONGO_HOST = host
+# The MongoDB port.
+port = os.getenv('MONGO_PORT')
+if port:
+ MONGO_PORT = int(port)
+
+# The MongoDB username.
+user = os.getenv('MONGO_USERNAME')
+if user:
+ MONGO_USERNAME = user
+
+# The MongoDB password.
+pswd = os.getenv('MONGO_PASSWORD')
+i... |
b5e368437a600d78e22a53abe53c0103b20daa24 | _python/main/migrations/0003_auto_20191029_2015.py | _python/main/migrations/0003_auto_20191029_2015.py | # Generated by Django 2.2.6 on 2019-10-29 20:15
from django.db import migrations, models
import main.models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='contentnode',
... | # Generated by Django 2.2.6 on 2019-10-29 20:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20191007_1639'),
]
operations = [
migrations.AlterField(
model_name='default',
name='url',
... | Repair migration, which was a no-op in SQL and was 'faked' anyway. | Repair migration, which was a no-op in SQL and was 'faked' anyway.
| Python | agpl-3.0 | harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o,harvard-lil/h2o | ---
+++
@@ -1,7 +1,6 @@
# Generated by Django 2.2.6 on 2019-10-29 20:15
from django.db import migrations, models
-import main.models
class Migration(migrations.Migration):
@@ -12,18 +11,8 @@
operations = [
migrations.AlterField(
- model_name='contentnode',
- name='headno... |
f87b979443bd4a578884bdb327dbd72616d07533 | changes/backends/jenkins/generic_builder.py | changes/backends/jenkins/generic_builder.py | from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
def get_job_parameters(self, job, ... | from .builder import JenkinsBuilder
class JenkinsGenericBuilder(JenkinsBuilder):
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
self.path = kwargs.pop('path', '')
super(JenkinsGenericBuilder, self).__init__(*args, **kwar... | Support fixed path in generic builder | Support fixed path in generic builder
| Python | apache-2.0 | wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes | ---
+++
@@ -5,11 +5,15 @@
def __init__(self, *args, **kwargs):
self.script = kwargs.pop('script')
self.cluster = kwargs.pop('cluster')
+ self.path = kwargs.pop('path', '')
super(JenkinsGenericBuilder, self).__init__(*args, **kwargs)
- def get_job_parameters(self, job, scrip... |
5cff34d49edfc5697b3e84b84d110c49728d0338 | samples/blaze_sql.py | samples/blaze_sql.py | __author__ = 'mark'
| # -*- coding: utf-8 -*-
"""
This example shows some examples of how to access data in SQL databases using
blaze. It walks through how blaze syntax corresponds to SQL queries.
Select Queries
--------------
"""
from __future__ import absolute_import, division, print_function
import sqlite3 as db
from blaze.io.sql ... | Work on SQL example set | Work on SQL example set
| Python | bsd-3-clause | xlhtc007/blaze,cpcloud/blaze,scls19fr/blaze,ContinuumIO/blaze,aterrel/blaze,FrancescAlted/blaze,mrocklin/blaze,FrancescAlted/blaze,ChinaQuants/blaze,maxalbert/blaze,cpcloud/blaze,LiaoPan/blaze,mwiebe/blaze,aterrel/blaze,cowlicks/blaze,FrancescAlted/blaze,alexmojaki/blaze,maxalbert/blaze,mwiebe/blaze,jdmcbr/blaze,caseyc... | ---
+++
@@ -1 +1,79 @@
-__author__ = 'mark'
+# -*- coding: utf-8 -*-
+
+"""
+This example shows some examples of how to access data in SQL databases using
+blaze. It walks through how blaze syntax corresponds to SQL queries.
+
+Select Queries
+--------------
+
+
+"""
+
+from __future__ import absolute_import, divisio... |
ba0334459b8318a62014ec945a753fc36fc7d519 | account_verification_flask/models/models.py | account_verification_flask/models/models.py | #from flask.ext.login import UserMixin
from account_verification_flask import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String, nullable = False)
email = db.Column(db.String, nullable = False)
password = db.Column(d... | #from flask.ext.login import UserMixin
from account_verification_flask import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String, nullable = False)
email = db.Column(db.String, nullable = False)
password = db.Column(d... | Remove confirm_phone_number method from model | Remove confirm_phone_number method from model
| Python | mit | TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask | ---
+++
@@ -33,9 +33,6 @@
def get_id(self):
return unicode(self.id)
- def confirm_phone_number(self):
- self.phone_number_confirmed = True
-
def __unicode__(self):
return self.name
|
1dc2856368e5e6852b526d86a0c78c5fe10b1550 | myhronet/models.py | myhronet/models.py | # -*- coding: utf-8 -*-
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
... | # -*- coding: utf-8 -*-
import string
from django.db import models
class Blacklist(models.Model):
domain = models.CharField(max_length=255, unique=True, null=True)
def __unicode__(self):
return self.domain
class URL(models.Model):
hashcode = models.CharField(max_length=10, unique=True,
... | Fix hashcode generation for existing URLs | Fix hashcode generation for existing URLs
| Python | mit | myhro/myhronet,myhro/myhronet | ---
+++
@@ -21,16 +21,17 @@
data = models.DateTimeField(auto_now_add=True, null=True)
def save(self, *args, **kwargs):
- if URL.objects.count():
- last = URL.objects.latest('id').pk + 1
- alphabet = string.digits + string.ascii_lowercase
- base36 = ''
- w... |
1cad9ab61148173b0f61971805b3e6203da3050d | faker/providers/en_CA/ssn.py | faker/providers/en_CA/ssn.py | # coding=utf-8
from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
class Provider(SsnProvider):
ssn_formats = ("### ### ###",)
@classmethod
def ssn(cls):
return cls.bothify(cls.random_element(cls.ssn_formats)) | # coding=utf-8
from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
import random
class Provider(SsnProvider):
#in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Algorithmn checksum
#this function essentially reverses the checksum st... | Update Canada SSN/SIN provider to create a valid number | Update Canada SSN/SIN provider to create a valid number
The first revision generated a random number in the correct format.
This commit creates a SIN number that passes the checksum as described
here http://http://en.wikipedia.org/wiki/Social_Insurance_Number
| Python | mit | jaredculp/faker,trtd/faker,xfxf/faker-python,HAYASAKA-Ryosuke/faker,johnraz/faker,joke2k/faker,joke2k/faker,venmo/faker,ericchaves/faker,xfxf/faker-1,GLMeece/faker,danhuss/faker,beetleman/faker,thedrow/faker,meganlkm/faker,yiliaofan/faker,MaryanMorel/faker | ---
+++
@@ -1,10 +1,38 @@
# coding=utf-8
from __future__ import unicode_literals
from ..ssn import Provider as SsnProvider
+import random
class Provider(SsnProvider):
- ssn_formats = ("### ### ###",)
+ #in order to create a valid SIN we need to provide a number that passes a simple modified Luhn Alg... |
dd1ed907532526a4a70694c46918136ca6d93277 | nqueens/nqueens.py | nqueens/nqueens.py | from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
board = Chessboard.create(8)
solver = Solver.create(board)
solution = solver.solve()
if solution is not None:
printer = Printer.create(solution)
printer.printBoard()
| #!/usr/bin/env python3
import os
import sys
import getopt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
def main():
try:
n = parse_command_line()
except ... | Add ability to run problems from command line | Add ability to run problems from command line
| Python | mit | stevecshanks/nqueens | ---
+++
@@ -1,11 +1,52 @@
+#!/usr/bin/env python3
+import os
+import sys
+import getopt
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from nqueens.chessboard import Chessboard
from nqueens.printer import Printer
from nqueens.solver import Solver
-board = Chessboard.create(... |
c9cc5585e030951a09687c6a61a489ec51f83446 | cr2/plotter/__init__.py | cr2/plotter/__init__.py | # $Copyright:
# ----------------------------------------------------------------
# This confidential and proprietary software may be used only as
# authorised by a licensing agreement from ARM Limited
# (C) COPYRIGHT 2015 ARM Limited
# ALL RIGHTS RESERVED
# The entire notice above must be reproduced on all autho... | # $Copyright:
# ----------------------------------------------------------------
# This confidential and proprietary software may be used only as
# authorised by a licensing agreement from ARM Limited
# (C) COPYRIGHT 2015 ARM Limited
# ALL RIGHTS RESERVED
# The entire notice above must be reproduced on all autho... | Enable user specified arg forwarding to matplotlib | plotter: Enable user specified arg forwarding to matplotlib
This change allows the user to register args for forwarding to
matplotlib and also unregister the same.
Change-Id: If53dab43dd4a2f530b3d1faf35582206ac925740
Signed-off-by: Kapileshwar Singh <d373e2b6407ea84be359ce4a11e8631121819e79@arm.com>
| Python | apache-2.0 | JaviMerino/trappy,joelagnel/trappy,bjackman/trappy,derkling/trappy,ARM-software/trappy,sinkap/trappy,JaviMerino/trappy,joelagnel/trappy,ARM-software/trappy,derkling/trappy,bjackman/trappy,sinkap/trappy,ARM-software/trappy,ARM-software/trappy,bjackman/trappy,sinkap/trappy,joelagnel/trappy,sinkap/trappy,JaviMerino/trappy... | ---
+++
@@ -17,3 +17,21 @@
import pandas as pd
from LinePlot import LinePlot
+import AttrConf
+
+
+def register_forwarding_arg(arg_name):
+ """Allows the user to register args to
+ be forwarded to matplotlib
+ """
+ if arg_name not in AttrConf.ARGS_TO_FORWARD:
+ AttrConf.ARGS_TO_FORWARD.appe... |
38cd50805e080f6613d7e1d5867a84952ec88580 | flask_resty/related.py | flask_resty/related.py | from .exceptions import ApiError
# -----------------------------------------------------------------------------
class Related(object):
def __init__(self, item_class=None, **kwargs):
self._item_class = item_class
self._view_classes = kwargs
def resolve_related(self, data):
for field_... | from .exceptions import ApiError
# -----------------------------------------------------------------------------
class Related(object):
def __init__(self, item_class=None, **kwargs):
self._item_class = item_class
self._resolvers = kwargs
def resolve_related(self, data):
for field_nam... | Fix variable names in Related | Fix variable names in Related
| Python | mit | taion/flask-jsonapiview,4Catalyzer/flask-jsonapiview,4Catalyzer/flask-resty | ---
+++
@@ -6,10 +6,10 @@
class Related(object):
def __init__(self, item_class=None, **kwargs):
self._item_class = item_class
- self._view_classes = kwargs
+ self._resolvers = kwargs
def resolve_related(self, data):
- for field_name, view_class in self._view_classes.items():... |
8cdbbb52ebe161b0b7fea342e8a3d197ec290ab1 | satnogsclient/settings.py | satnogsclient/settings.py | from os import environ
DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None)
ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None)
DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None)
OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
| from os import environ
DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', 'rtl_fm')
ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', 'oggenc')
DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', 'multimon-ng')
OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', '/tmp')
| Add default commands for encoding/decoding/demodulation. | Add default commands for encoding/decoding/demodulation.
| Python | agpl-3.0 | adamkalis/satnogs-client,adamkalis/satnogs-client,cshields/satnogs-client,cshields/satnogs-client | ---
+++
@@ -1,6 +1,6 @@
from os import environ
-DEMODULATION_COMMAND = environ.get('SATNOGS_DEMODULATION_COMMAND', None)
-ENCODING_COMMAND = environ.get('SATNOGS_ENCODING_COMMAND', None)
-DECODING_COMMAND = environ.get('SATNOGS_DECODING_COMMAND', None)
-OUTPUT_PATH = environ.get('SATNOGS_OUTPUT_PATH', None)
+DEMOD... |
3335c8c9ce8419d9d1d1034903687aa02983280d | tests/rules_tests/NoRuleSpecifiedTest.py | tests/rules_tests/NoRuleSpecifiedTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
class NoRuleSpecifiedTest(TestCase):
pass
if __name__ == '__main__':
main() | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import Rule
from grammpy.exceptions import RuleNotDefinedException
class NoRuleSpecifiedTest(TestCase):
def test_noRule(self):
class tmp(Rule):
... | Add tests when no rules is specified | Add tests when no rules is specified
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -9,11 +9,26 @@
from unittest import main, TestCase
from grammpy import Rule
+from grammpy.exceptions import RuleNotDefinedException
class NoRuleSpecifiedTest(TestCase):
- pass
+ def test_noRule(self):
+ class tmp(Rule):
+ x = 5
+ with self.assertRaises(RuleNotDefin... |
0b3f6ae3b21cd51b99bcecf17d5ea1275c04abfd | statirator/project_template/project_name/settings.py | statirator/project_template/project_name/settings.py | # Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')
# languages setup
LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s
LANGUAGES ... | # Generated by statirator
import os
# directories setup
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
SOURCE_DIR = os.path.join(ROOT_DIR, '{{ source }}')
BUILD_DIR = os.path.join(ROOT_DIR, '{{ build }}')
# languages setup
LANGUAGE_CODE = '{{default_lang}}'
_ = lambda s:s
LANGUAGES ... | Add taggit and statirator.blog to INSTALLED_APPS | Add taggit and statirator.blog to INSTALLED_APPS
| Python | mit | MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator | ---
+++
@@ -27,6 +27,8 @@
'django.contrib.sites',
'django.contrib.staticfiles',
'django_medusa',
+ 'taggit',
+ 'statirator.blog',
)
MEDUSA_RENDERER_CLASS = "django_medusa.renderers.DiskStaticSiteRenderer" |
9a8d552b9424c11d6a58fcf38abea6bc2d55b1f0 | tests/install_tests.py | tests/install_tests.py | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... | import sys
import logging
import subprocess
sys.path.insert(0, '..')
from unittest2 import TestCase
class MockLoggingHandler(logging.Handler):
"""Mock logging handler to check for expected logs."""
def __init__(self, *args, **kwargs):
self.reset()
logging.Handler.__init__(self, *args, **kwa... | Update test to reflect new default version for node | Update test to reflect new default version for node
| Python | bsd-3-clause | elbaschid/virtual-node | ---
+++
@@ -32,4 +32,4 @@
def test_is_installed(self):
proc = subprocess.Popen(['node', '--version'], stdout=subprocess.PIPE)
output = proc.stdout.read()
- self.assertEquals(output.strip(), 'v0.8.11')
+ self.assertEquals(output.strip(), 'v0.10.26') |
c87f47a3cf4bfd921f7953a9bb14fbc4675ea0e6 | examples/delete_all_policies.py | examples/delete_all_policies.py | #!/usr/bin/env python
#
# Delete all secure policies.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdSecureClient
def usage():
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can find your token at h... | #!/usr/bin/env python
#
# Delete all secure policies.
#
import os
import sys
import json
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..'))
from sdcclient import SdSecureClient
def usage():
print('usage: %s <sysdig-token>' % sys.argv[0])
print('You can find your token at h... | Fix legacy use of action result | Fix legacy use of action result
| Python | mit | draios/python-sdc-client,draios/python-sdc-client | ---
+++
@@ -37,7 +37,7 @@
print(res)
sys.exit(1)
else:
- policies = res[1]['policies']
+ policies = res['policies']
for policy in policies:
print("deleting policy: " + str(policy['id'])) |
91a7e4ba30c2c455c58b7069015680b7af511cc4 | tests/test_get_joke.py | tests/test_get_joke.py |
def test_get_joke():
from pyjokes import get_joke
for i in range(10):
assert get_joke()
languages = ['eng', 'de', 'spa']
categories = ['neutral', 'explicit', 'all']
for lang in languages:
for cat in categories:
for i in range(10):
assert get_joke(cat,... |
import pytest
from pyjokes import get_joke
from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError
def test_get_joke():
assert get_joke()
languages = ['en', 'de', 'es']
categories = ['neutral', 'explicit', 'all']
for lang in languages:
assert get_joke(language=lang)
... | Simplify get_joke test, add raise checks | Simplify get_joke test, add raise checks
| Python | bsd-3-clause | borjaayerdi/pyjokes,trojjer/pyjokes,martinohanlon/pyjokes,bennuttall/pyjokes,ElectronicsGeek/pyjokes,pyjokes/pyjokes,gmarkall/pyjokes | ---
+++
@@ -1,15 +1,25 @@
+
+import pytest
+from pyjokes import get_joke
+from pyjokes.pyjokes import LanguageNotFoundError, CategoryNotFoundError
def test_get_joke():
- from pyjokes import get_joke
+ assert get_joke()
- for i in range(10):
- assert get_joke()
-
- languages = ['eng', 'de... |
67d067fe499ba2ec78d34083640a4bfe9835d62b | tests/test_sequence.py | tests/test_sequence.py | from unittest import TestCase
from prudent.sequence import Sequence
class SequenceTest(TestCase):
def setUp(self):
self.seq = Sequence([1, 2, 3])
def test_getitem(self):
assert self.seq[0] == 1
self.seq[2]
assert self.seq[2] == 3
def test_len(self):
assert len(sel... | from unittest import TestCase
from prudent.sequence import Sequence
class SequenceTest(TestCase):
def setUp(self):
self.seq = Sequence([1, 2, 3])
def test_getitem(self):
assert self.seq[0] == 1
assert self.seq[2] == 3
def test_getitem_raises_indexerror(self):
self.assertR... | Test that IndexError is raised when appropriate | Test that IndexError is raised when appropriate
| Python | mit | eugene-eeo/prudent | ---
+++
@@ -8,14 +8,16 @@
def test_getitem(self):
assert self.seq[0] == 1
- self.seq[2]
assert self.seq[2] == 3
- def test_len(self):
+ def test_getitem_raises_indexerror(self):
+ self.assertRaises(IndexError, lambda: self.seq[3])
+
+ def test_len_returns_current_size... |
987e3b3387124c9eee7b0d69647fe2eeba40b70d | snippets/list_holidays.py | snippets/list_holidays.py | #!/usr/bin/env python
import pandas as pd
from datetime import date
import holidays
def sanitize_holiday_name(name):
new_name = [c for c in name if c.isalpha() or c.isdigit() or c == ' ']
new_name = "".join(new_name).lower().replace(" ", "_")
return new_name
def process_holidays(df):
# Create a dat... | #!/usr/bin/env python
import pandas as pd
from datetime import date
import holidays
def sanitize_holiday_name(name):
new_name = [c for c in name if c.isalpha() or c.isdigit() or c == ' ']
new_name = "".join(new_name).lower().replace(" ", "_")
return new_name
def process_holidays(df):
# Create a dat... | Update with real train users | Update with real train users
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -13,7 +13,11 @@
def process_holidays(df):
# Create a date object
- user_date = date(df['year'], df['month'], df['day'])
+ user_date = date(
+ df['year_account_created'],
+ df['month_account_created'],
+ df['day_account_created']
+ )
# Get US holidays for this ye... |
4a8aaf3c9e1da5fd10580cc5a3859d801f2c9553 | django_docker/django_docker/urls.py | django_docker/django_docker/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'hello_world.views.hello_world', name='hello_world'),
)
| from django.conf.urls import include, url
from hello_world import views as hello_world_views
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', hello_world_views.hello_world, name='hello_world'),
]
| Update URLs to be compatible with Django 1.10 | Update URLs to be compatible with Django 1.10
| Python | mit | morninj/django-docker,morninj/django-docker,morninj/django-docker | ---
+++
@@ -1,9 +1,10 @@
-from django.conf.urls import patterns, include, url
+from django.conf.urls import include, url
+from hello_world import views as hello_world_views
from django.contrib import admin
admin.autodiscover()
-urlpatterns = patterns('',
+urlpatterns = [
url(r'^admin/', include(admin.site.... |
caeb76cbcb6cdd49138e41f57144573598b722ba | source/clique/__init__.py | source/clique/__init__.py | # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
from ._version import __version__
| # :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import re
from collections import defaultdict
from ._version import __version__
from .collection import Collection
from .error import CollectionError
#: Pattern for matching an index with optional padding.
DIGITS... | Add top level function to help assemble collections from arbitrary items. | Add top level function to help assemble collections from arbitrary items.
| Python | apache-2.0 | 4degrees/clique | ---
+++
@@ -2,5 +2,97 @@
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
+import re
+from collections import defaultdict
+
from ._version import __version__
+from .collection import Collection
+from .error import CollectionError
+
+#: Pattern for matching an index with op... |
21b97ceea5b2e667940ddd45682313261eba845b | discode_server/notify.py | discode_server/notify.py | import json
from discode_server import db
from discode_server import fragments
connected = set()
notified = set()
async def feed(request, ws):
global connected
connected.add(ws)
print("Open WebSockets: ", len(connected))
try:
while True:
if not ws.open:
return
... | import asyncio
import json
from discode_server import db
from discode_server import fragments
connected = set()
notified = set()
async def feed(request, ws):
global connected
connected.add(ws)
print("Open WebSockets: ", len(connected))
try:
while True:
if not ws.open:
... | Add the asyncio wait_for back in | Add the asyncio wait_for back in
| Python | bsd-2-clause | d0ugal/discode-server,d0ugal/discode-server,d0ugal/discode-server | ---
+++
@@ -1,3 +1,4 @@
+import asyncio
import json
from discode_server import db
@@ -20,7 +21,11 @@
async with request.app.config.DB.acquire() as conn:
await conn.execute(f"LISTEN channel")
- msg = await conn.connection.notifies.get()
+ try:
+ ... |
c3d03629734abfead5ae1eae83d1b6dcec792b45 | iconizer/django_in_iconizer/django_server.py | iconizer/django_in_iconizer/django_server.py | import os
class DjangoServer(object):
default_django_manage_script = "manage.py"
def __init__(self, django_manage_script=None):
super(DjangoServer, self).__init__()
if django_manage_script is None:
self.django_manage_script = self.default_django_manage_script
else:
... | import os
class DjangoServer(object):
default_django_manage_script = "manage.py"
def __init__(self, django_manage_script=None):
super(DjangoServer, self).__init__()
if django_manage_script is None:
self.django_manage_script = self.default_django_manage_script
else:
... | Enable specify command line processor. | Enable specify command line processor.
| Python | bsd-3-clause | weijia/iconizer | ---
+++
@@ -10,6 +10,7 @@
self.django_manage_script = self.default_django_manage_script
else:
self.django_manage_script = django_manage_script
+ self.django_manage_script = os.environ.get("MANAGE_PY", self.django_manage_script)
def get_task_descriptor(self, task_name, ... |
6b57d186173234dbedcfa4758eeb1cb00a90eba7 | src/adhocracy/migration/versions/053_add_votedetail_table.py | src/adhocracy/migration/versions/053_add_votedetail_table.py | from sqlalchemy import MetaData, Column, Table
from sqlalchemy import Integer, ForeignKey
metadata = MetaData()
votedetail_table = Table(
'votedetail', metadata,
Column('instance_id', Integer,
ForeignKey('instance.id', ondelete='CASCADE')),
Column('badge_id', Integer,
ForeignKey('b... | from sqlalchemy import MetaData, Column, Table
from sqlalchemy import Integer, ForeignKey
metadata = MetaData()
votedetail_table = Table(
'votedetail', metadata,
Column('instance_id', Integer,
ForeignKey('instance.id', ondelete='CASCADE')),
Column('badge_id', Integer,
ForeignKey('b... | Fix typo in migration script | Fix typo in migration script
| Python | agpl-3.0 | liqd/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,liqd/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,phihag/adhocracy,phihag/adhocracy,alkadis/vcv,alkadis/vcv,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,alkadis/vcv,DanielNeugebauer... | ---
+++
@@ -8,7 +8,7 @@
Column('instance_id', Integer,
ForeignKey('instance.id', ondelete='CASCADE')),
Column('badge_id', Integer,
- ForeignKey('badge.id'), ondelete='CASCADE')),
+ ForeignKey('badge.id', ondelete='CASCADE')),
)
def upgrade(migrate_engine): |
fce890ce9046dd055f219ac880ae9734f334f534 | greenlight/harness/arguments.py | greenlight/harness/arguments.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette import BaseMarionetteOptions
from greenlight import tests
class ReleaseTestParser(BaseMarionetteOptio... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette import BaseMarionetteOptions
from greenlight import tests
class ReleaseTestParser(BaseMarionetteOptio... | Make colored terminal output the default log formatter. | Make colored terminal output the default log formatter.
| Python | mpl-2.0 | myrdd/firefox-ui-tests,gbrmachado/firefox-ui-tests,utvar/firefox-ui-tests,chmanchester/firefox-ui-tests,armenzg/firefox-ui-tests,whimboo/firefox-ui-tests,myrdd/firefox-ui-tests,gbrmachado/firefox-ui-tests,sr-murthy/firefox-ui-tests,armenzg/firefox-ui-tests,Motwani/firefox-ui-tests,galgeek/firefox-ui-tests,armenzg/firef... | ---
+++
@@ -12,6 +12,11 @@
def parse_args(self, *args, **kwargs):
options, test_files = BaseMarionetteOptions.parse_args(self,
*args, **kwargs)
+
+ if not any([(k.startswith('log_') and v is not None and '-' in v)
+ ... |
f684692a013e80d0c4d07b1c0eba204bd94d2314 | config.py | config.py |
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# Address to listen for clients on
HOST = "0.0... |
# Enables detailed tracebacks and an interactive Python console on errors.
# Never use in production!
#DEBUG = True
# Makes the server more performant at sending static files when the
# server is being proxied by a server that supports X-Sendfile.
#USE_X_SENDFILE = True
# Address to listen for clients on
HOST = "0.0... | Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems | Add note that 'ALLOW_UPDATE_WITHOUT_OLD' causes problems
| Python | lgpl-2.1 | minetest/master-server,minetest/master-server,minetest/master-server | ---
+++
@@ -26,4 +26,5 @@
# Creates server entries if a server sends an 'update' and there is no entry yet
# This should only be used to populate the server list after list.json was deleted.
+# This WILL cause problems such as mapgen, mods and privilege information missing from the list
ALLOW_UPDATE_WITHOUT_OLD ... |
63e09b77e3b00a7483249417020fb093f98773a9 | infrastructure/tests/helpers.py | infrastructure/tests/helpers.py | from datetime import datetime
from django.contrib.staticfiles.testing import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.... | from datetime import datetime
from django.contrib.staticfiles.testing import LiveServerTestCase
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.... | Add logging to selector testing | Add logging to selector testing
| Python | mit | Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data | ---
+++
@@ -7,6 +7,8 @@
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
+import logging
+logger = logging.Logger(__name__)
class BaseSeleniumTestCase(LiveServerTestCase):
@@ -27,6 +29,8 @@
self.addCleanup(self.selenium.quit)
... |
d07b6483d110eb4c51f7c631f888d1bf30eacc1c | destroyer-runner.py | destroyer-runner.py | #!/usr/bin/python
"""destroyer-runner.py - Run the main application"""
import sys
import subprocess
if __name__ == '__main__':
subprocess.call(['python', './destroyer/destroyer.py'] + [str(arg) for arg in sys.argv[1:]])
| #!/usr/bin/python
"""destroyer-runner.py - Run the main application"""
from destroyer.destroyer import main
if __name__ == '__main__':
main()
| Update with working code to run destroyer | Update with working code to run destroyer
| Python | mit | jaredmichaelsmith/destroyer | ---
+++
@@ -2,10 +2,9 @@
"""destroyer-runner.py - Run the main application"""
-import sys
-import subprocess
+from destroyer.destroyer import main
if __name__ == '__main__':
- subprocess.call(['python', './destroyer/destroyer.py'] + [str(arg) for arg in sys.argv[1:]])
+ main()
|
261c294690427b57d111c777cdc4d13b9c84f9d2 | cloudkittydashboard/dashboards/admin/modules/forms.py | cloudkittydashboard/dashboards/admin/modules/forms.py | # Copyright 2017 Objectif Libre
#
# 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 agr... | # Copyright 2017 Objectif Libre
#
# 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 agr... | Delete the unused LOG code | Delete the unused LOG code
Change-Id: Ief253cdd226f8c2688429b0ff00785151a99759b
| Python | apache-2.0 | stackforge/cloudkitty-dashboard,openstack/cloudkitty-dashboard,openstack/cloudkitty-dashboard,openstack/cloudkitty-dashboard,stackforge/cloudkitty-dashboard,stackforge/cloudkitty-dashboard | ---
+++
@@ -12,14 +12,10 @@
# License for the specific language governing permissions and limitations
# under the License.
-import logging
-
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from cloudkittydashboard.api import cloudkitty as api
-
-LOG = logging.getLogger... |
316323387c508c88595f205182ea2436c271621d | src/highdicom/uid.py | src/highdicom/uid.py | import logging
import pydicom
logger = logging.getLogger(__name__)
class UID(pydicom.uid.UID):
"""Unique DICOM identifier with a highdicom-specific UID prefix."""
def __new__(cls: type) -> str:
prefix = '1.2.826.0.1.3680043.10.511.3.'
identifier = pydicom.uid.generate_uid(prefix=prefix)
... | import logging
from typing import Type, TypeVar
import pydicom
logger = logging.getLogger(__name__)
T = TypeVar('T', bound='UID')
class UID(pydicom.uid.UID):
"""Unique DICOM identifier with a highdicom-specific UID prefix."""
def __new__(cls: Type[T]) -> T:
prefix = '1.2.826.0.1.3680043.10.511.3... | Fix typing for UID class | Fix typing for UID class
| Python | mit | MGHComputationalPathology/highdicom | ---
+++
@@ -1,15 +1,19 @@
import logging
+from typing import Type, TypeVar
import pydicom
logger = logging.getLogger(__name__)
+T = TypeVar('T', bound='UID')
+
+
class UID(pydicom.uid.UID):
"""Unique DICOM identifier with a highdicom-specific UID prefix."""
- def __new__(cls: type) -> str:
+ ... |
ee53ec51d98802bf0bc55e70c39cc0918f2bb274 | icekit/plugins/blog_post/content_plugins.py | icekit/plugins/blog_post/content_plugins.py | """
Definition of the plugin.
"""
from django.apps import apps
from django.conf import settings
from django.db.models.loading import get_model
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
default_blog_model = 'blog_tools.BlogPost'
icekit_blo... | """
Definition of the plugin.
"""
from django.apps import apps
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
default_blog_model = 'blog_tools.BlogPost'
icekit_blog_model = getattr(settings, 'ICEKIT_BLOG_MODEL'... | Update Blog model and content item matching | Update Blog model and content item matching
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -3,7 +3,6 @@
"""
from django.apps import apps
from django.conf import settings
-from django.db.models.loading import get_model
from django.utils.translation import ugettext_lazy as _
from fluent_contents.extensions import ContentPlugin, plugin_pool
@@ -15,7 +14,7 @@
if icekit_blog_model != default_... |
c7143cd725fc829c33ad9f9150e5975deb7be93a | irctest/optional_extensions.py | irctest/optional_extensions.py | import unittest
import operator
import itertools
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'.format(self.args[0])
class OptionalSaslMechanismNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported SASL mechanism:... | import unittest
import operator
import itertools
class NotImplementedByController(unittest.SkipTest):
def __str__(self):
return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
return 'Unsupported extension: {}'... | Add an exception to tell a controller does not implement something. | Add an exception to tell a controller does not implement something.
| Python | mit | ProgVal/irctest | ---
+++
@@ -1,6 +1,10 @@
import unittest
import operator
import itertools
+
+class NotImplementedByController(unittest.SkipTest):
+ def __str__(self):
+ return 'Not implemented by controller: {}'.format(self.args[0])
class OptionalExtensionNotSupported(unittest.SkipTest):
def __str__(self):
@@ -1... |
a0ce4d366681f2f62f232f4f952ac18df07667d4 | ideascube/conf/idb_fra_cultura.py | ideascube/conf/idb_fra_cultura.py | # -*- coding: utf-8 -*-
"""Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['ser... | # -*- coding: utf-8 -*-
"""Ideaxbox Cultura, France"""
from .idb import * # noqa
from django.utils.translation import ugettext_lazy as _
IDEASCUBE_NAME = u"Cultura"
IDEASCUBE_PLACE_NAME = _("city")
COUNTRIES_FIRST = ['FR']
TIME_ZONE = None
LANGUAGE_CODE = 'fr'
LOAN_DURATION = 14
MONITORING_ENTRY_EXPORT_FIELDS = ['ser... | Remove "software" card from Cultura conf | Remove "software" card from Cultura conf
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube | ---
+++
@@ -21,9 +21,6 @@
'id': 'wikisource',
},
{
- 'id': 'software',
- },
- {
'id': 'ted',
},
{ |
a977908efcc176e1e5adbd82843033805953c6cb | tools/reago/format_reago_input_files.py | tools/reago/format_reago_input_files.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
reago_dir = '/tools/rna_manipulation/reago/reago/'
def add_read_pair_num(input_filepath, output_filepath, read_pair_num):
to_add = '.' + str(read_pair_num)
with open(input_filepath,'r') as input_file:
with open(o... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
reago_dir = '/tools/rna_manipulation/reago/reago/'
def add_read_pair_num(input_filepath, output_filepath, read_pair_num):
to_add = '.' + str(read_pair_num)
with open(input_filepath,'r') as input_file:
with open(o... | Correct argument name in script to format reago input file | Correct argument name in script to format reago input file
| Python | apache-2.0 | ASaiM/galaxytools,ASaiM/galaxytools | ---
+++
@@ -28,5 +28,5 @@
parser.add_argument('--r2_sequence_file', required=True)
args = parser.parse_args()
- add_read_pair_num(args.r1_input_sequence_file, args.r1_input_sequence_file, 1)
- add_read_pair_num(args.r2_input_sequence_file, args.r2_input_sequence_file, 2)
+ add_read_pair_num(args.... |
37c59a8535ac0d68a995af378fcb61f03070e018 | kombu_fernet/serializers/__init__.py | kombu_fernet/serializers/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
from cryptography.fernet import Fernet, MultiFernet
fernet = Fernet(os.environ['KOMBU_FERNET_KEY'])
fallback_fernet = None
try:
fallback_fernet = Fernet(os.environ['OLD_KOMBU_FERNET_KEY'])
except KeyError:
pass
else:
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
import os
from cryptography.fernet import Fernet, MultiFernet
fernet = Fernet(os.environ['KOMBU_FERNET_KEY'])
fallback_fernet = None
try:
fallback_fernet = Fernet(os.environ['KOMBU_FERNET_KEY_PREVIOUS'])
except KeyError:
pass
els... | Make update previous key name | Make update previous key name
| Python | mit | heroku/kombu-fernet-serializers | ---
+++
@@ -7,7 +7,7 @@
fernet = Fernet(os.environ['KOMBU_FERNET_KEY'])
fallback_fernet = None
try:
- fallback_fernet = Fernet(os.environ['OLD_KOMBU_FERNET_KEY'])
+ fallback_fernet = Fernet(os.environ['KOMBU_FERNET_KEY_PREVIOUS'])
except KeyError:
pass
else: |
a83dd9bfce43a898cf71c9e66192ad589a02b6c8 | macroeco/compare/__init__.py | macroeco/compare/__init__.py | """
=================================
Compare (:mod:`macroeco.compare`)
=================================
This module contains functions that compare the goodness of fit of a
distribution/curve to data or the fit of two distributions/curves to each
other.
Comparison Functions
====================
.. autosummary::
... | """
=================================
Compare (:mod:`macroeco.compare`)
=================================
This module contains functions that compare the goodness of fit of a
distribution/curve to data or the fit of two distributions/curves to each
other.
Comparison Functions
====================
.. autosummary::
... | Remove get_ prefixes from compare docstring | Remove get_ prefixes from compare docstring
| Python | bsd-2-clause | jkitzes/macroeco | ---
+++
@@ -13,15 +13,15 @@
.. autosummary::
:toctree: generated/
- get_AIC
- get_AICC
- get_AIC_weights
- get_nll
- get_empirical_cdf
- get_sum_of_squares
- get_r_squared
- get_chi_squared
- get_lrt
+ AIC
+ AICC
+ AIC_weights
+ nll
+ empirical_cdf
+ sum_of_squares
+ r_squared
+... |
a0972fe1fba507a1e6d17fb18846fb7a13c8cbbe | src/msd/msd_utils.py | src/msd/msd_utils.py | # media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is dist... | # media-service-demo
#
# Copyright (C) 2012 Intel Corporation. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms and conditions of the GNU Lesser General Public License,
# version 2.1, as published by the Free Software Foundation.
#
# This program is dist... | Increment timeout when getting images | [FIX] Increment timeout when getting images
Signed-off-by: Ludovic Ferrandis <22de32f469b6975001fde4e8fec94685fb50d109@intel.com>
| Python | lgpl-2.1 | lferrandis/dleyna-control,01org/dleyna-control,jku/media-service-demo,markdryan/dleyna-control,rmerlino/dleyna-control,jku/dleyna-control | ---
+++
@@ -31,7 +31,7 @@
image = None
try:
with tmpfile:
- message = urllib2.urlopen(url, None, 1)
+ message = urllib2.urlopen(url, None, 15)
tmpfile.write(message.read())
image = gtk.Image()
image.set_from_file(tmpfile.name) |
2015233d252e625419485c269f1f70a7e0edada8 | skmisc/__init__.py | skmisc/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
__all__ = ['__version__']
# We first need to detect if we're being called as part of the skmisc
# setup procedure itself in a reliable manner.
try:
__SKMISC_SETUP__
except NameError:
__SKMISC_SETUP__ = False
if __SKM... | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
__all__ = ['__version__']
# We first need to detect if we're being called as part of the skmisc
# setup procedure itself in a reliable manner.
try:
__SKMISC_SETUP__
except NameError:
__SKMISC_SETUP__ = False
if __SKM... | Fix pytest path to root of package | Fix pytest path to root of package
Instead of the package init file.
| Python | bsd-3-clause | has2k1/onelib,has2k1/onelib,has2k1/onelib | ---
+++
@@ -17,14 +17,13 @@
_sys.stderr.write('Running from skmisc source directory.\n')
del _sys
else:
- from skmisc.__config__ import show as show_config # noqa: F401
- # try:
- # from skmisc.__config__ import show as show_config # noqa: F401
- # except ImportError:
- # msg = """... |
8187591a0f8255487f4b16b653ba5070bfffe739 | specs/test_diff.py | specs/test_diff.py | '''
This is an example of a python test
that compares a diff function (in this case
a hardcoded one that doesn't work) to the
reference JSON to check compliance.
'''
from nose.tools import eq_
import json
def diff(before, after):
return []
def test_diffs():
test_cases = json.load(open('test_cases.json'))
... | '''
This is an example of a python test
that compares a diff function (in this case
a hardcoded one that doesn't work) to the
reference JSON to check compliance.
'''
from nose.tools import eq_
import json
def diff(before, after):
return []
def test_diffs():
test_cases = json.load(open('test_cases_simple.json... | Add code to specs example test | Add code to specs example test
| Python | mit | tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff,tarmstrong/nbdiff | ---
+++
@@ -10,8 +10,16 @@
def diff(before, after):
return []
+
def test_diffs():
- test_cases = json.load(open('test_cases.json'))
+ test_cases = json.load(open('test_cases_simple.json'))
for test_case in test_cases:
result = diff(test_case['before'], test_case['after'])
eq_(res... |
66f6bb4b64ec13412edeef77c6db2f0a2e1932ba | src/sbml_model_checkup.py | src/sbml_model_checkup.py | """Debugging/cleanup checks."""
import itertools
import chen_2009_original_sbml
model = chen_2009_original_sbml.get_model()
# determine truly redundant species -- same name, same compartment
sa = sorted(model.species, key=lambda s: (s.label, s.compartment))
rs = [x
for x in ((n, map(lambda s: s.compartment, it... | """Debugging/cleanup checks."""
import itertools
import chen_2009_original_sbml
model = chen_2009_original_sbml.get_model()
# determine redundant species (same name)
sa = sorted(model.species, key=lambda s: (s.label, s.compartment))
rs = [x
for x in ((n, map(lambda s: s.compartment, it))
for n, it in... | Rework model_checkup to print results and make results more useful | Rework model_checkup to print results and make results more useful
| Python | mit | johnbachman/rasmodel,jmuhlich/rasmodel,subkar/rasmodel,johnbachman/ras_model,sorgerlab/rasmodel,jmuhlich/ras_model,jmuhlich/ras_model,jmuhlich/rasmodel,sorgerlab/ras_model,johnbachman/rasmodel,johnbachman/ras_model,sorgerlab/rasmodel,sorgerlab/ras_model | ---
+++
@@ -5,14 +5,32 @@
model = chen_2009_original_sbml.get_model()
-# determine truly redundant species -- same name, same compartment
+# determine redundant species (same name)
sa = sorted(model.species, key=lambda s: (s.label, s.compartment))
rs = [x
for x in ((n, map(lambda s: s.compartment, it))
... |
05151bb3ccd018b37097ddf5288e9984f5b45716 | ci/management/commands/cancel_old_jobs.py | ci/management/commands/cancel_old_jobs.py | from __future__ import unicode_literals, absolute_import
from django.core.management.base import BaseCommand
from ci import models, views, TimeUtils
from datetime import timedelta
class Command(BaseCommand):
help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying a... | from __future__ import unicode_literals, absolute_import
from django.core.management.base import BaseCommand
from ci import models, views, TimeUtils
from datetime import timedelta
class Command(BaseCommand):
help = 'Cancel old Civet jobs. When a specific civet client is no longer running, it can leave jobs lying a... | Update cancel old job message | Update cancel old job message
| Python | apache-2.0 | idaholab/civet,brianmoose/civet,idaholab/civet,brianmoose/civet,brianmoose/civet,idaholab/civet,idaholab/civet,brianmoose/civet | ---
+++
@@ -23,7 +23,7 @@
for job in jobs.all():
self.stdout.write("%sCancel job %s: %s: %s" % (prefix, job.pk, job, job.created))
if not dryrun:
- views.set_job_canceled(job, "Civet client hasn't run this job in too long a time")
+ views.set_job_cancel... |
d93f1ff0b226d2e85cefc02afd0d5c44571f70ce | curious/utils.py | curious/utils.py | import time
from . import settings
# for development/debugging
def report_time(f):
def wrap(*args, **kwargs):
t = time.time()
r = f(*args, **kwargs)
if settings.DEBUG:
print '%s.%s: %.4f' % (f.__module__, f.func_name, time.time()-t)
return r
return wrap
| from functools import wraps
import time
from . import settings
# for development/debugging
def report_time(f):
@wraps(f)
def wrap(*args, **kwargs):
t = time.time()
r = f(*args, **kwargs)
if settings.DEBUG:
print '%s.%s: %.4f' % (f.__module__, f.func_name, time.time()-t)
return r
return wrap... | Add functools wraps to report_time decorator | Add functools wraps to report_time decorator
(cherry picked from commit 93d9de9e004896407214c5b67e64cb050bfaa63c)
| Python | mit | ginkgobioworks/curious,benjiec/curious,benjiec/curious,ginkgobioworks/curious,benjiec/curious,ginkgobioworks/curious | ---
+++
@@ -1,8 +1,10 @@
+from functools import wraps
import time
from . import settings
# for development/debugging
def report_time(f):
+ @wraps(f)
def wrap(*args, **kwargs):
t = time.time()
r = f(*args, **kwargs) |
aef51ce5ece86d054f76d86dafca9667f88d3b1a | ccui/testexecution/templatetags/results.py | ccui/testexecution/templatetags/results.py | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011 uTest Inc.
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011 uTest Inc.
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | Fix result status chiclet links for new-style filter querystrings. | Fix result status chiclet links for new-style filter querystrings.
| Python | bsd-2-clause | shinglyu/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mozilla/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mozilla/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,shinglyu/moztra... | ---
+++
@@ -29,9 +29,9 @@
@register.filter
def results_detail_url(obj):
if isinstance(obj, TestCycle):
- return reverse("results_testruns") + "?testCycle=%s" % obj.id
+ return reverse("results_testruns") + "?filter-testCycle=%s" % obj.id
elif isinstance(obj, TestRun):
- return reverse... |
538acc8a114c9fda8489dc5fe91fed2314a37c9b | src/sentry/web/forms/invite_organization_member.py | src/sentry/web/forms/invite_organization_member.py | from __future__ import absolute_import
from django import forms
from django.db import transaction, IntegrityError
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, OrganizationMember,
OrganizationMemberType
)
class InviteOrganizationMemberForm(forms.ModelForm):
class Meta:
fields = ... | from __future__ import absolute_import
from django import forms
from django.db import transaction, IntegrityError
from sentry.models import (
AuditLogEntry, AuditLogEntryEvent, OrganizationMember,
OrganizationMemberType
)
class InviteOrganizationMemberForm(forms.ModelForm):
class Meta:
fields = ... | Handle members with duplicate email addresses | Handle members with duplicate email addresses
| Python | bsd-3-clause | ifduyue/sentry,jean/sentry,gg7/sentry,daevaorn/sentry,Kryz/sentry,songyi199111/sentry,felixbuenemann/sentry,vperron/sentry,looker/sentry,jean/sentry,looker/sentry,hongliang5623/sentry,alexm92/sentry,daevaorn/sentry,pauloschilling/sentry,fuziontech/sentry,TedaLIEz/sentry,mvaled/sentry,beeftornado/sentry,pauloschilling/s... | ---
+++
@@ -20,11 +20,11 @@
om.type = OrganizationMemberType.MEMBER
try:
- existing = OrganizationMember.objects.get(
+ existing = OrganizationMember.objects.filter(
organization=organization,
user__email__iexact=om.email,
- )
- ... |
3c7641c3380acab821dcbf2ae274da4fb8fade96 | students/psbriant/final_project/test_clean_data.py | students/psbriant/final_project/test_clean_data.py | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import pandas
import io
def get_data():
"""
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
def te... | """
Name: Paul Briant
Date: 12/11/16
Class: Introduction to Python
Assignment: Final Project
Description:
Tests for Final Project
"""
import clean_data as cd
import pandas
def get_data():
"""
Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_To... | Add docstrings for get_data and test_rename_columns and remove import io statement. | Add docstrings for get_data and test_rename_columns and remove import io statement.
| Python | unlicense | weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016 | ---
+++
@@ -10,14 +10,15 @@
import clean_data as cd
import pandas
-import io
+
def get_data():
"""
-
+ Retrieve data from csv file to test.
"""
data = pandas.read_csv("data/Residential_Water_Usage_Zip_Code_on_Top.csv")
return data
+
def test_clean():
"""
@@ -27,7 +28,7 @@
def ... |
17ddcb1b6c293197834b3154830b9521769d76fb | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Hardy Jones
# Copyright (c) 2013
#
# License: MIT
#
"""This module exports the Hlint plugin class."""
from SublimeLinter.lint import Linter
class Hlint(Linter):
"""Provides an interface to hlint."""
synta... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Hardy Jones
# Copyright (c) 2013
#
# License: MIT
#
"""This module exports the Hlint plugin class."""
from SublimeLinter.lint import Linter
class Hlint(Linter):
"""Provides an interface to hlint."""
defau... | Update to new `defaults` configuration | Update to new `defaults` configuration
| Python | mit | SublimeLinter/SublimeLinter-hlint | ---
+++
@@ -16,7 +16,9 @@
class Hlint(Linter):
"""Provides an interface to hlint."""
- syntax = ('haskell', 'haskell-sublimehaskell', 'literate haskell')
+ defaults = {
+ 'selector': 'source.haskell'
+ }
cmd = 'hlint'
regex = (
r'^.+:(?P<line>\d+):'
@@ -25,8 +27,4 @@
... |
2bab1888b43a9c232b37cc26c37df992ea5df2c5 | project/apps/api/signals.py | project/apps/api/signals.py | from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Performance)
def performance_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw... | from django.db.models.signals import (
post_save,
)
from django.dispatch import receiver
from .models import (
Performance,
Session,
)
@receiver(post_save, sender=Session)
def session_post_save(sender, instance=None, created=False, raw=False, **kwargs):
"""Create sentinels."""
if not raw:
... | Create sentinel rounds on Session creation | Create sentinel rounds on Session creation
| Python | bsd-2-clause | barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api | ---
+++
@@ -8,6 +8,20 @@
Performance,
Session,
)
+
+
+@receiver(post_save, sender=Session)
+def session_post_save(sender, instance=None, created=False, raw=False, **kwargs):
+ """Create sentinels."""
+ if not raw:
+ if created:
+ i = 1
+ while i <= instance.num_rounds:
+ ... |
0f3f9ac26e968eab788a9ee2e95c34f2fa05ddbf | hooks/settings/settings_gunicorn.py | hooks/settings/settings_gunicorn.py | # -*- coding: utf-8 -*-
"""
Related article: https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/
Parameters you might want to override:
GUNICORN_BIND="0.0.0.0:8005"
"""
import os
workers = 4
bind = "0.0.0.0:8005"
worker_class = "eventlet"
worker_connections = 100
# Overwrite some Gunicorn... | # -*- coding: utf-8 -*-
"""
Related article: https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/
Parameters you might want to override:
GUNICORN_BIND="0.0.0.0:8005"
"""
import os
workers = 4
bind = "0.0.0.0:8005"
worker_class = "eventlet"
worker_connections = 1000
# Overwrite some Gunicor... | Increase Gunicorn worker connections, 100 -> 1000 | Increase Gunicorn worker connections, 100 -> 1000
| Python | mit | business-factory/captain-hook | ---
+++
@@ -12,7 +12,7 @@
workers = 4
bind = "0.0.0.0:8005"
worker_class = "eventlet"
-worker_connections = 100
+worker_connections = 1000
# Overwrite some Gunicorns params by ENV variables
for k, v in os.environ.items(): |
a5a5c21dfc8fa03cbf0a5585af3b1e7bd8c875bc | trac/web/__init__.py | trac/web/__init__.py | # With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE variable is set from there
#
# TODO: Remove this once the Genshi zip_safe issue has been resolved.
import os
from pkg_resources import get_distribution
if not os.path.isdir(get_... | # Workaround for http://bugs.python.org/issue6763 and
# http://bugs.python.org/issue5853 thread issues
import mimetypes
mimetypes.init()
# With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE variable is set from there
#
# TODO: Re... | Fix race condition during `mimetypes` initialization. | Fix race condition during `mimetypes` initialization.
Initial patch from Steven R. Loomis.
Closes #8629.
| Python | bsd-3-clause | pkdevbox/trac,pkdevbox/trac,pkdevbox/trac,pkdevbox/trac | ---
+++
@@ -1,8 +1,14 @@
+# Workaround for http://bugs.python.org/issue6763 and
+# http://bugs.python.org/issue5853 thread issues
+import mimetypes
+mimetypes.init()
+
# With mod_python we'll have to delay importing trac.web.api until
# modpython_frontend.handler() has been called since the
# PYTHON_EGG_CACHE vari... |
375b26fbb6e5ba043a1017e28027241c12374207 | napalm_logs/transport/zeromq.py | napalm_logs/transport/zeromq.py | # -*- coding: utf-8 -*-
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.transport.base import TransportBase
class ZMQTransport(Transpo... | # -*- coding: utf-8 -*-
'''
ZeroMQ transport for napalm-logs.
'''
from __future__ import absolute_import
from __future__ import unicode_literals
# Import stdlib
import json
import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
from napalm_logs.exceptions import BindException
from napalm_logs.... | Raise bind exception and log | Raise bind exception and log
| Python | apache-2.0 | napalm-automation/napalm-logs,napalm-automation/napalm-logs | ---
+++
@@ -7,12 +7,16 @@
# Import stdlib
import json
+import logging
# Import third party libs
import zmq
# Import napalm-logs pkgs
+from napalm_logs.exceptions import BindException
from napalm_logs.transport.base import TransportBase
+
+log = logging.getLogger(__name__)
class ZMQTransport(Transport... |
c8ce1315caf762f2c0073ab0ebed8ef627be5581 | profile/files/openstack/horizon/overrides.py | profile/files/openstack/horizon/overrides.py | # Disable Floating IPs
from openstack_dashboard.dashboards.project.access_and_security import tabs
from openstack_dashboard.dashboards.project.instances import tables
import horizon
NO = lambda *x: False
tabs.FloatingIPsTab.allowed = NO
tabs.APIAccessTab.allowed = NO
tables.AssociateIP.allowed = NO
tables.SimpleAssoc... | # Disable Floating IPs
from openstack_dashboard.dashboards.project.access_and_security import tabs
from openstack_dashboard.dashboards.project.instances import tables
import horizon
NO = lambda *x: False
tabs.FloatingIPsTab.allowed = NO
tabs.APIAccessTab.allowed = NO
tables.AssociateIP.allowed = NO
tables.SimpleAssoc... | Remove volume consistency group tab from horizon in mitaka | Remove volume consistency group tab from horizon in mitaka
| Python | apache-2.0 | raykrist/himlar,tanzr/himlar,mikaeld66/himlar,raykrist/himlar,norcams/himlar,eckhart/himlar,mikaeld66/himlar,norcams/himlar,mikaeld66/himlar,raykrist/himlar,tanzr/himlar,TorLdre/himlar,tanzr/himlar,TorLdre/himlar,mikaeld66/himlar,tanzr/himlar,eckhart/himlar,norcams/himlar,raykrist/himlar,eckhart/himlar,TorLdre/himlar,n... | ---
+++
@@ -21,3 +21,7 @@
# Completely remove panel Network->Networks
networks_panel = project_dashboard.get_panel("networks")
project_dashboard.unregister(networks_panel.__class__) # Disable Floating IPs
+
+# Remove "Volume Consistency Groups" tab
+from openstack_dashboard.dashboards.project.volumes import tab... |
88dc672b8797834b03d67b962dda2de2d40ad4f1 | demos/minimal.py | demos/minimal.py | #!/usr/bin/env python
from gi.repository import GtkClutter
GtkClutter.init([])
from gi.repository import GObject, Gtk, GtkChamplain
GObject.threads_init()
GtkClutter.init([])
window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
window.connect("destroy", Gtk.main_quit)
widget = GtkChamplain.Embed()
widget.set_size_req... | #!/usr/bin/env python
# To run this example, you need to set the GI_TYPELIB_PATH environment
# variable to point to the gir directory:
#
# export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/usr/local/lib/girepository-1.0/
from gi.repository import GtkClutter
GtkClutter.init([])
from gi.repository import GObject, Gtk, GtkChampl... | Add description how to run the python demo | Add description how to run the python demo
| Python | lgpl-2.1 | Distrotech/libchamplain,PabloCastellano/libchamplain,PabloCastellano/libchamplain,StanciuMarius/Libchamplain-map-wrapping,PabloCastellano/libchamplain,StanciuMarius/Libchamplain-map-wrapping,StanciuMarius/Libchamplain-map-wrapping,PabloCastellano/libchamplain,GNOME/libchamplain,StanciuMarius/Libchamplain-map-wrapping,D... | ---
+++
@@ -1,4 +1,9 @@
#!/usr/bin/env python
+
+# To run this example, you need to set the GI_TYPELIB_PATH environment
+# variable to point to the gir directory:
+#
+# export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/usr/local/lib/girepository-1.0/
from gi.repository import GtkClutter
GtkClutter.init([]) |
0cda8aae3c5a8ad4d110c41007279a3364c6f33a | manage.py | manage.py | __author__ = 'zifnab'
from flask_script import Manager, Server
from app import app
manager=Manager(app)
manager.add_command('runserver', Server(host=app.config.get('HOST', '0.0.0.0'), port=app.config.get('PORT', 5000)))
@manager.command
def print_routes():
for rule in app.url_map.iter_rules():
print rule... | __author__ = 'zifnab'
from flask_script import Manager, Server
from app import app
from database import Paste
import arrow
manager=Manager(app)
manager.add_command('runserver', Server(host=app.config.get('HOST', '0.0.0.0'), port=app.config.get('PORT', 5000)))
@manager.command
def print_routes():
for rule in app.... | Add way to remove old pastes | Add way to remove old pastes
| Python | mit | zifnab06/zifb.in,zifnab06/zifb.in | ---
+++
@@ -1,6 +1,8 @@
__author__ = 'zifnab'
from flask_script import Manager, Server
from app import app
+from database import Paste
+import arrow
manager=Manager(app)
@@ -10,6 +12,11 @@
def print_routes():
for rule in app.url_map.iter_rules():
print rule
+@manager.command
+def remove_expired... |
d2f3ff32e6d0a8c03a76f93669bb1f37d28ae124 | parsl/tests/configs/local_threads_globus.py | parsl/tests/configs/local_threads_globus.py | from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this a... | from parsl.config import Config
from parsl.data_provider.scheme import GlobusScheme
from parsl.executors.threads import ThreadPoolExecutor
from parsl.tests.utils import get_rundir
# If you are a developer running tests, make sure to update parsl/tests/configs/user_opts.py
# If you are a user copying-and-pasting this a... | Fix storage_access in the test config | Fix storage_access in the test config
| Python | apache-2.0 | Parsl/parsl,Parsl/parsl,Parsl/parsl,swift-lang/swift-e-lab,Parsl/parsl,swift-lang/swift-e-lab | ---
+++
@@ -14,10 +14,10 @@
executors=[
ThreadPoolExecutor(
label='local_threads_globus',
- storage_access=GlobusScheme(
+ storage_access=[GlobusScheme(
endpoint_uuid=user_opts['globus']['endpoint'],
endpoint_path=user_opts['globus']['... |
3260594268f19dcfe1ea5613f939c892d609b47e | skimage/filters/tests/test_filter_import.py | skimage/filters/tests/test_filter_import.py | from warnings import catch_warnings, simplefilter
def test_filter_import():
with catch_warnings():
simplefilter('ignore')
from skimage import filter as F
assert('sobel' in dir(F))
assert any(['has been renamed' in w
for (w, _, _) in F.__warningregistry__])
| from warnings import catch_warnings, simplefilter
def test_filter_import():
with catch_warnings():
simplefilter('ignore')
from skimage import filter as F
assert('sobel' in dir(F))
assert any(['has been renamed' in w
for (w, _, _) in F.__warningregistry__]), F.__warningregi... | Add debug print to failing assert | Add debug print to failing assert
| Python | bsd-3-clause | Hiyorimi/scikit-image,juliusbierk/scikit-image,dpshelio/scikit-image,chriscrosscutler/scikit-image,Britefury/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,jwiggins/scikit-image,WarrenWeckesser/scikits-image,rjeli/scikit-image,Britefury/scikit-image,youprofit/scikit-image,ajaybhat/scikit-image,benn... | ---
+++
@@ -8,4 +8,4 @@
assert('sobel' in dir(F))
assert any(['has been renamed' in w
- for (w, _, _) in F.__warningregistry__])
+ for (w, _, _) in F.__warningregistry__]), F.__warningregistry__ |
d469a02c697a20d7db36a3a80d44cfca2257a5cd | django/models.py | django/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
{%% for model_name, props in all_models.iteritems() %%}
{%% set model_name = model_name|capitalize %%}
class {{{ model_name }}}(models.Model):
{%% for prop, value in props.iteritems() %%}
{{{ prop }}} = {{{ value|model_field }}... | from django.db import models
from django.utils.translation import ugettext_lazy as _
{%% for model_name, props in all_models.iteritems() %%}
{%% set model_name = model_name|capitalize %%}
class {{{ model_name }}}(models.Model):
{%% for prop, value in props.iteritems() %%}
{{{ prop }}} = {{{ value|model_field }}... | Change string representation for django model | Change string representation for django model
| Python | apache-2.0 | christabor/Skaffold,christabor/Skaffold | ---
+++
@@ -8,5 +8,5 @@
def __unicode__(self):
fields = [{%% for prop, value in props.iteritems() %%}'{{{ prop }}}', {%% endfor %%}]
- return unicode('{%% for prop, value in props.iteritems() %%}<{}>, {%% endfor %%}'.format(*fields))
+ return unicode('<{%% for prop, value in props.iterit... |
7756236c5e1fa70f1173dbd58b7e57f56214c19f | unitTestUtils/parseXML.py | unitTestUtils/parseXML.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
tr... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from xml.etree.ElementTree import ParseError
import xml.etree.ElementTree as ET
import glob
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def parse():
for infile in glob.glob('*.xml'):
tr... | Add a verbose error reporting on Travis | Add a verbose error reporting on Travis
| Python | apache-2.0 | wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework,wkrzemien/j-pet-framework | ---
+++
@@ -16,8 +16,10 @@
tree = ET.parse(infile)
root = tree.getroot()
if root.findall('.//FatalError'):
+ element=root.findall('.//FatalError')[0]
eprint("Error detected")
print(infile)
+ print(element.text)
... |
0df35e81754f703d1a8164cf0ea5169a53355185 | code/python/knub/thesis/word2vec_gaussian_lda_preprocessing.py | code/python/knub/thesis/word2vec_gaussian_lda_preprocessing.py | import argparse
import logging
import os
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prepare model for Gaussian LDA")
parser.add_argument("--topic_model", type=str)
... | import argparse
from codecs import open
import logging
import os
from gensim.models import Word2Vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prepare model for Gaussian LDA")
parser.add_argument("--... | Fix parameter parsing in gaussian lda preprocessing. | Fix parameter parsing in gaussian lda preprocessing.
| Python | apache-2.0 | knub/master-thesis,knub/master-thesis,knub/master-thesis,knub/master-thesis | ---
+++
@@ -1,4 +1,5 @@
import argparse
+from codecs import open
import logging
import os
@@ -8,16 +9,16 @@
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prepare model for Gaussian LDA")
- parser.add_argument("--topic_model", type=str)
- parser.add_argument("--embedding_model", type=... |
9ad55a4d532dc98f257206ae82b5d06f4203a4d4 | server/lib/python/cartodb_services/setup.py | server/lib/python/cartodb_services/setup.py | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/geocoder-api',
author='Data Serv... | """
CartoDB Services Python Library
See:
https://github.com/CartoDB/geocoder-api
"""
from setuptools import setup, find_packages
setup(
name='cartodb_services',
version='0.6.2',
description='CartoDB Services API Python Library',
url='https://github.com/CartoDB/dataservices-api',
author='Data ... | Update url of pip package | Update url of pip package
| Python | bsd-3-clause | CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api | ---
+++
@@ -14,7 +14,7 @@
description='CartoDB Services API Python Library',
- url='https://github.com/CartoDB/geocoder-api',
+ url='https://github.com/CartoDB/dataservices-api',
author='Data Services Team - CartoDB',
author_email='dataservices@cartodb.com', |
ce0be23f554eb9949a3769da1e4a3d3d51b546f1 | src/server/datab.py | src/server/datab.py | '''
Database module.
Get the database, convert it to the built-in data structure and hold a link
to it. The module should be initialized before any other modules except mailer
and log.
Design: Heranort
'''
'''
Connect to the database.
'''
def connect_to_datab():
pass
'''
Get raw data of the database.
'''
def data... | '''
Database module.
Get the database, convert it to the built-in data structure and hold a link
to it. The module should be initialized before any other modules except mailer
and log.
Design: Heranort
'''
import sqlite3, os
'''
Connect to the database.
'''
def connect_to_datab():
path = os.getcwd()
pparent_... | Add function of data connection | Add function of data connection
| Python | mit | niwtr/map-walker | ---
+++
@@ -6,23 +6,42 @@
Design: Heranort
'''
+import sqlite3, os
+
+
'''
Connect to the database.
'''
def connect_to_datab():
- pass
+ path = os.getcwd()
+ pparent_path = os.path.dirname(os.path.dirname(path)) #get the root dir
+ # print(pparent_path)
+ sql = sqlite3.connect(pparent_path + ... |
5c6df7c8ddb6ae698ab54b30f211bbcd28549c95 | packages/Python/lldbsuite/test/lang/cpp/template-function/TestTemplateFunctions.py | packages/Python/lldbsuite/test/lang/cpp/template-function/TestTemplateFunctions.py | """
Test that we can call C++ template fucntions.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TemplateFunctionsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def do_test_template_function(self, add_cast... | """
Test that we can call C++ template fucntions.
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TemplateFunctionsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
def do_test_template_function(self, add_cast... | Add a missing debug info variant. | [TestTemplateFunction] Add a missing debug info variant.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@359249 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb | ---
+++
@@ -27,6 +27,6 @@
self.do_test_template_function(True)
@skipIfWindows
- @expectedFailureAll(debug_info=["dwarf", "gmodules"])
+ @expectedFailureAll(debug_info=["dwarf", "gmodules", "dwo"])
def test_template_function_without_cast(self):
self.do_test_template_function(False) |
5d3d47e0fae9ddb9f445972e5186429163aabf40 | statirator/core/management/commands/init.py | statirator/core/management/commands/init.py | import os
from optparse import make_option
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Init the static site project"
args = '[directory]'
option_list = (
make_option(
'--title', '-t', dest='title', default='Default site',
help=... | import os
import logging
from django.core.management.base import BaseCommand
from optparse import make_option
class Command(BaseCommand):
help = "Init the static site project"
args = '[directory]'
option_list = (
make_option(
'--title', '-t', dest='title', default='Default site',
... | Create the directory before calling the startprojcet command | Create the directory before calling the startprojcet command
| Python | mit | MeirKriheli/statirator,MeirKriheli/statirator,MeirKriheli/statirator | ---
+++
@@ -1,6 +1,7 @@
import os
+import logging
+from django.core.management.base import BaseCommand
from optparse import make_option
-from django.core.management.base import BaseCommand
class Command(BaseCommand):
@@ -23,6 +24,9 @@
def handle(self, directory, **options):
+ logging.info("Init... |
2d584531d043804f3dcf3acf132cb60b463e4c1a | azdweb/markdown_serv.py | azdweb/markdown_serv.py | import os
from flask import request, render_template
from azdweb import app
from azdweb.util import gh_markdown
root_path = os.path.abspath("markdown")
# {filename: (mtime, contents)}
cache = {}
def load(filename):
with open(filename) as file:
return gh_markdown.markdown(file.read())
def load_cached... | import codecs
import os
from flask import render_template
from azdweb import app
from azdweb.util import gh_markdown
root_path = os.path.abspath("markdown")
# {filename: (mtime, contents)}
cache = {}
def load(filename):
with codecs.open(filename, encoding="utf-8") as file:
return gh_markdown.markdown(... | Add support for a sidebar, and also add a /sw/ alias for /md/skywars/ | Add support for a sidebar, and also add a /sw/ alias for /md/skywars/
| Python | apache-2.0 | daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru | ---
+++
@@ -1,6 +1,7 @@
+import codecs
import os
-from flask import request, render_template
+from flask import render_template
from azdweb import app
from azdweb.util import gh_markdown
@@ -12,7 +13,7 @@
def load(filename):
- with open(filename) as file:
+ with codecs.open(filename, encoding="utf-8... |
a4c24372ffcbac656a9879cc2fd705d67a875a3e | prime-factors/prime_factors.py | prime-factors/prime_factors.py | # File: prime_factors.py
# Purpose: Compute the prime factors of a given natural number.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Monday 26 September 2016, 12:05 AM
| # File: prime_factors.py
# Purpose: Compute the prime factors of a given natural number.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Monday 26 September 2016, 12:05 AM
def prime(number):
if number <= 1:
return False
else:
if number % 1 == 0 and number % range(2,... | Set condition [1 is not a prime] | Set condition [1 is not a prime]
| Python | mit | amalshehu/exercism-python | ---
+++
@@ -3,3 +3,10 @@
# Programmer: Amal Shehu
# Course: Exercism
# Date: Monday 26 September 2016, 12:05 AM
+
+
+def prime(number):
+ if number <= 1:
+ return False
+ else:
+ if number % 1 == 0 and number % range(2, number) |
14fb663019038b80d42f212e0ad8169cd0d37e84 | neutron_lib/exceptions/address_group.py | neutron_lib/exceptions/address_group.py | # All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | # All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | Add address group in use exception | Add address group in use exception
Related change: https://review.opendev.org/#/c/751110/
Change-Id: I2a9872890ca4d5e59a9e266c1dcacd3488a3265c
| Python | apache-2.0 | openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib,openstack/neutron-lib | ---
+++
@@ -20,6 +20,11 @@
message = _("Address group %(address_group_id)s could not be found.")
+class AddressGroupInUse(exceptions.InUse):
+ message = _("Address group %(address_group_id)s is in use on one or more "
+ "security group rules.")
+
+
class AddressesNotFound(exceptions.NotFou... |
c6e10155743eb506c82fb578de180180eb5f1e69 | imagedownloader/stations/tests/units/test_brands.py | imagedownloader/stations/tests/units/test_brands.py | # -*- coding: utf-8 -*-
from stations.models import *
from django.test import TestCase
from datetime import datetime
import pytz
class TestBrands(TestCase):
fixtures = [ 'initial_data.yaml', '*']
def setUp(self):
self.brand = Brand.objects.filter(name = 'Kip&Zonen')[0]
def test_serialization(self):
# check... | # -*- coding: utf-8 -*-
from stations.models import *
from django.test import TestCase
from datetime import datetime
import pytz
class TestBrands(TestCase):
fixtures = [ 'initial_data.yaml', '*']
def setUp(self):
self.brand = Brand.objects.filter(name = 'Kipp&Zonen')[0]
def test_serialization(self):
# chec... | Fix a test failure produced by stations/fixture brand change (Kipp&Zonen). | Fix a test failure produced by stations/fixture brand change (Kipp&Zonen).
| Python | mit | gersolar/solar_radiation_model,ahMarrone/solar_radiation_model,scottlittle/solar_radiation_model | ---
+++
@@ -9,7 +9,7 @@
fixtures = [ 'initial_data.yaml', '*']
def setUp(self):
- self.brand = Brand.objects.filter(name = 'Kip&Zonen')[0]
+ self.brand = Brand.objects.filter(name = 'Kipp&Zonen')[0]
def test_serialization(self):
# check if the __str__ method is defined to return the object name. |
14d51aa701dcc8d1d3f026af947c935abb0eabe3 | examples/rune.py | examples/rune.py | import cassiopeia as cass
from cassiopeia.core import Summoner
def test_cass():
name = "Kalturi"
runes = cass.get_runes()
for rune in runes:
if rune.tier == 3:
print(rune.name)
if __name__ == "__main__":
test_cass()
| import cassiopeia as cass
def print_t3_runes():
for rune in cass.get_runes():
if rune.tier == 3:
print(rune.name)
if __name__ == "__main__":
print_t3_runes()
| Change function name, remove unneeded summoner name | Change function name, remove unneeded summoner name
| Python | mit | robrua/cassiopeia,10se1ucgo/cassiopeia,meraki-analytics/cassiopeia | ---
+++
@@ -1,14 +1,11 @@
import cassiopeia as cass
-from cassiopeia.core import Summoner
-def test_cass():
- name = "Kalturi"
- runes = cass.get_runes()
- for rune in runes:
+def print_t3_runes():
+ for rune in cass.get_runes():
if rune.tier == 3:
print(rune.name)
if __nam... |
d72df78e0dea27ae93bde52e43cec360a963b32c | openprescribing/frontend/management/commands/delete_measure.py | openprescribing/frontend/management/commands/delete_measure.py | from django.conf import settings
from django.core.management import BaseCommand, CommandError
from frontend.models import Measure
class Command(BaseCommand):
def handle(self, measure_id, **options):
if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX):
raise CommandError(
... | from django.conf import settings
from django.core.management import BaseCommand, CommandError
from frontend.models import Measure
from gcutils.bigquery import Client
class Command(BaseCommand):
def handle(self, measure_id, **options):
if not measure_id.startswith(settings.MEASURE_PREVIEW_PREFIX):
... | Delete measures from BigQuery as well | Delete measures from BigQuery as well
| Python | mit | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc | ---
+++
@@ -2,6 +2,7 @@
from django.core.management import BaseCommand, CommandError
from frontend.models import Measure
+from gcutils.bigquery import Client
class Command(BaseCommand):
@@ -15,6 +16,7 @@
measure = Measure.objects.get(id=measure_id)
except Measure.DoesNotExist:
... |
d30eb17fbcc011291418373c1a89e508f8d1c7fe | scs_core/osio/client/topic_client.py | scs_core/osio/client/topic_client.py | """
Created on 9 Nov 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.data.json import JSONify
from scs_core.data.path_dict import PathDict
# --------------------------------------------------------------------------------------------------------------------
class TopicClient(objec... | """
Created on 9 Nov 2016
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from scs_core.data.json import JSONify
from scs_core.data.path_dict import PathDict
# --------------------------------------------------------------------------------------------------------------------
class TopicClient(objec... | Set abandoned clause in osio_topic_publisher. | Set abandoned clause in osio_topic_publisher.
| Python | mit | south-coast-science/scs_core | ---
+++
@@ -17,7 +17,7 @@
__HOST = "mqtt.opensensors.io" # hard-coded URL
- __TIMEOUT = 10.0
+ __TIMEOUT = 30.0
# ----------------------------------------------------------------------------------------------------------------
|
9b6ff8eb88084b69190fed24de92eca31f8509d5 | palindrome-products/palindrome_products.py | palindrome-products/palindrome_products.py | def largest_palindrome():
pass
def smallest_palindrome():
pass
| from collections import defaultdict
def largest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, max)
def smallest_palindrome(max_factor, min_factor=0):
return _palindromes(max_factor, min_factor, min)
def _palindromes(max_factor, min_factor, minmax):
pals = defaultdic... | Add an initial solution that works, but with the wrong output format | Add an initial solution that works, but with the wrong output format
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,6 +1,27 @@
-def largest_palindrome():
- pass
+from collections import defaultdict
-def smallest_palindrome():
- pass
+def largest_palindrome(max_factor, min_factor=0):
+ return _palindromes(max_factor, min_factor, max)
+
+
+def smallest_palindrome(max_factor, min_factor=0):
+ return _pal... |
cdcc0aa43025cace37fc1f51379928f0c1a8877d | scripts/staff_public_regs.py | scripts/staff_public_regs.py | # -*- coding: utf-8 -*-
"""Get public registrations for staff members.
python -m scripts.staff_public_regs
"""
from collections import defaultdict
import logging
from modularodm import Q
from website.models import Node, User
from website.app import init_app
logger = logging.getLogger('staff_public_regs')
STAFF... | # -*- coding: utf-8 -*-
"""Get public registrations for staff members.
python -m scripts.staff_public_regs
"""
from collections import defaultdict
import logging
from modularodm import Q
from website.models import Node, User
from website.app import init_app
logger = logging.getLogger('staff_public_regs')
STAFF... | Remove backref in main migration | Remove backref in main migration
| Python | apache-2.0 | billyhunt/osf.io,laurenrevere/osf.io,sloria/osf.io,brandonPurvis/osf.io,Ghalko/osf.io,chennan47/osf.io,emetsger/osf.io,hmoco/osf.io,icereval/osf.io,felliott/osf.io,DanielSBrown/osf.io,brianjgeiger/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,alexschiller/osf.io,samchrisinger/osf.io,kc... | ---
+++
@@ -27,7 +27,7 @@
users = [User.load(each) for each in STAFF_GUIDS]
for registration in Node.find(Q('is_registration', 'eq', True) & Q('is_public', 'eq', True)):
for user in users:
- if registration in user.node__contributed:
+ if registration in user.contributed:
... |
d0df78e9f660b138b5f79d6714312740ebcf1648 | fparser/setup.py | fparser/setup.py |
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
return config
|
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
config.add_data_files('log.config')
return config
| Add log.config to data files to fix installed fparser. | Add log.config to data files to fix installed fparser.
| Python | bsd-3-clause | pemryan/f2py,travellhyne/f2py,pearu/f2py,pemryan/f2py | ---
+++
@@ -2,4 +2,5 @@
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('fparser',parent_package,top_path)
+ config.add_data_files('log.config')
return config |
fa191537e15dd0729deb94aaa91dbb7fa9295e04 | mathdeck/loadproblem.py | mathdeck/loadproblem.py | # -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file):
"""
Load problem file a... | # -*- coding: utf-8 -*-
"""
mathdeck.loadproblem
~~~~~~~~~~~~~~~~~~~~
This module loads a problem file as a module.
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import os
import sys
# Load problem file as
def load_file_as_module(file_path):
"""
Load p... | Change package name in loadmodule call | Change package name in loadmodule call
Not much reason to do this. It just happened.
| Python | apache-2.0 | patrickspencer/mathdeck,patrickspencer/mathdeck | ---
+++
@@ -2,7 +2,7 @@
"""
mathdeck.loadproblem
-~~~~~~~~~~~~
+~~~~~~~~~~~~~~~~~~~~
This module loads a problem file as a module.
@@ -15,7 +15,7 @@
import sys
# Load problem file as
-def load_file_as_module(file):
+def load_file_as_module(file_path):
"""
Load problem file as a module.
@@ -29... |
6c39f3504dad1cf918189fd46d9e8529a2fc9586 | Functions/template-python/lambda_function.py | Functions/template-python/lambda_function.py | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
def __init__(self, context):
self.context = context
def event(self, message, ev... | """Created By: Andrew Ryan DeFilippis"""
print('Lambda cold-start...')
from json import dumps, loads
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
verbose = True
class CWLogs(object):
"""Define the structure of log events to match all other CloudWatch Log Events logged by AWS ... | Add documentation, and modify default return value | Add documentation, and modify default return value
| Python | apache-2.0 | andrewdefilippis/aws-lambda | ---
+++
@@ -3,7 +3,6 @@
print('Lambda cold-start...')
from json import dumps, loads
-
# Disable 'testing_locally' when deploying to AWS Lambda
testing_locally = True
@@ -11,18 +10,44 @@
class CWLogs(object):
+ """Define the structure of log events to match all other CloudWatch Log Events logged by AWS... |
e6046cf33af1a4b1f16424740b5093ebd423842e | scipy/spatial/transform/__init__.py | scipy/spatial/transform/__init__.py | """
========================================================
Spatial Transformations (:mod:`scipy.spatial.transform`)
========================================================
.. currentmodule:: scipy.spatial.transform
This package implements various spatial transformations. For now,
only rotations are supported.
Rot... | """
========================================================
Spatial Transformations (:mod:`scipy.spatial.transform`)
========================================================
.. currentmodule:: scipy.spatial.transform
This package implements various spatial transformations. For now,
only rotations are supported.
Rot... | Add Slerp class to transform package | BLD: Add Slerp class to transform package
| Python | bsd-3-clause | aarchiba/scipy,rgommers/scipy,mdhaber/scipy,grlee77/scipy,vigna/scipy,perimosocordiae/scipy,gertingold/scipy,anntzer/scipy,ilayn/scipy,anntzer/scipy,jamestwebber/scipy,person142/scipy,grlee77/scipy,gfyoung/scipy,e-q/scipy,perimosocordiae/scipy,matthew-brett/scipy,endolith/scipy,person142/scipy,scipy/scipy,jor-/scipy,il... | ---
+++
@@ -14,13 +14,14 @@
:toctree: generated/
Rotation
+ Slerp
"""
from __future__ import division, print_function, absolute_import
-from .rotation import Rotation
+from .rotation import Rotation, Slerp
-__all__ = ['Rotation']
+__all__ = ['Rotation', 'Slerp']
from scipy._lib._testutils im... |
9a543a84bce123329aec985739a44d0e230838d8 | homedisplay/info_internet_connection/management/commands/fetch_internet_information.py | homedisplay/info_internet_connection/management/commands/fetch_internet_information.py | from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from info_internet_connection.models import Internet
import datetime
import huawei_b593_status
import json
import redis
#{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connec... | from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from info_internet_connection.models import Internet
import datetime
import huawei_b593_status
import json
import redis
#{'WIFI': 'off', 'SIG': '5', 'Mode': '4g', 'Roam': 'home', 'SIM': 'normal', 'Connect': 'connec... | Fix wrong key in websocket message | Fix wrong key in websocket message
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | ---
+++
@@ -34,4 +34,4 @@
latest_data.connect_status = data["Connect"]
latest_data.update_timestamp = now()
latest_data.save()
- r.publish("home:broadcast:generic", json.dumps({"key": "internet", "value": "updated"}) # TODO: send all information
+ r.publish("home:broadcast:gen... |
f8555e70610df47b726e20f312be5beba67f8435 | mopidy/utils/process.py | mopidy/utils/process.py | import logging
import multiprocessing
from multiprocessing.reduction import reduce_connection
import pickle
import sys
from mopidy import SettingsError
logger = logging.getLogger('mopidy.utils.process')
def pickle_connection(connection):
return pickle.dumps(reduce_connection(connection))
def unpickle_connection... | import logging
import multiprocessing
import multiprocessing.dummy
from multiprocessing.reduction import reduce_connection
import pickle
import sys
from mopidy import SettingsError
logger = logging.getLogger('mopidy.utils.process')
def pickle_connection(connection):
return pickle.dumps(reduce_connection(connecti... | Create BaseThread as copy of BaseProcess but with different superclass | Create BaseThread as copy of BaseProcess but with different superclass
| Python | apache-2.0 | jmarsik/mopidy,hkariti/mopidy,glogiotatidis/mopidy,dbrgn/mopidy,diandiankan/mopidy,mopidy/mopidy,abarisain/mopidy,dbrgn/mopidy,rawdlite/mopidy,tkem/mopidy,mokieyue/mopidy,priestd09/mopidy,ZenithDK/mopidy,ZenithDK/mopidy,adamcik/mopidy,quartz55/mopidy,rawdlite/mopidy,rawdlite/mopidy,woutervanwijk/mopidy,diandiankan/mopi... | ---
+++
@@ -1,5 +1,6 @@
import logging
import multiprocessing
+import multiprocessing.dummy
from multiprocessing.reduction import reduce_connection
import pickle
import sys
@@ -37,3 +38,25 @@
def run_inside_try(self):
raise NotImplementedError
+
+
+class BaseThread(multiprocessing.dummy.Process):... |
f9365594e415e9485dc6a4435cb14b3eaf8b9c58 | situational/settings/heroku.py | situational/settings/heroku.py | import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Sym Roe', 'lmtools@talusdesign.co.uk'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ['.herokuapp.com']
INTERNAL_IPS = ()
# Redirect any non-HTTP request to HTTPS
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROT... | import os
from .base import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Sym Roe', 'lmtools@talusdesign.co.uk'),
)
MANAGERS = ADMINS
ALLOWED_HOSTS = ['.herokuapp.com']
INTERNAL_IPS = ()
# Redirect any non-HTTP request to HTTPS
SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROT... | Remove RedisCloud URL form Heroku | Remove RedisCloud URL form Heroku
| Python | bsd-3-clause | lm-tools/sectors,lm-tools/sectors,lm-tools/sectors,lm-tools/sectors | ---
+++
@@ -31,8 +31,6 @@
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django_postgrespool'
-REDIS_URL = os.environ['REDISCLOUD_URL']
-
EMAIL_HOST = os.environ['MAILGUN_SMTP_SERVER']
EMAIL_HOST_USER = os.environ['MAILGUN_SMTP_LOGIN']
EMAIL_HOST_PASSWORD = os.environ['MAILGU... |
6db8a9e779031ae97977a49e4edd11d42fb6389d | samples/04_markdown_parse/epub2markdown.py | samples/04_markdown_parse/epub2markdown.py | #!/usr/bin/env python
import sys
import subprocess
import os
import os.path
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.... | #!/usr/bin/env python
import os.path
import subprocess
import sys
from ebooklib import epub
# This is just a basic example which can easily break in real world.
if __name__ == '__main__':
# read epub
book = epub.read_epub(sys.argv[1])
# get base filename from the epub
base_name = os.path.basename(os... | Make `samples/04_markdown_parse` Python 2+3 compatible | Make `samples/04_markdown_parse` Python 2+3 compatible
| Python | agpl-3.0 | booktype/ebooklib,aerkalov/ebooklib | ---
+++
@@ -1,9 +1,7 @@
#!/usr/bin/env python
-
+import os.path
+import subprocess
import sys
-import subprocess
-import os
-import os.path
from ebooklib import epub
@@ -21,23 +19,20 @@
if isinstance(item, epub.EpubHtml):
proc = subprocess.Popen(['pandoc', '-f', 'html', '-t', 'markdown', ... |
82696dd76351f8d0bb4fcfe9f173ada652947acc | whacked4/whacked4/ui/dialogs/errordialog.py | whacked4/whacked4/ui/dialogs/errordialog.py | #!/usr/bin/env python
#coding=utf8
"""
Error dialog interface.
"""
from whacked4.ui import windows
import wx
class ErrorDialog(windows.ErrorDialogBase):
def __init__(self, parent):
windows.ErrorDialogBase.__init__(self, parent)
wx.EndBusyCursor()
def set_log(self,... | #!/usr/bin/env python
#coding=utf8
"""
Error dialog interface.
"""
from whacked4.ui import windows
import wx
class ErrorDialog(windows.ErrorDialogBase):
def __init__(self, parent):
windows.ErrorDialogBase.__init__(self, parent)
if wx.IsBusy() == True:
wx.EndBusyCursor()
... | Fix exceptions not displaying if a busy cursor was set. | Fix exceptions not displaying if a busy cursor was set.
| Python | bsd-2-clause | GitExl/WhackEd4,GitExl/WhackEd4 | ---
+++
@@ -14,7 +14,8 @@
def __init__(self, parent):
windows.ErrorDialogBase.__init__(self, parent)
- wx.EndBusyCursor()
+ if wx.IsBusy() == True:
+ wx.EndBusyCursor()
def set_log(self, log_file): |
2575946f1b05ac1601a00f8936ab3a701b05bc7e | tests/test_utils.py | tests/test_utils.py | import unittest
from utils import TextLoader
import numpy as np
class TestUtilsMethods(unittest.TestCase):
def setUp(self):
self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5)
def test_init(self):
print (self.data_loader.vocab)
print (self.data_loader.tensor)
... | import unittest
from utils import TextLoader
import numpy as np
from collections import Counter
class TestUtilsMethods(unittest.TestCase):
def setUp(self):
self.data_loader = TextLoader("tests/test_data", batch_size=2, seq_length=5)
def test_init(self):
print (self.data_loader.vocab)
print... | Generalize method names to be compatible with Python 2.7 and 3.4 | Generalize method names to be compatible with Python 2.7 and 3.4
| Python | mit | hunkim/word-rnn-tensorflow,bahmanh/word-rnn-tensorflow | ---
+++
@@ -1,6 +1,7 @@
import unittest
from utils import TextLoader
import numpy as np
+from collections import Counter
class TestUtilsMethods(unittest.TestCase):
def setUp(self):
@@ -17,17 +18,17 @@
print (vocab, vocab_inv)
# Must include I, love, and cat
- self.assertItemsEqua... |
dbcc7604b7ab554b7bb6000029071bfa8d2a5971 | saleor/payment/gateways/stripe/utils.py | saleor/payment/gateways/stripe/utils.py | from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as... | from decimal import Decimal
# FIXME: The amount should be dynamically calculated by payment's currency.
# For example, amount will wrong for JPY since JPY does not support cents
def get_amount_for_stripe(amount, currency):
"""Get appropriate amount for stripe.
Stripe is using currency's smallest unit such as... | Fix bug where amount for stripe is not correctly converted | Fix bug where amount for stripe is not correctly converted
| Python | bsd-3-clause | UITools/saleor,mociepka/saleor,maferelo/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor,mociepka/saleor | ---
+++
@@ -9,7 +9,9 @@
Stripe is using currency's smallest unit such as cents for USD.
Stripe requires integer instead of decimal.
"""
- return int(amount * 100)
+ # Using int(Decimal) directly may yield wrong result
+ # such as int(Decimal(24.24)) will equal to 2423
+ return int((amount *... |
52fc9bc79343632a034d2dc51645306f4b58210c | tests/services/conftest.py | tests/services/conftest.py | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | import pytest
from responses import RequestsMock
from netvisor import Netvisor
@pytest.fixture
def netvisor():
kwargs = dict(
sender='Test client',
partner_id='xxx_yyy',
partner_key='E2CEBB1966C7016730C70CA92CBB93DD',
customer_id='xx_yyyy_zz',
customer_key='7767899D6F5FB33... | Fix tests to work with responses 0.3.0 | Fix tests to work with responses 0.3.0
| Python | mit | fastmonkeys/netvisor.py | ---
+++
@@ -20,8 +20,6 @@
@pytest.yield_fixture(autouse=True)
def responses():
- requests_mock = RequestsMock()
- requests_mock._start()
- yield requests_mock
- requests_mock._stop()
- requests_mock.reset()
+ r = RequestsMock()
+ with r:
+ yield r |
99386fdd222988ca41d3781905cc1b185ca009f1 | plata/__init__.py | plata/__init__.py | VERSION = (1, 0, 0)
__version__ = '.'.join(map(str, VERSION))
import logging
logger = logging.getLogger('plata')
class LazySettings(object):
def _load_settings(self):
from plata import default_settings
from django.conf import settings as django_settings
for key in dir(default_settings):... | VERSION = (1, 1, 0, 'pre')
__version__ = '.'.join(map(str, VERSION))
import logging
logger = logging.getLogger('plata')
class LazySettings(object):
def _load_settings(self):
from plata import default_settings
from django.conf import settings as django_settings
for key in dir(default_set... | Change the VERSION to 1.1.0.pre | Change the VERSION to 1.1.0.pre
| Python | bsd-3-clause | armicron/plata,armicron/plata,armicron/plata,stefanklug/plata,allink/plata | ---
+++
@@ -1,4 +1,4 @@
-VERSION = (1, 0, 0)
+VERSION = (1, 1, 0, 'pre')
__version__ = '.'.join(map(str, VERSION))
|
a92118d7ee6acde57ab9853186c43a5c6748e8a6 | tracpro/__init__.py | tracpro/__init__.py | from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa
__version__ = "1.0.0"
| from __future__ import absolute_import
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app # noqa
VERSION = (1, 0, 0, "dev")
def get_version(version):
assert len(version) == 4, "Version must be formatted as (major, ... | Use tuple to represent version | Use tuple to represent version
| Python | bsd-3-clause | rapidpro/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro,xkmato/tracpro,rapidpro/tracpro,rapidpro/tracpro | ---
+++
@@ -5,4 +5,23 @@
from .celery import app as celery_app # noqa
-__version__ = "1.0.0"
+VERSION = (1, 0, 0, "dev")
+
+
+def get_version(version):
+ assert len(version) == 4, "Version must be formatted as (major, minor, micro, state)"
+
+ major, minor, micro, state = version
+
+ assert isinstance(... |
2b8674528972655937eff797e61fa6819bfc3ba8 | apps/feeds/signals.py | apps/feeds/signals.py | from libs.djpubsubhubbub.signals import updated
def update_handler(sender, update, **kwargs):
"""
Process new content being provided from SuperFeedr
"""
print sender
for entry in update.entries:
print entry
updated.connect(update_handler, dispatch_uid='superfeedr')
| from libs.djpubsubhubbub.signals import updated
from .models import Feed
def update_handler(sender, update, **kwargs):
"""
Process new content being provided from SuperFeedr
"""
print sender.topic
users = []
feeds = Feed.objects.filter(feed_url=sender.topic)
for feed in feeds:
... | Handle new content from SuperFeedr to Kippt | Handle new content from SuperFeedr to Kippt | Python | mit | jpadilla/feedleap,jpadilla/feedleap | ---
+++
@@ -1,4 +1,6 @@
from libs.djpubsubhubbub.signals import updated
+
+from .models import Feed
def update_handler(sender, update, **kwargs):
@@ -6,8 +8,24 @@
Process new content being provided from SuperFeedr
"""
- print sender
- for entry in update.entries:
- print entry
+
+ pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.