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 |
|---|---|---|---|---|---|---|---|---|---|---|
489ac862bf5efc70d1af3933d1c518489a0e95a6 | tests/test_pubtator.py | tests/test_pubtator.py |
import kindred
def test_pubtator():
data = kindred.pubtator.load([19894120,19894121])
assert isinstance(data,list)
for d in data:
assert isinstance(d,kindred.RelationData)
fileCount = len(data)
entityCount = sum([ len(d.getEntities()) for d in data ])
relationCount = sum([ len(d.getRelations()) for d in dat... |
import kindred
def test_pubtator():
data = kindred.pubtator.load([19894120,19894121])
assert isinstance(data,list)
for d in data:
assert isinstance(d,kindred.RelationData)
fileCount = len(data)
entityCount = sum([ len(d.getEntities()) for d in data ])
relationCount = sum([ len(d.getRelations()) for d in dat... | Update pubtator test given new pubtator output | Update pubtator test given new pubtator output
| Python | mit | jakelever/kindred,jakelever/kindred | ---
+++
@@ -14,7 +14,7 @@
assert fileCount == 2
assert relationCount == 0
- assert entityCount == 17
+ assert entityCount == 39
if __name__ == '__main__':
test_pubtator() |
11103afa4a46cc1835f1479651bcd7c808d6a33c | sdks/python/apache_beam/runners/api/__init__.py | sdks/python/apache_beam/runners/api/__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Add instructions to regenerate Python proto wrappers. | Add instructions to regenerate Python proto wrappers.
| Python | apache-2.0 | apache/beam,staslev/incubator-beam,jbonofre/beam,iemejia/incubator-beam,lukecwik/incubator-beam,rangadi/beam,wtanaka/beam,rangadi/beam,markflyhigh/incubator-beam,chamikaramj/beam,manuzhang/beam,tgroh/incubator-beam,wangyum/beam,charlesccychen/beam,RyanSkraba/beam,manuzhang/beam,eljefe6a/incubator-beam,apache/beam,charl... | ---
+++
@@ -14,3 +14,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+
+"""Checked in to avoid protoc dependency for Python development.
+
+Regenerate files with::
+
+ protoc -I../common/runner-api/src/main/proto/ \
+ --python_out=apache_beam... |
7176ec5d4abe678d8f0d01baeacf4dc78204b18f | tests/integration/modules/grains.py | tests/integration/modules/grains.py | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['... | '''
Test the grains module
'''
import integration
class TestModulesGrains(integration.ModuleCase):
'''
Test the grains module
'''
def test_items(self):
'''
grains.items
'''
opts = self.minion_opts
self.assertEqual(
self.run_function('grains.items')['... | Add test to test if os_family grain is provided. | Add test to test if os_family grain is provided.
Corey Quinn reported a issue where __grains__['os_family'] returned a
KeyError. This commits adds a check to the grains module test to ensure
os_family is present.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -45,6 +45,7 @@
'mem_total',
'num_cpus',
'os',
+ 'os_family',
'path',
'ps',
'pythonpath', |
f3b960da24f2f9486eca3936a5be0d5001c24ab3 | package_name/module.py | package_name/module.py | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
X : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `X` where it is p... | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... | Fix X -> x in cubic_rectification | DOC: Fix X -> x in cubic_rectification
| Python | mit | scottclowe/python-continuous-integration,scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-ci | ---
+++
@@ -11,13 +11,13 @@
Parameters
----------
- X : numpy.ndarray
+ x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
- Elementwise, the cube of `X` where it is positive and `0` otherwise.
+ Elementwise, the cube of `x` where it is positive and ... |
6f199c9f2fb54931fa852700598b3c0fe24e40ad | viewflow/exceptions.py | viewflow/exceptions.py | class FlowRuntimeError(Exception):
"""Unrecovable flow runtime error."""
class FlowLockFailed(Exception):
"""Flow lock failed."""
| class FlowRuntimeError(Exception):
"""Unrecoverable flow runtime error."""
class FlowLockFailed(Exception):
"""Flow lock failed."""
| Fix typo in exception docstring | Fix typo in exception docstring | Python | agpl-3.0 | viewflow/viewflow,viewflow/viewflow,viewflow/viewflow | ---
+++
@@ -1,5 +1,5 @@
class FlowRuntimeError(Exception):
- """Unrecovable flow runtime error."""
+ """Unrecoverable flow runtime error."""
class FlowLockFailed(Exception): |
fb8f77553d75cdcf2c50423cb2e4159350a13e5a | tests/test_person.py | tests/test_person.py | import unittest
from classes.person import Person
class PersonClassTest(unittest.TestCase):
def test_full_name_only_returns_strings(self):
with self.assertRaises(ValueError, msg='Only strings are allowed as names'):
my_class_instance = Person("staff", "Peter", "Musonye")
my_class_i... | import unittest
from classes.person import Person
class PersonClassTest(unittest.TestCase):
def test_full_name_only_returns_strings(self):
with self.assertRaises(ValueError, msg='Only strings are allowed as names'):
my_class_instance = Person("staff", "Peter", 1234)
my_class_instan... | Fix test case for class Person | Fix test case for class Person
| Python | mit | peterpaints/room-allocator | ---
+++
@@ -5,5 +5,5 @@
class PersonClassTest(unittest.TestCase):
def test_full_name_only_returns_strings(self):
with self.assertRaises(ValueError, msg='Only strings are allowed as names'):
- my_class_instance = Person("staff", "Peter", "Musonye")
+ my_class_instance = Person("sta... |
892393458612ea78319cceeb98957c34ccb91d2d | django_react_templatetags/encoders.py | django_react_templatetags/encoders.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
conte... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.serializers.json import DjangoJSONEncoder
from django_react_templatetags.mixins import RepresentationMixin
def json_encoder_cls_factory(context):
class ReqReactRepresentationJSONEncoder(ReactRepresentationJSONEncoder):
conte... | Drop support for reacct_representation property | Drop support for reacct_representation property
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags | ---
+++
@@ -20,10 +20,6 @@
def default(self, o):
if isinstance(o, RepresentationMixin):
- # Allow backwards compability with react_representation prop
- if not hasattr(o, 'to_react_representation'):
- return o.react_representation
-
args = [self.contex... |
cfe78dabea226e24928d26183f4b135c52b64663 | feder/cases/forms.py | feder/cases/forms.py | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from django import forms
from .models import Case
class CaseForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
self.moni... | # -*- coding: utf-8 -*-
from atom.ext.crispy_forms.forms import SingleButtonMixin
from braces.forms import UserKwargModelFormMixin
from django import forms
from .models import Case
class CaseForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm):
def __init__(self, *args, **kwargs):
self.moni... | Clean up form in CaseForm | Clean up form in CaseForm
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder | ---
+++
@@ -11,11 +11,8 @@
def __init__(self, *args, **kwargs):
self.monitoring = kwargs.pop('monitoring', None)
super(CaseForm, self).__init__(*args, **kwargs)
-
- def save(self, *args, **kwargs):
if self.monitoring:
self.instance.monitoring = self.monitoring
- ... |
06ec0a7f0a6a53fddfb2038b0ae8cc1bad2c8511 | blankspot/node_registration/models.py | blankspot/node_registration/models.py | from django.db import models
class Contact(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
nick = models.CharField(max_length=128)
email = models.EmailField(max_length=254)
def __unicode__(self):
return (self.... | from django.db import models
class Position(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
nick = models.CharField(max_length=128)
email = models.EmailField(max_length=254)
street = models.CharField(max_length=2... | Revert splitting of model as its adding to much complexitiy for the timebeing to later logics IIt's just not adding enought value for having a more complicated implementation. | Revert splitting of model as its adding to much complexitiy for the timebeing to later logics
IIt's just not adding enought value for having a more complicated implementation.
| Python | agpl-3.0 | frlan/blankspot | ---
+++
@@ -1,19 +1,10 @@
from django.db import models
-class Contact(models.Model):
+class Position(models.Model):
first_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
nick = models.CharField(max_length=128)
email = models.E... |
b86d88a10839ba642f992dcaf3e69de3a244f984 | golingo/urls.py | golingo/urls.py | """golingo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | """golingo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... | Add initial url to question | Add initial url to question
| Python | bsd-3-clause | jesuejunior/golingo,jesuejunior/golingo,jesuejunior/golingo | ---
+++
@@ -15,7 +15,9 @@
"""
from django.conf.urls import include, url
from django.contrib import admin
+from quiz.views import QuestionTemplateView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
+ url(r'^question/$', QuestionTemplateView.as_view(), name='question'),
] |
4a330e190dcb727cb7483b826f2927b94b081e8a | yardcam.py | yardcam.py | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
wait = delay.next_capture() # Delay time in seconds from delay.py
waithours = wait / 60 / 60 # Co... | import capture
from picamera import PiCamera
import time
import delay
def image_cap_loop(camera, status=None):
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
# wait = delay.next_capture() # Delay time in seconds from delay.py
wait = 60
waithours = wait... | Remove delay from loop for testing | Remove delay from loop for testing
| Python | mit | gnfrazier/YardCam | ---
+++
@@ -8,7 +8,8 @@
"""Set image parameters, capture image, set wait time, repeat"""
resolution = (1640, 1232)
- wait = delay.next_capture() # Delay time in seconds from delay.py
+ # wait = delay.next_capture() # Delay time in seconds from delay.py
+ wait = 60
waithours = wait / 60 / 6... |
f2d3d52c4118b9ff0161a8db5d53d83c199918e3 | gunicorn_cfg.py | gunicorn_cfg.py | """
This file contains gunicorn settings.
To run sqmpy with gunicorn run the following command:
gunicorn -c gunicorn_cfg.py run:app
In order to daemonize gunicorn add -D flag:
gunicorn -c gunicorn_cfg.py run:app -D
"""
import multiprocessing
# Gunicorn will listen on the given host:port
bind = '0.0.0.0:30... | """
This file contains gunicorn settings.
To run sqmpy with gunicorn run the following command:
gunicorn -c gunicorn_cfg.py run:app
In order to daemonize gunicorn add -D flag:
gunicorn -c gunicorn_cfg.py run:app -D
"""
import multiprocessing
# Gunicorn will listen on the given host:port
bind = '0.0.0.0:30... | Update gunicorn config with docs | Update gunicorn config with docs
| Python | bsd-3-clause | mehdisadeghi/sqmpy,simphony/sqmpy,mehdisadeghi/sqmpy,simphony/sqmpy,simphony/sqmpy,mehdisadeghi/sqmpy | ---
+++
@@ -16,7 +16,7 @@
bind = '0.0.0.0:3000'
# The only tested worker class is gevent
-worker_class = 'gevent'
+#worker_class = 'gevent'
# Set number of workers based on CPU count
workers = multiprocessing.cpu_count() * 2 + 1
@@ -31,5 +31,5 @@
keyfile = 'server.key'
certfile = 'server.crt'
-# Applicati... |
3f6b18304a3f947cc165201a507a672a56af851f | warehouse/cli.py | warehouse/cli.py | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | # Copyright 2013 Donald Stufft
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | Remove a useless function call | Remove a useless function call
| Python | apache-2.0 | robhudson/warehouse,mattrobenolt/warehouse,techtonik/warehouse,mattrobenolt/warehouse,mattrobenolt/warehouse,robhudson/warehouse,techtonik/warehouse | ---
+++
@@ -17,10 +17,6 @@
import warehouse.migrations.cli
-def include(module):
- return getattr(module, "__commands__", {})
-
-
__commands__ = {
- "migrate": include(warehouse.migrations.cli),
+ "migrate": warehouse.migrations.cli.__commands__,
} |
aff8cebfd168493a4a9dff77cf9722507429d570 | contrib/examples/actions/pythonactions/isprime.py | contrib/examples/actions/pythonactions/isprime.py | import math
class PrimeChecker(object):
def run(self, **kwargs):
return self._is_prime(**kwargs)
def _is_prime(self, value=0):
if math.floor(value) != value:
raise ValueError('%s should be an integer.' % value)
if value < 2:
return False
for test in ra... | import math
class PrimeChecker(object):
def run(self, value=0):
if math.floor(value) != value:
raise ValueError('%s should be an integer.' % value)
if value < 2:
return False
for test in range(2, int(math.floor(math.sqrt(value)))+1):
if value % test == ... | Update pythonaction sample for simpler run. | Update pythonaction sample for simpler run.
| Python | apache-2.0 | peak6/st2,lakshmi-kannan/st2,pixelrebel/st2,StackStorm/st2,jtopjian/st2,pinterb/st2,Plexxi/st2,punalpatel/st2,armab/st2,grengojbo/st2,grengojbo/st2,punalpatel/st2,pixelrebel/st2,Itxaka/st2,lakshmi-kannan/st2,emedvedev/st2,lakshmi-kannan/st2,pixelrebel/st2,nzlosh/st2,peak6/st2,dennybaa/st2,pinterb/st2,Plexxi/st2,nzlosh/... | ---
+++
@@ -3,10 +3,7 @@
class PrimeChecker(object):
- def run(self, **kwargs):
- return self._is_prime(**kwargs)
-
- def _is_prime(self, value=0):
+ def run(self, value=0):
if math.floor(value) != value:
raise ValueError('%s should be an integer.' % value)
if value... |
035ae3b2acf5c29304a1c2ec327feb5cc7160559 | django_vend/core/forms.py | django_vend/core/forms.py | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... | import re
from django import forms
from django.utils.dateparse import parse_datetime
from django.core.exceptions import ValidationError
def valid_date(date):
regex = ("^(?:[1-9]\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\d|2[0-8])|(?:0[13"
"-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\d(?:0[48]|[... | Allow VendDateTimeField to accept null dates (if required is set to False) | Allow VendDateTimeField to accept null dates (if required is set to False)
| Python | bsd-3-clause | remarkablerocket/django-vend,remarkablerocket/django-vend | ---
+++
@@ -18,4 +18,6 @@
value = parse_datetime(value)
except ValueError:
pass
+ elif value == "null":
+ value = None
return super(VendDateTimeField, self).to_python(value) |
080637c99898082d38b306ef73983552b263e628 | inbox/ignition.py | inbox/ignition.py | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | from sqlalchemy import create_engine
from inbox.sqlalchemy_ext.util import ForceStrictMode
from inbox.config import db_uri, config
DB_POOL_SIZE = config.get_required('DB_POOL_SIZE')
def main_engine(pool_size=DB_POOL_SIZE, max_overflow=5):
engine = create_engine(db_uri(),
listeners=[Fo... | Set pool_recycle to deal with MySQL closing idle connections. | Set pool_recycle to deal with MySQL closing idle connections.
See http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#connection-timeouts
Cherry-picking this onto master so it definitely gets deployed.
| Python | agpl-3.0 | Eagles2F/sync-engine,Eagles2F/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,jobscore/sync-engine,jobscore/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-eng... | ---
+++
@@ -12,6 +12,7 @@
isolation_level='READ COMMITTED',
echo=False,
pool_size=pool_size,
+ pool_recycle=3600,
max_overflow=max_overflow,
connect_arg... |
1513532e473866438ac9dabbfb462e9348a5895e | hug/output_format.py | hug/output_format.py | import json as json_converter
from datetime import date, datetime
from hug.format import content_type
def _json_converter(item):
if isinstance(item, (date, datetime)):
return item.isoformat()
elif isinstance(item, bytes):
return item.decode('utf8')
raise TypeError("Type not serializable")... | import json as json_converter
from datetime import date, datetime
from hug.format import content_type
def _json_converter(item):
if isinstance(item, (date, datetime)):
return item.isoformat()
elif isinstance(item, bytes):
return item.decode('utf8')
elif getattr(item, '__json__', None):
... | Add the ability for individual objects to define how they would like there data to be outputed for json | Add the ability for individual objects to define how they would like there data to be outputed for json
| Python | mit | janusnic/hug,yasoob/hug,janusnic/hug,shaunstanislaus/hug,timothycrosley/hug,alisaifee/hug,gbn972/hug,MuhammadAlkarouri/hug,philiptzou/hug,giserh/hug,timothycrosley/hug,STANAPO/hug,shaunstanislaus/hug,STANAPO/hug,origingod/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,alisaifee/hug,giserh/hug,yasoob/hug,gbn972/hug,phi... | ---
+++
@@ -9,6 +9,8 @@
return item.isoformat()
elif isinstance(item, bytes):
return item.decode('utf8')
+ elif getattr(item, '__json__', None):
+ return item.__json__()
raise TypeError("Type not serializable")
|
e507461dba5020726c9505fef187098ad234a68a | kazoo/tests/__init__.py | kazoo/tests/__init__.py | import os
import unittest
import time
import uuid
from kazoo.client import KazooClient, KazooState
# if this env variable is set, ZK client integration tests are run
# against the specified host list
ENV_TEST_HOSTS = "KAZOO_TEST_HOSTS"
def get_hosts_or_skip():
if ENV_TEST_HOSTS in os.environ:
return os.... | import os
import unittest
import time
import uuid
from nose import SkipTest
from kazoo.client import KazooClient, KazooState
# if this env variable is set, ZK client integration tests are run
# against the specified host list
ENV_TEST_HOSTS = "KAZOO_TEST_HOSTS"
def get_hosts_or_skip():
if ENV_TEST_HOSTS in os.... | Use SkipTest that works on Py2.6 | Use SkipTest that works on Py2.6
| Python | apache-2.0 | kormat/kazoo,rackerlabs/kazoo,tempbottle/kazoo,max0d41/kazoo,rgs1/kazoo,rockerbox/kazoo,harlowja/kazoo,kormat/kazoo,rgs1/kazoo,harlowja/kazoo,pombredanne/kazoo,python-zk/kazoo,python-zk/kazoo,pombredanne/kazoo,rockerbox/kazoo,tempbottle/kazoo,AlexanderplUs/kazoo,jacksontj/kazoo,max0d41/kazoo,Asana/kazoo,jacksontj/kazoo... | ---
+++
@@ -2,6 +2,8 @@
import unittest
import time
import uuid
+
+from nose import SkipTest
from kazoo.client import KazooClient, KazooState
@@ -13,9 +15,9 @@
def get_hosts_or_skip():
if ENV_TEST_HOSTS in os.environ:
return os.environ[ENV_TEST_HOSTS]
- raise unittest.SkipTest("Skipping ZooK... |
544f00f73657bbc06f4dd7f5faae2ce2546fe788 | lava_server/__init__.py | lava_server/__init__.py | # Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software F... | # Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software F... | Mark final for 0.2 release | Mark final for 0.2 release
| Python | agpl-3.0 | Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server | ---
+++
@@ -17,4 +17,4 @@
# along with LAVA Server. If not, see <http://www.gnu.org/licenses/>.
-__version__ = (0, 2, 0, "dev", 0)
+__version__ = (0, 2, 0, "final", 0) |
f55af10f1767d39fdba65fb4c17beee526f96748 | lib/__init__.py | lib/__init__.py | """retriever.lib contains the core EcoData Retriever modules."""
|
"""retriever.lib contains the core EcoData Retriever modules."""
import os
def set_proxy():
proxies = ["https_proxy", "http_proxy", "ftp_proxy", "HTTP_PROXY", "HTTPS_PROXY", "FTP_PROXY"]
for proxy in proxies:
if os.getenv(proxy):
if len(os.environ[proxy]) != 0:
for i in proxies:
os.env... | Check for and use system proxies for downloading files | Check for and use system proxies for downloading files
In some cases when the user is using a proxy urlib.urlopen() will fail to successfully open https files. This prevents the retriever from accessing the scripts stored on GitHub and causes the installation to fail (see #268). This change checks for the existence of... | Python | mit | embaldridge/retriever,davharris/retriever,davharris/retriever,davharris/retriever,embaldridge/retriever,goelakash/retriever,henrykironde/deletedret,goelakash/retriever,henrykironde/deletedret,embaldridge/retriever | ---
+++
@@ -1 +1,14 @@
+
"""retriever.lib contains the core EcoData Retriever modules."""
+import os
+
+def set_proxy():
+ proxies = ["https_proxy", "http_proxy", "ftp_proxy", "HTTP_PROXY", "HTTPS_PROXY", "FTP_PROXY"]
+ for proxy in proxies:
+ if os.getenv(proxy):
+ if len(os.environ[proxy]) != 0:
+ ... |
a0d32bb36674863a0e9a04aa97e8c1f7e8ca0f37 | lecturer/tests.py | lecturer/tests.py |
from django.test import Client, TestCase
c = Client()
class WebsiteStabilityTestCase(TestCase):
def test_availability(self):
self.assertEqual(c.get('/lecturer/').status_code, 302) # We are getting redirect when not logged in, so 302
# TODO maybe check for something more reliable than 302?
|
from django.test import Client, TestCase
from django.contrib.auth import get_user_model
c = Client()
class WebsiteStabilityTestCase(TestCase):
def test_availability(self):
self.assertEqual(c.get('/lecturer/').status_code, 302) # We are getting redirect when not logged in, so 302
# TODO maybe ch... | Test if lecturer is logged in upon login-request | Test if lecturer is logged in upon login-request
| Python | mit | martinlunde/RealBack,martinlunde/RealBack,martinlunde/RealBack | ---
+++
@@ -1,6 +1,6 @@
from django.test import Client, TestCase
-
+from django.contrib.auth import get_user_model
c = Client()
@@ -9,3 +9,10 @@
def test_availability(self):
self.assertEqual(c.get('/lecturer/').status_code, 302) # We are getting redirect when not logged in, so 302
# TO... |
0867054258e231b2ce9b028c5ce2bc3a26bca7be | gamernews/apps/threadedcomments/views.py | gamernews/apps/threadedcomments/views.py | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.utils.translation import ugettext as _
from django.views.generic.list import ListView
from core.models import Account as User
from django_c... | Remove name, url and email from comment form | Remove name, url and email from comment form
| Python | mit | underlost/GamerNews,underlost/GamerNews | ---
+++
@@ -14,12 +14,13 @@
variables = RequestContext(request, {'comment': comment})
return render_to_response('comments/single.html', variables)
-def comment_posted( request ):
+def comment_posted(request):
if request.GET['c']:
- comment_id, blob_id = request.GET['c'].split( ':' )
- ... |
8cd11782d4b3558d204f438accdc15b3b702839b | unn/cli.py | unn/cli.py | import sys
commands = {}
args = []
kwargs = {}
def EXIT(msg, code=1):
print(msg)
sys.exit(code)
def command(fn):
commands[fn.__name__] = fn
return fn
def run():
if len(sys.argv) < 2:
EXIT('No command provided')
cmd = sys.argv[1]
if cmd not in commands:
EXIT('Unkown co... | import sys
commands = {}
args = []
kwargs = {}
def EXIT(msg, code=1):
print(msg)
sys.exit(code)
def command(fn):
commands[fn.__name__] = fn
return fn
def run():
if len(sys.argv) < 2:
EXIT('Valid commands are:\n ' + '\n '.join(commands))
cmd = sys.argv[1]
if cmd not in command... | Add a helpful message if no command given | Add a helpful message if no command given
| Python | mit | runningskull/unn | ---
+++
@@ -16,7 +16,7 @@
def run():
if len(sys.argv) < 2:
- EXIT('No command provided')
+ EXIT('Valid commands are:\n ' + '\n '.join(commands))
cmd = sys.argv[1]
|
ab6526b14f5bdc544367bcaa281a861d2314330b | gi2fasta.py | gi2fasta.py | import sys
from Bio import Entrez
from Bio import SeqIO
Entrez.email = "davidsshin@lbl.gov"
infilename = sys.argv[1]
outfilename = sys.argv[2]
with open(infilename) as f:
gi_numbers=', '.join(line.rstrip() for line in f)
handle = Entrez.efetch(db="protein", rettype="fasta", retmode="text", id=gi_numbers)
records... | import sys
#from Bio import Entrez
#from Bio import SeqIO
user_email = "" # User must supply email here to access NCBI api
# Add error message in the event no email address is supplied
if user_email == "":
sys.exit("Error: Please supply your email address to line 5 of gi2fasta.py")
Entrez.email = user_email
inf... | Add error message if User does not enter email address | Add error message if User does not enter email address
| Python | bsd-2-clause | datadaveshin/bioinformatics,datadaveshin/bioinformatics | ---
+++
@@ -1,7 +1,13 @@
import sys
-from Bio import Entrez
-from Bio import SeqIO
-Entrez.email = "davidsshin@lbl.gov"
+#from Bio import Entrez
+#from Bio import SeqIO
+
+user_email = "" # User must supply email here to access NCBI api
+# Add error message in the event no email address is supplied
+if user_email =... |
10c6112dd343901b502c31655a001e612ed6e441 | api/logs/permissions.py | api/logs/permissions.py | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... | # -*- coding: utf-8 -*-
from rest_framework import permissions
from website.models import Node, NodeLog
from api.nodes.permissions import ContributorOrPublic
from api.base.utils import get_object_or_error
class ContributorOrPublicForLogs(permissions.BasePermission):
def has_object_permission(self, request, vie... | Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged. | Add case for when there are no node backrefs on logs. Again, this whole method will change when eliminating backrefs from nodelogs is merged.
| Python | apache-2.0 | doublebits/osf.io,mluo613/osf.io,cwisecarver/osf.io,billyhunt/osf.io,baylee-d/osf.io,caneruguz/osf.io,mattclark/osf.io,Johnetordoff/osf.io,kwierman/osf.io,kwierman/osf.io,amyshi188/osf.io,acshi/osf.io,mfraezz/osf.io,zamattiac/osf.io,pattisdr/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,hmoco/osf.io,alexschiller/osf.io... | ---
+++
@@ -12,8 +12,14 @@
def has_object_permission(self, request, view, obj):
assert isinstance(obj, (NodeLog)), 'obj must be a NodeLog, got {}'.format(obj)
- for node_id in obj._backrefs['logged']['node']['logs']:
- node = get_object_or_error(Node, node_id, display_name='node')
- ... |
66f6529880da4e8c444c2872820fb6b207c3794e | Server/main.py | Server/main.py | from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
debug = True
@app.before_first_request
def before_first_request():
pass
@app.before_request
def before_request():
pass
@app.after_request
def after_request(response):
# flask.wrapper.Response 클래스의 인스턴스
r... | from flask import Flask
from flask_restful import Api
import logging
from logging.handlers import RotatingFileHandler
app = Flask(__name__)
api = Api(app)
debug = True
@app.before_first_request
def before_first_request():
handler = RotatingFileHandler('server_log.log', maxBytes=100000, backupCount=5)
handl... | Add logging to before_first_request decorator | Add logging to before_first_request decorator
| Python | mit | DSM-GRAM/Artist,DSM-GRAM/Artist | ---
+++
@@ -1,6 +1,8 @@
from flask import Flask
from flask_restful import Api
+import logging
+from logging.handlers import RotatingFileHandler
app = Flask(__name__)
api = Api(app)
@@ -10,7 +12,14 @@
@app.before_first_request
def before_first_request():
- pass
+ handler = RotatingFileHandler('server... |
acec4dd403201dec5d22623c37ce1aff3324bc67 | drivnal/remote_snapshot.py | drivnal/remote_snapshot.py | from constants import *
from core_snapshot import CoreSnapshot
import logging
logger = logging.getLogger(APP_NAME)
class RemoteSnapshot(CoreSnapshot):
def _get_path(self):
return ''
def _get_log_path(self):
return ''
def _setup_snapshot(self, last_snapshot):
pass
def set_sta... | from constants import *
from core_snapshot import CoreSnapshot
import logging
logger = logging.getLogger(APP_NAME)
class RemoteSnapshot(CoreSnapshot):
def _get_path(self):
dir_name = str(self.id)
if self.state != COMPLETE:
dir_name = '%s.%s' % (dir_name, self.state)
return '%s@... | Add get path for remote snapshot | Add get path for remote snapshot
| Python | agpl-3.0 | drivnal/drivnal,drivnal/drivnal,drivnal/drivnal | ---
+++
@@ -6,7 +6,11 @@
class RemoteSnapshot(CoreSnapshot):
def _get_path(self):
- return ''
+ dir_name = str(self.id)
+ if self.state != COMPLETE:
+ dir_name = '%s.%s' % (dir_name, self.state)
+ return '%s@%s%s' % (self.volume.ssh_user, self.volume.ssh_path,
+ ... |
5b1ab860a0706831b8abc77a060d6ba89cf8946a | interface/subprocess/001.backticks.py | interface/subprocess/001.backticks.py | import subprocess
# --- replacing shell backticks ---
# https://docs.python.org/2/library/subprocess.html#replacing-bin-sh-shell-backquote
# output=`mycmd myarg`
# output = check_output(["mycmd", "myarg"])
# not true, because mycmd is not passed to shell
try:
output = subprocess.check_output(["mycmd", "myarg"]... | import subprocess
# --- replacing shell backticks ---
# https://docs.python.org/2/library/subprocess.html#replacing-bin-sh-shell-backquote
# output=`mycmd myarg`
# output = check_output(["mycmd", "myarg"])
# not true, because mycmd is not passed to shell
try:
output = subprocess.check_output(["mycmd", "myarg"]... | Add docs to backtics function | interface.subprocess: Add docs to backtics function
| Python | unlicense | techtonik/discovery,techtonik/discovery,techtonik/discovery | ---
+++
@@ -26,6 +26,12 @@
def backticks(command):
+ '''
+ Execute `command and return output.
+ - no return code
+ - no stderr capture
+ - bailed out with MemoryError on Windows with 500Mb of output
+ '''
try:
# this doesn't escape shell patterns, such as:
# ^ (windows cmd.exe sh... |
91bb9574ec760efd8aba2d9ae8fe67fe2e69d0a2 | jacquard/buckets/tests/test_bucket.py | jacquard/buckets/tests/test_bucket.py | import pytest
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_three_buckets_per_percent():
assert NUM_BUCKETS / 100 >= 3
| import pytest
from jacquard.odm import Session
from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@pytest.mark.parametrize('divisor', (
2,
3,
4,
5,
6,
10,
100,
))
def test_divisible(divisor):
assert NUM_BUCKETS % divisor == 0
def test_at_least_thr... | Add a test for getting an empty bucket | Add a test for getting an empty bucket
| Python | mit | prophile/jacquard,prophile/jacquard | ---
+++
@@ -1,5 +1,7 @@
import pytest
+from jacquard.odm import Session
+from jacquard.buckets import Bucket
from jacquard.buckets.constants import NUM_BUCKETS
@@ -18,3 +20,9 @@
def test_at_least_three_buckets_per_percent():
assert NUM_BUCKETS / 100 >= 3
+
+
+def test_can_get_empty_bucket_from_old_for... |
6c4e94f1133c9c9cd18b97a386f04f56b229f9a8 | las_reader/las2excel.py | las_reader/las2excel.py | try:
import argparse
except ImportError:
argparse = None
import sys
import core
def main():
if argparse:
args = get_parser().parse_args(sys.argv[1:])
lasfn = args.las_filename
xlsfn = args.xls_filename
else:
if len(sys.argv >= 3):
lasfn = sys.argv[1]
... | try:
import argparse
except ImportError:
argparse = None
import sys
import core
def main():
if argparse:
args = get_parser().parse_args(sys.argv[1:])
print args.__dict__.keys()
lasfn = args.las_filename
xlsfn = args.xls_filename
else:
if len(sys.argv >= 3):... | Fix Namespace for cmd line args | Fix Namespace for cmd line args
| Python | mit | kinverarity1/las-reader,Kramer477/lasio,kinverarity1/lasio,VelizarVESSELINOV/las-reader,kwinkunks/lasio | ---
+++
@@ -10,6 +10,7 @@
def main():
if argparse:
args = get_parser().parse_args(sys.argv[1:])
+ print args.__dict__.keys()
lasfn = args.las_filename
xlsfn = args.xls_filename
else:
@@ -29,8 +30,8 @@
def get_parser():
parser = argparse.ArgumentParser('Convert ... |
ccb774b58ab7dbe704abfb7df3fa29915fad8f8f | examples/memnn/download.py | examples/memnn/download.py | #!/usr/bin/env python
from six.moves.urllib import request
def main():
opener = request.FancyURLopener()
opener.addheaders = [('User-Agent', '')]
opener.retrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
... | #!/usr/bin/env python
from six.moves.urllib import request
def main():
request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
if __name__ == '__main__':
main()
| Replace deprecated URLopener in `donwload.py` | Replace deprecated URLopener in `donwload.py`
| Python | mit | niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,wkentaro/chainer,pfnet/chainer,keisuke-umezawa/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,chainer/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,keisuke-umezawa/chainer,hvy/chai... | ---
+++
@@ -4,9 +4,7 @@
def main():
- opener = request.FancyURLopener()
- opener.addheaders = [('User-Agent', '')]
- opener.retrieve(
+ request.urlretrieve(
'http://www.thespermwhale.com/jaseweston/babi/tasks_1-20_v1-2.tar.gz',
'tasks_1-20_v1-2.tar.gz')
|
1a1600b0cd27d5e004be344574901c64cdd6f7a2 | scripts/imgtool/__init__.py | scripts/imgtool/__init__.py | # Copyright 2017 Linaro Limited
#
# 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 writin... | # Copyright 2017-2020 Linaro Limited
#
# 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 w... | Change imgtool version to 1.7.0a1 | Change imgtool version to 1.7.0a1
Signed-off-by: Ihor Slabkyy <5b878c9a28a92b9cb7e9988086921fcb7ae33592@cypress.com>
| Python | apache-2.0 | utzig/mcuboot,tamban01/mcuboot,utzig/mcuboot,runtimeco/mcuboot,runtimeco/mcuboot,runtimeco/mcuboot,tamban01/mcuboot,runtimeco/mcuboot,ATmobica/mcuboot,ATmobica/mcuboot,utzig/mcuboot,tamban01/mcuboot,tamban01/mcuboot,ATmobica/mcuboot,runtimeco/mcuboot,tamban01/mcuboot,utzig/mcuboot,utzig/mcuboot,ATmobica/mcuboot,ATmobic... | ---
+++
@@ -1,4 +1,4 @@
-# Copyright 2017 Linaro Limited
+# Copyright 2017-2020 Linaro Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -12,4 +12,4 @@
# See the License for the specific language governing permissions ... |
361ebc774fba5489c1911ac40dde4828f6cbd374 | flysight_manager/report.py | flysight_manager/report.py | #!/usr/bin/env python
import log
from jinja2 import Template
import traceback
class Report(object):
def __init__(self):
self.logs = log.LogAggregator.new()
def format_exception_as_reason(exc):
return traceback.format_exc(exc)
@log.make_loggable
class UploadReport(Report):
TEMPLATE_FILENAME = '... | #!/usr/bin/env python
import log
import time
from jinja2 import Template
import traceback
class Report(object):
TIME_FMT = ": %y/%m/%d %H:%M %z (%Z)"
def __init__(self):
self.logs = log.LogAggregator.new()
self.started = time.strftime(TIME_FMT)
def format_exception_as_reason(exc):
return ... | Include the time in the email | Include the time in the email
| Python | mit | richo/flysight-manager,richo/flysight-manager | ---
+++
@@ -1,12 +1,15 @@
#!/usr/bin/env python
import log
+import time
from jinja2 import Template
import traceback
class Report(object):
+ TIME_FMT = ": %y/%m/%d %H:%M %z (%Z)"
def __init__(self):
self.logs = log.LogAggregator.new()
+ self.started = time.strftime(TIME_FMT)
def fo... |
e2919039a20a255232fefe3b78e173587710baf0 | cla_backend/apps/core/middleware.py | cla_backend/apps/core/middleware.py | from django.http import Http404
from django_statsd.clients import statsd
class GraphiteMiddleware(object):
def process_response(self, request, response):
statsd.incr("response.%s" % response.status_code)
return response
def process_exception(self, request, exception):
if not isinstanc... | class GraphiteMiddleware(object):
def process_response(self, request, response):
return response
| Remove statsd code and resultant redundant code | Remove statsd code and resultant redundant code | Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -1,12 +1,3 @@
-from django.http import Http404
-from django_statsd.clients import statsd
-
-
class GraphiteMiddleware(object):
def process_response(self, request, response):
- statsd.incr("response.%s" % response.status_code)
return response
-
- def process_exception(self, request,... |
6784c455cf93c16237661d6d9fed6af06726a880 | conveyor/processor.py | conveyor/processor.py | from __future__ import absolute_import
from __future__ import division
import collections
from xmlrpc2 import client as xmlrpc2
class BaseProcessor(object):
def __init__(self, index, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
self.index = index
self.client =... | from __future__ import absolute_import
from __future__ import division
import collections
import slumber
import slumber.exceptions
import xmlrpc2.client
class BaseProcessor(object):
def __init__(self, index, warehouse, *args, **kwargs):
super(BaseProcessor, self).__init__(*args, **kwargs)
warg... | Switch to more obvious imports | Switch to more obvious imports
| Python | bsd-2-clause | crateio/carrier | ---
+++
@@ -3,16 +3,20 @@
import collections
-from xmlrpc2 import client as xmlrpc2
+import slumber
+import slumber.exceptions
+import xmlrpc2.client
class BaseProcessor(object):
- def __init__(self, index, *args, **kwargs):
+ def __init__(self, index, warehouse, *args, **kwargs):
super(Bas... |
59becaccfc93e1d737be26483a18e9de1dfe1db1 | openedx/core/release.py | openedx/core/release.py | """
Information about the release line of this Open edX code.
"""
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
RELEASE_LINE = "hawthorn"
d... | """
Information about the release line of this Open edX code.
"""
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
RELEASE_LINE = "master"
def... | Revert "Set the RELEASE_LINE to hawthorn" | Revert "Set the RELEASE_LINE to hawthorn"
This reverts commit f44ac32bc9060cfa5ea6ce4284ce7f15b466be28.
| Python | agpl-3.0 | appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform,appsembler/edx-platform | ---
+++
@@ -5,7 +5,7 @@
# The release line: an Open edX release name ("ficus"), or "master".
# This should always be "master" on the master branch, and will be changed
# manually when we start release-line branches, like open-release/ficus.master.
-RELEASE_LINE = "hawthorn"
+RELEASE_LINE = "master"
def doc_ve... |
2f56f7dccbc3c9fc416200160bd8616a5e4ab954 | barf/barf/__init__.py | barf/barf/__init__.py | # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... | # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... | Set logging in overwrite mode | Set logging in overwrite mode
| Python | bsd-2-clause | cnheitman/barf-project,chubbymaggie/barf-project,programa-stic/barf-project,programa-stic/barf-project,cnheitman/barf-project,chubbymaggie/barf-project,chubbymaggie/barf-project,cnheitman/barf-project | ---
+++
@@ -34,5 +34,6 @@
logging.basicConfig(
filename="barf.log",
format="%(asctime)s: %(name)s:%(levelname)s: %(message)s",
+ filemode='w',
level=logging.DEBUG
) |
1d63f615ac58cc8c548cdd8e359694355e5b1843 | portal/forms.py | portal/forms.py | from django.contrib.auth.models import User
from django import forms
# Create your forms here.
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
| from django.contrib.auth.models import User
from django import forms
# Create your forms here.
class BootstrapForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form... | Add BootstrapForm to beautify form_template | Add BootstrapForm to beautify form_template
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist | ---
+++
@@ -3,7 +3,16 @@
# Create your forms here.
-class UserForm(forms.ModelForm):
+class BootstrapForm(forms.ModelForm):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ for visible in self.visible_fields():
+ visible.field.widget.attrs['class'] = 'for... |
d0b9824fe29e9c5772c0fc2838e2c6e373013819 | portal/forms.py | portal/forms.py | from django import forms
from django.contrib.auth.models import User
from portal.models import Profile
# Create your forms here.
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
class ... | from django import forms
from django.contrib.auth.models import User
from portal.models import Profile
# Create your forms here.
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
class... | Fix indents on form module | Fix indents on form module
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist | ---
+++
@@ -12,6 +12,7 @@
model = User
fields = ['username', 'email', 'password']
+
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile |
6b880f3c783e6a278906b8da2aabea29bb106252 | thinc/neural/_classes/resnet.py | thinc/neural/_classes/resnet.py | from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
def Residual(layer):
def residual_fwd(X, drop=0.):
y, bp_y = layer.begin_update(X, drop=drop)
output = X+y
def residual_bwd(d_output, sgd=None):
return d_output + bp_y(d_out... | from .model import Model
from ...api import layerize
from .affine import Affine
import cytoolz as toolz
class Residual(Model):
def __init__(self, layer):
Model.__init__(self)
self._layers.append(layer)
self.on_data_hooks.append(on_data)
def __call__(self, X):
return X + self.... | Add predict path for Residual | Add predict path for Residual
| Python | mit | spacy-io/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,explosion/thinc,explosion/thinc | ---
+++
@@ -5,18 +5,25 @@
import cytoolz as toolz
-def Residual(layer):
- def residual_fwd(X, drop=0.):
- y, bp_y = layer.begin_update(X, drop=drop)
+class Residual(Model):
+ def __init__(self, layer):
+ Model.__init__(self)
+ self._layers.append(layer)
+ self.on_data_hooks.appe... |
105ac0020dbc60fe57da7db75fb82cf872a0834d | crm_switzerland/models/res_partner.py | crm_switzerland/models/res_partner.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2018 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | FIX bug when sending notification to multiple partners | FIX bug when sending notification to multiple partners
| Python | agpl-3.0 | ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland | ---
+++
@@ -30,6 +30,6 @@
@api.model
def _notify_prepare_template_context(self, message):
# modification of context for lang
- message = message.with_context(lang=self.lang)
+ message = message.with_context(lang=self[:1].lang or self.env.lang)
return super(ResPartner, self).\... |
bb8d2fa458dd565b88db4e2185062f641864e990 | tornado/test/httpserver_test.py | tornado/test/httpserver_test.py | #!/usr/bin/env python
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase
from tornado.web import Application, RequestHandler
import os
import pycurl
import re
import unittest
import urllib
class HelloWorldRequestHandler(RequestHandler):
def get(self):
self.finish("Hello world")
class SSLTest(... | #!/usr/bin/env python
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase
from tornado.web import Application, RequestHandler
import os
import pycurl
import re
import unittest
import urllib
try:
import ssl
except ImportError:
ssl = None
class HelloWorldRequestHandler(RequestHandler):
def get(s... | Disable SSL test on python 2.5 | Disable SSL test on python 2.5
| Python | apache-2.0 | bywbilly/tornado,AlphaStaxLLC/tornado,felixonmars/tornado,jarrahwu/tornado,BencoLee/tornado,MjAbuz/tornado,shaohung001/tornado,sunjeammy/tornado,zhuochenKIDD/tornado,VShangxiao/tornado,LTD-Beget/tornado,Snamint/tornado,304471720/tornado,Callwoola/tornado,shashankbassi92/tornado,InverseLina/tornado,Batterfii/tornado,cyr... | ---
+++
@@ -7,6 +7,11 @@
import re
import unittest
import urllib
+
+try:
+ import ssl
+except ImportError:
+ ssl = None
class HelloWorldRequestHandler(RequestHandler):
def get(self):
@@ -33,3 +38,7 @@
prepare_curl_callback=disable_cert_check)
response = self.w... |
39cc30f2f6c74d3a506c5d1a46cf0ccc6377b80f | pylibscrypt/__init__.py | pylibscrypt/__init__.py |
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, get the inlined Python version
if not _done:
try:
from pypyscrypt_inline import *
except ImportError:
pass
else:
_done = True
... |
# First, try loading libscrypt
_done = False
try:
from pylibscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't work, try the scrypt module
if not _done:
try:
from pyscrypt import *
except ImportError:
pass
else:
_done = True
# If that didn't w... | Use pyscrypt.py in package import if libscrypt isn't available | Use pyscrypt.py in package import if libscrypt isn't available
| Python | isc | jvarho/pylibscrypt,jvarho/pylibscrypt | ---
+++
@@ -8,7 +8,16 @@
else:
_done = True
-# If that didn't work, get the inlined Python version
+# If that didn't work, try the scrypt module
+if not _done:
+ try:
+ from pyscrypt import *
+ except ImportError:
+ pass
+ else:
+ _done = True
+
+# If that didn't work either, the... |
00aa59468c4dbfde282891f1396e29bd3f28fb62 | gunny/reveille/service.py | gunny/reveille/service.py | from twisted.application import internet
from twisted.application.service import Service
from twisted.internet import reactor
from autobahn.websocket import connectWS
class ControlService(Service):
pass
class PlayerService(Service):
def __init__(self, factory):
self.factory = factory
self.... | from twisted.application.service import Service
from twisted.internet import stdio
from autobahn.websocket import connectWS
class CoxswainService(Service):
def __init__(self, factory):
self.factory = factory
self.conn = None
def startService(self):
#self.factory(ReveilleCommandProto... | Rename classes to reflect intended use. | Rename classes to reflect intended use.
| Python | bsd-2-clause | davidblewett/gunny,davidblewett/gunny | ---
+++
@@ -1,27 +1,22 @@
-from twisted.application import internet
from twisted.application.service import Service
-from twisted.internet import reactor
+from twisted.internet import stdio
from autobahn.websocket import connectWS
-class ControlService(Service):
- pass
-
-
-class PlayerService(Service):
+c... |
7df1ed120281c82d166fa1c2218def4c84b48a3d | alfred_db/migrations/versions/30c0aec2ca06_improve_repository_o.py | alfred_db/migrations/versions/30c0aec2ca06_improve_repository_o.py | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... | """Improve repository owner information
Revision ID: 30c0aec2ca06
Revises: 4fdf1059c4ba
Create Date: 2012-09-02 14:45:05.241933
"""
# revision identifiers, used by Alembic.
revision = '30c0aec2ca06'
down_revision = '4fdf1059c4ba'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column(
... | Remove unicode string markers which are removed in python3 | Remove unicode string markers which are removed in python3
| Python | isc | alfredhq/alfred-db | ---
+++
@@ -28,7 +28,7 @@
'repositories',
sa.Column('owner_id', sa.Integer(), nullable=False)
)
- op.drop_column('repositories', u'user')
+ op.drop_column('repositories', 'user')
op.create_unique_constraint(
"uq_owner_type_owner_name",
"repositories",
@@ -39,7 +39,7... |
9938678e05270c06d328aeb466ab827bab232e3a | solar_neighbourhood/prepare_data_add_kinematics.py | solar_neighbourhood/prepare_data_add_kinematics.py | """
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = Table.read('../data/ScoCen_box_result.fits')
d = Table.read(datafile)
# Set missing radial velocities ... | """
Add very large RV errors for stars with no known RVs.
Convert to cartesian.
"""
import numpy as np
import sys
sys.path.insert(0, '..')
from chronostar import tabletool
from astropy.table import Table
datafile = '../data/ScoCen_box_result.fits')
d = tabletool.read(datafile)
# Set missing radial velocities (nan) t... | Convert entire table to cartesian | Convert entire table to cartesian
| Python | mit | mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar,mikeireland/chronostar | ---
+++
@@ -9,8 +9,8 @@
from chronostar import tabletool
from astropy.table import Table
-datafile = Table.read('../data/ScoCen_box_result.fits')
-d = Table.read(datafile)
+datafile = '../data/ScoCen_box_result.fits')
+d = tabletool.read(datafile)
# Set missing radial velocities (nan) to 0
d['radial_velocity'... |
364d83c8add1fdde679aa2823ae94ad7f264cb48 | raco/relation_key.py | raco/relation_key.py | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... | """Representation of a Myria relation key.
Myria relations are identified by a tuple of user, program, relation_name."""
class RelationKey(object):
def __init__(self, user='public', program='adhoc', relation=None):
assert relation
self.user = user
self.program = program
self.relati... | Add hash function to RelationKey | Add hash function to RelationKey
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco | ---
+++
@@ -16,8 +16,10 @@
return '%s:%s:%s' % (self.user, self.program, self.relation)
def __eq__(self, other):
- return self.user == other.user and self.program == other.program \
- and self.relation == other.relation
+ return self.__dict__ == other.__dict__
+
+ def __has... |
93a23b3aed48da6953914036ae488c5b3ab891c7 | scikits/audiolab/soundio/alsa.py | scikits/audiolab/soundio/alsa.py | import numpy as np
from _alsa import card_name, card_indexes, asoundlib_version
from _alsa import Device, AlsaException
def play(input, samplerate = 48000):
if input.ndim == 1:
n = input.size
nc = 1
elif input.ndim == 2:
n, nc = input.shape
else:
raise ValueError("Only ndim... | import numpy as np
from _alsa import card_name, card_indexes, asoundlib_version
from _alsa import Device, AlsaException
def play(input, samplerate = 48000):
if input.ndim == 1:
n = input.size
nc = 1
elif input.ndim == 2:
n, nc = input.shape
else:
raise ValueError("Only ndim... | Check input dtype before creating pcm device. | Check input dtype before creating pcm device.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab | ---
+++
@@ -12,12 +12,11 @@
else:
raise ValueError("Only ndim 1 or 2 supported")
+ if not input.dtype in (np.float32, np.float64):
+ raise ValueError("input should be array of float32 or float64 !")
+
try:
dev = Device(samplerate = samplerate, channels = nc)
-
- assert n... |
9c650cb3fb37e8c96ef9642af553ce77a28a1587 | problem-static/Intro-Eval_50/admin/eval.py | problem-static/Intro-Eval_50/admin/eval.py | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | #!/usr/bin/python2.7
import sys
del __builtins__.__dict__['__import__']
del __builtins__.__dict__['reload']
flag = "eval_is_fun"
class UnbufferedStream(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def... | Move welcome message to outside the loop | Move welcome message to outside the loop
| Python | mit | james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF,james9909/IntroCTF | ---
+++
@@ -17,9 +17,9 @@
return getattr(self.stream, attr)
sys.stdout = UnbufferedStream(sys.stdout)
-def main():
+def main():
+ print "Welcome to the flag database! We are currently under construction. Please do not hack the flags."
while True:
- print "Welcome to the flag database! W... |
1bbffc2152ea1c48b47153005beeb2974b682f3c | bot/actions/action.py | bot/actions/action.py | from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
pass
class Update(Event):
def __init__(self, update, is_pending):
super().__init__()
self.update = update
self.is_pending = ... | from bot.api.api import Api
from bot.storage import Config, State, Cache
from bot.utils.dictionaryobject import DictionaryObject
class Event(DictionaryObject):
pass
class Update(Event):
def __init__(self, update, is_pending):
super().__init__()
self.update = update
self.is_pending = ... | Fix for_each incorrectly using lazy map operator | Fix for_each incorrectly using lazy map operator
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -51,7 +51,8 @@
self.for_each(lambda action: action.process(event._copy()))
def for_each(self, func):
- map(func, self.actions)
+ for action in self.actions:
+ func(action)
class IntermediateAction(ActionGroup): |
eb7ff9cec9360af0b5c18915164a54d4755e657b | mistraldashboard/dashboards/mistral/executions/tables.py | mistraldashboard/dashboards/mistral/executions/tables.py | # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | # -*- coding: utf-8 -*-
#
# Copyright 2014 - StackStorm, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Add Task's output and parameters columns | Add Task's output and parameters columns
Change-Id: I98f57a6a0178bb7258d82f3a165127f060f42f7b
Implements: blueprint mistral-ui
| Python | apache-2.0 | openstack/mistral-dashboard,openstack/mistral-dashboard,openstack/mistral-dashboard | ---
+++
@@ -34,7 +34,8 @@
class TaskTable(tables.DataTable):
id = tables.Column("id", verbose_name=_("ID"))
name = tables.Column("name", verbose_name=_("Name"))
- action = tables.Column("action", verbose_name=_("Action"))
+ parameters = tables.Column("parameters", verbose_name=_("Parameters"))
+ o... |
557cf0bc733c49e973a12bd14fb596af6a7fb5ff | refugeedata/admin.py | refugeedata/admin.py | from django.contrib import admin
from refugeedata import models, forms
class NumberAdmin(admin.ModelAdmin):
list_display = ("number", "short_id", "active")
class BatchAdmin(admin.ModelAdmin):
list_display = ("registration_number_format", "data_file")
def get_form(self, request, obj=None, **kwargs):
... | from django.core.management import call_command
from django.contrib import admin
from refugeedata import models, forms
class NumberAdmin(admin.ModelAdmin):
list_display = ("number", "short_id", "active")
class BatchAdmin(admin.ModelAdmin):
list_display = ("registration_number_format", "data_file")
d... | Call export_card_data on batch save | Call export_card_data on batch save
| Python | mit | ukch/refugeedata,ukch/refugeedata,ukch/refugeedata,ukch/refugeedata | ---
+++
@@ -1,3 +1,4 @@
+from django.core.management import call_command
from django.contrib import admin
from refugeedata import models, forms
@@ -24,8 +25,8 @@
form.cleaned_data["registration_numbers"] = (
models.RegistrationNumber.objects.filter(
id__in=[n.id ... |
a4fa3b9866ac9712f029c7cabe64121f80875207 | biobox_cli/main.py | biobox_cli/main.py | """
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a D... | """
biobox - A command line interface for running biobox Docker containers
Usage:
biobox <command> <biobox_type> <image> [<args>...]
Options:
-h, --help Show this screen.
-v, --version Show version.
Commands:
run Run a biobox Docker image with input parameters
verify Verify that a D... | Use str methods instead of string module | Use str methods instead of string module
| Python | mit | bioboxes/command-line-interface,pbelmann/command-line-interface,michaelbarton/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface,pbelmann/command-line-interface | ---
+++
@@ -17,7 +17,7 @@
short_read_assembler Assemble short reads into contigs
"""
-import sys, string
+import sys
from fn import F
@@ -35,5 +35,5 @@
"""
return fn.thread([
sys.argv[1:],
- F(map, string.strip),
+ F(map, str.strip),
F(filter, fn.is_not_empty)... |
a6804dd0baefbbd9681edc2f0ba0ec13e84f5cc3 | nimp/utilities/paths.py | nimp/utilities/paths.py | # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, ... | # -*- coding: utf-8 -*-
import os
import os.path
import sys
import fnmatch
import glob
from nimp.utilities.logging import *
from nimp.utilities.system import *
#-------------------------------------------------------------------------------
def split_path(path):
splitted_path = []
while True:
(path, ... | Fix case where path is None in sanitize_path | Fix case where path is None in sanitize_path
| Python | mit | dontnod/nimp | ---
+++
@@ -26,6 +26,9 @@
def sanitize_path(path):
+ if path is None:
+ return None
+
if is_windows() and not is_msys():
if path[0:1] == '/' and path[1:2].isalpha() and path[2:3] == '/':
return '%s:\\%s' % (path[1], path[3:].replace('/', '\\')) |
65c22394fad7929a7de1e78be7569a2895915dc9 | protocols/admin.py | protocols/admin.py | from django.contrib import admin
from .models import Protocol, Topic, Institution
class ProtocolAdmin(admin.ModelAdmin):
list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution']
list_display_links = ['number']
list_filter = ['institution__name',... | from django.contrib import admin
from .models import Protocol, Topic, Institution
class ProtocolAdminIndex(admin.ModelAdmin):
list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution']
list_display_links = ['number']
list_filter = ['institution__n... | Add Topics index page customization | Add Topics index page customization
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | ---
+++
@@ -2,7 +2,7 @@
from .models import Protocol, Topic, Institution
-class ProtocolAdmin(admin.ModelAdmin):
+class ProtocolAdminIndex(admin.ModelAdmin):
list_display = ['number', 'start_time', 'get_topics', 'information', 'majority', 'current_majority', 'institution']
list_display_links = ['numb... |
22326bdd9265d8ae97055cbcc1f64939dd6bfcda | reviewboard/notifications/templatetags/markdown_email.py | reviewboard/notifications/templatetags/markdown_email.py | from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
... | from __future__ import unicode_literals
import markdown
from django import template
from django.utils.safestring import mark_safe
from djblets.markdown import markdown_unescape
register = template.Library()
@register.filter
def markdown_email_html(text, is_rich_text):
if not is_rich_text:
return text
... | Remove a legacy Markdown extension when generating e-mails. | Remove a legacy Markdown extension when generating e-mails.
The recent updates for using Python-Markdown 3.x removed the
`smart_strong` extension from the main Markdown procssing, but failed to
remove it for the list of extensions used in e-mails. This is a trivial
change that simply removes that entry.
| Python | mit | reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,reviewboard/reviewboard,chipx86/reviewboard,chipx86/reviewboard | ---
+++
@@ -25,7 +25,6 @@
'markdown.extensions.codehilite',
'markdown.extensions.tables',
'markdown.extensions.sane_lists',
- 'markdown.extensions.smart_strong',
'pymdownx.tilde',
'djblets.markdown.extensions.escape_html',
'djble... |
681cc1dc53851a2d127b4c00fc4e7d9e54bd8fba | cms/envs/devstack_docker.py | cms/envs/devstack_docker.py | """ Overrides for Docker-based devstack. """
from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import
# Docker does not support the syslog socket at /dev/log. Rely on the console.
LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
'class': 'logging.NullHandler',
}
LOGGIN... | """ Overrides for Docker-based devstack. """
from .devstack import * # pylint: disable=wildcard-import, unused-wildcard-import
# Docker does not support the syslog socket at /dev/log. Rely on the console.
LOGGING['handlers']['local'] = LOGGING['handlers']['tracking'] = {
'class': 'logging.NullHandler',
}
LOGGIN... | Set LMS_BASE setting for Studio | Set LMS_BASE setting for Studio
This allows previews in LMS to work properly.
ECOM-6634
| Python | agpl-3.0 | jolyonb/edx-platform,ahmedaljazzar/edx-platform,proversity-org/edx-platform,raccoongang/edx-platform,edx/edx-platform,hastexo/edx-platform,fintech-circle/edx-platform,Stanford-Online/edx-platform,eduNEXT/edunext-platform,jolyonb/edx-platform,eduNEXT/edx-platform,ESOedX/edx-platform,a-parhom/edx-platform,prarthitm/edxpl... | ---
+++
@@ -13,6 +13,9 @@
SITE_NAME = HOST
LMS_ROOT_URL = 'http://{}:18000'.format(HOST)
+# This is the public-facing host used for previews
+LMS_BASE = 'localhost:18000'
+
OAUTH_OIDC_ISSUER = '{}/oauth2'.format(LMS_ROOT_URL)
JWT_AUTH.update({ |
594cd5d490786bbbdcf877d8c155530c36acd2c1 | src/services/TemperatureMonitor/src/temperature.py | src/services/TemperatureMonitor/src/temperature.py | import smbus
class TemperatureSensor:
temp_history = []
last_temp = 0
def __init__(self, address):
self.bus = smbus.SMBus(1)
self.address = address
def get_temp(self):
MSB = self.bus.read_byte_data(self.address, 0)
LSB = self.bus.read_byte_data(self.address, 1)
... | import smbus
class TemperatureSensor:
temp_history = []
last_temp = 0
def __init__(self, address):
self.bus = smbus.SMBus(1)
self.address = address
def get_temp(self):
MSB = self.bus.read_byte_data(self.address, 0)
LSB = self.bus.read_byte_data(self.address, 1)
... | Remove Smoothing From Temp Sensor | Remove Smoothing From Temp Sensor
| Python | mit | IAPark/PITherm | ---
+++
@@ -16,16 +16,4 @@
temp = ((MSB << 8 | LSB) >> 4) * 0.0625
result = temp
- # smooth the data slightly
- history_length = 3
-
- for t in self.temp_history:
- if abs(t - temp) > 0.2:
- result = self.last_temp
- break
-
- se... |
70f5a3fd7e28c574912a0318eba83f11789c2c7b | ankieta/contact/urls.py | ankieta/contact/urls.py | from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from . import views
urlpatterns = patterns('',
url(r'^$', views.ContactView.as_view(), name="form"),
url(r'^success$', TemplateView.as_view(template_name="contact/success.html"), name="success"),
)
| from django.conf.urls import patterns, url
from django.views.generic import TemplateView
from . import views
urlpatterns = patterns('',
url(r'^$', views.ContactView.as_view(), name="form"),
url(r'^/success$', TemplateView.as_view(template_name="contact/success.html"), name="success"),
)
| Fix URLS in contact form | Fix URLS in contact form
| Python | bsd-3-clause | watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl,watchdogpolska/prezydent.siecobywatelska.pl | ---
+++
@@ -4,6 +4,6 @@
urlpatterns = patterns('',
url(r'^$', views.ContactView.as_view(), name="form"),
- url(r'^success$', TemplateView.as_view(template_name="contact/success.html"), name="success"),
+ url(r'^/success$', TemplateView.as_view(template_name="contact/success.html"), name="success"),
) |
72d33ea47458cace13dac920ce2a82e55f83caba | statsmodels/stats/tests/test_outliers_influence.py | statsmodels/stats/tests/test_outliers_influence.py | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime, get_rdataset
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools imp... | from numpy.testing import assert_almost_equal
from statsmodels.datasets import statecrime
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.outliers_influence import variance_inflation_factor
from statsmodels.tools import add_consta... | Add pandas dataframe capability in variance_inflation_factor | ENH: Add pandas dataframe capability in variance_inflation_factor
| Python | bsd-3-clause | bashtage/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,bashtage/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,josef-pkt/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,basht... | ---
+++
@@ -1,6 +1,6 @@
from numpy.testing import assert_almost_equal
-from statsmodels.datasets import statecrime, get_rdataset
+from statsmodels.datasets import statecrime
from statsmodels.regression.linear_model import OLS
from statsmodels.stats.outliers_influence import reset_ramsey
from statsmodels.stats.o... |
e787e4981441198e2b015b1b4f4971fbc112c78b | cyder/base/eav/utils.py | cyder/base/eav/utils.py | import re
from django.core.exceptions import ValidationError
default_validator = lambda x: x != '' # FIXME: Do we need this?
def validate_list(value, validator=default_validator, separator=',',
strip_whitespace=True, min_length=0, die=False):
"""Validate a "list" of things
separator: the ch... | import re
from django.core.exceptions import ValidationError
default_validator = lambda x: x != '' # FIXME: Do we need this?
def validate_list(value, validator=default_validator, separator=',',
strip_whitespace=True, min_length=0, die=False):
"""Validate a "list" of things
separator: the ch... | Fix yet another stupid mistake | Fix yet another stupid mistake
| Python | bsd-3-clause | akeym/cyder,murrown/cyder,murrown/cyder,murrown/cyder,zeeman/cyder,drkitty/cyder,drkitty/cyder,murrown/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,akeym/cyder,akeym/cyder,OSU-Net/cyder,OSU-Net/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,zeeman/cyder | ---
+++
@@ -41,7 +41,7 @@
def is_hex_byte_sequence(value):
- return validate_list(value, _hex_byte, separator=':',
+ return validate_list(value, is_hex_byte, separator=':',
strip_whitespace=False)
|
295fc64b8fac9852e92356f61ff4698e011c798e | seam/util.py | seam/util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" util.py
Utility functions/constants across seam
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
import sys
PY2 = sys.version_info[0] == 2
if PY2:
STRING_TYPE = basestring
el... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" util.py
Utility functions/constants across seam
"""
__author__ = 'Scott Burns <scott.s.burns@vanderbilt.edu>'
__copyright__ = 'Copyright 2014 Vanderbilt University. All Rights Reserved'
import sys
PY2 = sys.version_info[0] == 2
if PY2:
STRING_TYPE = basestring
el... | Make xvfb e files end with .err | Make xvfb e files end with .err
| Python | mit | VUIIS/seam,VUIIS/seam | ---
+++
@@ -30,7 +30,7 @@
parts = ['xvfb-run',
'-a', # automatically get a free server number
'-f {}'.format(get_tmp_filename()),
- '-e {}'.format(get_tmp_filename()),
+ '-e {}'.format(get_tmp_filename(ext='err')),
'--wait={:d}'.format(wait),
'--server-args="{}"'... |
d18c715f8f0d86d58fcec4df8710f0370ff87308 | channels/worker.py | channels/worker.py | from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
... | from __future__ import unicode_literals
import logging
import time
from .message import Message
from .utils import name_that_thing
logger = logging.getLogger('django.channels')
class Worker(object):
"""
A "worker" process that continually looks for available messages to run
and runs their consumers.
... | Fix core logging when no message on channel | Fix core logging when no message on channel
| Python | bsd-3-clause | Krukov/channels,Coread/channels,Krukov/channels,raiderrobert/channels,Coread/channels,andrewgodwin/django-channels,andrewgodwin/channels,linuxlewis/channels,django/channels,raphael-boucher/channels | ---
+++
@@ -26,12 +26,12 @@
channels = self.channel_layer.registry.all_channel_names()
while True:
channel, content = self.channel_layer.receive_many(channels, block=True)
- logger.debug("Worker got message on %s: repl %s", channel, content.get("reply_channel", "none"))
... |
da3c8b01512466e8b0c71a239378b8643d5384ef | tests/state_tests.py | tests/state_tests.py | """
state_tests.py
"""
import os
from os.path import splitext
from minicps.state import SQLiteState
def test_SQLiteState():
# TODO: change to /tmp when install SQLitesutdio in ubuntu
PATH = "temp/state_test_db.sqlite"
# sqlite use text instead of VARCHAR
SCHEMA = """
CREATE TABLE state_test (
... | """
state_tests.py
"""
import os
from os.path import splitext
from minicps.state import SQLiteState
def test_SQLiteState():
# TODO: change to /tmp when install SQLitesutdio in ubuntu
PATH = "temp/state_test_db.sqlite"
# sqlite use text instead of VARCHAR
SCHEMA = """
CREATE TABLE state_test (
... | Use same tagname but different scope | Use same tagname but different scope
| Python | mit | remmihsorp/minicps,scy-phy/minicps,remmihsorp/minicps,scy-phy/minicps | ---
+++
@@ -26,6 +26,7 @@
SCHEMA_INIT = """
INSERT INTO state_test VALUES ('SENSOR1', 'int', '0', 1);
INSERT INTO state_test VALUES ('SENSOR2', 'float', '0.0', 1);
+ INSERT INTO state_test VALUES ('SENSOR3', 'int', '0.0', 1);
INSERT INTO state_test VALUES ('SENSOR3', 'int', '0.0... |
c820e3ed4d78b975a6bdff54a2ecae26354ae10e | tests/test_itunes.py | tests/test_itunes.py | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functionality.
"""
def test_pa... | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value
class ITunesTests(unittest.TestCase):
"""
Test cases for iTunes functiona... | Add `parse_value` test for AppleScript dates | Add `parse_value` test for AppleScript dates
Added a test case to `parse_value` to parse dates returned in
AppleScript responses.
| Python | mit | adanoff/iTunesTUI | ---
+++
@@ -8,6 +8,7 @@
"""
import unittest
+from datetime import datetime
from itunes.itunes import parse_value
@@ -24,3 +25,5 @@
self.assertIsNone(parse_value(""))
self.assertIsNone(parse_value('""'))
self.assertIsNone(parse_value("missing value"))
+ self.assertEquals(pars... |
d69b137bd19e0363173b120ff4f68becc6be7b3c | mama_cas/tests/backends.py | mama_cas/tests/backends.py | from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class ExceptionBackend(ModelBackend):
"""Raise an exception on authentication for testing purposes."""
def authenticate(self, username=None, password=None):
raise Exception
class CaseInsensitiveBackend(... | from django.contrib.auth.backends import ModelBackend
from mama_cas.compat import get_user_model
class ExceptionBackend(ModelBackend):
"""Raise an exception on authentication for testing purposes."""
def authenticate(self, username=None, password=None):
raise Exception
class CaseInsensitiveBackend(... | Use get_user_model within test backend | Use get_user_model within test backend
| Python | bsd-3-clause | orbitvu/django-mama-cas,harlov/django-mama-cas,forcityplatform/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,forcityplatform/django-mama-cas,jbittel/django-mama-cas,harlov/django-mama-cas | ---
+++
@@ -1,5 +1,6 @@
from django.contrib.auth.backends import ModelBackend
-from django.contrib.auth.models import User
+
+from mama_cas.compat import get_user_model
class ExceptionBackend(ModelBackend):
@@ -11,9 +12,10 @@
class CaseInsensitiveBackend(ModelBackend):
"""A case-insenstitive authenticatio... |
46077269450f98505308736251b3f08ed3c6827f | scripts/poweron/DRAC.py | scripts/poweron/DRAC.py | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | import subprocess, sys, os.path
class DRAC_NO_SUPP_PACK(Exception):
"""Base Exception class for all transfer plugin errors."""
def __init__(self, *args):
Exception.__init__(self, *args)
class DRAC_POWERON_FAILED(Exception):
"""Base Exception class for all transfer plugin errors."""
def... | Change path to the supplemental pack | CA-40618: Change path to the supplemental pack
Signed-off-by: Javier Alvarez-Valle <cf4c8668a0b4c5e013f594a6940d05b3d4d9ddcf@citrix.com>
| Python | lgpl-2.1 | Frezzle/xen-api,vasilenkomike/xen-api,simonjbeaumont/xen-api,euanh/xen-api,cheng-z/xen-api,jjd27/xen-api,vasilenkomike/xen-api,rafalmiel/xen-api,robertbreker/xen-api,koushikcgit/xen-api,huizh/xen-api,agimofcarmen/xen-api,cheng--zhang/xen-api,salvocambria/xen-api,jjd27/xen-api,djs55/xen-api,thomassa/xen-api,huizh/xen-ap... | ---
+++
@@ -18,7 +18,7 @@
return run.returncode, out, err
-drac_path='/usr/sbin/racadm'
+drac_path='/opt/dell/srvadmin/sbin/racadm'
def DRAC( power_on_ip, user, password):
if( not os.path.exists(drac_path)):
raise DRAC_NO_SUPP_PACK() |
1fe22f9750c618ede99f9b0a0d088aa67b7929a1 | stock_available_unreserved/models/quant.py | stock_available_unreserved/models/quant.py | # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
stri... | # Copyright 2018 Camptocamp SA
# Copyright 2016-19 ForgeFlow S.L. (https://www.forgeflow.com)
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockQuant(models.Model):
_inherit = "stock.quant"
contains_unreserved = fields.Boolean(
stri... | Fix compute contains_unreserved on NewId records | [FIX] Fix compute contains_unreserved on NewId records
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse | ---
+++
@@ -17,6 +17,10 @@
@api.depends("product_id", "location_id", "quantity", "reserved_quantity")
def _compute_contains_unreserved(self):
for record in self:
+ # Avoid error when adding a new line on manually Update Quantity
+ if isinstance(record.id, models.NewId):
+ ... |
828b78767c17419513337ca29b5c2dab08995714 | ctypeslib/test/test_dynmodule.py | ctypeslib/test/test_dynmodule.py | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def tearDown(self):
for fnm in glob.glob(stdio._gen_basename + ".*"):
try:
os.remove(fnm)
except IOError:
... | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def test_fopen(self):
self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING... | Remove now useless TearDown method. | Remove now useless TearDown method.
git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@53797 6015fed2-1504-0410-9fe1-9d1591cc4771
| Python | mit | trolldbois/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib | ---
+++
@@ -6,12 +6,6 @@
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
- def tearDown(self):
- for fnm in glob.glob(stdio._gen_basename + ".*"):
- try:
- os.remove(fnm)
- except IOError:
- pass
def test_fopen(self):
... |
ddb79d01e7ae0c840a3f3181a600aae34613c4e5 | login_token/models.py | login_token/models.py | import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
... | import random
import re
from django.contrib.auth.models import User
from django.db import models
from instances.models import InstanceMixin
NUMBER_OF_TOKEN_WORDS = 3
def generate_token():
def useful_word(w):
# FIXME: should try to exclude offensive words
if len(w) < 4:
return False
... | Add a __repr__ method for LoginToken | Add a __repr__ method for LoginToken
| Python | agpl-3.0 | opencorato/sayit,opencorato/sayit,opencorato/sayit,opencorato/sayit | ---
+++
@@ -40,3 +40,9 @@
def regenerate_token(self):
token = generate_token()
token.save()
+
+ def __repr__(self):
+ repr_format = '<LoginToken: "%s" user="%s" instance="%s">'
+ return repr_format % (self.token,
+ self.user.username,
+ ... |
23e3197f15d13445defe6ec7cfb4f08484089068 | tests/test_scripts/test_simulate_data.py | tests/test_scripts/test_simulate_data.py | import json
import numpy as np
from click.testing import CliRunner
from fastimgproto.scripts.simulate_data import cli as sim_cli
def test_simulate_data():
runner = CliRunner()
with runner.isolated_filesystem():
output_filename = 'simdata.npz'
result = runner.invoke(sim_cli,
... | import json
import numpy as np
from click.testing import CliRunner
from fastimgproto.scripts.simulate_data import cli as sim_cli
def test_simulate_data():
runner = CliRunner()
with runner.isolated_filesystem():
output_filename = 'simdata.npz'
result = runner.invoke(sim_cli,
... | Use few nsteps for testing sim-script | Use few nsteps for testing sim-script
| Python | apache-2.0 | SKA-ScienceDataProcessor/FastImaging-Python,SKA-ScienceDataProcessor/FastImaging-Python | ---
+++
@@ -11,7 +11,9 @@
output_filename = 'simdata.npz'
result = runner.invoke(sim_cli,
- [output_filename,])
+ [output_filename,
+ '--nstep','5'
+ ])
assert result.... |
5972644fe7d0267849440d8e60509baba6e013a3 | test/test_exception.py | test/test_exception.py | from mock import MagicMock
import pyaem
import unittest
class TestPyAemException(unittest.TestCase):
def test_init(self):
exception = pyaem.PyAemException(123, 'somemessage')
self.assertEqual(exception.code, 123)
self.assertEqual(exception.message, 'somemessage')
if __name__ == '__main__':
unittes... | import pyaem
import unittest
class TestException(unittest.TestCase):
def test_init(self):
exception = pyaem.PyAemException(123, 'somemessage')
self.assertEqual(exception.code, 123)
self.assertEqual(exception.message, 'somemessage')
if __name__ == '__main__':
unittest.main() | Rename class name to be consistent with file name. Remove unused import. | Rename class name to be consistent with file name. Remove unused import.
| Python | mit | Sensis/pyaem,wildone/pyaem | ---
+++
@@ -1,8 +1,7 @@
-from mock import MagicMock
import pyaem
import unittest
-class TestPyAemException(unittest.TestCase):
+class TestException(unittest.TestCase):
def test_init(self): |
dfea77df6e6ba27bada1c80da6efab392507736b | forklift/services/satellite.py | forklift/services/satellite.py | #
# Copyright 2014 Infoxchange Australia
#
# 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... | #
# Copyright 2014 Infoxchange Australia
#
# 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... | Fix making threads daemonic on Python 3.2 | Fix making threads daemonic on Python 3.2
| Python | apache-2.0 | infoxchange/docker-forklift,infoxchange/docker-forklift | ---
+++
@@ -38,8 +38,8 @@
target=target,
args=args,
kwargs=kwargs,
- daemon=True,
)
+ payload.daemon = True
payload.start()
# Cannot wait for the process that's not our child |
d41af20b1bdf5b630962a2e474b5d9c7ed62cd5c | nuxeo-drive-client/nxdrive/gui/resources.py | nuxeo-drive-client/nxdrive/gui/resources.py | """Helper to lookup UI resources from package"""
import re
import os
from nxdrive.logging_config import get_logger
log = get_logger(__name__)
def find_icon(icon_filename):
"""Find the FS path of an icon on various OS binary packages"""
import nxdrive
nxdrive_path = os.path.dirname(nxdrive.__file__)
... | """Helper to lookup UI resources from package"""
import os
from nxdrive.logging_config import get_logger
from nxdrive.utils import find_resource_dir
log = get_logger(__name__)
def find_icon(icon_filename):
"""Find the FS path of an icon in various OS binary packages"""
import nxdrive
nxdrive_path = os.p... | Use generic resource directory finder for icon files | NXP-12694: Use generic resource directory finder for icon files
| Python | lgpl-2.1 | arameshkumar/base-nuxeo-drive,IsaacYangSLA/nuxeo-drive,rsoumyassdi/nuxeo-drive,arameshkumar/nuxeo-drive,ssdi-drive/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/nuxeo-drive,arameshkumar/base-nuxeo-drive,DirkHoffmann/nuxeo-drive,loopingz/nuxeo-drive,rsoumyassdi/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/nuxeo... | ---
+++
@@ -1,35 +1,26 @@
"""Helper to lookup UI resources from package"""
-import re
import os
from nxdrive.logging_config import get_logger
+from nxdrive.utils import find_resource_dir
log = get_logger(__name__)
def find_icon(icon_filename):
- """Find the FS path of an icon on various OS binary pack... |
72dea9616a84cefd8424f965060552c84cfd241d | tests/test_luabject.py | tests/test_luabject.py | try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCOb... | try:
import unittest2 as unittest
except ImportError:
import unittest
from village import _luabject
class TestDirect(unittest.TestCase):
def test_new(self):
state = _luabject.new()
# PyCObject isn't available to assertIsInstance, so:
self.assertEqual(type(state).__name__, 'PyCOb... | Test unrunnable script exceptions too | Test unrunnable script exceptions too
| Python | mit | markpasc/luabject,markpasc/luabject | ---
+++
@@ -33,5 +33,13 @@
with self.assertRaises(ValueError):
_luabject.load_script(state, "1+1")
- # Can load a syntactically correct script even after loading an incorrect script raises an exception.
+ # Can load a syntactically correct script even after a load_script() except... |
9f20f232a9507f0002adc682a87bb792f6fbdd4e | django_plim/template.py | django_plim/template.py | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
from functools import partial
from django.conf import settings
from plim import preprocessor as plim_preprocessor
from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
lookup = TemplateLookup(directories=settings.TEMPLATE_DIRS)
Templat... | #!/usr/bin/env python
#-*- coding: UTF-8 -*-
from functools import partial
from django.conf import settings
from plim import preprocessor as plim_preprocessor
from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
from django.template.loaders import app_directories
lookup = Templa... | Add example code copied from django doc | Add example code copied from django doc
| Python | mit | imom0/django-plim | ---
+++
@@ -7,8 +7,26 @@
from plim import preprocessor as plim_preprocessor
from mako.template import Template as MakoTemplate
from mako.lookup import TemplateLookup
+from django.template.loaders import app_directories
lookup = TemplateLookup(directories=settings.TEMPLATE_DIRS)
Template = partial(MakoTemplat... |
c53824a3427235c814cfe35c5c85fd5e1e312b40 | i3/.config/i3/scripts/lock_screen/lock_screen.py | i3/.config/i3/scripts/lock_screen/lock_screen.py | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
curr... | #!/usr/bin/env python
from subprocess import check_call, CalledProcessError
from tempfile import NamedTemporaryFile
from dpms import DPMS
from mss import mss
from PIL import Image, ImageFilter
GAUSSIAN_BLUR_RADIUS = 5
SCREEN_TIMEOUT = (5, 5, 5) # Standby, Suspend, Off
# Get current DPMS settings
dpms = DPMS()
curr... | Remove call to GetTimeouts() after SetTimeouts() | i3: Remove call to GetTimeouts() after SetTimeouts()
Fixed in commit 72e984a54049c77208546b8565cece100e87be48 from
m45t3r/python-dpms.
| Python | mit | m45t3r/dotfiles,m45t3r/dotfiles,m45t3r/dotfiles | ---
+++
@@ -29,7 +29,6 @@
img.save(tempfile.name, optimize=False, compress_level=1)
# Set monitor timeout to SCREEN_TIMEOUT
dpms.SetTimeouts(*SCREEN_TIMEOUT)
- dpms.GetTimeouts()
try:
# Load image in i3lock
check_call(["i3lock", "-nei", tempfile.name])
@@ -39,4 +38,3 @@
f... |
55c72a5297244ba51fba5ebc5b71efc3001e0dd4 | otz/__init__.py | otz/__init__.py | from otz.Timestream import CalibrationTimestream, CapturedTimestream
from otz.Calibration import Calibration
| from otz.Timestream import CalibrationTimestream, CapturedTimestream
from otz.Calibration import Calibration
from otz.Beam import Beam, Bead
| Add Beam, Bead to main module | Add Beam, Bead to main module
| Python | unlicense | ghallsimpsons/optical_tweezers | ---
+++
@@ -1,2 +1,3 @@
from otz.Timestream import CalibrationTimestream, CapturedTimestream
from otz.Calibration import Calibration
+from otz.Beam import Beam, Bead |
cd75c139910e8968e5262d0f0f5289119b258f21 | phileo/views.py | phileo/views.py | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | from django.contrib.auth.decorators import login_required
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponse
from django.utils import simplejson as json
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_POST
from phil... | Remove user from count query to show likes count for all users for obj | Remove user from count query to show likes count for all users for obj
| Python | mit | pinax/phileo,jacobwegner/phileo,rizumu/pinax-likes,rizumu/pinax-likes,jacobwegner/phileo,pinax/pinax-likes,pinax/phileo | ---
+++
@@ -35,7 +35,6 @@
if request.is_ajax():
return HttpResponse(json.dumps({
"likes_count": Like.objects.filter(
- sender = request.user,
receiver_content_type = content_type,
receiver_object_id = object_id
).count() |
8b0e39eec8a82fd3f5a424ec75678426b2bf523e | cinder/version.py | cinder/version.py | # Copyright 2011 OpenStack Foundation
#
# 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 l... | # Copyright 2011 OpenStack Foundation
#
# 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 l... | Remove runtime dep on python-pbr, python-d2to1 | Remove runtime dep on python-pbr, python-d2to1
Requires RPM spec to fill in REDHATCINDERVERSION.
| Python | apache-2.0 | alex8866/cinder,alex8866/cinder | ---
+++
@@ -12,12 +12,22 @@
# License for the specific language governing permissions and limitations
# under the License.
-from pbr import version as pbr_version
-
CINDER_VENDOR = "OpenStack Foundation"
CINDER_PRODUCT = "OpenStack Cinder"
CINDER_PACKAGE = None # OS distro package version suffix
load... |
9c6739830ea8ccfbe697bc691de001a42f01f9c6 | serial_protocol/test.py | serial_protocol/test.py | import serial
import time
import binascii
import struct
def establishConnection():
# Define Constants
SERIAL_DEVICE = "/dev/ttyACM0"
# Establish Connection
ser = serial.Serial(SERIAL_DEVICE, 9600)
time.sleep(2)
print("Connection Established")
return ser
# Each motor speed is a float from -1.0 to 1.0
d... | import serial
import time
import binascii
import struct
def establishConnection():
# Define Constants
SERIAL_DEVICE = "/dev/ttyACM0"
# Establish Connection
ser = serial.Serial(SERIAL_DEVICE, 9600)
time.sleep(2)
print("Connection Established")
return ser
# Each motor speed is a float from -1.0 to 1.0
d... | Write each byte at a time in protocol | Write each byte at a time in protocol
| Python | mit | zacharylawrence/ENEE408I-Team-9,zacharylawrence/ENEE408I-Team-9,zacharylawrence/ENEE408I-Team-9 | ---
+++
@@ -20,23 +20,34 @@
print("Incorrectly formated drive command!")
return;
+ # Write OpCode
ser.write('1')
- #ser.write('0' if left >= 0 else '1')
- #ser.write(struct.pack("B", abs(left) * 255))
- #ser.write('0' if right >= 0 else '1')
- #ser.write(struct.pack("B", abs(right) * 255))
- se... |
1503bf01903f088d812a9cb38a4ce7582e063a58 | gaphor/misc/tests/test_gidlethread.py | gaphor/misc/tests/test_gidlethread.py | import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.02 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result =... | import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.05 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result =... | Fix test flakiness by changing timeout to a longer value | Fix test flakiness by changing timeout to a longer value
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -10,11 +10,11 @@
@pytest.fixture
def gidle_counter(request):
- # Setup GIdle Thread with 0.02 sec timeout
+ # Setup GIdle Thread with 0.05 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
- wait_result = t.wait(0.02)
+ wait_result = t.wait(0.0... |
072bc480cbc489cd89d03405026f152934893b7e | go/routers/keyword/view_definition.py | go/routers/keyword/view_definition.py | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... | from django import forms
from go.router.view_definition import RouterViewDefinitionBase, EditRouterView
class KeywordForm(forms.Form):
keyword = forms.CharField()
target_endpoint = forms.CharField()
class BaseKeywordFormSet(forms.formsets.BaseFormSet):
@staticmethod
def initial_from_config(data):
... | Revert "Remove unnecessary and broken DELETE check." | Revert "Remove unnecessary and broken DELETE check."
This reverts commit 7906153b4718f34ed31c193a8e80b171e567209c.
Reverting commit accidentally commited straight to develop.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go | ---
+++
@@ -17,7 +17,7 @@
def to_config(self):
keyword_endpoint_mapping = {}
for form in self:
- if not form.is_valid():
+ if (not form.is_valid()) or form.cleaned_data['DELETE']:
continue
keyword = form.cleaned_data['keyword']
ta... |
2867ea119a846e1eb61c64a206058dc0d28d090b | src/foremast/utils/check_task.py | src/foremast/utils/check_task.py | """Check Taskid status."""
import logging
import requests
from tryagain import retries
from ..exceptions import SpinnakerTaskError
HEADERS = {'Content-Type': 'application/json', 'Accept': '*/*'}
GATE_URL = "http://gate-api.build.example.com:8084"
LOG = logging.getLogger(__name__)
@retries(max_attempts=10, wait=10,... | """Check Taskid status."""
import logging
import requests
from tryagain import retries
from ..consts import API_URL, HEADERS
from ..exceptions import SpinnakerTaskError
LOG = logging.getLogger(__name__)
@retries(max_attempts=10, wait=10, exceptions=(AssertionError, ValueError))
def check_task(taskid, app_name):
... | Use global API_URL and HEADERS | refactor: Use global API_URL and HEADERS
See also: PSOBAT-1197
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast | ---
+++
@@ -4,10 +4,9 @@
import requests
from tryagain import retries
+from ..consts import API_URL, HEADERS
from ..exceptions import SpinnakerTaskError
-HEADERS = {'Content-Type': 'application/json', 'Accept': '*/*'}
-GATE_URL = "http://gate-api.build.example.com:8084"
LOG = logging.getLogger(__name__)
@... |
939998db349c364aa0f5ba4705d4feb2da7104d5 | nn/flags.py | nn/flags.py | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | import functools
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("batch-size", 64, "")
tf.app.flags.DEFINE_float("dropout-prob", 0, "")
tf.app.flags.DEFINE_string("word-file", None, "")
tf.app.flags.DEFINE_integer("num-threads-per-queue", 2, "")
tf.app.flags.DEFINE_integer("queue-capac... | Fix float type flag definition | Fix float type flag definition
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | ---
+++
@@ -12,7 +12,7 @@
tf.app.flags.DEFINE_integer("queue-capacity", 2, "")
tf.app.flags.DEFINE_string("length-boundaries", "", "")
tf.app.flags.DEFINE_string("rnn-cell", "ln_lstm", "Default RNN cell")
-tf.app.flags.DEFINE_string("float32", "", "")
+tf.app.flags.DEFINE_string("float-type", "float32", "")
@... |
10db5e8b893a84e765162535f64e1ede81d48b47 | empty_check.py | empty_check.py | from django.core.exceptions import ValidationError
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| from django.core.exceptions import ValidationError
# Usage example in a custom form
# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0:
raise ValidationError("Value cannot be empty")
| Add comment to show usage example | Add comment to show usage example | Python | mit | vishalsodani/django-empty-check-validator | ---
+++
@@ -1,5 +1,7 @@
from django.core.exceptions import ValidationError
+# Usage example in a custom form
+# firstname = forms.CharField(validators = [EmptyCheck()])
class EmptyCheck(object):
def __call__(self, value):
if len(value.strip()) == 0: |
34812fe2deec64229efd4119640f3c2ddf0ed415 | visualize.py | visualize.py | '''
Create a visual representation of the various DAGs defined
'''
import sys
import requests
import networkx as nx
import matplotlib.pyplot as plt
if __name__ == '__main__':
g = nx.DiGraph()
labels = {
'edges': {},
'nodes': {},
}
nodes = {}
for routeKey, routeMap in requests.ge... | '''
Create a visual representation of the various DAGs defined
'''
import sys
import requests
import networkx as nx
import matplotlib.pyplot as plt
if __name__ == '__main__':
g = nx.DiGraph()
labels = {
'edges': {},
'nodes': {},
}
for routeKey, routeMap in requests.get(sys.argv[1]).j... | Make the sprint layout a bit easier to look at | Make the sprint layout a bit easier to look at
| Python | mit | jacksontj/dnms,jacksontj/dnms | ---
+++
@@ -15,8 +15,6 @@
'nodes': {},
}
- nodes = {}
-
for routeKey, routeMap in requests.get(sys.argv[1]).json().iteritems():
for i, node in enumerate(routeMap['Path']):
g.add_node(node['Name'])
@@ -26,11 +24,16 @@
labels['edges'][(routeMap['Path'][i-1]... |
67a230dd5673601f2e1f1a8c3deb8597f29287db | src/tmlib/workflow/align/args.py | src/tmlib/workflow/align/args.py | from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
r... | from tmlib.workflow.args import BatchArguments
from tmlib.workflow.args import SubmissionArguments
from tmlib.workflow.args import Argument
from tmlib.workflow import register_batch_args
from tmlib.workflow import register_submission_args
@register_batch_args('align')
class AlignBatchArguments(BatchArguments):
r... | Increase default batch size for align step | Increase default batch size for align step
| Python | agpl-3.0 | TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary,TissueMAPS/TmLibrary | ---
+++
@@ -21,7 +21,7 @@
)
batch_size = Argument(
- type=int, default=10, flag='b',
+ type=int, default=100, flag='b',
help='number of image files that should be processed per job'
)
|
057510c78f80c3592c562006413049ab1292d0a3 | ipaqe_provision_hosts/backend/base.py | ipaqe_provision_hosts/backend/base.py | # author: Milan Kubik
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
class IDMBackendException(Exception):
pass
class VMsNotCreatedError(IDMBackendException):
pass
class IDMBackendMissingName(IDMBackendException):
pass
class IDMBackendBase(object):
"""IDMBackendBase class... | # author: Milan Kubik
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
class VMsNotCreatedError(IPAQEProvisionerError):
pass
class IDMBackendBase(object):
"""IDMBackendBase class
This class represents a contract b... | Replace the exceptions in backend classes | Replace the exceptions in backend classes
| Python | mit | apophys/ipaqe-provision-hosts | ---
+++
@@ -2,15 +2,10 @@
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
-
-class IDMBackendException(Exception):
- pass
+from ipaqe_provision_hosts.errors import IPAQEProvisionerError
-class VMsNotCreatedError(IDMBackendException):
- pass
-
-class IDMBackendMissingName(IDMBacke... |
ecde3e00de3782024f0dfbab7f2d7912ab62342b | src/birding/__init__.py | src/birding/__init__.py | from __future__ import absolute_import, print_function
import logging
from . import bolt, config, follow, search, spout, twitter_api
from .search import SearchManager
from .twitter_api import Twitter
from .version import VERSION, __version__
from .version import __doc__ as __license__
__all__ = [
'SearchManager... | from __future__ import absolute_import, print_function
import logging
from . import bolt, config, follow, search, spout, twitter_api
from .version import VERSION, __version__
from .version import __doc__ as __license__
__all__ = [
'VERSION',
'__license__',
'__version__',
'bolt',
'config',
'f... | Remove unnecessary objects from root namespace. | Remove unnecessary objects from root namespace.
| Python | apache-2.0 | Parsely/birding,Parsely/birding | ---
+++
@@ -3,15 +3,11 @@
import logging
from . import bolt, config, follow, search, spout, twitter_api
-from .search import SearchManager
-from .twitter_api import Twitter
from .version import VERSION, __version__
from .version import __doc__ as __license__
__all__ = [
- 'SearchManager',
- 'Twitter'... |
8a43cf58791a665a4fc23bc5d0911af61f7e1fb6 | qipr_approver/approver/views/similar_projects.py | qipr_approver/approver/views/similar_projects.py | from django.shortcuts import redirect
from approver.workflows import project_crud
from approver.decorators import login_required
import approver.utils as utils
from django.core.urlresolvers import reverse
@login_required
def similar_projects(request, project_id=None,from_page=None):
project = project_crud.ge... | from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from approver.workflows import project_crud
import approver.utils as utils
@login_required
def similar_projects(request, project_id=None,from_page=None):
project = project... | Add shib auth to similar projects page | Add shib auth to similar projects page
| Python | apache-2.0 | DevMattM/qipr_approver,DevMattM/qipr_approver,ctsit/qipr_approver,ctsit/qipr_approver,ctsit/qipr_approver,DevMattM/qipr_approver,DevMattM/qipr_approver,PFWhite/qipr_approver,DevMattM/qipr_approver,PFWhite/qipr_approver,ctsit/qipr_approver,PFWhite/qipr_approver,ctsit/qipr_approver,PFWhite/qipr_approver,PFWhite/qipr_appr... | ---
+++
@@ -1,13 +1,14 @@
from django.shortcuts import redirect
+from django.core.urlresolvers import reverse
+from django.contrib.auth.decorators import login_required
from approver.workflows import project_crud
-from approver.decorators import login_required
+
import approver.utils as utils
-from django.core.u... |
1e574befc82b7df53fe62b9c5089772172f99178 | apps/reactions/serializers.py | apps/reactions/serializers.py | from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
from rest_framework.fields import HyperlinkedIdentityField
class ReactionAuthorSerializer(serializers.ModelSerializ... | from apps.bluebottle_utils.serializers import SorlImageField, SlugHyperlinkedIdentityField
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Reaction
from rest_framework.fields import HyperlinkedIdentityField
class ReactionAuthorSerializer(serializers.ModelSerializ... | Add id to API reponse for Reaction. | Add id to API reponse for Reaction.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | ---
+++
@@ -25,11 +25,11 @@
class Meta:
model = Reaction
- fields = ('created', 'author', 'reaction')
+ fields = ('created', 'author', 'reaction', 'id')
class ReactionListSerializer(ReactionDetailSerializer):
class Meta:
model = Reaction
- fields = ('created',... |
896b385f983ecf939bdc2ea938b9949fdc3fdbb8 | colorise/color_tools.py | colorise/color_tools.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for converting and comparing colors."""
import colorsys
import math
import operator
def hls_to_rgb(hue, lightness, saturation):
"""Convert HLS (hue, lightness, saturation) values to RGB."""
return tuple(int(math.ceil(c * 255.))
for ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Functions for converting and comparing colors."""
import colorsys
import math
import operator
def hls_to_rgb(hue, lightness, saturation):
"""Convert HLS (hue, lightness, saturation) values to RGB."""
return tuple(int(math.ceil(c * 255.))
for ... | Remove unused color distance function | Remove unused color distance function
| Python | bsd-3-clause | MisanthropicBit/colorise | ---
+++
@@ -27,14 +27,6 @@
return sum(abs(i - j) for i, j in zip(rgb1, rgb2))
-def color_distance(rgb1, rgb2):
- """Compute the Euclidian distance between two colors."""
- r1, g1, b1 = rgb1
- r2, g2, b2 = rgb2
-
- return math.sqrt((r2 - r1)**2 + (g2 - g1)**2 + (b2 - b1)**2)
-
-
def closest_color... |
1c0644d5629008c98f8402b95b797beea1a50bc5 | promgen/sender/__init__.py | promgen/sender/__init__.py | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
def send(self, data):
sent = 0
for alert in data['alerts']:
if 'project' in alert['labels']:
logger.debug('Checking for projects')
... | import logging
from promgen.models import Project, Service
logger = logging.getLogger(__name__)
class SenderBase(object):
MAPPING = [
('project', Project),
('service', Service),
]
def send(self, data):
sent = 0
for alert in data['alerts']:
for label, klass in... | Add a MAPPING table to remove duplicated loop logic | Add a MAPPING table to remove duplicated loop logic
| Python | mit | kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen | ---
+++
@@ -6,27 +6,25 @@
class SenderBase(object):
+ MAPPING = [
+ ('project', Project),
+ ('service', Service),
+ ]
+
def send(self, data):
sent = 0
for alert in data['alerts']:
- if 'project' in alert['labels']:
- logger.debug('Checking for ... |
e174a898595664ff291cbf8ccda0f1c404a73575 | control/server.py | control/server.py | import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, host="localhost"):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.bind((host, port))
... | import asyncore
import socket
from logging import error, info, warning
from client import Client
class Server(asyncore.dispatcher):
def __init__(self, port, connect_fn=None, msg_fn=None, close_fn=None):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
... | Remove disconnected client from clients list, allow client callbacks to be set in constructor. | Remove disconnected client from clients list, allow client callbacks to be set in constructor.
| Python | mit | zwarren/morse-car-controller,zwarren/morse-car-controller | ---
+++
@@ -6,28 +6,34 @@
class Server(asyncore.dispatcher):
- def __init__(self, port, host="localhost"):
+ def __init__(self, port, connect_fn=None, msg_fn=None, close_fn=None):
asyncore.dispatcher.__init__(self)
self.create_socket()
self.set_reuse_addr()
- self.bind((ho... |
91720739af3c7b35e331949cdd64a98023e23799 | parkings/api/public/parking_area.py | parkings/api/public/parking_area.py | from rest_framework import viewsets
from rest_framework_gis.pagination import GeoJsonPagination
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from parkings.models import ParkingArea
class ParkingAreaSerializer(GeoFeatureModelSerializer):
wgs84_areas = Geometr... | from rest_framework import viewsets
from rest_framework_gis.pagination import GeoJsonPagination
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from parkings.models import ParkingArea
from ..common import WGS84InBBoxFilter
class ParkingAreaSerializer(GeoFeatureMod... | Add bbox to parking area view set | Add bbox to parking area view set
| Python | mit | tuomas777/parkkihubi | ---
+++
@@ -3,6 +3,8 @@
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField
from parkings.models import ParkingArea
+
+from ..common import WGS84InBBoxFilter
class ParkingAreaSerializer(GeoFeatureModelSerializer):
@@ -24,3 +26,6 @@
queryset = ParkingArea.o... |
d52034eddeb510acc367c87c88e4277994157338 | githubsetupircnotifications.py | githubsetupircnotifications.py | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import getpass
import sys
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argumen... | Create the hook for each repo | Create the hook for each repo
| Python | mit | kragniz/github-setup-irc-notifications | ---
+++
@@ -15,6 +15,7 @@
parser.add_argument('--username')
parser.add_argument('--password')
parser.add_argument('--org')
+ parser.add_argument('--channel')
args = parser.parse_args()
if args.password is None:
@@ -34,3 +35,21 @@
if org is None:
print('Organization "{}" doe... |
ed4c80aa8e9ee628876c3cc96907ca407ee4ff5d | backend/scripts/ddirdenorm.py | backend/scripts/ddirdenorm.py | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | #!/usr/bin/env python
import rethinkdb as r
import optparse
if __name__ == "__main__":
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="rethinkdb port", default=30815)
(options, args) = parser.parse_args()
conn = r.connect('localhost', int(op... | Handle non-existent files in the database. | Handle non-existent files in the database.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -22,6 +22,8 @@
ddir['datafiles'] = []
for dfid in datadir['datafiles']:
datafile = r.table('datafiles').get(dfid).run(conn)
+ if datafile is None:
+ continue
df = {}
df['id'] = datafile['id']
df['name'] = datafi... |
e7627ee439e2e4f17466bf124629ae353460a68d | __init__.py | __init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2012 OpenERP - Team de Localización Argentina.
# https://launchpad.net/~openerp-l10n-ar-localization
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of t... | Change product types are really dangerous!!! | [FIX] Change product types are really dangerous!!! | Python | agpl-3.0 | odoo-l10n-ar/l10n_ar_invoice | ---
+++
@@ -28,6 +28,5 @@
import country
import report
import currency
-import product
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
abea9151ce3f97033038102b4b01e84b66b8b670 | __init__.py | __init__.py | ###
# Copyright (c) 2007, Max Kanat-Alexander
# All rights reserved.
#
#
###
"""
Interact with Bugzilla installations.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
_... | ###
# Copyright (c) 2007, Max Kanat-Alexander
# All rights reserved.
#
#
###
"""
Interact with Bugzilla installations.
"""
import supybot
import supybot.world as world
# Use this for the version of this plugin. You may wish to put a CVS keyword
# in here if you're keeping the plugin in CVS or some similar system.
_... | Make the bot reload its secondary modules when you reload the plugin. | Make the bot reload its secondary modules when you reload the plugin.
| Python | bsd-3-clause | aleb/supybot-bugzilla | ---
+++
@@ -30,6 +30,9 @@
import config
import plugin
reload(plugin) # In case we're being reloaded.
+reload(bugmail)
+reload(traceparser)
+
# Add more reloads here if you add third-party modules and want them to be
# reloaded when this plugin is reloaded. Don't forget to import them as well!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.