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 |
|---|---|---|---|---|---|---|---|---|---|---|
03d942731f970984bf039c531bff080affbb3b34 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Rajat Agarwal
from setuptools import setup, find_packages
import sqoot
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambd... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# (c) 2014 Rajat Agarwal
from setuptools import setup, find_packages
import sqoot
# Work around mbcs bug in distutils.
# http://bugs.python.org/issue10945
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambd... | Update the version number after last change | Update the version number after last change
| Python | mit | ragarwal6397/sqoot | ---
+++
@@ -18,7 +18,7 @@
setup(
name='sqoot',
- version='20140727',
+ version='20140923',
author='Rajat Agarwal',
author_email='rajatagarwal@alumni.purdue.edu',
url='https://github.com/ragarwal6397', |
841cb6e54c40ee745e69f8e0d538024a40e113c2 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-template-tests',
url="https://chris-lamb.co.uk/projects/django-template-tests",
version='1.0.0',
description="Performs some quick static analysis on your templates",
author="Chris Lamb",
author_email="chris... | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-template-tests',
url="https://chris-lamb.co.uk/projects/django-template-tests",
version='1.0.0',
description="Performs some quick static analysis on your templates",
author="Chris Lamb",
author_email="chris... | Update Django requirement to latest LTS | Update Django requirement to latest LTS
| Python | bsd-3-clause | lamby/django-template-tests | ---
+++
@@ -15,4 +15,8 @@
packages=find_packages(),
include_package_data=True,
+
+ install_requires=(
+ 'Django>=1.8',
+ ),
) |
6f3b45cd6b5558a7d81472c0298aae7d04f64846 | jsonit/utils.py | jsonit/utils.py | import os
from django.http import HttpResponse
from django.template import RequestContext, loader
def ajax_aware_render(request, template_list, extra_context=None, **kwargs):
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
new_template_list = []... | import os
from django.http import HttpResponse
from django.template import RequestContext, loader
def ajax_aware_render(request, template_list, extra_context=None, **kwargs):
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
ajax_template_list = [... | Change the ordering of templates to pick from for the ajax render helper | Change the ordering of templates to pick from for the ajax render helper
| Python | bsd-3-clause | lincolnloop/django-jsonit | ---
+++
@@ -8,11 +8,10 @@
if isinstance(template_list, basestring):
template_list = [template_list]
if request.is_ajax():
- new_template_list = []
+ ajax_template_list = []
for name in template_list:
- new_template_list.append('%s.ajax.%s' % os.path.splitext(name))... |
253e4e9df1b6a6cec7c20bc34a8ccf9423c8018e | scripts/create_neurohdf.py | scripts/create_neurohdf.py | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 1
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(fil... | #!/usr/bin/python
# Create a project and stack associated HDF5 file with additional
# data such as labels, meshes etc.
import os.path as op
import h5py
from contextlib import closing
import numpy as np
project_id = 1
stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(fil... | Change in coordinates in the NeuroHDF create | Change in coordinates in the NeuroHDF create
| Python | agpl-3.0 | htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID | ---
+++
@@ -9,13 +9,13 @@
import numpy as np
project_id = 1
-stack_id = 1
+stack_id = 2
filepath = '/home/stephan/dev/CATMAID/django/hdf5'
with closing(h5py.File(op.join(filepath, '%s_%s.hdf' % (project_id, stack_id)), 'w')) as hfile:
mesh=hfile.create_group('meshes')
midline=mesh.create_group('midl... |
a134179d143f05842315a134f0a744f61003d2ca | tests.py | tests.py | #!/usr/bin/env python
from datetime import date
import os
import sys
argv = sys.argv
if '-w' not in argv and '--where' not in argv:
argv[1:1] = ['-w', 'tests']
if '--logging-level' not in argv:
argv[1:1] = ['--logging-level', 'INFO']
try:
import nose
except ImportError:
print('Could not find the nose ... | #!/usr/bin/env python
from datetime import date
import os
import sys
argv = sys.argv
if '-w' not in argv and '--where' not in argv:
argv[1:1] = ['-w', 'tests']
if '--logging-level' not in argv:
argv[1:1] = ['--logging-level', 'INFO']
try:
import nose
except ImportError:
print('Could not find the nose ... | Use nose.main instead of nose.run. | Use nose.main instead of nose.run.
| Python | apache-2.0 | mikekap/batchy | ---
+++
@@ -16,4 +16,4 @@
sys.exit(1)
print('Running nosetests %s' % ' '.join(argv[1:]))
-nose.run(argv=argv)
+nose.main(argv=argv) |
f06c7813663dc9ac4bf63601574617acf5d7324d | tests.py | tests.py | from models import AuthenticationError,AuthenticationRequired
import trello
import unittest
import os
class TestTrello(unittest.TestCase):
def test_login(self):
username = os.environ['TRELLO_TEST_USER']
password = os.environ['TRELLO_TEST_PASS']
try:
trello.login(username, password)
except AuthenticationEr... | from models import AuthenticationError,AuthenticationRequired
from trello import Trello
import unittest
import os
class BoardTestCase(unittest.TestCase):
def setUp(self):
self._trello = Trello(os.environ['TRELLO_TEST_USER'], os.environ['TRELLO_TEST_PASS'])
def test01_list_boards(self):
print "list boards"
se... | Add some more test cases | Add some more test cases
| Python | bsd-3-clause | mehdy/py-trello,sarumont/py-trello,nMustaki/py-trello,Wooble/py-trello,ntrepid8/py-trello,WoLpH/py-trello,portante/py-trello,merlinpatt/py-trello,gchp/py-trello | ---
+++
@@ -1,19 +1,32 @@
from models import AuthenticationError,AuthenticationRequired
-import trello
+from trello import Trello
import unittest
import os
-class TestTrello(unittest.TestCase):
+class BoardTestCase(unittest.TestCase):
- def test_login(self):
- username = os.environ['TRELLO_TEST_USER']
- pass... |
14f3df107a2b129ff7f22c849de2aa19326db074 | worker.py | worker.py | import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
... | import os
class Worker():
def __init__(self,job,name):
self.fn = job
self.name = name
def do(self,timestamp):
pid = None
try:
print('[{timestamp}] {name}'.format(timestamp=timestamp,name=self.name))
pid = os.fork()
if pid == 0:
... | Add temporary error logging for debugging | Add temporary error logging for debugging
Now just print out the Exception message for debugging,
it will change to logging in the future
| Python | apache-2.0 | stvreumi/electronic-blackboard,stvreumi/electronic-blackboard,stvreumi/electronic-blackboard,SWLBot/electronic-blackboard,Billy4195/electronic-blackboard,Billy4195/electronic-blackboard,SWLBot/electronic-blackboard,stvreumi/electronic-blackboard,SWLBot/electronic-blackboard,SWLBot/electronic-blackboard,Billy4195/electr... | ---
+++
@@ -16,6 +16,8 @@
else:
return 0
except Exception as e:
+ #TODO logging the error message
+ print(str(e))
if pid is not None and pid == 0: # child fn() raise exception
exit(1)
else: # fork fail |
f2ef48c3b1753e4b53b86c1f9d7a3da517a6d136 | web/impact/impact/models/utils.py | web/impact/impact/models/utils.py | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import re
LABEL_LENGTH = 255
def is_managed(db_table):
return False
def model_name_to_snake(value):
original_model_string = re.findall('[A-Z][^A-Z]*', value)
holder = ""
for word in original_model_string:
holder += word.lower() + "_"
... | # MIT License
# Copyright (c) 2017 MassChallenge, Inc.
import re
from django.utils.text import camel_case_to_spaces
LABEL_LENGTH = 255
def is_managed(db_table):
return False
def model_name_to_snake(value):
original_model_string = camel_case_to_spaces(value)
new_model_string = original_model_string.rep... | Remove Custom Reegex And Use Django Util For Case Conversion | [AC-5010] Remove Custom Reegex And Use Django Util For Case Conversion
This commit uses the django built in to switch from camel case to lower case. Then the loop was removed in favor of replace().
| Python | mit | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | ---
+++
@@ -2,6 +2,7 @@
# Copyright (c) 2017 MassChallenge, Inc.
import re
+from django.utils.text import camel_case_to_spaces
LABEL_LENGTH = 255
@@ -11,11 +12,8 @@
def model_name_to_snake(value):
- original_model_string = re.findall('[A-Z][^A-Z]*', value)
- holder = ""
- for word in original_m... |
28bf565f30a6d9b25bd6bc24ce5958a98a106161 | mpi/__init__.py | mpi/__init__.py | #! /usr/bin/env python
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def finalize():
return MPI.Finalize()
| #! /usr/bin/env python
from mpi4py import MPI
comm = MPI.COMM_WORLD
def get_host():
return MPI.Get_processor_name()
def get_rank():
return comm.Get_rank()
def host_rank_mapping():
"""Get host to rank mapping
Return dictionary mapping ranks to host
"""
d = {}
for (host, rank) in com... | Add function to get the host-rank mapping of mpi tasks | Add function to get the host-rank mapping of mpi tasks
| Python | mit | IanLee1521/utilities | ---
+++
@@ -14,5 +14,18 @@
return comm.Get_rank()
+def host_rank_mapping():
+ """Get host to rank mapping
+
+ Return dictionary mapping ranks to host
+ """
+ d = {}
+ for (host, rank) in comm.allgather((get_host(), get_rank())):
+ if host not in d:
+ d[host] = []
+ d[h... |
67a5eb0921f746c205e555ae296b6c15e4eb7eab | property_transformation.py | property_transformation.py | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... | Add support for null values in property mapping | Add support for null values in property mapping
| Python | mit | OpenBounds/Processing | ---
+++
@@ -20,6 +20,8 @@
raise PropertyMappingFailedException(
"Found mapping, but no key specified to map")
source_value = source_properties[value['key']]
+ if source_value is None:
+ source_value = "null"
... |
71a417d2558776cd29195c1a1b905070a08407b5 | proteus/config/__init__.py | proteus/config/__init__.py | import platform
if platform.node().startswith('garnet') or platform.node().startswith('copper'):
from garnet import *
else:
from default import * | import os
if 'HOSTNAME' in os.environ:
if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'):
from garnet import *
else:
from default import * | Correct detection on Garnet/Copper compute nodes | Correct detection on Garnet/Copper compute nodes
| Python | mit | erdc/proteus,erdc/proteus,erdc/proteus,erdc/proteus | ---
+++
@@ -1,6 +1,7 @@
-import platform
+import os
-if platform.node().startswith('garnet') or platform.node().startswith('copper'):
- from garnet import *
+if 'HOSTNAME' in os.environ:
+ if os.environ['HOSTNAME'].startswith('garnet') or os.environ['HOSTNAME'].startswith('copper'):
+ from garnet impor... |
633c52cf90655981d1adc962d7571d5d67619ccb | genome_designer/genome_finish/contig_display_utils.py | genome_designer/genome_finish/contig_display_utils.py | from collections import namedtuple
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
return (contig.parent_reference_genome.get_client_jbrowse_link() +
'&loc=' + str(loc))
def decorate_with_link_to_loc(contig, lo... | from collections import namedtuple
import settings
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
sample_alignment = contig.experiment_sample_to_alignment
bam_dataset = sample_alignment.dataset_set.get(
type='BWA ... | Include more tracks in jbrowsing of junctions | Include more tracks in jbrowsing of junctions
| Python | mit | churchlab/millstone,churchlab/millstone,woodymit/millstone,woodymit/millstone,woodymit/millstone,churchlab/millstone,woodymit/millstone,churchlab/millstone | ---
+++
@@ -1,17 +1,30 @@
from collections import namedtuple
+
+import settings
+
Junction = namedtuple('Junction',
['ref', 'ref_count', 'contig', 'contig_count'])
def get_ref_jbrowse_link(contig, loc):
- return (contig.parent_reference_genome.get_client_jbrowse_link() +
- '&lo... |
bbe425da10607692c1aace560b1b61b089137704 | frappe/patches/v12_0/rename_events_repeat_on.py | frappe/patches/v12_0/rename_events_repeat_on.py | import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", ... | import frappe
from frappe.utils import get_datetime
def execute():
weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
weekly_events = frappe.get_list("Event", filters={"repeat_this_event": 1, "repeat_on": "Every Week"}, fields=["name", "starts_on"])
frappe.reload_doc("desk", ... | Convert to SQL to set_value | fix: Convert to SQL to set_value | Python | mit | mhbu50/frappe,saurabh6790/frappe,vjFaLk/frappe,almeidapaulopt/frappe,vjFaLk/frappe,frappe/frappe,almeidapaulopt/frappe,vjFaLk/frappe,mhbu50/frappe,mhbu50/frappe,StrellaGroup/frappe,StrellaGroup/frappe,almeidapaulopt/frappe,adityahase/frappe,adityahase/frappe,yashodhank/frappe,almeidapaulopt/frappe,mhbu50/frappe,yashodh... | ---
+++
@@ -15,4 +15,4 @@
for weekly_event in weekly_events:
# Set WeekDay based on the starts_on so that event can repeat Weekly
- frappe.db.sql("""UPDATE `tabEvent` SET `tabEvent`.{0}=1 WHERE `tabEvent`.name='{1}'""".format(weekdays[get_datetime(weekly_event.starts_on).weekday()], weekly_event.name))
+ fra... |
468f41f0bf734cdbb27dea7b5d910b6234f4c21a | homedisplay/control_milight/management/commands/run_timed.py | homedisplay/control_milight/management/commands/run_timed.py | from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Com... | from control_milight.models import LightAutomation
from control_milight.views import update_lightstate
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django.utils.timezone import now
from ledcontroller import LedController
import datetime
import redis
class Com... | Add support for weekend animations | Add support for weekend animations
| Python | bsd-3-clause | ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display,ojarva/home-info-display | ---
+++
@@ -21,10 +21,10 @@
if not item.is_running(time):
continue
percent_done = item.percent_done(time)
- if item.action == "evening":
+ if item.action == "evening" or item.action == "evening-weekend":
print "Setting evening brightnes... |
18a3b758311174d0be2519789f985d8113438c90 | tests/test_dirty_mark.py | tests/test_dirty_mark.py | def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
def test_set_parent(nested_config):
nested_config.root.value += 1
assert nested_config.is_dirty()
def test_set_child(nested_config):
nested_config.root.a.value += 1
asser... | from confetti import Config
def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
def test_set_parent(nested_config):
nested_config.root.value += 1
assert nested_config.is_dirty()
def test_set_child(nested_config):
nested_con... | Add test for extending not being marked as dirty | Add test for extending not being marked as dirty
| Python | bsd-3-clause | vmalloc/confetti | ---
+++
@@ -1,3 +1,6 @@
+from confetti import Config
+
+
def test_not_dirty_by_default(nested_config):
assert not nested_config.is_dirty()
assert not nested_config['a'].is_dirty()
@@ -7,13 +10,21 @@
nested_config.root.value += 1
assert nested_config.is_dirty()
+
def test_set_child(nested_confi... |
22e41d02d9c877703f21c5121202d295cb5fbcb0 | test/swig/canvas.py | test/swig/canvas.py | # RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
mgr = uwhd.GameModelManager()
print('# SET-VERSION: %d' % (version,))
print('# SET-STATE: FirstHalf')
print('# SET-BLACK: %d' % (black_score,))
print('# SET-WHITE: %d' % (white_score,))... | # RUN: python %s | display-check -
import uwhd
def main():
version = 1
black_score = 3
white_score = 5
time = 42
# Build a GameModelManager with a known state:
mgr = uwhd.GameModelManager()
mgr.setGameStateFirstHalf()
mgr.setBlackScore(black_score)
mgr.setWhiteScore(white_score)
mgr.setGameClock(... | Clean up the SWIG test. Add comments. NFC | [tests] Clean up the SWIG test. Add comments. NFC
| Python | bsd-3-clause | Navisjon/uwh-display,Navisjon/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,Navisjon/uwh-display,jroelofs/uwh-display,jroelofs/uwh-display | ---
+++
@@ -8,24 +8,25 @@
white_score = 5
time = 42
+ # Build a GameModelManager with a known state:
mgr = uwhd.GameModelManager()
+ mgr.setGameStateFirstHalf()
+ mgr.setBlackScore(black_score)
+ mgr.setWhiteScore(white_score)
+ mgr.setGameClock(time)
+ # Render that state to a canvas:
+ canvas = ... |
02d7f2b946293169e3d46f84f50f2fa801a33c95 | distarray/tests/test_client.py | distarray/tests/test_client.py | import unittest
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain vanilla context?'''
... | import unittest
import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
class TestDistArrayContext(unittest.TestCase):
def setUp(self):
self.client = Client()
self.dv = self.client[:]
def test_create_DAC(self):
'''Can we create a plain van... | Add simple failing test for DistArrayProxy getitem. | Add simple failing test for DistArrayProxy getitem. | Python | bsd-3-clause | RaoUmer/distarray,enthought/distarray,enthought/distarray,RaoUmer/distarray | ---
+++
@@ -1,4 +1,5 @@
import unittest
+import numpy as np
from IPython.parallel import Client
from distarray.client import DistArrayContext
@@ -20,5 +21,18 @@
self.assertIs(dac.view, self.dv)
+class TestDistArrayProxy(unittest.TestCase):
+
+ def setUp(self):
+ self.client = Client()
+ ... |
e99f7b6d25464f36accc2f04899edfa9e982bee2 | tests/cpydiff/core_fstring_concat.py | tests/cpydiff/core_fstring_concat.py | """
categories: Core
description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces
cause: MicroPython is optimised for code space.
workaround: Use the + operator between literal strings when either is an f-string
"""
x = 1
print("aa" f"{x}")
print(f"{x}" "ab")
print(... | """
categories: Core
description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces or are f-strings
cause: MicroPython is optimised for code space.
workaround: Use the + operator between literal strings when either or both are f-strings
"""
x, y = 1, 2
print("aa" f"{... | Clarify f-string diffs regarding concatenation. | tests/cpydiff: Clarify f-string diffs regarding concatenation.
Concatenation of any literals (including f-strings) should be avoided.
Signed-off-by: Jim Mussared <e84f5c941266186d0c97dcc873413469b954847e@gmail.com>
| Python | mit | adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython,adafruit/circuitpython | ---
+++
@@ -1,12 +1,13 @@
"""
categories: Core
-description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces
+description: f-strings don't support concatenation with adjacent literals if the adjacent literals contain braces or are f-strings
cause: MicroPython is... |
55b0d7eba281fc2c13505c956f5c23bb49b34988 | tests/test_qiniu.py | tests/test_qiniu.py | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | import os
from os.path import dirname, join
import uuid
import qiniu.conf
import qiniu.io
import qiniu.rs
import qiniu.rsf
QINIU_ACCESS_KEY = os.environ.get('QINIU_ACCESS_KEY')
QINIU_SECRET_KEY = os.environ.get('QINIU_SECRET_KEY')
QINIU_BUCKET_NAME = os.environ.get('QINIU_BUCKET_NAME')
QINIU_BUCKET_DOMAIN = os.envir... | Test with even smaller files | Test with even smaller files
| Python | mit | glasslion/django-qiniu-storage,jeffrey4l/django-qiniu-storage,Mark-Shine/django-qiniu-storage,jackeyGao/django-qiniu-storage | ---
+++
@@ -22,6 +22,7 @@
ASSET_FILE_NAME = 'jquery-1.11.1.min.js'
with open(join(dirname(__file__),'assets', ASSET_FILE_NAME), 'rb') as assset_file:
text = assset_file.read()
+ text = text[:len(text)/10]
print "Test text: %s" % text
token = QINIU_PUT_POLICY.token() |
f67704c271b8b88ba97d1b44c73552119d79b048 | tests/test_utils.py | tests/test_utils.py | import pickle
from six.moves import range
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_pickable", "bulky_attr")
class TestClass(object):
def __init__(self):
self.load()
def load(self):
self.bulky_attr = list(range(100))
self.non_pickable = lambda x: ... | from numpy.testing import assert_raises, assert_equal
from six.moves import range, cPickle
from fuel.iterator import DataIterator
from fuel.utils import do_not_pickle_attributes
@do_not_pickle_attributes("non_picklable", "bulky_attr")
class DummyClass(object):
def __init__(self):
self.load()
def loa... | Increase test coverage in utils.py | Increase test coverage in utils.py
| Python | mit | chrishokamp/fuel,ejls/fuel,harmdevries89/fuel,glewis17/fuel,EderSantana/fuel,rodrigob/fuel,markusnagel/fuel,bouthilx/fuel,janchorowski/fuel,aalmah/fuel,vdumoulin/fuel,rodrigob/fuel,orhanf/fuel,laurent-dinh/fuel,rizar/fuel,capybaralet/fuel,aalmah/fuel,hantek/fuel,mila-udem/fuel,janchorowski/fuel,hantek/fuel,dmitriy-serd... | ---
+++
@@ -1,24 +1,50 @@
-import pickle
-from six.moves import range
+from numpy.testing import assert_raises, assert_equal
+from six.moves import range, cPickle
+from fuel.iterator import DataIterator
from fuel.utils import do_not_pickle_attributes
-@do_not_pickle_attributes("non_pickable", "bulky_attr")
-cl... |
527d460289cb574528f70a2a6c530e86627eb81a | framework/archiver/listeners.py | framework/archiver/listeners.py | from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyEr... | from framework.tasks.handlers import enqueue_task
from framework.archiver.tasks import archive, send_success_message
from framework.archiver.utils import (
link_archive_provider,
)
from framework.archiver import (
ARCHIVER_SUCCESS,
ARCHIVER_FAILURE,
)
from framework.archiver.exceptions import ArchiverCopyEr... | Use list comp instead of unnecessary dict comp | Use list comp instead of unnecessary dict comp
| Python | apache-2.0 | pattisdr/osf.io,ticklemepierce/osf.io,billyhunt/osf.io,wearpants/osf.io,mluo613/osf.io,ckc6cz/osf.io,doublebits/osf.io,aaxelb/osf.io,chrisseto/osf.io,amyshi188/osf.io,abought/osf.io,DanielSBrown/osf.io,adlius/osf.io,Nesiehr/osf.io,laurenrevere/osf.io,monikagrabowska/osf.io,kwierman/osf.io,amyshi188/osf.io,reinaH/osf.io... | ---
+++
@@ -31,8 +31,8 @@
"""
if not dst.archiving:
return
- pending = {key: value for key, value in dst.archived_providers.iteritems() if value['status'] not in (ARCHIVER_SUCCESS, ARCHIVER_FAILURE)}
- if not len(pending):
+ pending = [value for value in dst.archived_providers.values() if ... |
8a80e33c80732fc03ba2293e1b1219407c3c634c | frameworks/Perl/dancer/setup.py | frameworks/Perl/dancer/setup.py | import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dance... | import subprocess
import sys
import setup_util
from os.path import expanduser
import os
import getpass
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
setup_util.replace_text("dance... | Update dancer's nginx.conf to find new test root | Update dancer's nginx.conf to find new test root
| Python | bsd-3-clause | joshk/FrameworkBenchmarks,sgml/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,Eyepea/FrameworkBenchmarks,steveklabnik/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,testn/FrameworkBenchmarks,RockinRoel/FrameworkBenchmarks,Synchro/FrameworkBenchmarks,nbrady-techempower/Framework... | ---
+++
@@ -8,7 +8,7 @@
def start(args, logfile, errfile):
setup_util.replace_text("dancer/app.pl", "localhost", args.database_host)
setup_util.replace_text("dancer/nginx.conf", "USR", getpass.getuser())
- setup_util.replace_text("dancer/nginx.conf", "server unix:.*\/FrameworkBenchmarks", "server unix:" + arg... |
7932f3b5c3be34a37c82b1b6f08db63dc2f0eee7 | lib/rapidsms/webui/urls.py | lib/rapidsms/webui/urls.py | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os
urlpatterns = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
# iterate each of the active rapidsms apps (from the ini),
# and (attempt to) import the urls.py from each. it's okay
# if t... | #!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
import os, sys
urlpatterns = []
loaded = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
# iterate each of the active rapidsms apps (from the ini),
# and (attempt to) import the urls.py from each. it... | Print a list of which URLs got loaded. This doesn't help that much when trying to debug errors that keep URLs from getting loaded. But it's a start. | Print a list of which URLs got loaded. This doesn't help that much when
trying to debug errors that keep URLs from getting loaded. But it's a
start.
| Python | bsd-3-clause | dimagi/rapidsms-core-dev,eHealthAfrica/rapidsms,unicefuganda/edtrac,ehealthafrica-ci/rapidsms,peterayeni/rapidsms,lsgunth/rapidsms,unicefuganda/edtrac,ken-muturi/rapidsms,rapidsms/rapidsms-core-dev,ehealthafrica-ci/rapidsms,eHealthAfrica/rapidsms,caktus/rapidsms,dimagi/rapidsms,lsgunth/rapidsms,dimagi/rapidsms-core-dev... | ---
+++
@@ -1,16 +1,14 @@
#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
-import os
-
+import os, sys
urlpatterns = []
-
+loaded = []
# load the rapidsms configuration
from rapidsms.config import Config
conf = Config(os.environ["RAPIDSMS_INI"])
-
# iterate each of the active rapidsms apps (from the... |
1e082f8c39dd1a1d41064f522db10478b0c820e1 | icekit/page_types/layout_page/page_type_plugins.py | icekit/page_types/layout_page/page_type_plugins.py | from django.conf.urls import patterns, url
from fluent_pages.extensions import page_type_pool
from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin
from fluent_pages.models import UrlNode
from . import admin, models
# Register this plugin to the page plugin pool.
@page_type_... | from django.conf.urls import patterns, url
from fluent_pages.extensions import page_type_pool
from fluent_pages.integration.fluent_contents.page_type_plugins import FluentContentsPagePlugin
from fluent_pages.models import UrlNode
from . import admin, models
# Register this plugin to the page plugin pool.
@page_type_... | Add smart template render method to LayoutPage | Add smart template render method to LayoutPage
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -12,3 +12,8 @@
model = models.LayoutPage
model_admin = admin.LayoutPageAdmin
+ def get_render_template(self, request, fluentpage, **kwargs):
+ # Allow subclasses to easily override it by specifying `render_template` after all.
+ # The default, is to use the template_path from t... |
95b6035b82ffeee73bbde953e5d036c50fa4fa8c | unit_tests/test_analyse_idynomics.py | unit_tests/test_analyse_idynomics.py | from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
sel... | from nose.tools import *
from analyse_idynomics import *
from os.path import join, dirname, realpath
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
expected_timesteps = 2
expected_dimensions = (20.0, 20.0, 2.0)
def setUp(self):
self... | Add unit tests for timesteps and dimensions | Add unit tests for timesteps and dimensions
| Python | mit | fophillips/pyDynoMiCS | ---
+++
@@ -5,6 +5,8 @@
class TestAnalyseiDynomics:
expected_solutes = ['MyAtmos', 'pressure']
expected_species = ['MyBact']
+ expected_timesteps = 2
+ expected_dimensions = (20.0, 20.0, 2.0)
def setUp(self):
self.directory = join(dirname(realpath(__file__)), 'test_data')
@@ -20,3... |
d5a00553101dd3d431dd79494b9b57cfa56cb4be | worker.py | worker.py | import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
q = Queue(name=queue_name, connection=Redis())
def enqueue(*args, **kwargs):
q.enqueue(*args, **kwargs)
| import os
from redis import Redis
from rq import Queue
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
# `srm` can take a long time on large files, so allow it run for up to an hour
q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enqueue(*args, **kwargs):
... | Increase job timeout for securely deleting files | Increase job timeout for securely deleting files
| Python | agpl-3.0 | mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code,mark-in/securedrop-app-code | ---
+++
@@ -5,7 +5,8 @@
queue_name = 'test' if os.environ.get('SECUREDROP_ENV') == 'test' else 'default'
-q = Queue(name=queue_name, connection=Redis())
+# `srm` can take a long time on large files, so allow it run for up to an hour
+q = Queue(name=queue_name, connection=Redis(), default_timeout=3600)
def enq... |
d32e1d8349c115027e3095d61f8fa882fca1ab52 | functions/test_lambda.py | functions/test_lambda.py | """ Explore how python works with lambda expressions. """
import unittest
import string
import random
class TestGetWebsites(unittest.TestCase):
def test_closure(self, m):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
... | """ Explore how python works with lambda expressions. """
import unittest
import string
import random
class TestGetWebsites(unittest.TestCase):
def test_closure(self):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
... | Add a test to generate a range of functions with closures. Check if it returns the expected value | Add a test to generate a range of functions with closures. Check if it returns the expected value
| Python | mit | b-ritter/python-notes,b-ritter/python-notes | ---
+++
@@ -5,15 +5,28 @@
class TestGetWebsites(unittest.TestCase):
- def test_closure(self, m):
+ def test_closure(self):
""" See that python supports closures similar to JavaScript """
def gibberish():
""" Some random string """
return ''.join([random.choice(st... |
670a5ffe8de9f21fbb2fe65e72e006d143bfa8e3 | pirx/utils.py | pirx/utils.py | import os
def path(*p):
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p)
| import os
def path(*p):
"""Return full path of a directory inside project's root"""
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p)
| Set docstring for "path" function | Set docstring for "path" function
| Python | mit | piotrekw/pirx | ---
+++
@@ -2,6 +2,7 @@
def path(*p):
+ """Return full path of a directory inside project's root"""
import __main__
project_root = os.path.dirname(os.path.realpath(__main__.__file__))
return os.path.join(project_root, *p) |
d0b0a89a7149c5853e0e827fa819deb17699bf55 | dthm4kaiako/config/__init__.py | dthm4kaiako/config/__init__.py | """Configuration for Django system."""
__version__ = "0.9.3"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| """Configuration for Django system."""
__version__ = "0.9.4"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num
for num in __version__.replace("-", ".", 1).split(".")
]
)
| Increment version number to 0.9.4 | Increment version number to 0.9.4
| Python | mit | uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers | ---
+++
@@ -1,6 +1,6 @@
"""Configuration for Django system."""
-__version__ = "0.9.3"
+__version__ = "0.9.4"
__version_info__ = tuple(
[
int(num) if num.isdigit() else num |
384f7a8da21ca5e4ffa529e0e5f9407ce2ec0142 | backend/unichat/models/user.py | backend/unichat/models/user.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
MALE = -1
UNDEFINED = 0
FEMALE = 1
GENDER_CHOICES = (
(MALE, 'Male'),
(UNDEFINED, 'Undefined'),
(FEMALE, 'Female')
)
school = models.ForeignKey('unich... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from .managers import UserManager
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailFiel... | Change User to use Django's AbstractBaseUser | Change User to use Django's AbstractBaseUser
| Python | mit | dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet,dimkarakostas/unimeet | ---
+++
@@ -1,9 +1,36 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
+from django.contrib.auth.models import PermissionsMixin
+from django.contrib.auth.base_user import AbstractBaseUser
+from .managers import UserManager
-class User(models.Model):
+class User(Ab... |
b59d1dd5afd63422cd478d8ee519347bd1c43e3b | project/urls.py | project/urls.py | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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-based... | """share URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/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-based... | Change ember app prefix to 'share/' | Change ember app prefix to 'share/'
| Python | apache-2.0 | CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE,aaxelb/SHARE,laurenbarker/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,zamattiac/SHARE,laurenbarker/SHARE,CenterForOpenScience/SHARE,aaxelb/SHARE,zamattiac/SHARE | ---
+++
@@ -26,6 +26,6 @@
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
url(r'^accounts/', include('allauth.urls')),
- url(r'^(?P<path>app/.*)$', ProxyView.as_view(upstream=settings.EMBER_SHARE_URL)),
- url(r'^$', RedirectView.as_view(url='app/discover')),
+ url(r'^(?... |
048f2d9469b3f9eb266a343602ddf608e3bd6d86 | highton/models/email_address.py | highton/models/email_address.py | from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar addres... | from highton.models import HightonModel
from highton.highton_constants import HightonConstants
from highton import fields
class EmailAddress(
HightonModel,
):
"""
:ivar id: fields.IntegerField(name=HightonConstants.ID)
:ivar location: fields.StringField(name=HightonConstants.LOCATION)
:ivar addres... | Set EmailAddress Things to required | Set EmailAddress Things to required
| Python | apache-2.0 | seibert-media/Highton,seibert-media/Highton | ---
+++
@@ -14,7 +14,7 @@
TAG_NAME = HightonConstants.EMAIL_ADDRESS
def __init__(self, **kwargs):
- self.location = fields.StringField(name=HightonConstants.LOCATION)
- self.address = fields.StringField(name=HightonConstants.ADDRESS)
+ self.location = fields.StringField(name=HightonCo... |
a651e748164865a8ca658085819c1d978338824c | angular_flask/__init__.py | angular_flask/__init__.py | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
ap... | import os
import json
from flask import Flask, request, Response
from flask import render_template, send_from_directory, url_for
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd... | Fix path for saving imgs | Fix path for saving imgs
| Python | mit | Clarity-89/blog,Clarity-89/blog,Clarity-89/blog | ---
+++
@@ -5,12 +5,12 @@
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname('data'))
-
+basedir_img = os.path.abspath(os.path.dirname('angular_flask'))
app.config["SECRET_KEY"] = "\xed\x9c\xac\xcd4\x83k\xd1\x17\xd54\xe71\x03\xaf\xd8\x04\xe3\xcd\xaa\xf4\x97\x82\x1e"
app.config["SQLALCHEMY_DATABASE_... |
01847c64869298a436980eb17c549d49f09d6a91 | src/nodeconductor_openstack/openstack_tenant/perms.py | src/nodeconductor_openstack/openstack_tenant/perms.py | from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.service_project_link_permission_logic),
)
| from nodeconductor.core.permissions import StaffPermissionLogic
from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceProjectLink', structure_perms.servi... | Add permissions to service properties | Add permissions to service properties
- wal-94
| Python | mit | opennode/nodeconductor-openstack | ---
+++
@@ -1,7 +1,12 @@
+from nodeconductor.core.permissions import StaffPermissionLogic
from nodeconductor.structure import perms as structure_perms
PERMISSION_LOGICS = (
('openstack_tenant.OpenStackTenantService', structure_perms.service_permission_logic),
('openstack_tenant.OpenStackTenantServiceP... |
95d80b076d374ab8552e292014f9fbed08e7b6e1 | ibmcnx/menu/MenuClass.py | ibmcnx/menu/MenuClass.py | ######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
... | ######
# Class for Menus
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
class cnxMenu:
def __init__( self ):
self.menuitems = []
... | Test all scripts on Windows | 10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -19,7 +19,7 @@
self.menuitems.append( {'text': text, 'func':function} )
# Function for printing
- def Show( menutitle, self ):
+ def Show( self, menutitle ):
self.c = 1
print '\n\t' + menutitle
print '\t----------------------------------------', '\n' |
f463247198354b0af1d0b8a4ff63c0757d4c2839 | regression.py | regression.py | import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_call(["coverage", "html", "--directory", ".cover"])
| import subprocess
subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "nose"])
subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "--omit", "toyplot/testing.py", "-m", "behave"])
subprocess.check_call(["coverage", "report"])
subprocess.check_... | Exclude the testing module from coverage results. | Exclude the testing module from coverage results.
| Python | bsd-3-clause | cmorgan/toyplot,cmorgan/toyplot | ---
+++
@@ -1,6 +1,6 @@
import subprocess
-subprocess.check_call(["coverage", "run", "--source", "toyplot", "-m", "nose"])
-subprocess.check_call(["coverage", "run", "--append", "--source", "toyplot", "-m", "behave"])
+subprocess.check_call(["coverage", "run", "--source", "toyplot", "--omit", "toyplot/testing.py",... |
c458b78ccecc28971ef239de5a5366bd56d2562e | web/portal/views/home.py | web/portal/views/home.py | from flask import redirect, url_for
from portal import app
@app.route('/', methods=['GET'])
def index():
return redirect(url_for('practices_index', _external=True))
| from flask import redirect, url_for
from portal import app
@app.route('/', methods=['GET'])
def index():
return redirect(url_for('practices_index', _external=True, _scheme="https"))
| Fix incorrect protocol being using when behin reverse proxy | Fix incorrect protocol being using when behin reverse proxy
| Python | mit | LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal,LCBRU/genvasc_portal | ---
+++
@@ -3,4 +3,4 @@
@app.route('/', methods=['GET'])
def index():
- return redirect(url_for('practices_index', _external=True))
+ return redirect(url_for('practices_index', _external=True, _scheme="https")) |
8f2cf9f30b5748117a6cc98d74aa0c8493f21852 | sft/agent/ah/RunningAvg.py | sft/agent/ah/RunningAvg.py | import theano
from sft import Size
from sft.Actions import Actions
from sft.agent.ah.ActionHistory import ActionHistory
import numpy as np
class RunningAvg(ActionHistory):
def __init__(self, logger, n, factor):
self.logger = logger
self.n = n
self.factor = factor
self.actions = np.zeros([self.n, self.ACTIO... | import theano
from sft import Size
from sft.Actions import Actions
from sft.agent.ah.ActionHistory import ActionHistory
import numpy as np
class RunningAvg(ActionHistory):
def __init__(self, logger, n, factor):
self.logger = logger
self.n = n
self.factor = factor
self.actions = np.zeros([self.n, self.ACTIO... | Fix running average action history | Fix running average action history
| Python | mit | kevinkepp/search-for-this | ---
+++
@@ -21,7 +21,7 @@
return self.actions
def new_action(self, a):
- for i in range(1, self.n):
+ for i in range(1, self.n)[::-1]:
self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1]
self.actions[0, :] = Actions.get_one_hot(a)
self.logger.log_parameter("act... |
813ddc03b652d0594bc9cb540a5a5f50a196a073 | fjord/urls.py | fjord/urls.py | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus... | from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.http import HttpResponse
from funfactory.monkeypatches import patch
patch()
from django.contrib import admin
from adminplus import AdminSitePlus... | Add TODO for removing stubs | Add TODO for removing stubs
| Python | bsd-3-clause | Ritsyy/fjord,mozilla/fjord,mozilla/fjord,mozilla/fjord,rlr/fjord,DESHRAJ/fjord,Ritsyy/fjord,staranjeet/fjord,Ritsyy/fjord,staranjeet/fjord,hoosteeno/fjord,rlr/fjord,mozilla/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,rlr/fjord,DESHRAJ/fjord,lgp171188/fjord,hoosteeno/fjord,hoosteeno/fjord,staranjeet/fjord,staran... | ---
+++
@@ -20,6 +20,7 @@
(r'', include('fjord.feedback.urls')),
(r'', include('fjord.search.urls')),
+ # TODO: Remove this stub. /about and /search point to it.
url(r'stub', lambda r: HttpResponse('this is a stub'), name='stub'),
# Generate a robots.txt
@@ -36,6 +37,6 @@
)
-## In DEBU... |
980a1a40aeb5f76bc8675890237f5624920b7602 | pinax/stripe/management/commands/init_customers.py | pinax/stripe/management/commands/init_customers.py | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
... | from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from ...actions import customers
class Command(BaseCommand):
help = "Create customer objects for existing users that do not have one"
def handle(self, *args, **options):
User = get_user_model()
... | Make sure the customer has no plan nor is charged | Make sure the customer has no plan nor is charged
Stripe throws an error because we try to make a charge without having a card. Because we don't have a card for this user yet, it doesn't make sense to charge them immediately. | Python | mit | pinax/django-stripe-payments | ---
+++
@@ -11,5 +11,5 @@
def handle(self, *args, **options):
User = get_user_model()
for user in User.objects.filter(customer__isnull=True):
- customers.create(user=user)
+ customers.create(user=user, charge_immediately=False)
self.stdout.write("Created custo... |
e8708c28e79a9063469e684b5583114c69ec425f | datadog_checks_dev/datadog_checks/dev/spec.py | datadog_checks_dev/datadog_checks/dev/spec.py | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def g... | # (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def g... | Fix CI for logs E2E with v2 manifests | Fix CI for logs E2E with v2 manifests | Python | bsd-3-clause | DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core | ---
+++
@@ -15,7 +15,11 @@
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
- relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
+ assets = manifest.get('assets', {})
+ if 'integration' in assets:
+ re... |
a41d2e79dcf83793dab5c37c4a4b46ad6225d719 | anchor/names.py | anchor/names.py | """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = '~0'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE = '~1'... | """
Names of the modalities
"""
# Set constants of the names of the models so they can always be referenced
# as variables rather than strings
# Most of the density is at 0
NEAR_ZERO = 'excluded'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
NEAR_ONE ... | Use words for near zero and near one | Use words for near zero and near one
| Python | bsd-3-clause | YeoLab/anchor | ---
+++
@@ -6,13 +6,13 @@
# as variables rather than strings
# Most of the density is at 0
-NEAR_ZERO = '~0'
+NEAR_ZERO = 'excluded'
# Old "middle" modality - most of the density is at 0.5
NEAR_HALF = 'concurrent'
# Most of the density is at 1
-NEAR_ONE = '~1'
+NEAR_ONE = 'included'
# The density is spl... |
1c14d45ba620118401728c56e5ef3a189f9b4145 | samples/fire.py | samples/fire.py | from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
effects = [
Prin... | from asciimatics.renderers import FigletText, Fire
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
from pyfiglet import Figlet
import sys
def demo(screen):
scenes = []
text = Figlet(font="bann... | Fix shadow for wide screens. | Fix shadow for wide screens.
| Python | apache-2.0 | peterbrittain/asciimatics,peterbrittain/asciimatics | ---
+++
@@ -10,17 +10,18 @@
def demo(screen):
scenes = []
+ text = Figlet(font="banner", width=200).renderText("ASCIIMATICS")
+ width = max([len(x) for x in text.split("\n")])
+
effects = [
Print(screen,
- Fire(screen.height, 80,
- Figlet(font="banner", width... |
f7a8c4a293538c4cd592ba23860b873cb378f28f | pyaxiom/netcdf/dataset.py | pyaxiom/netcdf/dataset.py | #!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.v... | #!python
# coding=utf-8
from netCDF4 import Dataset
class EnhancedDataset(Dataset):
def __init__(self, *args, **kwargs):
super(EnhancedDataset, self).__init__(*args, **kwargs)
def get_variables_by_attributes(self, **kwargs):
vs = []
has_value_flag = False
for vname in self.v... | Add a close method to EnhancedDataset that won't raise a RuntimeError | Add a close method to EnhancedDataset that won't raise a RuntimeError
| Python | mit | axiom-data-science/pyaxiom,ocefpaf/pyaxiom,ocefpaf/pyaxiom,axiom-data-science/pyaxiom | ---
+++
@@ -24,3 +24,10 @@
vs.append(self.variables[vname])
return vs
+
+ def close(self):
+ try:
+ self.sync()
+ self.close()
+ except RuntimeError:
+ pass |
86968b5bc34a0c7f75ff04ad261ee59da8dcf94f | app/soc/models/host.py | app/soc/models/host.py | #!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# 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 appl... | #!/usr/bin/env python2.5
#
# Copyright 2008 the Melange authors.
#
# 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 appl... | Replace the old Host model with a new one. | Replace the old Host model with a new one.
The new Host model doesn't need the host user to have a profile.
Instead it will contain the user to whom the Host entity belongs
to as the parent of the Host entity to maintain transactionality
between User and Host updates.
--HG--
extra : rebase_source : cee68153ab1cfdb77c... | Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son | ---
+++
@@ -14,20 +14,29 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""This module contains the Host Model."""
+"""This module contains the Model for Host."""
__authors__ = [
- '"Todd Larsen" <tlarsen@google.com>',
- '"Sverre Rabbelier" <sverre@... |
f023d6e112638c58ed1e0adc764263b64f50e15a | apps/documents/urls.py | apps/documents/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^chapters/(?P<pk>\d+)/$',
views.ChapterDetailView.as_view(),
name='chapter-detail'
),
url(
r'^paragraphs/(?P<pk>\d+)/$',
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
... | from django.conf.urls import url
from . import views
urlpatterns = [
url(
r'^chapters/(?P<pk>\d+)/$',
views.ChapterDetailView.as_view(),
name='chapter-detail'
),
url(
r'^paragraphs/(?P<pk>\d+)/$',
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
... | Unify url routes to plural | Unify url routes to plural
| Python | agpl-3.0 | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | ---
+++
@@ -13,9 +13,8 @@
views.ParagraphDetailView.as_view(),
name='paragraph-detail'
),
- # url(r'^chapters/(?P<pk>\d+)/$'
url(
- r'^manage/chapter/(?P<pk>\d+)/$',
+ r'^manage/chapters/(?P<pk>\d+)/$',
views.ChapterManagementView.as_view(),
name='chapter... |
17f3a2a491f8e4d1b1b6c2644a1642f02cfada17 | apps/i4p_base/views.py | apps/i4p_base/views.py | # -*- coding: utf-8 -*-
from django.http import QueryDict
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils import translation
from apps.project_sheet.models import I4pProject
from apps.project_sheet.utils import get_project_translations_from_parents,... | # -*- coding: utf-8 -*-
from django.http import QueryDict
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils import translation
from apps.project_sheet.models import I4pProject
from apps.project_sheet.utils import get_project_translations_from_parents,... | Remove pre-selection of best-on filter | Remove pre-selection of best-on filter
| Python | agpl-3.0 | ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople,ImaginationForPeople/imaginationforpeople | ---
+++
@@ -17,8 +17,6 @@
language_code=translation.get_language()
)
data = request.GET
- if not data :
- data = QueryDict('best_of=on')
context = {'project_sheets'... |
d7b3579edf9efb48fc80290fe0cf1c9c6db3b7bc | run-quince.py | run-quince.py | #!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import *
if __name__ == "__main__":
parser = argparse.ArgumentPar... | #!C:\Users\qlab\Anaconda3\envs\pyqt5\python.exe
# coding: utf-8
# Raytheon BBN Technologies 2016
# Contributiors: Graham Rowlands
#
# This file runs the main loop
# Use PyQt5 by default
import os
os.environ["QT_API"] = 'pyqt5'
from qtpy.QtWidgets import QApplication
import sys
import argparse
from quince.view import... | Set desired qt version explicitly in run_quince.py | Set desired qt version explicitly in run_quince.py
| Python | apache-2.0 | BBN-Q/Quince | ---
+++
@@ -4,6 +4,10 @@
# Contributiors: Graham Rowlands
#
# This file runs the main loop
+
+# Use PyQt5 by default
+import os
+os.environ["QT_API"] = 'pyqt5'
from qtpy.QtWidgets import QApplication
import sys |
3b5e66f8051043e8b6863fe1b3c9fc81a13fc38c | bash_kernel/install.py | bash_kernel/install.py | import json
import os
import sys
from IPython.kernel.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"],
"display_name":"Bash",
"language":"bash",
"codemirror_mode":"shell",
"env":{"PS1": "... | import json
import os
import sys
from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"],
"display_name":"Bash",
"language":"bash",
"codemirror_mode":"shell",
"env":{"PS1": "... | Remove warning from jupyter 4 | Remove warning from jupyter 4
| Python | bsd-3-clause | newtux/KdbQ_kernel | ---
+++
@@ -2,7 +2,7 @@
import os
import sys
-from IPython.kernel.kernelspec import install_kernel_spec
+from jupyter_client.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {"argv":[sys.executable,"-m","bash_kernel", "-f", "{connection_file}"], |
4965511fdb9843233e84a8aa9aa0414bf1c02133 | mail/views.py | mail/views.py | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = re... | from django.shortcuts import redirect
from django.http import JsonResponse
from django.core.mail import EmailMessage
from django.middleware import csrf
from rest_framework.decorators import api_view
@api_view(['POST', 'GET'])
def send_contact_message(request):
if request.method == 'POST':
to_address = re... | Revert "return json of message being sent to debug mail issue" | Revert "return json of message being sent to debug mail issue"
| Python | agpl-3.0 | openstax/openstax-cms,Connexions/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,openstax/openstax-cms,Connexions/openstax-cms | ---
+++
@@ -15,25 +15,15 @@
from_string = '{} <{}>'.format(from_name, from_address)
subject = request.POST.get("subject", "")
message_body = request.POST.get("message_body", "")
- csrf_token = request.POST.get("csrfmiddlewaretoken", "")
email = EmailMessage(subject,
... |
aa5ad938c96d1c6241015e182c7aefb835f13e45 | goodtablesio/utils/frontend.py | goodtablesio/utils/frontend.py | from flask import render_template
from flask_login import current_user
from goodtablesio import settings
# Module API
def render_component(component, props=None):
"""Render frontend component within html layout.
Args:
component (str): component name
props (dict): component props
Return... | from flask import render_template
from flask_login import current_user
from goodtablesio import settings
# Module API
def render_component(component, props=None):
"""Render frontend component within html layout.
Args:
component (str): component name
props (dict): component props
Return... | Fix user name addition to props | Fix user name addition to props
| Python | agpl-3.0 | frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io,frictionlessdata/goodtables.io | ---
+++
@@ -26,10 +26,10 @@
# Common props
if props == {} or (props and 'userName' not in props):
- user_name = getattr(current_user, 'display_name',
- getattr(current_user, 'name', None))
+ user_name = getattr(current_user, 'display_name')
+ if not user_nam... |
d6c228468ad519f735a12388383b719ee9830f5e | reviewboard/notifications/evolutions/webhooktarget_extra_state.py | reviewboard/notifications/evolutions/webhooktarget_extra_state.py | from django_evolution.mutations import AddField, RenameField
from django.db import models
from djblets.db.fields import JSONField
MUTATIONS = [
AddField('WebHookTarget', 'encoding', models.CharField,
initial='application/json', max_length=40),
AddField('WebHookTarget', 'repositories', models.Many... | from django_evolution.mutations import AddField, RenameField
from django.db import models
from djblets.db.fields import JSONField
MUTATIONS = [
AddField('WebHookTarget', 'encoding', models.CharField,
initial='application/json', max_length=40),
AddField('WebHookTarget', 'repositories', models.Many... | Remove the initial value for WebHookTarget.extra_data in the evolution. | Remove the initial value for WebHookTarget.extra_data in the evolution.
The original evolution adding the WebHookTarget.extra_data had an
initial value, and even with changing that in another field, it will
still apply on existing installs. This needs to be modified in order to
allow installation on MySQL.
| Python | mit | reviewboard/reviewboard,beol/reviewboard,sgallagher/reviewboard,chipx86/reviewboard,custode/reviewboard,reviewboard/reviewboard,sgallagher/reviewboard,davidt/reviewboard,beol/reviewboard,KnowNo/reviewboard,bkochendorfer/reviewboard,davidt/reviewboard,davidt/reviewboard,chipx86/reviewboard,beol/reviewboard,reviewboard/r... | ---
+++
@@ -13,6 +13,6 @@
initial=False),
AddField('WebHookTarget', 'apply_to', models.CharField, initial='A',
max_length=1),
- AddField('WebHookTarget', 'extra_data', JSONField, initial='{}'),
+ AddField('WebHookTarget', 'extra_data', JSONField, initial=None),
RenameField(... |
05b6eaf259117cc6254e2b13c5a02569713e6356 | inbox/contacts/process_mail.py | inbox/contacts/process_mail.py | import uuid
from inbox.models import Contact, MessageContactAssociation
def update_contacts_from_message(db_session, message, account_id):
with db_session.no_autoflush:
for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'):
if getattr(message, field) is None:
continue
... | import uuid
from inbox.models import Contact, MessageContactAssociation
def update_contacts_from_message(db_session, message, account_id):
with db_session.no_autoflush:
for field in ('to_addr', 'from_addr', 'cc_addr', 'bcc_addr'):
if getattr(message, field) is None:
continue
... | Fix filtering criterion when updating contacts from message. | Fix filtering criterion when updating contacts from message.
| Python | agpl-3.0 | gale320/sync-engine,closeio/nylas,wakermahmud/sync-engine,nylas/sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,gale320/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,Eagles2F/sync-engine,nylas/sync-engine,ErinCall/sync-engine,PriviPK/privipk-sync-engine,closeio/nylas,ErinCal... | ---
+++
@@ -10,7 +10,8 @@
items = set(getattr(message, field))
for name, email_address in items:
contact = db_session.query(Contact).filter(
- Contact.email_address == email_address).first()
+ Contact.email_address == email_address,
+ ... |
523a25d30241ecdd0abdb7545b1454714b003edc | astrospam/pyastro16.py | astrospam/pyastro16.py | """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.n... | """
Python in Astronomy 2016 is the second iteration of the Python in Astronomy
conference series.
This is the docstring for the pyastro module, this gets included as the
description for the module.
"""
import numpy as np
def times(a, b):
"""
Multiply a by b.
Parameters
----------
a : `numpy.n... | Add a subclass for the dot graph | Add a subclass for the dot graph
| Python | mit | cdeil/sphinx-tutorial | ---
+++
@@ -69,3 +69,11 @@
Properties are automatically documented as attributes
"""
return self._day
+
+
+class PyAstro16(PyAstro):
+ """
+ The 2016 edition of the python in astronomy conference.
+
+ """
+ __doc__ += PyAstro.__doc__ |
aab9efbcec0bbded807bf207e2324266573fa3a6 | tensorflow/python/tf2.py | tensorflow/python/tf2.py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Remove the redundant `else` condition. | Remove the redundant `else` condition.
PiperOrigin-RevId: 302901741
Change-Id: I65281a07fc2789fbc13775c1365fd01789a1bb7e
| Python | apache-2.0 | petewarden/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,petewarden/tensorflow,paolodedios/tensorflow,aldian/tensorflow,yongtang/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experime... | ---
+++
@@ -24,7 +24,6 @@
import os
-
_force_enable = None
@@ -44,5 +43,5 @@
"""Returns True iff TensorFlow 2.0 behavior should be enabled."""
if _force_enable is None:
return os.getenv("TF2_BEHAVIOR", "0") != "0"
- else:
- return _force_enable
+
+ return _force_enable |
afd10d89ead46a8df35f6a0d17a2ca7dd4c7e826 | changes/api/validators/datetime.py | changes/api/validators/datetime.py | from __future__ import absolute_import
from datetime import datetime
import logging
class ISODatetime(object):
def __call__(self, value):
# type: (str) -> datetime
try:
return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ')
except Exception:
logging.exception("F... | from __future__ import absolute_import
from datetime import datetime
import logging
# We appear to be hitting https://bugs.python.org/issue7980, but by using
# strptime early on, the race should be avoided.
datetime.strptime("", "")
class ISODatetime(object):
def __call__(self, value):
# type: (str) ->... | Use strptime at import time to avoid a race | Use strptime at import time to avoid a race
Summary:
We've observed funny AttributeErrors and similar in accessing _strptime, which
are likely the result of a known race. This might possibly fix it.
Test Plan: None
Reviewers: benjamin
Reviewed By: benjamin
Subscribers: changesbot, anupc
Differential Revision: htt... | Python | apache-2.0 | dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes | ---
+++
@@ -3,6 +3,10 @@
from datetime import datetime
import logging
+
+# We appear to be hitting https://bugs.python.org/issue7980, but by using
+# strptime early on, the race should be avoided.
+datetime.strptime("", "")
class ISODatetime(object): |
51e9262ff273db870310453797dbeb48eefd4df7 | logcollector/__init__.py | logcollector/__init__.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db'
db = SQLAlchemy(app)
@app.route("/")
def hello():
return "Hello World!"
| from flask import Flask, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from .models import DataPoint
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../logcollector.db'
db = SQLAlchemy(app)
@app.route("/new", methods=['POST'])
def collect():
new_data = DataPoint(request.f... | Implement save functionality with POST request | Implement save functionality with POST request
| Python | agpl-3.0 | kissgyorgy/log-collector | ---
+++
@@ -1,5 +1,6 @@
-from flask import Flask
+from flask import Flask, request, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
+from .models import DataPoint
app = Flask(__name__)
@@ -7,6 +8,13 @@
db = SQLAlchemy(app)
-@app.route("/")
-def hello():
- return "Hello World!"
+@app.route("/new", me... |
a668afc87465989e85153c9bd2a608ba0ba54d9b | tests/test_containers.py | tests/test_containers.py | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import os
import threading
import unittest
import glob, os
import containers
... | try:
from http.server import SimpleHTTPRequestHandler
except ImportError:
from SimpleHTTPServer import SimpleHTTPRequestHandler
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
import glob
import os
import sys
import threading
import unittest
import conta... | Add test that aci was downloaded | Add test that aci was downloaded
| Python | mit | kragniz/containers | ---
+++
@@ -8,12 +8,21 @@
except ImportError:
from SocketServer import TCPServer
+import glob
import os
+import sys
import threading
import unittest
-import glob, os
import containers
+
+
+PY3 = sys.version_info[0] == 3
+
+if PY3:
+ string_types = str,
+else:
+ string_types = basestring,
PORT =... |
f3e1c74d9b85814cd56397560c5023e7ef536caa | tests/test_statuspage.py | tests/test_statuspage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
de... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
from helpers.statuspage import StatusPage
from test_postgresql import MockConnect
if sys.hexversion >= 0x03000000:
from io import BytesIO as IO
else:
from StringIO import StringIO as IO
class TestStatusPage(unittest.TestCase):
de... | Remove some more unneccesary code. | Unittests: Remove some more unneccesary code.
| Python | mit | zalando/patroni,zalando/patroni,sean-/patroni,pgexperts/patroni,sean-/patroni,pgexperts/patroni,jinty/patroni,jinty/patroni | ---
+++
@@ -36,7 +36,3 @@
self.postgresql = MockConnect()
self.postgresql.mock_values['mock_recovery'] = mock_recovery
Handler(MockRequest(path), ip_port, self)
-
-
-if __name__ == '__main__':
- unittest.main() |
c651034d74df524ad29cb4c381bf4cb12400d73f | src/event_manager/views.py | src/event_manager/views.py | from django.shortcuts import render
from event_manager.models import Suggestion, Event
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'login2.html', {})
#FIXME: Remove comment when login works
#@login_required
def my_suggestions(request):
#FIXME: Need to only sel... | from django.shortcuts import render
from event_manager.models import Suggestion, Event
from django.contrib.auth.decorators import login_required
def home(request):
return render(request, 'login2.html', {})
#FIXME: Remove comment when login works
#@login_required
def my_suggestions(request):
#FIXME: Need to only sel... | Switch from raw dict to context dict | Switch from raw dict to context dict
| Python | agpl-3.0 | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit | ---
+++
@@ -10,12 +10,12 @@
def my_suggestions(request):
#FIXME: Need to only select so many, also only yours
suggestions = Suggestion.objects.values()
- return render(request, 'suggestions.html', suggestions)
+ return render(request, 'suggestions.html', {'suggestions': suggestions})
#FIXME: Remove comment w... |
550101a804cb48f07042014ac5d413071a0e29d7 | coap/test/test_request.py | coap/test/test_request.py | from ..code_registry import MethodCode, MessageType
from ..coap import Coap
def test_build_message():
c = Coap('coap.me')
result = c.get('hello')
print str(bytearray(result.server_reply_list[0].payload))
c.destroy()
| from ..code_registry import MethodCode, MessageType
from ..coap import Coap
import binascii
def test_build_message():
c = Coap('coap.me')
result1 = c.get('hello')
assert str(bytearray(result1.server_reply_list[0].payload)) == '\xffworld'
result2 = c.get('separate')
assert str(bytearray(result2.ser... | Add very basic testing for Coap request. | Add very basic testing for Coap request.
| Python | bsd-3-clause | samueldotj/pycoap | ---
+++
@@ -1,9 +1,14 @@
from ..code_registry import MethodCode, MessageType
from ..coap import Coap
+import binascii
def test_build_message():
c = Coap('coap.me')
- result = c.get('hello')
- print str(bytearray(result.server_reply_list[0].payload))
+ result1 = c.get('hello')
+ assert str(bytear... |
55d13c7f59d5500fbbf2cbe915a6f2fe8e538e14 | example/layout/__year__/index.html.py | example/layout/__year__/index.html.py | __name__ = "Year View"
__author__ = "Decklin Foster <decklin@red-bean.com>"
__description__ = "Calendar of all dates in a given year."
import time
def make(instance, entries, all, vars):
# we get all the entries for this year in ``entries``, in here we want to
# build some monthly calendars to pass to the nex... | __name__ = "Year View"
__author__ = "Decklin Foster <decklin@red-bean.com>"
__description__ = "Calendar of all dates in a given year."
import time
def make(instance, entries, all, vars):
# we get all the entries for this year in ``entries``, in here we want to
# build some monthly calendars to pass to the nex... | Make this a bit more readable. | Make this a bit more readable.
| Python | isc | decklin/ennepe | ---
+++
@@ -15,7 +15,8 @@
cal[m].setdefault(d, 0)
cal[m][d] += 1
- months = [muse.expand('calendar', m=m, days=d, **vars) for m, d in cal.items()]
+ months = [muse.expand('calendar', y=instance, m=month, days=days, **vars)
+ for month, days in cal.items()]
sidebar = muse.expand('... |
d1e2dc224b7b922d39f0f8f21affe39985769315 | src/loader.py | src/loader.py | from scipy.io import loadmat
def load_clean_data():
data = loadmat('data/cleandata_students.mat')
return data['x'], data['y']
def load_noisy_data():
data = loadmat('data/noisydata_students.mat')
return data['x'], data['y']
if __name__ == '__main__':
print('Clean Data:')
x, y = load_clean_data... | from scipy.io import loadmat
def load_data(data_file):
data = loadmat(data_file)
return data['x'], data['y']
if __name__ == '__main__':
print('Clean Data:')
x, y = load_data('data/cleandata_students.mat')
print('x:', x)
print('y:', y)
print()
print('Noisy Data:')
x, y = load_data... | Remove hard-coded data file path | Remove hard-coded data file path | Python | mit | MLNotWar/decision-trees-algorithm,MLNotWar/decision-trees-algorithm | ---
+++
@@ -1,22 +1,18 @@
from scipy.io import loadmat
-def load_clean_data():
- data = loadmat('data/cleandata_students.mat')
- return data['x'], data['y']
-
-def load_noisy_data():
- data = loadmat('data/noisydata_students.mat')
+def load_data(data_file):
+ data = loadmat(data_file)
return data[... |
6b5a4dd75bc1d6dc5187da4ea5e617f30e395b89 | orchard/views/__init__.py | orchard/views/__init__.py | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspecti... | # -*- coding: utf-8 -*-
"""
Simple testing blueprint. Will be deleted once real functionality is added.
"""
import flask
import flask_classful
views = flask.Blueprint('views', __name__)
class IndexView(flask_classful.FlaskView):
"""
A simple home page.
"""
route_base = '/'
# noinspecti... | Remove the intentional throwing of internal server errors. | Remove the intentional throwing of internal server errors.
Fixes failing tests.
| Python | mit | BMeu/Orchard,BMeu/Orchard | ---
+++
@@ -33,10 +33,6 @@
:param name: The name of the visitor.
:return: The home page with a message to the visitor.
"""
- if name == 'BMeu':
- flask.abort(500)
- elif name == 'BMeu2':
- raise ValueError
return flask.render_template('... |
579b566c33174b53276ece63c40d345b207890c8 | allure-behave/setup.py | allure-behave/setup.py | import os
from setuptools import setup
PACKAGE = "allure-behave"
VERSION = "2.6.4"
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic ::... | import os
from setuptools import setup
PACKAGE = "allure-behave"
VERSION = "2.6.4"
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic ::... | Add trove classifiers for python versions | Add trove classifiers for python versions
This marks the project as working on Python 2 and 3. As tests
currently run on python 3.6 and 3.7, I've added those classifiers.
| Python | apache-2.0 | allure-framework/allure-python | ---
+++
@@ -10,7 +10,12 @@
'License :: OSI Approved :: Apache Software License',
'Topic :: Software Development :: Quality Assurance',
'Topic :: Software Development :: Testing',
- 'Topic :: Software Development :: Testing :: BDD'
+ 'Topic :: Software Development :: Testing :: BDD',
+ 'Program... |
969a4f011c7f78a04b6939768d59ba768ff4d160 | Lib/importlib/__init__.py | Lib/importlib/__init__.py | """Backport of importlib.import_module from 3.x."""
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
level -= 1
try:
if package.count('.') < level:
raise ValueError("attempted relative import beyond top-level "
... | """Backport of importlib.import_module from 3.x."""
# While not critical (and in no way guaranteed!), it would be nice to keep this
# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
level -= 1
try:
if ... | Make importlib backwards-compatible to Python 2.2 (but this is not promised to last; just doing it to be nice). | Make importlib backwards-compatible to Python 2.2 (but this is not promised to
last; just doing it to be nice).
Also fix a message for an exception.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | ---
+++
@@ -1,4 +1,6 @@
"""Backport of importlib.import_module from 3.x."""
+# While not critical (and in no way guaranteed!), it would be nice to keep this
+# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
@@ -9,8 +11,14 @@
raise ValueError("attempted relative ... |
22a889dd8f12a11ff22f1b1e167b3c888f892f88 | typesetter/typesetter.py | typesetter/typesetter.py | from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
JSONIFY_PRETTYPRINT_REGULAR=False,
)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typesetter/data/words.txt') as f:
WORDS = f.read().spli... | from flask import Flask, render_template, jsonify
app = Flask(__name__)
app.config.update(
# Reduce response size by avoiding pretty printing.
JSONIFY_PRETTYPRINT_REGULAR=False,
)
# Read in the entire wordlist at startup and keep it in memory.
# Optimization for improving search response time.
with open('typ... | Add clarifying comment about avoiding pretty printing | Add clarifying comment about avoiding pretty printing
| Python | mit | rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter | ---
+++
@@ -3,6 +3,7 @@
app = Flask(__name__)
app.config.update(
+ # Reduce response size by avoiding pretty printing.
JSONIFY_PRETTYPRINT_REGULAR=False,
)
|
0d0434744efef091fd8d26725f21c8015a06d8be | opentreemap/treemap/templatetags/instance_config.py | opentreemap/treemap/templatetags/instance_config.py | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
... | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from django import template
from treemap.json_field import get_attr_from_json_field
register = template.Library()
def _get_color_from_config(config, name):
color = config.get(name)
if color:
... | Allow "writable" if *any* field is writable | Allow "writable" if *any* field is writable
Fixes Internal Issue 598
| Python | agpl-3.0 | recklessromeo/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,clever-crow-consulting/otm-core,maurizi/otm-core,RickMohr/otm-core,maurizi/otm-core,maurizi/otm-core,recklessromeo/otm-core,RickMohr/otm-core,recklessromeo/otm-core,maurizi/otm-core,RickMohr/o... | ---
+++
@@ -48,10 +48,7 @@
if field:
perms = perms.filter(field_name=field)
- if len(perms) == 0:
- return False
- else:
- return perms[0].allows_writes
+ return any(perm.allows_writes for perm in perms)
@register.filter |
b03c0898897bbd89f8701e1c4d6d84d263bbd039 | utils/publish_message.py | utils/publish_message.py | import amqp
from contextlib import closing
def publish_message(message_body, exchange, type, routing_key):
""" Publish a message to an exchange with exchange type and routing key specified.
A message is sent to a specified exchange with the provided routing_key.
:param message_body: The body of the mess... | import amqp
from contextlib import closing
def __get_channel(connection):
return connection.channel()
def __get_message(message_body):
return amqp.Message(message_body)
def __declare_exchange(channel, exchange, type):
channel.exchange_declare(exchange=exchange, type=type, durable=True, auto_delete=False... | Revert "EAFP and removing redundant functions" | Revert "EAFP and removing redundant functions"
This reverts commit fbb9eeded41e46c8fe8c3ddaba7f8d9fd1e3bff3.
| Python | mit | jdgillespie91/trackerSpend,jdgillespie91/trackerSpend | ---
+++
@@ -2,22 +2,36 @@
from contextlib import closing
+def __get_channel(connection):
+ return connection.channel()
+
+def __get_message(message_body):
+ return amqp.Message(message_body)
+
+def __declare_exchange(channel, exchange, type):
+ channel.exchange_declare(exchange=exchange, type=type, dura... |
f9c351bbddb9f0e212b92bdada4825d79bad2812 | categories/__init__.py | categories/__init__.py | __version_info__ = {
'major': 1,
'minor': 6,
'micro': 0,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not s... | __version_info__ = {
'major': 1,
'minor': 6,
'micro': 1,
'releaselevel': 'final',
'serial': 1
}
def get_version(short=False):
assert __version_info__['releaselevel'] in ('alpha', 'beta', 'final')
vers = ["%(major)i.%(minor)i" % __version_info__, ]
if __version_info__['micro'] and not s... | Update the version to 1.6.1 | Update the version to 1.6.1
| Python | apache-2.0 | callowayproject/django-categories,callowayproject/django-categories,callowayproject/django-categories | ---
+++
@@ -1,7 +1,7 @@
__version_info__ = {
'major': 1,
'minor': 6,
- 'micro': 0,
+ 'micro': 1,
'releaselevel': 'final',
'serial': 1
} |
6d04f0f924df11968b85aa2c885bde30cf6af597 | stack/vpc.py | stack/vpc.py | from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = InternetGateway(
"InternetG... | from troposphere import (
Ref,
)
from troposphere.ec2 import (
InternetGateway,
Route,
RouteTable,
VPC,
VPCGatewayAttachment,
)
from .template import template
vpc = VPC(
"Vpc",
template=template,
CidrBlock="10.0.0.0/16",
)
# Allow outgoing to outside VPC
internet_gateway = Inte... | Add a public route table | Add a public route table
| Python | mit | caktus/aws-web-stacks,tobiasmcnulty/aws-container-basics | ---
+++
@@ -4,6 +4,8 @@
from troposphere.ec2 import (
InternetGateway,
+ Route,
+ RouteTable,
VPC,
VPCGatewayAttachment,
)
@@ -32,3 +34,20 @@
VpcId=Ref(vpc),
InternetGatewayId=Ref(internet_gateway),
)
+
+
+# Public route table
+public_route_table = RouteTable(
+ "PublicRouteTabl... |
90e557d681c9ea3f974ee5357ec67f294322d224 | src/elm_doc/decorators.py | src/elm_doc/decorators.py | import functools
import subprocess
from doit.exceptions import TaskFailed
def capture_subprocess_error(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
return TaskFailed(
... | import functools
import subprocess
from doit.exceptions import TaskFailed
def capture_subprocess_error(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
command_string = e.cmd if isinstanc... | Clean error output when command is a string | Clean error output when command is a string
| Python | bsd-3-clause | ento/elm-doc,ento/elm-doc | ---
+++
@@ -10,9 +10,10 @@
try:
return fn(*args, **kwargs)
except subprocess.CalledProcessError as e:
+ command_string = e.cmd if isinstance(e.cmd, str) else ' '.join(e.cmd)
return TaskFailed(
'Error while executing {}:\nstdout:\n{}\n\nstderr:\n{... |
1107fc26cf9baa235d62813ea0006687d4710280 | src/engine/file_loader.py | src/engine/file_loader.py | import os
import json
from lib import contract
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
... | import os
import json
from lib import contract
data_dir = os.path.join(os.environ['PORTER'], 'data')
@contract.accepts(str)
@contract.returns(list)
def read_and_parse_json(data_type):
sub_dir = os.path.join(data_dir, data_type)
def full_path(file_name):
return os.path.join(sub_dir, file_name)
... | Add load_enum and load_struct functions | Add load_enum and load_struct functions
Load enumeration list json
Load full struct into dictionary
| Python | mit | Tactique/game_engine,Tactique/game_engine | ---
+++
@@ -22,3 +22,23 @@
return json.load(json_file)
return map(load_json, filter(only_json, map(full_path, os.listdir(sub_dir))))
+
+
+@contract.accepts(str)
+@contract.returns(dict)
+def load_enum(struct_name):
+ enum_ = {}
+ list_ = read_and_parse_json(struct_name)[0]
+ for enumerati... |
ab506307b6b3fc2997a7afd38c02cae630dbf90b | addons/hr_holidays/migrations/8.0.1.5/pre-migration.py | addons/hr_holidays/migrations/8.0.1.5/pre-migration.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Therp BV (<http://therp.nl>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of ... | Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues. | Remove hr_holidays_meeting_id_fkey constrain to avoid migration issues.
- The constraint will be reset by the ORM later.
- Not doing it may both slow the migration and abort it altogether.
| Python | agpl-3.0 | OpenUpgrade-dev/OpenUpgrade,kirca/OpenUpgrade,bwrsandman/OpenUpgrade,sebalix/OpenUpgrade,kirca/OpenUpgrade,hifly/OpenUpgrade,grap/OpenUpgrade,Endika/OpenUpgrade,bwrsandman/OpenUpgrade,damdam-s/OpenUpgrade,blaggacao/OpenUpgrade,mvaled/OpenUpgrade,blaggacao/OpenUpgrade,OpenUpgrade-dev/OpenUpgrade,OpenUpgrade/OpenUpgrade,... | ---
+++
@@ -24,6 +24,9 @@
@openupgrade.migrate()
def migrate(cr, version):
cr.execute(
+ "ALTER TABLE hr_holidays DROP CONSTRAINT hr_holidays_meeting_id_fkey"
+ )
+ cr.execute(
'''update hr_holidays
set meeting_id=calendar_event.id
from calendar_event where meeting_id=%s... |
8799197befd1f52278a4344fc41ba94cc45c548a | src/you_get/json_output.py | src/you_get/json_output.py |
import json
# save info from common.print_info()
last_info = None
def output(video_extractor, pretty_print=True):
ve = video_extractor
out = {}
out['url'] = ve.url
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
if pretty_print:
print(json.dumps(out, inde... |
import json
# save info from common.print_info()
last_info = None
def output(video_extractor, pretty_print=True):
ve = video_extractor
out = {}
out['url'] = ve.url
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
try:
if ve.audiolang:
out['audi... | Print audiolang in json output | Print audiolang in json output
| Python | mit | zmwangx/you-get,zmwangx/you-get,xyuanmu/you-get,qzane/you-get,qzane/you-get,xyuanmu/you-get,cnbeining/you-get,cnbeining/you-get | ---
+++
@@ -11,6 +11,11 @@
out['title'] = ve.title
out['site'] = ve.name
out['streams'] = ve.streams
+ try:
+ if ve.audiolang:
+ out['audiolang'] = ve.audiolang
+ except NameError:
+ pass
if pretty_print:
print(json.dumps(out, indent=4, sort_keys=True, ensur... |
1b36e4ec9c15a0f9064d605f7c7f60672416dcb0 | workers/subscriptions.py | workers/subscriptions.py | import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.... | import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
sen... | Remove collecting plugins every second | Remove collecting plugins every second
| Python | mit | sevazhidkov/leonard | ---
+++
@@ -1,4 +1,5 @@
import os
+import time
import telegram
@@ -8,10 +9,8 @@
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
- i = 0
+ bot.collect_plugins()
while True:
- if i % 10 == 0:
- bot.collect_plugins()... |
662d103adffd0592474378e2aaf98b8fafc3fb93 | salt/beacons/salt_proxy.py | salt/beacons/salt_proxy.py | # -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of
one or more salt proxy processes
.. versionadded:: 2015.8.3
'''
# Import python libs
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def _run_proxy_processes(proxies):
'''
Iterate over ... | # -*- coding: utf-8 -*-
'''
Beacon to manage and report the status of
one or more salt proxy processes
.. versionadded:: 2015.8.3
'''
# Import python libs
from __future__ import absolute_import
import logging
log = logging.getLogger(__name__)
def _run_proxy_processes(proxies):
'''
Iterate over ... | Move append out of if/else block | Move append out of if/else block
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -27,12 +27,11 @@
if not __salt__['salt_proxy.is_running'](proxy)['result']:
__salt__['salt_proxy.configure_proxy'](proxy, start=True)
result[proxy] = 'Proxy {0} was started'.format(proxy)
- ret.append(result)
else:
msg = 'Proxy {0} is alre... |
24da0f84e1a844b1f53e5afafc34cfcc915a9a67 | corehq/apps/userreports/tests/test_report_rendering.py | corehq/apps/userreports/tests/test_report_rendering.py | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
class VeryFakeReportView(ConfigurableReportView):
# note: this is very coupled to what it tests below, but i... | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
from django.test import SimpleTestCase
from corehq.apps.userreports.reports.view import ConfigurableReportView
from corehq.apps.userreports.reports.util import ReportExport
class VeryFakeReportExport(ReportExport):
de... | Update report_rendering test to use ReportExport | Update report_rendering test to use ReportExport
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,8 +1,19 @@
# coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
+
from django.test import SimpleTestCase
+
from corehq.apps.userreports.reports.view import ConfigurableReportView
+from corehq.apps.userreports.reports.util import ReportExport
+
+
+class Very... |
1768207c57b66812931d2586c5544c9b74446918 | peering/management/commands/update_peering_session_states.py | peering/management/commands/update_peering_session_states.py | import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = "Update peering session states for Internet Exchanges."
logger = logging.getLogger("peering.manager.peering")
def handle(self, *args, **options):
sel... | import logging
from django.core.management.base import BaseCommand
from peering.models import InternetExchange
class Command(BaseCommand):
help = "Update peering session states for Internet Exchanges."
logger = logging.getLogger("peering.manager.peering")
def handle(self, *args, **options):
sel... | Fix command polling sessions for IX. | Fix command polling sessions for IX.
| Python | apache-2.0 | respawner/peering-manager,respawner/peering-manager,respawner/peering-manager,respawner/peering-manager | ---
+++
@@ -14,4 +14,4 @@
internet_exchanges = InternetExchange.objects.all()
for internet_exchange in internet_exchanges:
- internet_exchange.update_peering_session_states()
+ internet_exchange.poll_peering_sessions() |
8170aca01f6922ef653bceb9121eb7fc098f85de | defenses/torch/audio/input_tranformation/resampling.py | defenses/torch/audio/input_tranformation/resampling.py | import torchaudio
import librosa
# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio
T = torchaudio.transforms
# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]
audio_data = torch.tensor(audio_data).float().to(device)
# Di... | import torchaudio
import librosa
# resampling reference https://core.ac.uk/download/pdf/228298313.pdf
# resampling input transformation defense for audio
T = torchaudio.transforms
# Read audio file
audio_data = librosa.load(files, sr=16000)[0][-19456:]
audio_data = torch.tensor(audio_data).float().to(device)
# Di... | Format the code to black | Format the code to black | Python | mit | cleverhans-lab/cleverhans,cleverhans-lab/cleverhans,cleverhans-lab/cleverhans | ---
+++
@@ -12,8 +12,7 @@
audio_data = torch.tensor(audio_data).float().to(device)
-# Discarding samples from a waveform during downsampling could remove a significant portion of the adversarial perturbation,
-# thereby prevents an adversarial attack.
+# Discarding samples from a waveform during downsampling cou... |
2fd3123eb00c16d325a7ec25dfcb6a92872a3849 | tests/test_init.py | tests/test_init.py | import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) ==... | import os
from click.testing import CliRunner
from morenines import application
def test_init(data_dir):
runner = CliRunner()
result = runner.invoke(application.main, ['init', data_dir])
assert result.exit_code == 0
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) ==... | Add commented-out test for init with no args | Add commented-out test for init with no args
| Python | mit | mcgid/morenines,mcgid/morenines | ---
+++
@@ -14,3 +14,22 @@
mn_dir = os.path.join(data_dir, '.morenines')
assert os.path.isdir(mn_dir) == True
+
+
+# XXX I can't get this test to work because chdir() isn't having any effect.
+# I suspect it's somehow related to testing with click, but I can't figure
+# out exactly why.
+#
+# ... |
88d65d4f9cf41bbc5b080fd4245a3a6d81c1ef46 | queen/helpers/__init__.py | queen/helpers/__init__.py | import serial
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
port.write('0;1;0;\n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
return drones | import serial
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
port.write('0;1;0; \n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
return drones | Add space for empty string. | Add space for empty string.
| Python | mit | kalail/queen,kalail/queen | ---
+++
@@ -2,11 +2,11 @@
def get_active_drones():
port = serial.Serial('/dev/ttyUSB0', 9600)
- port.write('0;1;0;\n')
+ port.write('0;1;0; \n')
drones = []
msg = port.readline()
drone_id = msg[2]
drones.append(drone_id)
-
+
return drones |
0f047cded957bc67441a9acd65b46fab4bac6302 | SUASImageParser/ADLC/characteristic_identifier.py | SUASImageParser/ADLC/characteristic_identifier.py | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
... | from SUASImageParser.utils.image import Image
from SUASImageParser.utils.color import bcolors
import cv2
import numpy as np
class CharacteristicIdentifier:
"""
Identify target characteristics
"""
def __init__(self, **kwargs):
pass
def identify_characteristics(self, target):
"""
... | Remove mention of Log parser | Remove mention of Log parser
| Python | mit | FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition | ---
+++
@@ -22,9 +22,6 @@
# into the following tasks:
# 1) Segmentation
# 2) OCR
- # 3) Pixhawk log parse to gather data about
- # 3a) GPS
- # 3b) Heading
# I'm not really sure how to implement this process, which is why I am
# le... |
c33ce5e8d998278d01310205598ceaf15b1573ab | logya/core.py | logya/core.py | # -*- coding: utf-8 -*-
from logya.content import read_all
from logya.template import init_env
from logya.util import load_yaml, paths
class Logya:
"""Object to store data such as site index and settings."""
def __init__(self, options):
"""Set required logya object properties."""
self.verbos... | # -*- coding: utf-8 -*-
from logya.content import read_all
from logya.template import init_env
from logya.util import load_yaml, paths
class Logya:
"""Object to store data such as site index and settings."""
def __init__(self, options):
"""Set required logya object properties."""
self.verbos... | Rename build_index to build and add logic to setup template env | Rename build_index to build and add logic to setup template env
| Python | mit | elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya | ---
+++
@@ -14,17 +14,14 @@
self.paths = paths(dir_site=getattr(options, 'dir_site', None))
self.settings = load_yaml(self.paths.root.joinpath('site.yaml').read_text())
- # Initialize template env and globel variables.
+ def build(self):
+ """Build index of documents and collectio... |
a2cb560851cbbabab0474092f59e1700e1c93284 | tests/chainer_tests/testing_tests/test_unary_math_function_test.py | tests/chainer_tests/testing_tests/test_unary_math_function_test.py | import unittest
from chainer import testing
class Dummy(object):
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(Dummy()) # no numpy.dummy
testing.run_module(__name__, __fil... | import unittest
from chainer import testing
def dummy():
pass
class TestNoNumpyFunction(unittest.TestCase):
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
testing.unary_math_function_unittest(dummy) # no numpy.dummy
testing.run_module(__name__, __file__)
| Fix test of math function testing helper. | Fix test of math function testing helper.
| Python | mit | wkentaro/chainer,jnishi/chainer,jnishi/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,ktnyt/chainer,niboshi/chainer,hvy/chainer,tkerola/chainer,ktnyt/chainer,hvy/chainer,niboshi/chainer,jnishi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,ronekko/chainer,okuta/chainer,aonotas/chainer,keisuke-umeza... | ---
+++
@@ -3,7 +3,7 @@
from chainer import testing
-class Dummy(object):
+def dummy():
pass
@@ -11,7 +11,7 @@
def test_no_numpy_function(self):
with self.assertRaises(ValueError):
- testing.unary_math_function_unittest(Dummy()) # no numpy.dummy
+ testing.unary_mat... |
850f6af90b99756e572b06803e40f55efd6734e6 | test/test_pocket_parser.py | test/test_pocket_parser.py | import unittest
import utils
import os
import sys
import re
import subprocess
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.append(os.path.join(TOPDIR, 'lib'))
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
def test_get_cnc(self):
"""Test get_cnc() func... | import unittest
import utils
import os
import sys
import re
import subprocess
import shutil
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
utils.set_search_paths(TOPDIR)
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
def test_get_cnc(self):
"""Test get_cnc() func... | Test simple complete run of pocket_parser. | Test simple complete run of pocket_parser.
| Python | lgpl-2.1 | salilab/cryptosite,salilab/cryptosite,salilab/cryptosite | ---
+++
@@ -4,9 +4,10 @@
import sys
import re
import subprocess
+import shutil
TOPDIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
-sys.path.append(os.path.join(TOPDIR, 'lib'))
+utils.set_search_paths(TOPDIR)
import cryptosite.pocket_parser
class Tests(unittest.TestCase):
@@ -19,5 +20,20... |
8680eac07c50546968c1525642cab41c1c99a6b3 | {{cookiecutter.repo_name}}/pages/context_processors.py | {{cookiecutter.repo_name}}/pages/context_processors.py | from django.contrib.sites.shortcuts import get_current_site
from urlparse import urljoin
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, sit... | from django.contrib.sites.shortcuts import get_current_site
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request)
#domain = "{}://{}".format(scheme, site.domain)
return {
'site_url': "{}://{}".format(scheme, site.domain),
'site_nam... | Remove urlparse import as not used and also renamed in Python 3 to urllib.parse | Remove urlparse import as not used and also renamed in Python 3 to urllib.parse
| Python | mit | Parbhat/wagtail-cookiecutter-foundation,aksh1/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ilendl2/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,Parbhat/wagtail-cookiecutter-foundation,ch... | ---
+++
@@ -1,5 +1,5 @@
from django.contrib.sites.shortcuts import get_current_site
-from urlparse import urljoin
+
def site_url(request):
scheme = 'https' if request.is_secure() else 'http'
site = get_current_site(request) |
ffab97ff91366f9045503853198126f1b965e83e | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handl... | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger('bb_log')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.handl... | Remove square brackets around log level in log ouput | Remove square brackets around log level in log ouput
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -18,8 +18,8 @@
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
-formatterch = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
-formattertfh = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s] %(message)s')
+formatterch = logging.Formatter('%(asctime)s %(lev... |
23c1413c14a81ee40bbb0bb3adeb20e1a231b9c5 | saleor/data_feeds/urls.py | saleor/data_feeds/urls.py | from django.conf.urls import url
from django.views.generic.base import RedirectView
from .google_merchant import get_feed_file_url
urlpatterns = [
url(r'google/$', RedirectView.as_view(
get_redirect_url=get_feed_file_url), name='google-feed')]
| from django.conf.urls import url
from django.views.generic.base import RedirectView
from .google_merchant import get_feed_file_url
urlpatterns = [
url(r'google/$', RedirectView.as_view(
get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')]
| Update feeds url due to RemovedInDjango19Warning | Update feeds url due to RemovedInDjango19Warning
| Python | bsd-3-clause | jreigel/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,KenMutemi/saleor,tfroehlich82/saleor,UITools/saleor,jreigel/saleor,car3oon/saleor,mociepka/saleor,car3oon/saleor,maferelo/saleor,HyperManTT/ECommerceSaleor,itbabu/saleor,UITools/saleor,tfroehlich82/saleor,itbabu/saleor,UITools/saleor,HyperManTT/ECommerceSaleo... | ---
+++
@@ -5,4 +5,4 @@
urlpatterns = [
url(r'google/$', RedirectView.as_view(
- get_redirect_url=get_feed_file_url), name='google-feed')]
+ get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')] |
3157a749cb7f4704e3fe4c949ee80772a9ed8eb3 | samples/debugging/main.py | samples/debugging/main.py | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apicl... | #!/usr/bin/python2.4
# -*- coding: utf-8 -*-
#
# Copyright 2010 Google Inc. All Rights Reserved.
"""Simple command-line example for Translate.
Command-line application that translates
some text.
"""
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
import gflags
import logging
import pprint
import sys
from apicl... | Update sample to reflect final destination in wiki documentation. | Update sample to reflect final destination in wiki documentation.
| Python | apache-2.0 | googleapis/google-api-python-client,jonparrott/oauth2client,googleapis/oauth2client,google/oauth2client,jonparrott/oauth2client,google/oauth2client,googleapis/google-api-python-client,clancychilds/oauth2client,clancychilds/oauth2client,googleapis/oauth2client | ---
+++
@@ -21,12 +21,17 @@
FLAGS = gflags.FLAGS
-FLAGS.dump_request_response = True
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def main(argv):
+ try:
+ argv = FLAGS(argv)
+ except gflags.FlagsError, e:
+ print '%s\\nUsage: %s ARGS\\n%s' % (e, argv[0], FLAGS)
+ sys.exit(1)
+
... |
6de2bd60922c012ae3ec179a49aaff950018076d | snactor/utils/variables.py | snactor/utils/variables.py | def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
ge... | def assign_to_variable_spec(data, spec, value):
if not spec.startswith('@') or not spec.endswith('@'):
raise ValueError("{} is not a reference".format(spec))
parts = spec.strip('@').split('.')
data[parts[0]] = {}
gen = data[parts[0]]
for part in parts[1:-1]:
gen[part] = {}
ge... | Allow empty data in value | Allow empty data in value
| Python | apache-2.0 | leapp-to/snactor | ---
+++
@@ -17,7 +17,7 @@
data = data.get(element, None)
if not data:
break
- if not data:
+ if data is None:
raise ValueError("unresolved reference: {}".format(spec.strip("@")))
return data
return spec |
b3540f744efbcb0f14f9b4081aeffda1f5ccae3c | pyscraper/patchfilter.py | pyscraper/patchfilter.py | #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Lo... | #! /usr/bin/python2.3
# vim:sw=8:ts=8:et:nowrap
import os
import shutil
def ApplyPatches(filein, fileout):
# Generate short name such as wrans/answers2003-03-31.html
(rest, name) = os.path.split(filein)
(rest, dir) = os.path.split(rest)
fileshort = os.path.join(dir, name)
# Lo... | Remove code which blanks patch files | Remove code which blanks patch files
| Python | agpl-3.0 | mysociety/publicwhip,mysociety/publicwhip,mysociety/publicwhip | ---
+++
@@ -29,9 +29,11 @@
if status == 0:
return True
- print "Error running 'patch' on file %s, blanking it out" % fileshort
- os.rename(patchfile, patchfile + ".old~")
- blankfile = open(patchfile, "w")
- blankf... |
1eff8a7d89fd3d63f020200207d87213f6182b22 | elasticsearch_flex/management/commands/flex_sync.py | elasticsearch_flex/management/commands/flex_sync.py | # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch import exceptions
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
... | # coding: utf-8
import hues
from django.core.management.base import BaseCommand
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
class Command(BaseCommand):
help = 'Sync search indices, templates, and scripts.'
def add_arguments(self, parser):
... | Use index context manager for sync | Use index context manager for sync
| Python | mit | prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex | ---
+++
@@ -3,7 +3,6 @@
from django.core.management.base import BaseCommand
-from elasticsearch import exceptions
from elasticsearch_dsl.connections import connections
from elasticsearch_flex.indexes import registered_indices
@@ -31,15 +30,10 @@
for i, index in enumerate(indices, 1):
hu... |
9742e372a6ccca843120cb5b4e8135033d30cdd6 | cauth/controllers/root.py | cauth/controllers/root.py | #!/usr/bin/env python
#
# Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# 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
#
# Unle... | #!/usr/bin/env python
#
# Copyright (C) 2014 eNovance SAS <licensing@enovance.com>
#
# 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
#
# Unle... | Fix app crashing at startup if some auth methods are not configured | Fix app crashing at startup if some auth methods are not configured
Change-Id: I201dbc646c6da39c5923a086a0498b7ccb854982
| Python | apache-2.0 | redhat-cip/cauth,enovance/cauth,redhat-cip/cauth,redhat-cip/cauth,enovance/cauth,enovance/cauth | ---
+++
@@ -19,6 +19,7 @@
from pecan import expose, response, conf
from pecan.rest import RestController
+from cauth.auth import base as exceptions
from cauth.controllers import base, github, introspection
from cauth.utils.common import LOGOUT_MSG
@@ -35,8 +36,11 @@
class RootController(object):
login... |
5ef8b09a055326e2a92c9eccbcb187fa5362fb95 | zipa/magic.py | zipa/magic.py | from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
... | from types import ModuleType
from .resource import Resource
class SelfWrapper(ModuleType):
def __init__(self, self_module, baked_args={}):
for attr in ["__builtins__", "__doc__", "__name__", "__package__"]:
setattr(self, attr, getattr(self_module, attr, None))
self.__path__ = []
... | Add possibility of using apis with dashes without any workarounds | Add possibility of using apis with dashes without any workarounds
| Python | apache-2.0 | PressLabs/zipa | ---
+++
@@ -28,6 +28,7 @@
return self.env[name]
def _parse_name(self, name):
+ name = name.replace('___', '-')
parts = name.split('__')
host = parts[0].replace('_', '.')
prefix = '/' |
689d1d1f128b4a72aad6783ea2f770c21cd4c2da | queryset_transform/__init__.py | queryset_transform/__init__.py | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone... | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clon... | Refactor the ever living hell out of this. | Refactor the ever living hell out of this. | Python | bsd-3-clause | alex/django-queryset-transform | ---
+++
@@ -1,4 +1,5 @@
from django.db import models
+
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
@@ -7,23 +8,20 @@
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
- c._transform_fn... |
fa0c63b37bd010f73fede319b5e2755fe1bfbd7c | registration/__init__.py | registration/__init__.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
def get_backend():
"""
Return an instance of the registration backend for use on this
site, as determined by the ``REGISTRATION_BACKEND`` setting. Raise
``django.cor... | Add utility function for retrieving the active registration backend. | Add utility function for retrieving the active registration backend.
| Python | bsd-3-clause | ratio/django-registration,danielsokolowski/django-registration,stefankoegl/django-couchdb-utils,ogirardot/django-registration,wuyuntao/django-registration,stefankoegl/django-registration-couchdb,bruth/django-registration2,stefankoegl/django-registration-couchdb,wuyuntao/django-registration,schmidsi/django-registration,... | ---
+++
@@ -0,0 +1,23 @@
+from django.conf import settings
+from django.core.exceptions import ImproperlyConfigured
+from django.utils.importlib import import_module
+
+def get_backend():
+ """
+ Return an instance of the registration backend for use on this
+ site, as determined by the ``REGISTRATION_BACKEN... | |
4169f60ce8fa6666b28a1129845c816889a6459a | chef/tests/__init__.py | chef/tests/__init__.py | import os
import random
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
... | import os
import random
from unittest2 import TestCase
from chef.api import ChefAPI
TEST_ROOT = os.path.dirname(os.path.abspath(__file__))
def test_chef_api():
return ChefAPI('https://api.opscode.com/organizations/pycheftest', os.path.join(TEST_ROOT, 'client.pem'), 'unittests')
class ChefTestCase(TestCase):
... | Add a system for tests to register objects for deletion. | Add a system for tests to register objects for deletion.
They should be deleted no matter the outcome of
the test. | Python | apache-2.0 | coderanger/pychef,jarosser06/pychef,jarosser06/pychef,Scalr/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,coderanger/pychef,dipakvwarade/pychef,cread/pychef | ---
+++
@@ -18,6 +18,18 @@
super(ChefTestCase, self).setUp()
self.api = test_chef_api()
self.api.set_default()
+ self.objects = []
+
+ def tearDown(self):
+ for obj in self.objects:
+ try:
+ obj.delete()
+ except ChefError, e:
+ ... |
44d701eea86f9c2152368f64e54c012cdb937bb1 | alexandria/views/home.py | alexandria/views/home.py | from pyramid.view import (
view_config,
notfound_view_config,
)
# Always send the default index.html
@notfound_view_config(renderer='templates/index.mako', accept='text/html')
@view_config(renderer='templates/index.mako', accept='text/html')
def index(request):
return {}
| from pyramid.view import (
view_config,
notfound_view_config,
)
# Always send the default index.html
@notfound_view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
@view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
def index(request):
return ... | Verify X-Requested-With is not set | Verify X-Requested-With is not set
| Python | isc | bertjwregeer/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,cdunklau/alexandria,cdunklau/alexandria | ---
+++
@@ -4,8 +4,8 @@
)
# Always send the default index.html
-@notfound_view_config(renderer='templates/index.mako', accept='text/html')
-@view_config(renderer='templates/index.mako', accept='text/html')
+@notfound_view_config(renderer='templates/index.mako', xhr=False, accept='text/html')
+@view_config... |
0b00187083b29a38eaf949e41824dcb9fd72f48c | amazonproduct/version.py | amazonproduct/version.py |
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
VERSION = '0.3'
|
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
VERSION = '0.3-dev'
| Mark as dev release until 0.3 is ready. | Mark as dev release until 0.3 is ready.
| Python | bsd-3-clause | redtoad/python-amazon-product-api,redtoad/python-amazon-product-api,redtoad/python-amazon-product-api | ---
+++
@@ -1,5 +1,5 @@
# The version is defined in its own module so we can import it from setup.py
# without introducing unwanted dependencies at that stage.
-VERSION = '0.3'
+VERSION = '0.3-dev'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.