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 |
|---|---|---|---|---|---|---|---|---|---|---|
56e11c3df02874867626551534693b488db82fb7 | example.py | example.py | import os
import pickle as pkl
from gso import load_up_answers, load_up_questions
#for result in load_up_questions("How to write a bubble sort", "python"):
#print result
#break
#question_url = 'https://stackoverflow.com/questions/895371/bubble-sort-homework'
#with open("html_dump.pkl", 'wb') as myfile:
#... | import os
import pickle as pkl
from lxml import etree
from gso import load_up_answers, load_up_questions
#for result in load_up_questions("How to write a bubble sort", "python"):
#print result
#break
#question_url = 'https://stackoverflow.com/questions/895371/bubble-sort-homework'
#with open("html_dump.pkl",... | Create wrapper tag for SO html | Create wrapper tag for SO html
| Python | mit | mdtmc/gso | ---
+++
@@ -1,5 +1,6 @@
import os
import pickle as pkl
+from lxml import etree
from gso import load_up_answers, load_up_questions
#for result in load_up_questions("How to write a bubble sort", "python"):
@@ -15,4 +16,9 @@
with open("html_dump.pkl", 'rb') as myfile:
html_dump = pkl.load(myfile)
-print ht... |
3c0fa80bcdd5a493e7415a49566b4eb7524c534b | fabfile.py | fabfile.py | from __future__ import with_statement
from fabric.api import local, cd, env, run
from fabric.colors import green
env.use_ssh_config = True
env.user = 'ubuntu'
env.hosts = [ 'dhlab-backend' ]
PRODUCTION_DIR = 'backend'
SUPERVISOR_NAME = 'dhlab_backend'
MONGODB_NAME = 'dhlab'
def backup_db():
'''Backup loca... | from __future__ import with_statement
from fabric.api import local, cd, env, run
from fabric.colors import green
env.use_ssh_config = True
env.user = 'ubuntu'
env.hosts = [ 'dhlab-backend' ]
PRODUCTION_DIR = 'backend'
SUPERVISOR_NAME = 'dhlab_backend'
MONGODB_NAME = 'dhlab'
def backup_db():
'''Backup loca... | Deploy script now checks to see if virtualenv has the latest dependencies | Deploy script now checks to see if virtualenv has
the latest dependencies | Python | mit | DHLabs/keep,9929105/KEEP,DHLabs/keep,9929105/KEEP,DHLabs/keep,9929105/KEEP | ---
+++
@@ -38,6 +38,10 @@
# Pull latest code from git
run( 'git pull origin master' )
+ # Ensure we have the latest dependencies
+ run( 'workon dhlab-backend' )
+ run( 'pip install -r deps.txt' )
+
# Start up all processes again
run( 'supervisorctl start all... |
423ea9128f01eb74790a3bb5a876c066acc9c2c1 | firesim.py | firesim.py | import functools
import signal
import sys
import logging as log
from firesimgui import FireSimGUI
from lib.arguments import parse_args
def sig_handler(app, sig, frame):
log.info("Firesim received signal %d. Shutting down.", sig)
try:
app.quit()
except Exception:
log.exception... | #!/usr/bin/env python3
import functools
import signal
import sys
import logging as log
from firesimgui import FireSimGUI
from lib.arguments import parse_args
def sig_handler(app, sig, frame):
log.info("Firesim received signal %d. Shutting down.", sig)
try:
app.quit()
except Exception:
lo... | Add shebang to main script and switch to Unix line endings | Add shebang to main script and switch to Unix line endings
| Python | mit | Openlights/firesim | ---
+++
@@ -1,3 +1,5 @@
+#!/usr/bin/env python3
+
import functools
import signal
import sys |
a99378deee9a802bf107d11e79d2df2f77481495 | silver/tests/spec/test_plan.py | silver/tests/spec/test_plan.py | # -*- coding: utf-8 -*-
# vim: ft=python:sw=4:ts=4:sts=4:et:
import json
from silver.models import Plan
from django.test.client import Client
from django.test import TestCase
class PlansSpecificationTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_create_plan(self):
resp... | # -*- coding: utf-8 -*-
# vim: ft=python:sw=4:ts=4:sts=4:et:
import json
from silver.models import Plan
from django.test.client import Client
from django.test import TestCase
class PlansSpecificationTestCase(TestCase):
def setUp(self):
self.client = Client()
def test_create_plan(self):
asse... | Comment out the failing Plan test | Comment out the failing Plan test
| Python | apache-2.0 | PressLabs/silver,PressLabs/silver,PressLabs/silver | ---
+++
@@ -13,24 +13,25 @@
self.client = Client()
def test_create_plan(self):
- response = self.client.put('/api/plans', json.dumps({
- 'name': 'Hydrogen',
- 'interval': 'month',
- 'interval_count': 1,
- 'amount': 150,
- 'currency': 'USD',... |
7726e51f2e3bb028700e5fc61779f6edc53cee36 | scripts/init_tree.py | scripts/init_tree.py | import os
import shutil
def main():
cwd = os.getcwd()
if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
print 'This script must be run in \"FRENSIE/scipts\"'
print 'Your CWD is', cwd
return 1
os.chdir('../../')
os.mkdir('frensie_build_tree')
#os.renames('FRENSIE'... | import os
import shutil
def main():
cwd = os.getcwd()
if not cwd.endswith(os.path.join('FRENSIE', 'scripts')):
print 'This script must be run in \"FRENSIE/scipts\"'
print 'Your CWD is', cwd
return 1
os.chdir('../../')
os.mkdir('frensie_build_tree')
#os.renames('FRENSIE'... | Update to copy new scripts | Update to copy new scripts
| Python | bsd-3-clause | lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123,lkersting/SCR-2123 | ---
+++
@@ -19,7 +19,9 @@
os.mkdir('deps/tars')
os.mkdir('build')
shutil.copyfile('src/scripts/makefile.deps', 'deps/makefile')
+ shutil.copyfile('src/scripts/lazy.sh', 'deps/lazy.sh')
shutil.copyfile('src/scripts/frensie.sh', 'build/frensie.sh')
+ #shutil.copyfile('src/scripts/source_dep... |
454c3228db731280eeed8d22c6811c2810018222 | export_layers/pygimplib/lib/__init__.py | export_layers/pygimplib/lib/__init__.py | #-------------------------------------------------------------------------------
#
# This file is part of pygimplib.
#
# Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com>
#
# pygimplib is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# t... | #-------------------------------------------------------------------------------
#
# This file is part of pygimplib.
#
# Copyright (C) 2014, 2015 khalim19 <khalim19@gmail.com>
#
# pygimplib is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# t... | Add description for `lib` package | Add description for `lib` package
| Python | bsd-3-clause | khalim19/gimp-plugin-export-layers,khalim19/gimp-plugin-export-layers | ---
+++
@@ -19,4 +19,6 @@
#
#-------------------------------------------------------------------------------
-# empty
+"""
+This package contains external libraries used in the `pygimplib` library.
+""" |
1b07cb1ec2fbe48af4f38a225c2237846ce8b314 | pyramid_es/tests/__init__.py | pyramid_es/tests/__init__.py | import logging
def setUp():
log = logging.getLogger('elasticsearch.trace')
log.setLevel(logging.CRITICAL)
| import logging
def setUp():
log = logging.getLogger('elasticsearch.trace')
log.addHandler(logging.NullHandler())
| Use a better method for silencing 'no handlers found' error | Use a better method for silencing 'no handlers found' error
| Python | mit | storborg/pyramid_es | ---
+++
@@ -3,4 +3,4 @@
def setUp():
log = logging.getLogger('elasticsearch.trace')
- log.setLevel(logging.CRITICAL)
+ log.addHandler(logging.NullHandler()) |
87955b791e702b67afb61eae0cc7abfbde338993 | Python/Product/PythonTools/ptvsd/setup.py | Python/Product/PythonTools/ptvsd/setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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 ... | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. 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 ... | Update ptvsd version number for 2.2 beta. | Update ptvsd version number for 2.2 beta.
| Python | apache-2.0 | Habatchii/PTVS,DEVSENSE/PTVS,denfromufa/PTVS,alanch-ms/PTVS,zooba/PTVS,MetSystem/PTVS,xNUTs/PTVS,Habatchii/PTVS,DinoV/PTVS,crwilcox/PTVS,bolabola/PTVS,DEVSENSE/PTVS,bolabola/PTVS,bolabola/PTVS,int19h/PTVS,crwilcox/PTVS,dut3062796s/PTVS,zooba/PTVS,juanyaw/PTVS,Microsoft/PTVS,Habatchii/PTVS,msunardi/PTVS,msunardi/PTVS,Me... | ---
+++
@@ -18,14 +18,14 @@
from distutils.core import setup
setup(name='ptvsd',
- version='2.1.0',
+ version='2.2.0b1',
description='Python Tools for Visual Studio remote debugging server',
license='Apache License 2.0',
author='Microsoft Corporation',
author_email='ptvshelp@... |
4148c03ce666f12b8b04be7103ae6a969dd0c022 | fabfile.py | fabfile.py | from fabric.api import *
env.hosts = [
'shaperia@lynx.uberspace.de'
]
env.target_directory = './happyman'
def init():
run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory)
with cd(env.target_directory):
run('virtualenv python_virtualenv')
def deploy():
local('... | from fabric.api import *
env.hosts = [
'shaperia@lynx.uberspace.de'
]
env.target_directory = './happyman'
def init():
run('git clone -q https://github.com/skyshaper/happyman.git ' + env.target_directory)
with cd(env.target_directory):
run('virtualenv python_virtualenv')
def deploy():
local('... | Use included carton executable on deploy | Use included carton executable on deploy
| Python | mit | skyshaper/happyman,skyshaper/happyman,skyshaper/happyman | ---
+++
@@ -15,7 +15,7 @@
local('git push')
with cd(env.target_directory):
run('git remote update && git reset --hard origin/master')
- run('carton install --cached --deployment')
+ run('./vendor/bin/carton install --cached --deployment')
with cd('python_virtualenv'):
... |
ddb3bcf4e5d5eb5dc4f8bb74313f333e54c385d6 | scripts/wall_stop.py | scripts/wall_stop.py | #!/usr/bin/env python
import rospy,copy
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from pimouse_ros.msg import LightSensorValues
class WallStop():
def __init__(self):
self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
self.sensor_values = Light... | #!/usr/bin/env python
import rospy,copy
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from pimouse_ros.msg import LightSensorValues
class WallStop():
def __init__(self):
self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
self.sensor_values = Light... | Reduce the name of a function | Reduce the name of a function
| Python | mit | citueda/pimouse_run_corridor,citueda/pimouse_run_corridor | ---
+++
@@ -9,9 +9,9 @@
self.cmd_vel = rospy.Publisher('/cmd_vel',Twist,queue_size=1)
self.sensor_values = LightSensorValues()
- rospy.Subscriber('/lightsensors', LightSensorValues, self.callback_lightsensors)
+ rospy.Subscriber('/lightsensors', LightSensorValues, self.callback)
- ... |
421b2d75f04717dd8acb461bd698ca8355e70480 | python2.7/music-organizer.py | python2.7/music-organizer.py | #!/usr/bin/env python2.7
import os
import re
import sys
from mutagen.easyid3 import EasyID3
replaceChars = (
(" ", "-"),
("(", ""),
(")", ""),
(",", ""),
(".", ""),
("'", ""),
("?", "")
)
def toNeat(s):
s = s.lower()
for r in replaceChars: s = s.replace(r[0], r[1])
search = re.search("[^a-z\-]", s... | #!/usr/bin/env python2.7
import os
import re
import sys
from mutagen.easyid3 import EasyID3
replaceChars = (
(" ", "-"),
("(", ""),
(")", ""),
(",", ""),
(".", ""),
("'", ""),
("?", "")
)
def toNeat(s):
s = s.lower()
for r in replaceChars: s = s.replace(r[0], r[1])
search = re.search("[^0-9a-z\-]"... | Allow 0-9 in song names. | Allow 0-9 in song names.
| Python | mit | bamos/python-scripts,bamos/python-scripts | ---
+++
@@ -17,7 +17,7 @@
def toNeat(s):
s = s.lower()
for r in replaceChars: s = s.replace(r[0], r[1])
- search = re.search("[^a-z\-]", s)
+ search = re.search("[^0-9a-z\-]", s)
if search:
print("Error: Unrecognized character in '" + s + "'")
sys.exit(-42) |
89e22a252adf6494cf59ae2289eb3f9bb1e2a893 | sandcats/trivial_tests.py | sandcats/trivial_tests.py | import requests
def register_asheesh():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
)
| import requests
def register_asheesh():
return requests.post(
'http://localhost:3000/register',
{'rawHostname': 'asheesh',
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
)
def register_asheesh2_bad_key_type():
... | Add test validating key format validation | Add test validating key format validation
| Python | apache-2.0 | sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats,sandstorm-io/sandcats | ---
+++
@@ -7,3 +7,11 @@
'email': 'asheesh@asheesh.org',
'pubkey': open('snakeoil-sample-certs/ssl-cert-snakeoil.pubkey').read()},
)
+
+def register_asheesh2_bad_key_type():
+ return requests.post(
+ 'http://localhost:3000/register',
+ {'rawHostname': 'asheesh2',
+ ... |
b442190966a818338e0e294a6835b30a10753708 | tests/providers/test_nfsn.py | tests/providers/test_nfsn.py | # Test for one implementation of the interface
from lexicon.providers.nfsn import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
import pytest
import os
"""
Some small info about running live tests.
NFSN doesn't have trial accounts, so these tests can only
be run by those with ... | # Test for one implementation of the interface
from lexicon.providers.nfsn import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
import pytest
import os
"""
Some small info about running live tests.
NFSN doesn't have trial accounts, so these tests can only
be run by those with ... | Add default NFSN test url | Add default NFSN test url
| Python | mit | AnalogJ/lexicon,AnalogJ/lexicon | ---
+++
@@ -32,12 +32,12 @@
Provider = Provider
provider_name = 'nfsn'
+ default_domain = 'koupia.xyz'
+
@property
def domain(self):
_domain = os.environ.get('LEXICON_NFSN_DOMAIN')
- if _domain is None:
- raise ValueError('LEXICON_NFSN_DOMAIN must be specified.')
- ... |
78c3589bbb80607321cf2b3e30699cde7df08ed8 | website/addons/s3/tests/factories.py | website/addons/s3/tests/factories.py | # -*- coding: utf-8 -*-
"""Factory boy factories for the Box addon."""
import mock
from datetime import datetime
from dateutil.relativedelta import relativedelta
from factory import SubFactory, Sequence
from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory
from website.add... | # -*- coding: utf-8 -*-
"""Factories for the S3 addon."""
from factory import SubFactory, Sequence
from tests.factories import ModularOdmFactory, UserFactory, ProjectFactory, ExternalAccountFactory
from website.addons.s3.model import (
S3UserSettings,
S3NodeSettings
)
class S3AccountFactory(ExternalAccountFac... | Fix docstring, remove unused import | Fix docstring, remove unused import
| Python | apache-2.0 | SSJohns/osf.io,caseyrollins/osf.io,jnayak1/osf.io,acshi/osf.io,felliott/osf.io,monikagrabowska/osf.io,TomBaxter/osf.io,RomanZWang/osf.io,leb2dg/osf.io,wearpants/osf.io,emetsger/osf.io,acshi/osf.io,chennan47/osf.io,zamattiac/osf.io,mluo613/osf.io,alexschiller/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io... | ---
+++
@@ -1,9 +1,5 @@
# -*- coding: utf-8 -*-
-"""Factory boy factories for the Box addon."""
-import mock
-from datetime import datetime
-from dateutil.relativedelta import relativedelta
-
+"""Factories for the S3 addon."""
from factory import SubFactory, Sequence
from tests.factories import ModularOdmFactory, ... |
09e0073a2aec6abc32a639fb2791af19e17eed1c | test/588-funicular-monorail.py | test/588-funicular-monorail.py | # way 93671417
assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
| # way 93671417
assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
# relation 6060405
assert_has_feature(
16, 18201, 24705, 'transit',
{ 'kind': 'funicular' })
| Add test for funicular feature | Add test for funicular feature
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource | ---
+++
@@ -2,3 +2,8 @@
assert_has_feature(
16, 10486, 25367, 'transit',
{ 'kind': 'monorail' })
+
+# relation 6060405
+assert_has_feature(
+ 16, 18201, 24705, 'transit',
+ { 'kind': 'funicular' }) |
293cbd9ac1ad6c8f53e40fa36c3fdce6d9dda7ec | ynr/apps/uk_results/views/api.py | ynr/apps/uk_results/views/api.py | from rest_framework import viewsets
from django_filters import filters, filterset
from api.v09.views import ResultsSetPagination
from ..models import CandidateResult, ResultSet
from ..serializers import CandidateResultSerializer, ResultSetSerializer
class CandidateResultViewSet(viewsets.ModelViewSet):
queryset ... | from rest_framework import viewsets
from django_filters import filters, filterset
from django.db.models import Prefetch
from api.v09.views import ResultsSetPagination
from popolo.models import Membership
from ..models import CandidateResult, ResultSet
from ..serializers import CandidateResultSerializer, ResultSetSeri... | Speed up results API view | Speed up results API view
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -1,7 +1,9 @@
from rest_framework import viewsets
from django_filters import filters, filterset
+from django.db.models import Prefetch
from api.v09.views import ResultsSetPagination
+from popolo.models import Membership
from ..models import CandidateResult, ResultSet
from ..serializers import Candi... |
f361ee6fb384a3500892a619279e229373a1b35f | src/config/svc-monitor/svc_monitor/tests/test_init.py | src/config/svc-monitor/svc_monitor/tests/test_init.py | import logging
import mock
import unittest
from mock import patch
from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh
class Arguments(object):
def __init__(self):
self.disc_server_ip = None
self.disc_server_port = None
self.collectors = None
s... | import logging
import mock
import unittest
from mock import patch
from svc_monitor.svc_monitor import SvcMonitor
from pysandesh.sandesh_base import Sandesh
class Arguments(object):
def __init__(self):
self.disc_server_ip = None
self.disc_server_port = None
self.collectors = None
s... | Fix svc_monitor tests by adding a missing arg | Fix svc_monitor tests by adding a missing arg
This commit d318b73fbab8f0c200c71adf642968a624a7db29
introduced a cluster_id arg but this arg is not
initialized in the test file.
Change-Id: I770e5f2c949afd408b8906439e711e7f619afa57
| Python | apache-2.0 | hthompson6/contrail-controller,tcpcloud/contrail-controller,rombie/contrail-controller,Juniper/contrail-dev-controller,vpramo/contrail-controller,facetothefate/contrail-controller,eonpatapon/contrail-controller,facetothefate/contrail-controller,numansiddique/contrail-controller,tcpcloud/contrail-controller,tcpcloud/con... | ---
+++
@@ -19,6 +19,7 @@
self.log_file = '/var/log/contrail/svc_monitor.log'
self.use_syslog = False
self.syslog_facility = Sandesh._DEFAULT_SYSLOG_FACILITY
+ self.cluster_id = None
class SvcMonitorInitTest(unittest.TestCase):
def setUp(self): |
9da50045cc9d67df8d8d075a6e2a2dc7e9f137ee | tsa/data/sb5b/tweets.py | tsa/data/sb5b/tweets.py | #!/usr/bin/env python
import os
from tsa.lib import tabular, html
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at least 'Labels' and 'Tweet' fields.'''
for row in tabular... | #!/usr/bin/env python
import os
from tsa.lib import tabular, html
import logging
logger = logging.getLogger(__name__)
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at least ... | Add specific iterable-like pickling handler for sb5b tweet data | Add specific iterable-like pickling handler for sb5b tweet data
| Python | mit | chbrown/tsa,chbrown/tsa,chbrown/tsa | ---
+++
@@ -1,6 +1,10 @@
#!/usr/bin/env python
import os
from tsa.lib import tabular, html
+
+import logging
+logger = logging.getLogger(__name__)
+
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
@@ -17,3 +21,23 @@
... |
c916ea93fc4bcd0383ae7a95ae73f2418e122e1f | Orange/tests/__init__.py | Orange/tests/__init__.py | import os
import unittest
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestLoader().discover(test_dir, )
test_suite = suite()
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| import os
import unittest
from Orange.widgets.tests import test_settings, test_setting_provider
def suite():
test_dir = os.path.dirname(__file__)
return unittest.TestSuite([
unittest.TestLoader().discover(test_dir),
unittest.TestLoader().loadTestsFromModule(test_settings),
unittest.Te... | Test settings when setup.py test is run. | Test settings when setup.py test is run.
| Python | bsd-2-clause | marinkaz/orange3,marinkaz/orange3,qPCR4vir/orange3,qusp/orange3,cheral/orange3,kwikadi/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,kwikadi/orange3,kwikadi/orange3,qPCR4vir/orange3,marinkaz/orange3,... | ---
+++
@@ -1,10 +1,17 @@
import os
import unittest
+
+from Orange.widgets.tests import test_settings, test_setting_provider
def suite():
test_dir = os.path.dirname(__file__)
- return unittest.TestLoader().discover(test_dir, )
+ return unittest.TestSuite([
+ unittest.TestLoader().discover(tes... |
f7d3fa716cd73c5a066aa0e40c337b50880befea | lc005_longest_palindromic_substring.py | lc005_longest_palindromic_substring.py | """Leetcode 5. Longest Palindromic Substring
Medium
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class Solution(object):
def ... | """Leetcode 5. Longest Palindromic Substring
Medium
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd"
Output: "bb"
"""
class SolutionNaive(object):
... | Complete naive longest palindromic substring | Complete naive longest palindromic substring
| Python | bsd-2-clause | bowen0701/algorithms_data_structures | ---
+++
@@ -14,22 +14,48 @@
Output: "bb"
"""
-class Solution(object):
- def longestPalindrome(self, s):
- """
- :type s: str
+class SolutionNaive(object):
+ def longestPalindrome(self, s):
+ """
+ :type s: str
:rtype: str
- """
- pass
+
+ Time limit exceeded.
+ """
+ ... |
4923c2e25cc7547e3b1e1b0ade35a03a931e3f84 | core/management/commands/run_urlscript.py | core/management/commands/run_urlscript.py | import urllib
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandError
from core.models import URL, Cron
def request_url(url):
urllib.urlopen... | try:
from urllib.request import urlopen
except ImportError:
from urllib import urlopen
import datetime
import multiprocessing
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand, CommandEr... | Fix a python3 import . | Fix a python3 import .
| Python | mit | theju/urlscript | ---
+++
@@ -1,4 +1,7 @@
-import urllib
+try:
+ from urllib.request import urlopen
+except ImportError:
+ from urllib import urlopen
import datetime
import multiprocessing
@@ -11,7 +14,7 @@
def request_url(url):
- urllib.urlopen("http://{0}{1}".format(
+ urlopen("http://{0}{1}".format(
Si... |
eab249a092da21d47b07fd9918d4b28dcbc6089b | server/dummy/dummy_server.py | server/dummy/dummy_server.py | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)... | #!/usr/bin/env python
import BaseHTTPServer
ServerClass = BaseHTTPServer.HTTPServer
RequestHandlerClass = BaseHTTPServer.BaseHTTPRequestHandler
SERVER_NAME = ''
SERVER_PORT = 9000
class JsonPostResponder(RequestHandlerClass):
def _get_content_from_stream(self, length, stream):
return stream.read(length)... | Clean up content and header output | Clean up content and header output
| Python | mit | jonspeicher/Puddle,jonspeicher/Puddle,jonspeicher/Puddle | ---
+++
@@ -16,11 +16,8 @@
content_length = int(self.headers['Content-Length'])
content = self._get_content_from_stream(content_length, self.rfile)
- print '\n---> dummy server: got post!'
- print 'command:', self.command
- print 'path:', self.path
- print 'headers:\n\n... |
fad3aa04d54d8804984a9c66bfde79f0f5cd8871 | app/views.py | app/views.py | import random
from flask import render_template, session, request
from app import app
import config
from app import request_logger
from app import questions
@app.route('/', methods=['GET', 'POST'])
def q():
# NOTE: this will break if questions are answered in wrong order
# TODO: make sure that is is not poss... | import random
from flask import render_template, session, request
from app import app
import config
from app import request_logger
from app import questions
@app.route('/', methods=['GET', 'POST'])
def q():
# NOTE: this will break if questions are answered in wrong order
# TODO: make sure that is is not poss... | Add debug page that tells id | Add debug page that tells id
| Python | mit | felixbade/visa | ---
+++
@@ -40,3 +40,7 @@
def again():
session['qnumber'] = 0
return q()
+
+@app.route('/id')
+def id():
+ return str(session['id']) |
c788398c2c89a7afcbbf899e7ed4d51fccf114b5 | php_coverage/command.py | php_coverage/command.py | import sublime_plugin
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(CoverageCommand, self).__init__(view)
self.co... | import sublime_plugin
from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
class CoverageCommand(sublime_plugin.TextCommand):
"""
Base class for a text command which has a coverage file.
"""
def __init__(self, view, coverage_finder=None):
super(Co... | Return coverage data in CoverageCommand::coverage() | Return coverage data in CoverageCommand::coverage()
| Python | mit | bradfeehan/SublimePHPCoverage,bradfeehan/SublimePHPCoverage | ---
+++
@@ -1,4 +1,6 @@
import sublime_plugin
+
+from php_coverage.data import CoverageDataFactory
from php_coverage.finder import CoverageFinder
@@ -24,7 +26,12 @@
def coverage(self):
"""
- Finds the coverage file which contains coverage data for the
- file open in the view which ... |
35a5e8717df9a5bcb60593700aa7e2f291816b0f | test/test_extensions/test_analytics.py | test/test_extensions/test_analytics.py | # encoding: utf-8
import time
from web.core.context import Context
from web.ext.analytics import AnalyticsExtension
def test_analytics_extension():
ctx = Context(response=Context(headers=dict()))
ext = AnalyticsExtension()
assert not hasattr(ctx, '_start_time')
ext.prepare(ctx)
assert hasattr(ctx, '_start_... | # encoding: utf-8
import time
import pytest
from webob import Request
from web.core import Application
from web.core.context import Context
from web.ext.analytics import AnalyticsExtension
def endpoint(context):
time.sleep(0.1)
return "Hi."
sample = Application(endpoint, extensions=[AnalyticsExtension()])
def... | Add test for full processing pipeline. | Add test for full processing pipeline.
| Python | mit | marrow/WebCore,marrow/WebCore | ---
+++
@@ -1,9 +1,20 @@
# encoding: utf-8
import time
+import pytest
+from webob import Request
+from web.core import Application
from web.core.context import Context
from web.ext.analytics import AnalyticsExtension
+
+
+def endpoint(context):
+ time.sleep(0.1)
+ return "Hi."
+
+
+sample = Application(endpoi... |
92d5e7078c86b50c0682e70e115271355442cea2 | pixie/utils/__init__.py | pixie/utils/__init__.py | # Standard library imports
import json
# Our setup file
with open('../../pixie/setup.json') as file:
setup_file = json.load(file)
# Our user agent
user_agent = "Pixie (https://github.com/GetRektByMe/Pixie)"
# A function to use with checks to check for owner
def is_owner(ctx):
return ctx.message.author.id ==... | # Standard library imports
import json
# Our setup file
with open('../setup.json') as file:
setup_file = json.load(file)
# Our user agent
user_agent = "Pixie (https://github.com/GetRektByMe/Pixie)"
# A function to use with checks to check for owner
def is_owner(ctx):
return ctx.message.author.id == setup_fi... | Change method of search for utils setup_file | Change method of search for utils setup_file
| Python | mit | GetRektByMe/Pixie | ---
+++
@@ -2,7 +2,7 @@
import json
# Our setup file
-with open('../../pixie/setup.json') as file:
+with open('../setup.json') as file:
setup_file = json.load(file)
# Our user agent |
01a832d1c761eda01ad94f29709c8e76bd7e82fe | project/models.py | project/models.py | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | import datetime
from project import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String, unique=True, nullable=False)
password = db.Column(db.String, nullable=False)
registered_on = db.Column(db.DateTime, nullable=Fal... | Add rating field to User model | Add rating field to User model
| Python | mit | dylanshine/streamschool,dylanshine/streamschool | ---
+++
@@ -14,6 +14,7 @@
admin = db.Column(db.Boolean, nullable=False, default=False)
confirmed = db.Column(db.Boolean, nullable=False, default=False)
confirmed_on = db.Column(db.DateTime, nullable=True)
+ rating = db.Column(db.Float, nullable=True)
def __init__(self, email, password, confir... |
a013cdbe690271c4ec9bc172c994ff5f6e5808c4 | test/test_assetstore_model_override.py | test/test_assetstore_model_override.py | import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(se... | import pytest
from girder.models.file import File
from girder.models.model_base import Model
from girder.utility import assetstore_utilities
from girder.utility.model_importer import ModelImporter
from girder.utility.abstract_assetstore_adapter import AbstractAssetstoreAdapter
class Fake(Model):
def initialize(se... | Improve clarity of fake assetstore model fixture | Improve clarity of fake assetstore model fixture
| Python | apache-2.0 | data-exp-lab/girder,girder/girder,manthey/girder,kotfic/girder,Xarthisius/girder,jbeezley/girder,girder/girder,manthey/girder,kotfic/girder,RafaelPalomar/girder,girder/girder,data-exp-lab/girder,girder/girder,manthey/girder,Xarthisius/girder,RafaelPalomar/girder,RafaelPalomar/girder,RafaelPalomar/girder,Kitware/girder,... | ---
+++
@@ -23,10 +23,7 @@
def fakeModel(db):
ModelImporter.registerModel('fake', Fake(), plugin='fake_plugin')
- yield Fake().save({
- 'foo': 'bar',
- 'type': 'fake'
- })
+ yield Fake
ModelImporter.unregisterModel('fake', plugin='fake_plugin')
@@ -41,9 +38,14 @@
def testA... |
817d9c78f939de2b01ff518356ed0414178aaa6d | avalonstar/apps/api/serializers.py | avalonstar/apps/api/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class SeriesSerializer(serializers.ModelSerializ... | # -*- coding: utf-8 -*-
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class RaidSerializer(serializers.ModelSeri... | Add Raid to the API. | Add Raid to the API.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | ---
+++
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from rest_framework import serializers
-from apps.broadcasts.models import Broadcast, Series
+from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
@@ -9,6 +9,11 @@
class Meta:
depth = 1
model = Bro... |
1275fec0e485deef75a4e12956acb919a9fb7439 | tests/modules/myInitialPythonModule.py | tests/modules/myInitialPythonModule.py | from jtapi import *
import os
import sys
import re
import numpy as np
from scipy import misc
mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1)
#########
# input #
#########
print('jt - %s:' % mfilename)
handles_stream = sys.stdin
handles = gethandles(handles_stream)
input_args = readinputargs(h... | from jtapi import *
import os
import sys
import re
import numpy as np
from scipy import misc
mfilename = re.search('(.*).py', os.path.basename(__file__)).group(1)
#########
# input #
#########
print('jt - %s:' % mfilename)
handles_stream = sys.stdin
handles = gethandles(handles_stream)
input_args = readinputargs(h... | Add more detailed print in first module | Add more detailed print in first module
| Python | mit | brainy-minds/Jterator,brainy-minds/Jterator,brainy-minds/Jterator,brainy-minds/Jterator | ---
+++
@@ -26,6 +26,7 @@
myImageFilename = input_args['myImageFilename']
+print '>>>>> loading "myImage" from "%s"' % myImageFilename
myImage = np.array(misc.imread(myImageFilename), dtype='float64')
print('>>>>> "myImage" has type "%s" and dimensions "%s".' % |
6deebdc7e5c93d5f61cad97870cea7fb445bb860 | onitu/utils.py | onitu/utils.py | import time
import redis
def connect_to_redis(*args, **kwargs):
client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs)
while True:
try:
assert client.ping()
except (redis.exceptions.ConnectionError, AssertionError):
time.sleep(0.5)
else:
... | import time
import redis
def connect_to_redis(*args, **kwargs):
client = redis.Redis(
*args,
unix_socket_path='redis/redis.sock',
decode_responses=True,
**kwargs
)
while True:
try:
assert client.ping()
except (redis.exceptions.ConnectionError, ... | Convert Redis keys and values to str | Convert Redis keys and values to str
| Python | mit | onitu/onitu,onitu/onitu,onitu/onitu | ---
+++
@@ -4,7 +4,12 @@
def connect_to_redis(*args, **kwargs):
- client = redis.Redis(*args, unix_socket_path='redis/redis.sock', **kwargs)
+ client = redis.Redis(
+ *args,
+ unix_socket_path='redis/redis.sock',
+ decode_responses=True,
+ **kwargs
+ )
while True:
... |
2049dbe3f672041b7b0e93b0b444a6ebb47f723a | streak-podium/read.py | streak-podium/read.py | import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
Query Github A... | import logging
import requests
def input_file(filename):
"""
Read a file and return list of usernames.
Assumes one username per line and ignores blank lines.
"""
with open(filename, 'r') as f:
return list(line.strip() for line in f if line.strip())
def org_members(org_name):
"""
... | Add missing 'logging' module import | Add missing 'logging' module import
| Python | mit | jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,supermitch/streak-podium,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak | ---
+++
@@ -1,3 +1,5 @@
+import logging
+
import requests
|
4d410dec85fc944717a6537e9eef2585a53159b6 | python_logging_rabbitmq/formatters.py | python_logging_rabbitmq/formatters.py | # coding: utf-8
import logging
from socket import gethostname
from .compat import json, text_type
class JSONFormatter(logging.Formatter):
"""
Formatter to convert LogRecord into JSON.
Thanks to: https://github.com/lobziik/rlog
"""
def __init__(self, *args, **kwargs):
include = kwargs.pop(... | # coding: utf-8
import logging
from socket import gethostname
from django.core.serializers.json import DjangoJSONEncoder
from .compat import json, text_type
class JSONFormatter(logging.Formatter):
"""
Formatter to convert LogRecord into JSON.
Thanks to: https://github.com/lobziik/rlog
"""
def __i... | Use DjangoJSONEncoder for JSON serialization | Use DjangoJSONEncoder for JSON serialization
| Python | mit | albertomr86/python-logging-rabbitmq | ---
+++
@@ -2,6 +2,7 @@
import logging
from socket import gethostname
+from django.core.serializers.json import DjangoJSONEncoder
from .compat import json, text_type
@@ -38,6 +39,7 @@
data = {f: data[f] for f in self.include}
elif self.exclude:
for f in self.exclude:
- ... |
bce093df2bbcf12d8eec8f812408a0ea88521d10 | squid_url_cleaner.py | squid_url_cleaner.py | #!/usr/bin/python
import sys
from url_cleaner import removeBlackListedParameters
while True:
line = sys.stdin.readline().strip()
urlList = line.split(' ')
urlInput = urlList[0]
newUrl = removeBlackListedParameters(urlInput)
sys.stdout.write('%s%s' % (newUrl, '\n'))
sys.stdout.flush()
| #!/usr/bin/python
import sys
import signal
from url_cleaner import removeBlackListedParameters
def sig_handle(signal, frame):
sys.exit(0)
while True:
signal.signal(signal.SIGINT, sig_handle)
signal.signal(signal.SIGTERM, sig_handle)
try:
line = sys.stdin.readline().strip()
urlList =... | Handle signals for daemon processes, removed deprecated python var sub | Handle signals for daemon processes, removed deprecated python var sub
| Python | mit | Ladoo/url_cleaner | ---
+++
@@ -1,13 +1,23 @@
#!/usr/bin/python
import sys
+import signal
from url_cleaner import removeBlackListedParameters
+def sig_handle(signal, frame):
+ sys.exit(0)
+
while True:
- line = sys.stdin.readline().strip()
- urlList = line.split(' ')
- urlInput = urlList[0]
- newUrl = removeBlac... |
e71e42ec8b7ee80937a983a80db61f4e450fb764 | tests/__init__.py | tests/__init__.py | from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sq... | from json import loads
from os import close, unlink
from tempfile import mkstemp
from unittest import TestCase
from cunhajacaiu import app
class FlaskTestCase(TestCase):
def setUp(self):
# set a test db
self.db_handler, self.db_path = mkstemp()
app.config['SQLALCHEMY_DATABASE_URI'] = 'sq... | Test the only untested line | Test the only untested line
| Python | mit | cuducos/cunhajacaiu,cuducos/cunhajacaiu,cuducos/cunhajacaiu | ---
+++
@@ -25,6 +25,9 @@
class MockJsonNewsResponse:
+ HTTP_STATUS_CODE = (500, 200)
+ COUNT = 0
+
@staticmethod
def json():
with open('tests/news.json') as file_handler:
@@ -32,4 +35,5 @@
@property
def status_code(self):
- return 200
+ self.COUNT += 1
+ ... |
d773b01721ab090021139fb9a9397cddd89bd487 | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
# REV - This has no effect - http://stackoverflow.com/q/18558666/656912
def pytest_report_header(config):
return "Testing Enigma functionality"
| #!/usr/bin/env python
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
from crypto_enigma import __version__
def pytest_report_header(config):
return "version: {}".format(__version__) | Add logging of tested package version | Add logging of tested package version
| Python | bsd-3-clause | orome/crypto-enigma-py | ---
+++
@@ -2,6 +2,8 @@
# encoding: utf8
from __future__ import (absolute_import, print_function, division, unicode_literals)
-# REV - This has no effect - http://stackoverflow.com/q/18558666/656912
+from crypto_enigma import __version__
+
+
def pytest_report_header(config):
- return "Testing Enigma functiona... |
c2731d22adbf2abc29d73f5759d5d9f0fa124f5f | tests/fixtures.py | tests/fixtures.py | from . import uuid
def task_crud(self, shotgun, trigger_poll=lambda: None):
name = uuid(8)
a = shotgun.create('Task', {'content': name})
trigger_poll()
b = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
self.assertSameEntity(a, b)
name += '-2'
shotgun.update('Task', a... | from . import uuid
def task_crud(self, shotgun, trigger_poll=lambda: None):
shot_name = uuid(8)
shot = shotgun.create('Shot', {'code': shot_name})
name = uuid(8)
task = shotgun.create('Task', {'content': name, 'entity': shot})
trigger_poll()
x = self.cached.find_one('Task', [('id', 'is', ta... | Add entity link to basic crud tests | Add entity link to basic crud tests
| Python | bsd-3-clause | westernx/sgcache,westernx/sgcache | ---
+++
@@ -3,19 +3,35 @@
def task_crud(self, shotgun, trigger_poll=lambda: None):
+ shot_name = uuid(8)
+ shot = shotgun.create('Shot', {'code': shot_name})
+
name = uuid(8)
- a = shotgun.create('Task', {'content': name})
+ task = shotgun.create('Task', {'content': name, 'entity': shot})
t... |
85b94f0d9caef0b1d22763371b1279ae2f433944 | pyinfra_cli/__main__.py | pyinfra_cli/__main__.py | import os
import signal
import sys
import click
import gevent
import pyinfra
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Set CLI mode
pyinfra.is_cli = True
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) be... | import os
import signal
import sys
import click
import gevent
import pyinfra
from .legacy import run_main_with_legacy_arguments
from .main import cli, main
# Set CLI mode
pyinfra.is_cli = True
# Don't write out deploy.pyc/config.pyc etc
sys.dont_write_bytecode = True
# Make sure imported files (deploy.py/etc) be... | Fix support for older gevent versions. | Fix support for older gevent versions.
Gevent 1.5 removed the `gevent.signal` alias, but some older versions
do not have the new `signal_handler` function.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | ---
+++
@@ -33,7 +33,13 @@
sys.exit(0)
-gevent.signal_handler(signal.SIGINT, gevent.kill) # kill any greenlets on ctrl+c
+try:
+ # Kill any greenlets on ctrl+c
+ gevent.signal_handler(signal.SIGINT, gevent.kill)
+except AttributeError:
+ # Legacy (gevent <1.2) support
+ gevent.signal(signal.SIGI... |
90132a3e4f9a0a251d9d1738703e6e927a0e23af | pytest_pipeline/utils.py | pytest_pipeline/utils.py | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
if unzip:
opener... | # -*- coding: utf-8 -*-
"""
pytest_pipeline.utils
~~~~~~~~~~~~~~~~~~~~~
General utilities.
:copyright: (c) 2014 Wibowo Arindrarto <bow@bow.web.id>
:license: BSD
"""
import gzip
import hashlib
import os
def file_md5sum(fname, unzip=False, blocksize=65536, encoding="utf-8"):
if unzip:
... | Use 'rb' mode explicitly in file_md5sum and allow for custom encoding | Use 'rb' mode explicitly in file_md5sum and allow for custom encoding
| Python | bsd-3-clause | bow/pytest-pipeline | ---
+++
@@ -15,14 +15,14 @@
import os
-def file_md5sum(fname, unzip=False, mode="r", blocksize=65536):
+def file_md5sum(fname, unzip=False, blocksize=65536, encoding="utf-8"):
if unzip:
opener = gzip.open
else:
opener = open
hasher = hashlib.md5()
- with opener(fname, mode) ... |
bc16915aa3c4a7cef456da4193bdcdc34117eab0 | tests/test_classes.py | tests/test_classes.py | import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html file and ungzip
@classmethod
def setUpClass(cls):
requester = MockRequests()
#... | import unittest
import os
import gzip
import bs4
import logging
from classes import (
NbaTeam
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
class MockRequests:
def get(self, url):
pass
class TestNbaTeamPage(unittest.TestCase):
# read html ... | Add more NbaTeam class tests | Add more NbaTeam class tests
| Python | mit | arosenberg01/asdata | ---
+++
@@ -6,6 +6,10 @@
from classes import (
NbaTeam
)
+
+logger = logging.getLogger()
+logger.setLevel(logging.INFO)
+logger.addHandler(logging.StreamHandler())
class MockRequests:
def get(self, url):
@@ -16,18 +20,28 @@
@classmethod
def setUpClass(cls):
- requester = MockRequests... |
29baa0a57fe49c790d4ef5dcdde1e744fc83efde | boundary/alarm_create.py | boundary/alarm_create.py | #
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | #
# Copyright 2015 BMC Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | Remove no needed to duplicate parent behaviour | Remove no needed to duplicate parent behaviour
| Python | apache-2.0 | boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/boundary-api-cli | ---
+++
@@ -39,8 +39,4 @@
def get_description(self):
return 'Creates an alarm definition in an {0} account'.format(self.product_name)
- def get_api_parameters(self):
- AlarmModify.get_api_parameters(self)
- self.path = 'v1/alarms'
- |
8d7b2597e73ca82e016e635fe0db840070b7bd7a | semillas_backend/users/serializers.py | semillas_backend/users/serializers.py | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | #from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from drf_extra_fields.geo_fields import PointField
from .models import User
class UserSerializer(serializers.ModelSerializer):
""" Usage:
from rest_framework.renderers import JSONRenderer
from ... | Add uuid to update user serializer | Add uuid to update user serializer
| Python | mit | Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_platform,Semillas/semillas_backend | ---
+++
@@ -24,10 +24,11 @@
#phone = PhoneNumberField(required=False)
email = serializers.CharField(required=False)
picture = serializers.ImageField(required=False)
+ uuid = serializers.CharField(read_only=True)
class Meta:
model = User
- fields = ('name', 'picture', 'phone', ... |
5bc3e6a3fb112b529f738142850860dd98a9d428 | tests/runtests.py | tests/runtests.py | import glob
import os
import unittest
def build_test_suite():
suite = unittest.TestSuite()
for test_case in glob.glob('tests/test_*.py'):
modname = os.path.splitext(test_case)[0]
modname = modname.replace('/', '.')
module = __import__(modname, {}, {}, ['1'])
suite.addTest(unit... | import glob
import os
import unittest
import sys
def build_test_suite():
suite = unittest.TestSuite()
for test_case in glob.glob('tests/test_*.py'):
modname = os.path.splitext(test_case)[0]
modname = modname.replace('/', '.')
module = __import__(modname, {}, {}, ['1'])
suite.ad... | Make unittest return exit code 1 on failure | Make unittest return exit code 1 on failure
This is to allow travis to catch test failures
| Python | bsd-3-clause | jorgecarleitao/pyglet-gui | ---
+++
@@ -1,7 +1,7 @@
import glob
import os
import unittest
-
+import sys
def build_test_suite():
suite = unittest.TestSuite()
@@ -19,4 +19,5 @@
suite = build_test_suite()
runner = unittest.TextTestRunner()
- runner.run(suite)
+ result = runner.run(suite)
+ sys.exit(not result.wasSuc... |
ecb3e8e9bea6388d2368fefdd24037f933a78dfe | tests/settings.py | tests/settings.py | """Settings file for the Django project used for tests."""
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
PROJECT_NAME = 'project'
# Base paths.
ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.join(ROOT, PROJECT_NAME)
# Django configuration.
DATABASES = {'default... | """Settings file for the Django project used for tests."""
import os
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
PROJECT_NAME = 'project'
# Base paths.
ROOT = os.path.abspath(os.path.dirname(__file__))
PROJECT = os.path.join(ROOT, PROJECT_NAME)
# Django configuration.
DATABASES = {'default... | Support providing SECRET_KEY as environment variable. | Support providing SECRET_KEY as environment variable.
| Python | mit | poswald/django-endless-pagination,poswald/django-endless-pagination,catalpainternational/django-endless-pagination,igorkramaric/django-endless-pagination,poswald/django-endless-pagination,kjefes/django-endless-pagination,igorkramaric/django-endless-pagination,catalpainternational/django-endless-pagination,catalpaintern... | ---
+++
@@ -20,7 +20,7 @@
PROJECT_NAME,
)
ROOT_URLCONF = PROJECT_NAME + '.urls'
-SECRET_KEY = 'secret'
+SECRET_KEY = os.getenv('ENDLESS_PAGINATION_SECRET_KEY', 'secret')
SITE_ID = 1
STATIC_ROOT = os.path.join(PROJECT, 'static')
STATIC_URL = '/static/' |
d4412f8573dbfc1b06f2a298cc5c3042c6c468e6 | tests/test_api.py | tests/test_api.py | from django.test import TestCase
from django_snooze import apis
class APITestCase(TestCase):
def setUp(self):
"""Sets up an API object to play with.
:returns: None
"""
self.api = apis.api
self.api.discover_models()
def test_apps(self):
"""Test if the right ap... | from django.test import TestCase
from django_snooze import apis
class APITestCase(TestCase):
def setUp(self):
"""Sets up an API object to play with.
:returns: None
"""
self.api = apis.api
self.api.discover_models()
def test_apps(self):
"""Test if the right ap... | Test to see if abstract classes sneak in. | Test to see if abstract classes sneak in.
Now that get_models has been found to skip abstract classes, we want to test
for this in case this behaviour ever changes.
| Python | bsd-3-clause | ainmosni/django-snooze,ainmosni/django-snooze | ---
+++
@@ -20,3 +20,5 @@
"""
self.assertIn('tests', self.api._resources.keys())
self.assertIn('auth', self.api._resources.keys())
+ tests_models = [x.model_name for x in self.api._resources['tests']]
+ self.assertNotIn('abstract', tests_models) |
4a9f0f909abb955ca579b3abec7c6ffef83429af | cli_tests.py | cli_tests.py | import unittest
from unittest.mock import patch, call
from crc import main
class CliTests(unittest.TestCase):
def test_cli_no_arguments_provided(self):
expected_exit_code = -1
argv = []
with patch('sys.exit') as exit_mock:
main(argv)
self.assertTrue(exit_mock.calle... | #!/usr/bin/env python3
#
# Copyright (c) 2021, Nicola Coretti
# All rights reserved.
import unittest
from unittest.mock import patch, call
from crc import main
class CliTests(unittest.TestCase):
def test_cli_no_arguments_provided(self):
expected_exit_code = -1
argv = []
with patch('sys.ex... | Add shebang to cli_tets.py module | Add shebang to cli_tets.py module
| Python | bsd-2-clause | Nicoretti/crc | ---
+++
@@ -1,3 +1,7 @@
+#!/usr/bin/env python3
+#
+# Copyright (c) 2021, Nicola Coretti
+# All rights reserved.
import unittest
from unittest.mock import patch, call
from crc import main |
1a5583fdba626059e5481e6099b14b8988316dfe | server/superdesk/locators/__init__.py | server/superdesk/locators/__init__.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import json
... | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import json
... | Fix locators reading on ubuntu | Fix locators reading on ubuntu
| Python | agpl-3.0 | thnkloud9/superdesk,superdesk/superdesk,marwoodandrew/superdesk-aap,ancafarcas/superdesk,ioanpocol/superdesk-ntb,gbbr/superdesk,liveblog/superdesk,plamut/superdesk,pavlovicnemanja92/superdesk,akintolga/superdesk,pavlovicnemanja92/superdesk,pavlovicnemanja/superdesk,verifiedpixel/superdesk,amagdas/superdesk,akintolga/su... | ---
+++
@@ -19,7 +19,7 @@
:param file_path: path of the file having JSON string.
:return: JSON Object
"""
- with open(file_path, 'r') as f:
+ with open(file_path, 'r', encoding='utf-8') as f:
return json.load(f)
|
cffaea8986aa300a632d3a0d39219431efe80f9e | rever/__init__.py | rever/__init__.py | import builtins
# setup xonsh ctx and execer
builtins.__xonsh_ctx__ = {}
from xonsh.execer import Execer
builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__)
from xonsh.shell import Shell
builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__,
ctx=builtins.__xonsh_c... | import builtins
# setup xonsh ctx and execer
builtins.__xonsh_ctx__ = {}
from xonsh.execer import Execer
builtins.__xonsh_execer__ = Execer(xonsh_ctx=builtins.__xonsh_ctx__)
from xonsh.shell import Shell
builtins.__xonsh_shell__ = Shell(builtins.__xonsh_execer__,
ctx=builtins.__xonsh_c... | Raise on subproc error everywhere in rever | Raise on subproc error everywhere in rever
| Python | bsd-3-clause | ergs/rever,scopatz/rever | ---
+++
@@ -9,6 +9,8 @@
ctx=builtins.__xonsh_ctx__,
shell_type='none')
+builtins.__xonsh_env__['RAISE_SUBPROC_ERROR'] = True
+
# setup import hooks
import xonsh.imphooks
xonsh.imphooks.install_import_hooks() |
1b75e25746305ec47a72874e854744c395cceec6 | src/ocspdash/constants.py | src/ocspdash/constants.py | import os
import requests.utils
from . import __name__, __version__
OCSPDASH_API_VERSION = 'v0'
OCSPDASH_DIRECTORY = os.path.join(os.path.expanduser('~'), '.ocspdash')
if not os.path.exists(OCSPDASH_DIRECTORY):
os.makedirs(OCSPDASH_DIRECTORY)
OCSPDASH_DATABASE_PATH = os.path.join(OCSPDASH_DIRECTORY, 'ocspdash... | import os
import requests.utils
from . import __name__, __version__
OCSPDASH_API_VERSION = 'v0'
OCSPDASH_DIRECTORY = os.environ.get('OCSPDASH_DIRECTORY', os.path.join(os.path.expanduser('~'), '.ocspdash'))
if not os.path.exists(OCSPDASH_DIRECTORY):
os.makedirs(OCSPDASH_DIRECTORY)
OCSPDASH_DATABASE_CONNECTION ... | Allow config to be set from environment | Allow config to be set from environment
| Python | mit | scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash | ---
+++
@@ -6,14 +6,13 @@
OCSPDASH_API_VERSION = 'v0'
-OCSPDASH_DIRECTORY = os.path.join(os.path.expanduser('~'), '.ocspdash')
+OCSPDASH_DIRECTORY = os.environ.get('OCSPDASH_DIRECTORY', os.path.join(os.path.expanduser('~'), '.ocspdash'))
if not os.path.exists(OCSPDASH_DIRECTORY):
os.makedirs(OCSPDASH_DIR... |
255ef7b16258c67586d14e6c8d8d531a3553cd3e | bot/games/tests/test_game_queryset.py | bot/games/tests/test_game_queryset.py | from django.test import TestCase
from ..models import Game
class QuerySetTests(TestCase):
def test_get_by_name(self):
gta_v = Game.objects.create(name='GTA V')
Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v)
game = Game.objects.get_by_name('gta V')
self.assertEq... | # -*- coding: utf-8 -*-
from django.test import TestCase
from ..models import Game
class QuerySetTests(TestCase):
def test_get_by_name(self):
gta_v = Game.objects.create(name='GTA V')
Game.objects.create(name='Grand Theft Auto V', alias_for=gta_v)
game = Game.objects.get_by_name('gta V... | Add extra test for regression | Add extra test for regression
| Python | mit | sergei-maertens/discord-bot,sergei-maertens/discord-bot,sergei-maertens/discord-bot | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from django.test import TestCase
from ..models import Game
@@ -19,3 +20,12 @@
# non-existing game should be created
overwatch = Game.objects.get_by_name('Overwatch')
self.assertIsNotNone(overwatch.pk)
+
+ def test_get_by_name_distinct(... |
b0b8483b6ff7085585a480308d553d2dd4c84c8b | pi/cli.py | pi/cli.py | import logging
import pkgutil
import pi
import pi.commands
commands = {}
for imp_importer, name, ispkg in pkgutil.iter_modules(pi.commands.__path__):
fullname = pi.commands.__name__ + '.' + name
# if fullname not in sys.modules:
imp_loader = imp_importer.find_module(fullname)
module = imp_loader.load... | import logging
import pkgutil
import pi
import pi.commands
commands = {}
for imp_importer, name, ispkg in pkgutil.iter_modules(pi.commands.__path__):
fullname = pi.commands.__name__ + '.' + name
# if fullname not in sys.modules:
imp_loader = imp_importer.find_module(fullname)
module = imp_loader.load... | Add short flags for version and verbose to match 'python' command | Add short flags for version and verbose to match 'python' command
| Python | mit | chbrown/pi | ---
+++
@@ -19,8 +19,8 @@
parser = argparse.ArgumentParser(description='Python package manipulation',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('command', choices=commands, help='Command to run')
- parser.add_argument('--version', action='version', version=pi.__... |
8e131a0382bac04aa8e04a4aeb3f9cf31d36671f | stock_move_description/__openerp__.py | stock_move_description/__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-15 Agile Business Group sagl
# (<http://www.agilebg.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Publ... | Remove delivery from depends as useless | Remove delivery from depends as useless
| Python | agpl-3.0 | open-synergy/stock-logistics-workflow,gurneyalex/stock-logistics-workflow,brain-tec/stock-logistics-workflow,Antiun/stock-logistics-workflow,BT-jmichaud/stock-logistics-workflow,Eficent/stock-logistics-workflow,gurneyalex/stock-logistics-workflow,archetipo/stock-logistics-workflow,acsone/stock-logistics-workflow,BT-fga... | ---
+++
@@ -27,7 +27,6 @@
'license': 'AGPL-3',
'depends': [
'stock_account',
- 'delivery',
],
'data': [
'security/stock_security.xml', |
d4dd06558287c655477ce9da9542f748d0261695 | notebooks/computer_vision/track_meta.py | notebooks/computer_vision/track_meta.py | # See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
course_name='computer_vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision'
)
lessons = [
dict(
# By convention, this should be a lowercase n... | # See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
course_name='Computer Vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision'
)
lessons = [
{'topic': topic_name} for topic_name in
[
'The Convolut... | Add tracking for lessons 1, 2, 3 | Add tracking for lessons 1, 2, 3
| Python | apache-2.0 | Kaggle/learntools,Kaggle/learntools | ---
+++
@@ -1,25 +1,43 @@
# See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
- course_name='computer_vision',
+ course_name='Computer Vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision'
)
lessons = [... |
2e63438deb6f733e7e905f4ea299aa0bdce88b3c | changes/api/author_build_index.py | changes/api/author_build_index.py | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
i... | from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
from uuid import UUID
from changes.api.base import APIView
from changes.api.auth import get_current_user
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self,... | Validate author_id and return 404 for missing data | Validate author_id and return 404 for missing data
| Python | apache-2.0 | wfxiang08/changes,dropbox/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes | ---
+++
@@ -1,6 +1,7 @@
from __future__ import absolute_import, division, unicode_literals
from sqlalchemy.orm import joinedload
+from uuid import UUID
from changes.api.base import APIView
from changes.api.auth import get_current_user
@@ -12,9 +13,13 @@
if author_id == 'me':
user = get_c... |
00435d8f0cc906878cd6084c78c17cbc5a49b66e | spacy/tests/parser/test_beam_parse.py | spacy/tests/parser/test_beam_parse.py | # coding: utf8
from __future__ import unicode_literals
import pytest
@pytest.mark.models('en')
def test_beam_parse(EN):
doc = EN(u'Australia is a country', disable=['ner'])
ents = EN.entity(doc, beam_width=2)
print(ents)
| # coding: utf8
from __future__ import unicode_literals
import pytest
from ...language import Language
from ...pipeline import DependencyParser
@pytest.mark.models('en')
def test_beam_parse_en(EN):
doc = EN(u'Australia is a country', disable=['ner'])
ents = EN.entity(doc, beam_width=2)
print(ents)
def t... | Add extra beam parsing test | Add extra beam parsing test
| Python | mit | aikramer2/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,recognai/spaCy,aikramer2/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/sp... | ---
+++
@@ -2,10 +2,22 @@
from __future__ import unicode_literals
import pytest
+from ...language import Language
+from ...pipeline import DependencyParser
@pytest.mark.models('en')
-def test_beam_parse(EN):
+def test_beam_parse_en(EN):
doc = EN(u'Australia is a country', disable=['ner'])
ents = EN... |
c03b731d9fcd64a0989c6b73245578eafc099b4f | greenquote.py | greenquote.py | import sys
import os
from threading import Thread
from flask import Flask
import pandas as pd
sys.path.insert(0, "../financialScraper")
from financialScraper import getqf
from sqlalchemy import create_engine
app = Flask(__name__)
app.config['DATABASE'] = os.environ.get(
'HEROKU_POSTGRESQL_GOLD_URL', ''
)
engine = cr... | import sys
import os
from threading import Thread
from flask import Flask
import pandas as pd
sys.path.insert(0, "../financialScraper")
from financialScraper import getqf
from sqlalchemy import create_engine
app = Flask(__name__)
# app.config['DATABASE'] = os.environ.get(
# 'HEROKU_POSTGRESQL_GOLD_URL', ''
# )
# eng... | Comment more to test heroku deployment. | Comment more to test heroku deployment.
| Python | mit | caseymacphee/green_quote,caseymacphee/green_quote | ---
+++
@@ -8,10 +8,10 @@
from sqlalchemy import create_engine
app = Flask(__name__)
-app.config['DATABASE'] = os.environ.get(
- 'HEROKU_POSTGRESQL_GOLD_URL', ''
- )
-engine = create_engine(app.config['DATABASE'])
+# app.config['DATABASE'] = os.environ.get(
+# 'HEROKU_POSTGRESQL_GOLD_URL', ''
+# )
+# engine = c... |
671aeff6fbdab93945a7b8a8f242bff9afc6a613 | src/odin/fields/future.py | src/odin/fields/future.py | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""... | from __future__ import absolute_import
from enum import Enum
from typing import TypeVar, Optional, Any, Type # noqa
from odin.exceptions import ValidationError
from . import Field
__all__ = ("EnumField",)
ET = TypeVar("ET", Enum, Enum)
class EnumField(Field):
"""
Field for handling Python enums.
"""... | Fix value is "" hand value being None in prepare | Fix value is "" hand value being None in prepare
| Python | bsd-3-clause | python-odin/odin | ---
+++
@@ -48,11 +48,11 @@
# If value is an empty string return None
# Do this check here to support enums that define an option using
# an empty string.
- if value is "":
+ if value == "":
return
raise ValidationError(self.er... |
c8c3227cba90a931edb9ae7ee89c5318258a2f25 | todoist/managers/live_notifications.py | todoist/managers/live_notifications.py | # -*- coding: utf-8 -*-
from .generic import Manager, GetByIdMixin, AllMixin, SyncMixin
class LiveNotificationsManager(Manager, GetByIdMixin, AllMixin, SyncMixin):
state_name = 'live_notifications'
object_type = None # there is no object type associated
def set_last_read(self, id):
"""
... | # -*- coding: utf-8 -*-
from .generic import Manager, GetByIdMixin, AllMixin, SyncMixin
class LiveNotificationsManager(Manager, GetByIdMixin, AllMixin, SyncMixin):
state_name = 'live_notifications'
object_type = None # there is no object type associated
def set_last_read(self, id):
"""
... | Add support for new is_unread live notification state. | Add support for new is_unread live notification state.
| Python | mit | Doist/todoist-python | ---
+++
@@ -9,7 +9,7 @@
def set_last_read(self, id):
"""
- Sets in the local state the last notification read.
+ Sets the last known notification.
"""
cmd = {
'type': 'live_notifications_set_last_read',
@@ -19,3 +19,39 @@
},
}
... |
0fb16c44b13ca467fb8ede67bdc93450712cb2bb | test/tiles/hitile_test.py | test/tiles/hitile_test.py | import dask.array as da
import h5py
import clodius.tiles.hitile as hghi
import numpy as np
import os.path as op
import tempfile
def test_hitile():
array_size = int(1e6)
chunk_size = 2**19
data = da.from_array(np.random.random((array_size,)), chunks=(chunk_size,))
with tempfile.TemporaryDirectory() a... | import dask.array as da
import h5py
import clodius.tiles.hitile as hghi
import numpy as np
import os.path as op
import tempfile
def test_hitile():
array_size = int(1e6)
chunk_size = 2**19
data = np.random.random((array_size,))
with tempfile.TemporaryDirectory() as td:
output_file = op.join(t... | Fix error of applying dask twice | Fix error of applying dask twice
| Python | mit | hms-dbmi/clodius,hms-dbmi/clodius | ---
+++
@@ -10,11 +10,13 @@
array_size = int(1e6)
chunk_size = 2**19
- data = da.from_array(np.random.random((array_size,)), chunks=(chunk_size,))
+ data = np.random.random((array_size,))
with tempfile.TemporaryDirectory() as td:
output_file = op.join(td, 'blah.hitile')
- hghi... |
dabc4eb0ad59599a0e801a3af5423861c7dd2105 | test_valid_object_file.py | test_valid_object_file.py | from astropy.table import Table
TABLE_NAME = 'feder_object_list.csv'
def test_table_can_be_read():
objs = Table.read(TABLE_NAME, format='ascii', delimiter=',')
columns = ['object', 'ra', 'dec']
for col in columns:
assert col in objs.colnames
| from astropy.table import Table
from astropy.coordinates import ICRS, name_resolve
from astropy import units as u
TABLE_NAME = 'feder_object_list.csv'
MAX_SEP = 5 # arcsec
def test_table_can_be_read_and_coords_good():
objs = Table.read(TABLE_NAME, format='ascii', delimiter=',')
columns = ['object', 'ra', 'd... | Add test that object coordinates are accurate | Add test that object coordinates are accurate
Skips over any cases where simbad cannot resolve the name, so it is not perfect...
| Python | bsd-2-clause | mwcraig/feder-object-list | ---
+++
@@ -1,10 +1,27 @@
from astropy.table import Table
+from astropy.coordinates import ICRS, name_resolve
+from astropy import units as u
TABLE_NAME = 'feder_object_list.csv'
+MAX_SEP = 5 # arcsec
-def test_table_can_be_read():
+def test_table_can_be_read_and_coords_good():
objs = Table.read(TABLE_N... |
358dc8e31477c27da8f286f19daa736489625035 | tests/integ/test_basic.py | tests/integ/test_basic.py | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | Use consistent load for integ test stability | Use consistent load for integ test stability
| Python | mit | numberoverzero/bloop,numberoverzero/bloop | ---
+++
@@ -24,13 +24,13 @@
same_user.profile = "second"
engine.save(same_user)
- engine.load(user)
+ engine.load(user, consistent=True)
assert user.profile == same_user.profile
engine.delete(user)
with pytest.raises(MissingObjects) as excinfo:
- engine.load(same_user)
+ ... |
a2b2e6b79ac28d886b3bb682beeadab06018de66 | test/copies/gyptest-attribs.py | test/copies/gyptest-attribs.py | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that copying files preserves file attributes.
"""
import TestGyp
import os
import stat
import sys
def check_attribs(path, e... | #!/usr/bin/env python
# Copyright (c) 2013 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that copying files preserves file attributes.
"""
import TestGyp
import os
import stat
import sys
def check_attribs(path, e... | Disable new test from r1779 for the android generator. | Disable new test from r1779 for the android generator.
BUG=gyp:379
TBR=torne@chromium.org
Review URL: https://codereview.chromium.org/68333002 | Python | bsd-3-clause | witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp,witwall/gyp | ---
+++
@@ -24,7 +24,8 @@
test.fail_test()
-test = TestGyp.TestGyp()
+# Doesn't pass with the android generator, see gyp bug 379.
+test = TestGyp.TestGyp(formats=['!android'])
test.run_gyp('copies-attribs.gyp', chdir='src')
|
2c86118cfa2c75787fea22909aaec767e432151e | tests/test_add_language/decorators.py | tests/test_add_language/decorators.py | # tests.decorators
import sys
from functools import wraps
from StringIO import StringIO
from mock import patch
def redirect_stdout(func):
"""temporarily redirect stdout to new output stream"""
@wraps(func)
def wrapper(*args, **kwargs):
original_stdout = sys.stdout
out = StringIO()
... | # tests.decorators
import sys
from functools import wraps
from StringIO import StringIO
def redirect_stdout(func):
"""temporarily redirect stdout to new output stream"""
@wraps(func)
def wrapper(*args, **kwargs):
original_stdout = sys.stdout
out = StringIO()
try:
sys.s... | Remove use_user_prefs decorator for add_language | Remove use_user_prefs decorator for add_language
| Python | mit | caleb531/youversion-suggest,caleb531/youversion-suggest | ---
+++
@@ -3,8 +3,6 @@
import sys
from functools import wraps
from StringIO import StringIO
-
-from mock import patch
def redirect_stdout(func):
@@ -19,14 +17,3 @@
finally:
sys.stdout = original_stdout
return wrapper
-
-
-def use_user_prefs(user_prefs):
- """temporarily use the ... |
bc005622a6fcce2ec53bf93a9b6519f923904a61 | turbustat/statistics/stats_warnings.py | turbustat/statistics/stats_warnings.py | # Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
''' | # Licensed under an MIT open source license - see LICENSE
from __future__ import print_function, absolute_import, division
class TurbuStatTestingWarning(Warning):
'''
Turbustat.statistics warning for untested methods.
'''
class TurbuStatMetricWarning(Warning):
'''
Turbustat.statistics warning fo... | Add warning for where a distance metric is being misused | Add warning for where a distance metric is being misused
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat | ---
+++
@@ -6,3 +6,9 @@
'''
Turbustat.statistics warning for untested methods.
'''
+
+
+class TurbuStatMetricWarning(Warning):
+ '''
+ Turbustat.statistics warning for misusing a distance metric.
+ ''' |
dfd02ec10a904c5ce52162fa512e0850c789ce32 | language_explorer/staging_settings.py | language_explorer/staging_settings.py | # Prod-like, but with resources in different locations
# Data sources
LANGUAGE_EXPLORER_DB_URL = 'postgresql://esteele@/language_explorer'
JPHARVEST_DB_URL = 'postgresql://esteele@/jpharvest'
WALS_DB_URL = 'postgresql://esteele@/wals2013'
SIL_RCEM_TSV_SOURCE = '/home/esteele/lex_data_bundle/iso-639-3_Retirements.tab'
... | # Prod-like, but with resources in different locations
# Data sources
LANGUAGE_EXPLORER_DB_URL = 'postgresql://esteele@/language_explorer'
JPHARVEST_DB_URL = 'postgresql://esteele@/jpharvest'
WALS_DB_URL = 'postgresql://esteele@/wals2013'
SIL_RCEM_TSV_SOURCE = '/home/esteele/lex_data_bundle/iso-639-3_Retirements.tab'
... | Use staging for creating a static copy, so refer to in-place assets, not deployed assets | Use staging for creating a static copy, so refer to in-place assets, not deployed assets
| Python | mit | edwinsteele/language_explorer,edwinsteele/language_explorer,edwinsteele/language_explorer | ---
+++
@@ -5,7 +5,7 @@
JPHARVEST_DB_URL = 'postgresql://esteele@/jpharvest'
WALS_DB_URL = 'postgresql://esteele@/wals2013'
SIL_RCEM_TSV_SOURCE = '/home/esteele/lex_data_bundle/iso-639-3_Retirements.tab'
-CENSUS_CSV_SOURCE = '/home/esteele/lex_data_bundle/census_2011_LANP_ENGLP.csv'
+CENSUS_CSV_SOURCE = '/Users/e... |
db8524c1085c16552e548dc7c702f80747804814 | unittesting/helpers/view_test_case.py | unittesting/helpers/view_test_case.py | import sublime
from unittest import TestCase
class ViewTestCase(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
settings = self.view.settings()
default_settings = getattr(self.__class__, 'view_settings', {})
for key, value in default_settings.items():
... | import sublime
from unittest import TestCase
class ViewTestCase(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
settings = self.view.settings()
default_settings = getattr(self.__class__, 'view_settings', {})
for key, value in default_settings.items():
... | Use view.close() to close view. | Use view.close() to close view.
| Python | mit | randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting,randy3k/UnitTesting | ---
+++
@@ -15,8 +15,7 @@
def tearDown(self):
if self.view:
self.view.set_scratch(True)
- self.view.window().focus_view(self.view)
- self.view.window().run_command("close_file")
+ self.view.close()
def _viewContents(self):
return self.view.su... |
c23acde7428d968016af760afe9624c138fc3074 | test/library/gyptest-shared-obj-install-path.py | test/library/gyptest-shared-obj-install-path.py | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
import... | #!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
# Pyth... | Add with_statement import for python2.5. | Add with_statement import for python2.5.
See http://www.python.org/dev/peps/pep-0343/ which describes
the with statement.
Review URL: http://codereview.chromium.org/5690003
| Python | bsd-3-clause | csulmone/gyp,csulmone/gyp,csulmone/gyp,csulmone/gyp | ---
+++
@@ -8,6 +8,9 @@
Verifies that .so files that are order only dependencies are specified by
their install location rather than by their alias.
"""
+
+# Python 2.5 needs this for the with statement.
+from __future__ import with_statement
import os
import TestGyp |
5a4317a22f84355de98a09bba408bfba6d895507 | examples/g/modulegen.py | examples/g/modulegen.py | #! /usr/bin/env python
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
def my_module_gen(out_file):
mod = Module('g')
mod.add_include('"g.h"')
mod.add_function('GDoA', None, [])
G = mod.add_cpp_namespace("G")
G.add_function('GDoB', None, [... | #! /usr/bin/env python
import sys
import pybindgen
from pybindgen import ReturnValue, Parameter, Module, Function, FileCodeSink
def my_module_gen(out_file):
mod = Module('g')
mod.add_include('"g.h"')
mod.add_function('GDoA', None, [])
G = mod.add_cpp_namespace("G")
G.add_function('GDoB', None, [... | Add wrapping of std::ofstream to the example | Add wrapping of std::ofstream to the example | Python | lgpl-2.1 | gjcarneiro/pybindgen,gjcarneiro/pybindgen,cawka/pybindgen-old,cawka/pybindgen-old,ftalbrecht/pybindgen,cawka/pybindgen-old,ftalbrecht/pybindgen,ftalbrecht/pybindgen,gjcarneiro/pybindgen,gjcarneiro/pybindgen,ftalbrecht/pybindgen,cawka/pybindgen-old | ---
+++
@@ -15,6 +15,21 @@
GInner = G.add_cpp_namespace("GInner")
GInner.add_function('GDoC', None, [])
+ G.add_include('<fstream>')
+
+ ofstream = G.add_class('ofstream', foreign_cpp_namespace='::std')
+ ofstream.add_enum('openmode', [
+ ('app', 'std::ios_base::app'),
+ ('a... |
88210804900c48a895c6ed90ae20dd08dc32e162 | alfred_listener/views.py | alfred_listener/views.py | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload', '')
try:
pa... | from flask import Blueprint, request, json
from alfred_db.models import Repository, Commit
from .database import db
from .helpers import parse_hook_data
webhooks = Blueprint('webhooks', __name__)
@webhooks.route('/', methods=['POST'])
def handler():
payload = request.form.get('payload')
try:
payloa... | Improve loading of payload from json | Improve loading of payload from json
| Python | isc | alfredhq/alfred-listener | ---
+++
@@ -10,10 +10,10 @@
@webhooks.route('/', methods=['POST'])
def handler():
- payload = request.form.get('payload', '')
+ payload = request.form.get('payload')
try:
payload_data = json.loads(payload)
- except ValueError:
+ except (ValueError, TypeError):
return 'Bad reques... |
c86c32453e241543317509495357e05c73b57047 | django_tenant_templates/middleware.py | django_tenant_templates/middleware.py | """
Middleware!
"""
from django_tenant_templates import local
class TenantMiddleware(object):
"""Middleware for enabling tenant-aware template loading."""
slug_property_name = 'tenant_slug'
def process_request(self, request):
local.tenant_slug = getattr(request, self.slug_property_name, None)
| """
Middleware!
"""
from django_tenant_templates import local
class TenantMiddleware(object):
"""Middleware for enabling tenant-aware template loading."""
slug_property_name = 'tenant_slug'
def process_request(self, request):
local.tenant_slug = getattr(request, self.slug_property_name, None)
... | Remove the thread local on exceptions | Remove the thread local on exceptions
| Python | mit | grampajoe/django-tenant-templates | ---
+++
@@ -10,3 +10,9 @@
def process_request(self, request):
local.tenant_slug = getattr(request, self.slug_property_name, None)
+
+ def process_exception(self, request, exception):
+ try:
+ del local.tenant_slug
+ except AttributeError:
+ pass |
cd5e52c8e1d481c8e1bf1e7a71b0c421e53c93c9 | featureflow/__init__.py | featureflow/__init__.py | __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider... | __version__ = '1.16.14'
from model import BaseModel
from feature import Feature, JSONFeature, TextFeature, CompressedFeature, \
PickleFeature
from extractor import Node, Graph, Aggregator, NotEnoughData
from bytestream import ByteStream, ByteStreamFeature, ZipWrapper, iter_zip
from data import \
IdProvider... | Add EventLog stuff to package-level exports | Add EventLog stuff to package-level exports
| Python | mit | JohnVinyard/featureflow,JohnVinyard/featureflow | ---
+++
@@ -30,6 +30,8 @@
from iteratornode import IteratorNode
+from eventlog import EventLog, RedisChannel
+
try:
from nmpy import NumpyEncoder, PackedNumpyEncoder, StreamingNumpyDecoder, \
BaseNumpyDecoder, NumpyMetaData, NumpyFeature |
e56e50cdecafd9de67255afe4567bc6c41cf2474 | skyfield/tests/test_against_horizons.py | skyfield/tests/test_against_horizons.py | """Tests against HORIZONS numbers."""
from skyfield import api
# see the top-level project ./horizons/ directory for where the
# following numbers come from; soon, we should automate the fetching of
# such numbers and their injection into test cases, as we do for results
# from NOVAS.
"""
Date__(UT)__HR:MN hEcl... | """Tests against HORIZONS numbers."""
from skyfield import api
# see the top-level project ./horizons/ directory for where the
# following numbers come from; soon, we should automate the fetching of
# such numbers and their injection into test cases, as we do for results
# from NOVAS.
"""
Date__(UT)__HR:MN hEcl... | Fix .format() patterns in test for Python 2.6 | Fix .format() patterns in test for Python 2.6
| Python | mit | GuidoBR/python-skyfield,ozialien/python-skyfield,skyfielders/python-skyfield,skyfielders/python-skyfield,exoanalytic/python-skyfield,GuidoBR/python-skyfield,ozialien/python-skyfield,exoanalytic/python-skyfield | ---
+++
@@ -18,8 +18,8 @@
def test_ecliptic_latlon():
astrometric = api.sun(utc=(1980, 1, 1)).observe(api.jupiter)
lat, lon, distance = astrometric.ecliptic_latlon()
- assert '{:.4f}'.format(lat.degrees) == '1.0130'
- assert '{:.4f}'.format(lon.degrees) == '151.3227'
+ assert '{0:.4f}'.format(lat.... |
fca7ad2068dfec30ad210964234957b46e6436bc | tests/test_client.py | tests/test_client.py | import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
}
def setUp(self):
self.client = Client(env='live', **self.... | import unittest
from bluesnap.client import Client
class ClientTestCase(unittest.TestCase):
DUMMY_CREDENTIALS = {
'username': 'username',
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
'default_currency': 'GBP'
}
def setUp(self):
self.c... | Send default_currency in Client init on client test | Send default_currency in Client init on client test
| Python | mit | kowito/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python,justyoyo/bluesnap-python | ---
+++
@@ -9,6 +9,7 @@
'password': 'password',
'default_store_id': '1',
'seller_id': '1',
+ 'default_currency': 'GBP'
}
def setUp(self): |
c83e0134104d4ee6de9a3e5b7d0e34be2a684daa | tests/test_shared.py | tests/test_shared.py | # -*- coding: utf-8 -*-
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DA... | # -*- coding: utf-8 -*-
from flask.ext.testing import TestCase
import os
import tempfile
import shutil
import websmash
class ModelTestCase(TestCase):
def create_app(self):
self.app = websmash.app
self.dl = websmash.dl
self.app.config['TESTING'] = True
self.app.config['SQLALCHEMY_DA... | Fix the temp file initialization | tests: Fix the temp file initialization
Signed-off-by: Kai Blin <94ddc6985b47aef772521e302594241f46a8f665@biotech.uni-tuebingen.de>
| Python | agpl-3.0 | antismash/ps-web,antismash/ps-web,antismash/websmash,antismash/ps-web | ---
+++
@@ -32,8 +32,11 @@
super(WebsmashTestCase, self).setUp()
self.tmpdir = tempfile.mkdtemp()
(fd, self.tmp_name) = tempfile.mkstemp(dir=self.tmpdir, suffix='.fa')
- self.tmp_file = os.fdopen(fd, 'w+b')
- self.tmp_file.write('>test\nATGACCGAGAGTACATAG\n')
+ tmp_file... |
184d31de904fad249c618766c715fef94ed4f369 | tools/upload_pending_delete.py | tools/upload_pending_delete.py | #!/usr/bin/env python
import sys
import os
import random
import urllib
import urllib2
import re
# POST_URL = 'http://localhost:8000/domains/'
POST_URL = 'http://scoretool.appspot.com/domains/'
TOP_LEVEL_DOMAINS = 'com net org'.split()
NAMES_PER_REQUEST = 200
def upload(filename):
date, tld, ext = os.path.basen... | #!/usr/bin/env python
import sys
import os
import random
import urllib
import urllib2
import re
# POST_URL = 'http://localhost:8000/domains/'
POST_URL = 'http://scoretool.appspot.com/domains/'
TOP_LEVEL_DOMAINS = 'com net org'.split()
NAMES_PER_REQUEST = 200
def upload(filename):
date, tld, ext = os.path.basen... | Split filename only twice (allow ext to contain dots). | Split filename only twice (allow ext to contain dots).
| Python | mit | jcrocholl/nxdom,jcrocholl/nxdom | ---
+++
@@ -15,7 +15,7 @@
def upload(filename):
- date, tld, ext = os.path.basename(filename).split('.')
+ date, tld, ext = os.path.basename(filename).split('.', 2)
names = []
for line in open(filename):
names.extend(line.split()) |
5547b0bfcd3903d7786be91c136366ada9c3ebae | detection.py | detection.py | import os
import sys
import datetime
from django.utils import timezone
from datetime import timedelta
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "madapp.settings")
from django.core.management import execute_from_command_line
from django.db.models import Count, Avg
from madapp import settings
from madapp.mad.mode... | import os
import sys
import datetime
import django
import commands
from django.utils import timezone
from datetime import timedelta
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "madapp.settings")
from django.core.management import execute_from_command_line
from django.db.models import Count, Avg
import django.db.... | Change in the Flows storage | Change in the Flows storage
| Python | apache-2.0 | gilneidp/TADD,gilneidp/TADD,gilneidp/TADD,gilneidp/TADD,gilneidp/TADD | ---
+++
@@ -1,26 +1,32 @@
import os
import sys
import datetime
+import django
+import commands
+
+
from django.utils import timezone
from datetime import timedelta
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "madapp.settings")
from django.core.management import execute_from_command_line
from django.db.m... |
474ba4b8983c0f0f40e7a9a7e045cec79dc6845f | SigmaPi/Secure/models.py | SigmaPi/Secure/models.py | from django.db import models
from django.contrib.auth.models import Group
class CalendarKey(models.Model):
# The group which has access to this key.
group = models.ForeignKey(Group, related_name="calendar_key", default=1)
# The calendar key.
key = models.CharField(max_length=100)
| from django.db import models
from django.contrib.auth.models import Group
class CalendarKey(models.Model):
# The group which has access to this key.
group = models.ForeignKey(Group, related_name="calendar_key", default=1)
# The calendar key.
key = models.CharField(max_length=100)
def __unicode__... | Add __unicode__ method to CalendarKey model. | Add __unicode__ method to CalendarKey model.
| Python | mit | sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web,sigmapi-gammaiota/sigmapi-web | ---
+++
@@ -9,3 +9,5 @@
# The calendar key.
key = models.CharField(max_length=100)
+ def __unicode__(self):
+ return self.group + " " + self.key |
60f88e2e90ff411f121236a0e44100ca2022f9bb | test_sequencer.py | test_sequencer.py | def run(tests):
print '=> Going to run', len(tests), 'tests'
ok = []
fail = []
for number, test in enumerate(tests):
print '\t-> [' + str(number) + '/' + str(len(tests)) + ']', test.__doc__
error = test()
if error is None:
ok.append((number, test))
else:
... | import sys
# "Test" is a function. It takes no arguments and returns any encountered errors.
# If there is no error, test should return 'None'. Tests shouldn't have any dependencies
# amongst themselves.
def run(tests):
"""If no arguments (sys.argv) are given, runs tests. If there are any arguments they are
... | Use formatted strings, add tests filter | Use formatted strings, add tests filter
| Python | mit | fmfi-svt-deadlock/hw-testing,fmfi-svt-deadlock/hw-testing | ---
+++
@@ -1,9 +1,27 @@
+import sys
+
+# "Test" is a function. It takes no arguments and returns any encountered errors.
+# If there is no error, test should return 'None'. Tests shouldn't have any dependencies
+# amongst themselves.
+
+
def run(tests):
- print '=> Going to run', len(tests), 'tests'
+ """If n... |
9c42a7925d4e872a6245301ef68b2b9aa1f0aa7b | tests/__init__.py | tests/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | Declare unittest lib used within python version | Declare unittest lib used within python version
| Python | apache-2.0 | glorizen/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,gorakhargosh/watchdog,javrasya/watchdog,ymero/watchdog,javrasya/watchdog,mconstantin/watchdog,teleyinex/watchdog,teleyinex/watchdog,glorizen/watchdog,glorizen/watchdog,gorakhargosh/watchdog,mconstantin/watchdog,ymero/watchdog | ---
+++
@@ -15,3 +15,15 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+
+from sys import version_info
+from os import name as OS_NAME
+
+__all__= ['unittest', 'skipIfNtMove']
+
+if... |
c68c88c0d90512bf315312b137b9a10ec5eee03e | tests/__init__.py | tests/__init__.py | import sys
# The unittest module got a significant overhaul
# in 2.7, so if we're in 2.6 we can use the backported
# version unittest2.
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest
else:
import unittest
| Add the compatiblity for py2.6 | Add the compatiblity for py2.6
| Python | apache-2.0 | henrysher/kamboo,henrysher/kamboo | ---
+++
@@ -0,0 +1,10 @@
+import sys
+
+
+# The unittest module got a significant overhaul
+# in 2.7, so if we're in 2.6 we can use the backported
+# version unittest2.
+if sys.version_info[:2] == (2, 6):
+ import unittest2 as unittest
+else:
+ import unittest | |
3ae6c0f4c4f13207386dbf0fa2004655e9f2c8d6 | UM/View/CompositePass.py | UM/View/CompositePass.py | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from UM.Application import Application
from UM.Resources import Resources
from UM.Math.Matrix import Matrix
from UM.View.RenderPass import RenderPass
from UM.View.GL.OpenGL import OpenGL
class CompositePass(RenderPass):
... | Add explicit render layer binding instead of assuming all render passes can be used for compositing | Add explicit render layer binding instead of assuming all render passes can be used for compositing
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | ---
+++
@@ -11,31 +11,37 @@
class CompositePass(RenderPass):
def __init__(self, width, height):
- super().__init__("composite", width, height)
+ super().__init__("composite", width, height, 999)
self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shader... |
46566c568b20a037006cf7bbebdc70353e163bb2 | paintings/processors.py | paintings/processors.py | from random import randrange
from paintings.models import Gallery, Painting
def get_Galleries(request):
return ( {'galleries' : Gallery.objects.all()} )
def get_random_canvasOilPainting(request):
paintings = Painting.objects.filter(surface='canvas', material='oil').extra(where=['width > height'])
rand_painting ... | from random import randrange
from paintings.models import Gallery, Painting
def get_Galleries(request):
return ( {'galleries' : Gallery.objects.all()} )
def get_random_canvasOilPainting(request):
try:
paintings = Painting.objects.filter(surface='canvas', material='oil').extra(where=['width > height'])
rand_p... | Fix bug with empty db | Fix bug with empty db
| Python | mit | hombit/olgart,hombit/olgart,hombit/olgart,hombit/olgart | ---
+++
@@ -8,6 +8,9 @@
def get_random_canvasOilPainting(request):
- paintings = Painting.objects.filter(surface='canvas', material='oil').extra(where=['width > height'])
- rand_painting = paintings[ randrange( paintings.__len__() ) ]
+ try:
+ paintings = Painting.objects.filter(surface='canvas', material='oil'... |
5b4c710df7149b0654fc731979978a9a561614a3 | wluopensource/osl_flatpages/models.py | wluopensource/osl_flatpages/models.py | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('con... | from django.db import models
import markdown
class Flatpage(models.Model):
page_name = models.CharField(max_length=100, primary_key=True, unique=True)
title = models.CharField(blank=True, max_length=100)
description = models.CharField(blank=True, max_length=255)
markdown_content = models.TextField('con... | Change flatpage ordering to order by page name ascending | Change flatpage ordering to order by page name ascending
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | ---
+++
@@ -8,6 +8,9 @@
markdown_content = models.TextField('content')
content = models.TextField(editable=False)
+ class Meta:
+ ordering = ['page_name']
+
def __unicode__(self):
return self.page_name
|
b6833a9ee7da9a59e50710c0bd4d3ad0b83439ab | fabfile.py | fabfile.py | import unipath
from fabric.api import *
from fabric.contrib import files
# Fab settings
env.hosts = ['ve.djangoproject.com']
# Deployment environment paths and settings and such.
env.deploy_base = unipath.Path('/home/buildbot')
env.virtualenv = env.deploy_base
env.code_dir = env.deploy_base.child('master')
env.git_ur... | import unipath
from fabric.api import *
from fabric.contrib import files
# Fab settings
env.hosts = ['ve.djangoproject.com']
env.user = "buildbot"
# Deployment environment paths and settings and such.
env.deploy_base = unipath.Path('/home/buildbot')
env.virtualenv = env.deploy_base
env.code_dir = env.deploy_base.chil... | Deploy as the buildbot user, not root. | Deploy as the buildbot user, not root.
| Python | bsd-3-clause | jacobian-archive/django-buildmaster,hochanh/django-buildmaster | ---
+++
@@ -4,6 +4,7 @@
# Fab settings
env.hosts = ['ve.djangoproject.com']
+env.user = "buildbot"
# Deployment environment paths and settings and such.
env.deploy_base = unipath.Path('/home/buildbot')
@@ -23,7 +24,7 @@
restart()
def restart():
- sudo('service buildbot restart')
+ pass #sudo('se... |
b9b095a2a66f79e36bbad1affaeb57b38e20803b | cwod_site/cwod/models.py | cwod_site/cwod/models.py | from django.db import models
# Create your models here.
class CongressionalRecordVolume(models.Model):
congress = models.IntegerField(db_index=True)
session = models.CharField(max_length=10, db_index=True)
volume = models.IntegerField()
| from django.db import models
# Create your models here.
class CongressionalRecordVolume(models.Model):
congress = models.IntegerField(db_index=True)
session = models.CharField(max_length=10, db_index=True)
volume = models.IntegerField()
class NgramDateCount(models.Model):
"""Storing the total number... | Create model for storing total n-gram counts by date | Create model for storing total n-gram counts by date
| Python | bsd-3-clause | sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words,sunlightlabs/Capitol-Words,sunlightlabs/Capitol-Words,propublica/Capitol-Words,propublica/Capitol-Words | ---
+++
@@ -6,3 +6,16 @@
congress = models.IntegerField(db_index=True)
session = models.CharField(max_length=10, db_index=True)
volume = models.IntegerField()
+
+
+class NgramDateCount(models.Model):
+ """Storing the total number of ngrams per date
+ allows us to show the percentage of a given ng... |
906c71ed59a6349aed83cd18248dfe8463e3a028 | src/integrate_tool.py | src/integrate_tool.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from bioblend import galaxy
from bioblend import toolshed
if __name__ == '__main__':
gi_url = "http://172.21.23.6:8080/"
ts_url = "http://172.21.23.6:9009/"
name = "qiime"
owner = "iuc"
tool_panel_section_id = "qiime_rRNA_taxonomic_assignation"
g... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import argparse
import re
from bioblend import galaxy
from bioblend import toolshed
def retrieve_changeset_revision(ts_url, name, owner):
ts = toolshed.ToolShedInstance(url=ts_url)
ts_repositories = ts.repositories.get_repositories()
ts_... | Improve integrate tool wrapper with arguments | Improve integrate tool wrapper with arguments
| Python | apache-2.0 | ASaiM/framework,ASaiM/framework | ---
+++
@@ -1,25 +1,48 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+import sys
+import os
+import argparse
+import re
from bioblend import galaxy
from bioblend import toolshed
+def retrieve_changeset_revision(ts_url, name, owner):
+ ts = toolshed.ToolShedInstance(url=ts_url)
+ ts_repositories = t... |
310d7043666726d503dc80894b072d3a7ae29f16 | html_snapshots/utils.py | html_snapshots/utils.py | import rmc.shared.constants as c
import rmc.models as m
import mongoengine as me
import os
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
HTML_DIR = os.path.join(FILE_DIR, 'html')
me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT)
def write(file_path, content):
ensure_dir(file_path)
wi... | import rmc.shared.constants as c
import rmc.models as m
import mongoengine as me
import os
FILE_DIR = os.path.dirname(os.path.realpath(__file__))
HTML_DIR = os.path.join(FILE_DIR, 'html')
me.connect(c.MONGO_DB_RMC, host=c.MONGO_HOST, port=c.MONGO_PORT)
def write(file_path, content):
ensure_dir(file_path)
wi... | Fix url path for homepage for sitemap | Fix url path for homepage for sitemap
| Python | mit | rageandqq/rmc,ccqi/rmc,rageandqq/rmc,sachdevs/rmc,UWFlow/rmc,shakilkanji/rmc,sachdevs/rmc,duaayousif/rmc,MichalKononenko/rmc,duaayousif/rmc,sachdevs/rmc,JGulbronson/rmc,shakilkanji/rmc,UWFlow/rmc,JGulbronson/rmc,rageandqq/rmc,sachdevs/rmc,UWFlow/rmc,rageandqq/rmc,shakilkanji/rmc,shakilkanji/rmc,UWFlow/rmc,UWFlow/rmc,JG... | ---
+++
@@ -22,7 +22,7 @@
def generate_urls():
urls = []
# Home page
- urls.append('/')
+ urls.append('')
# Course pages
for course in m.Course.objects:
course_id = course.id |
90fa23d1d1b2497d65507b7930323b118f512a25 | disco_aws_automation/disco_acm.py | disco_aws_automation/disco_acm.py | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
... | """
Some code to manage the Amazon Certificate Service.
"""
import logging
import boto3
import botocore
class DiscoACM(object):
"""
A class to manage the Amazon Certificate Service
"""
def __init__(self, connection=None):
self._acm = connection
@property
def acm(self):
"""
... | Revert "Swallow proxy exception from requests" | Revert "Swallow proxy exception from requests"
This reverts commit 8d9ccbb2bbde7c2f8dbe60b90f730d87b924d86e.
| Python | bsd-2-clause | amplifylitco/asiaq,amplifylitco/asiaq,amplifylitco/asiaq | ---
+++
@@ -41,6 +41,6 @@
certs = self.acm.list_certificates()["CertificateSummaryList"]
cert = [cert['CertificateArn'] for cert in certs if cert['DomainName'] == dns_name]
return cert[0] if cert else None
- except (botocore.exceptions.EndpointConnectionError, botocore.ve... |
e3c12bd54e143086dd332a51195e4eb3f7305201 | exercise3.py | exercise3.py | #!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__... | #!/usr/bin/env python
""" Assignment 1, Exercise 3, INF1340, Fall, 2015. Troubleshooting Car Issues.
This module contains one function diagnose_car(). It is an expert system to
interactive diagnose car issues.
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__... | Update - First question yes, small coding done | Update - First question yes, small coding done
| Python | mit | xueshen3/inf1340_2015_asst1 | ---
+++
@@ -25,5 +25,20 @@
Errors:
"""
+ # First Trouble shooting Question
+ print("Troubleshooting Car Issues")
+ print("For all questions answer y for Yes or n for No")
+
+ # First Question is Yes
+ question1 = raw_input("Is the car silent when you turn the key?")
+ if question1 == "y":... |
b6afc5f1db5c416fde43567623161bbe2244897b | docs/conf.py | docs/conf.py | #!/usr/bin/env python3
project = "dependencies"
copyright = "2016-2018, Artem Malyshev"
author = "Artem Malyshev"
version = "0.15"
release = "0.15"
templates_path = ["templates"]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
html_theme = ... | #!/usr/bin/env python3
project = "dependencies"
copyright = "2016-2018, Artem Malyshev"
author = "Artem Malyshev"
version = "0.15"
release = "0.15"
templates_path = ["templates"]
source_suffix = ".rst"
master_doc = "index"
language = None
exclude_patterns = ["_build"]
pygments_style = "sphinx"
html_theme = ... | Add Next/Previous page links to the docs. | Add Next/Previous page links to the docs.
| Python | bsd-2-clause | proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies | ---
+++
@@ -42,6 +42,7 @@
html_theme_options = {
"show_powered_by": False,
"show_related": True,
+ "show_relbars": True,
"description": "Dependency Injection for Humans. It provides a simple low-impact implementation of an IoC container and resolution support for your classes.",
"github_user"... |
ccc98ced56ee8dda02332720c7146e1548a3b53c | project/project/urls.py | project/project/urls.py | """
project URL Configuration
"""
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
url(r'^accounts/logout/$', 'allauth.account.views.logout', name='account_logout'),
... | """
project URL Configuration
"""
from django.conf.urls import include, url
from django.conf import settings
from django.contrib import admin
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls')),
... | Set up redirect to login view | Set up redirect to login view
| Python | mit | jonsimington/app,compsci-hfh/app,compsci-hfh/app,jonsimington/app | ---
+++
@@ -3,15 +3,20 @@
"""
from django.conf.urls import include, url
+from django.conf import settings
from django.contrib import admin
+from django.views.generic.base import RedirectView
+
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin_tools/', include('admin_tools.urls'... |
6c04c2dc0647f7103000aee2996ce243f7fe3535 | thinc/tests/layers/test_hash_embed.py | thinc/tests/layers/test_hash_embed.py | import numpy
from thinc.api import HashEmbed
def test_init():
model = HashEmbed(64, 1000).initialize()
assert model.get_dim("nV") == 1000
assert model.get_dim("nO") == 64
assert model.get_param("E").shape == (1001, 64)
def test_seed_changes_bucket():
model1 = HashEmbed(64, 1000, seed=2).initiali... | import numpy
from thinc.api import HashEmbed
def test_init():
model = HashEmbed(64, 1000).initialize()
assert model.get_dim("nV") == 1000
assert model.get_dim("nO") == 64
assert model.get_param("E").shape == (1000, 64)
def test_seed_changes_bucket():
model1 = HashEmbed(64, 1000, seed=2).initiali... | Fix off-by-one in HashEmbed test | Fix off-by-one in HashEmbed test
| Python | mit | explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc | ---
+++
@@ -6,7 +6,7 @@
model = HashEmbed(64, 1000).initialize()
assert model.get_dim("nV") == 1000
assert model.get_dim("nO") == 64
- assert model.get_param("E").shape == (1001, 64)
+ assert model.get_param("E").shape == (1000, 64)
def test_seed_changes_bucket(): |
5dc63d9c544f0335cd037bc2f6c0ce613e7783ea | gerrit/documentation.py | gerrit/documentation.py | # -*- coding: utf-8 -*-
URLS = {
}
class Documentation(object):
""" This class provide documentation-related methods
Documentation related REST endpoints:
https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html
"""
def __init__(self, gerrit):
self.gerrit = gerrit... | # -*- coding: utf-8 -*-
URLS = {
'SEARCH': 'Documentation/?q=%(keyword)s',
}
class Documentation(object):
""" This class provide documentation-related methods
Documentation related REST endpoints:
https://gerrit-review.googlesource.com/Documentation/rest-api-documentation.html
"""
def __init... | Add methods for Documentation Endpoints | Add methods for Documentation Endpoints
Signed-off-by: Huang Yaming <ce2ec9fa26f071590d1a68b9e7447b51f2c76084@gmail.com>
| Python | apache-2.0 | yumminhuang/gerrit.py | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
URLS = {
+ 'SEARCH': 'Documentation/?q=%(keyword)s',
}
@@ -13,3 +14,8 @@
def __init__(self, gerrit):
self.gerrit = gerrit
self.gerrit.URLS.update(URLS)
+
+ def search(self, keyword):
+ url = self.gerrit.url('SEARCH', keyword=... |
c4df7c0de4cadffc665a353763f6d5cabada1b85 | voicerecorder/settings.py | voicerecorder/settings.py | # -*- coding: utf-8 -*-
import os
import contextlib
from PyQt5 import QtCore
from . import __app_name__
from . import helperutils
def _qsettings_group_factory(settings: QtCore.QSettings):
@contextlib.contextmanager
def qsettings_group_context(group_name: str):
settings.beginGroup(group_name)
... | # -*- coding: utf-8 -*-
import os
import contextlib
from PyQt5 import QtCore
from . import __app_name__
from . import helperutils
def _qsettings_group_factory(settings: QtCore.QSettings):
@contextlib.contextmanager
def qsettings_group_context(group_name: str):
settings.beginGroup(group_name)
... | Add "s" attr for QSettings | Add "s" attr for QSettings
| Python | mit | espdev/VoiceRecorder | ---
+++
@@ -44,5 +44,9 @@
return self._filename
@property
+ def s(self):
+ return self._settings
+
+ @property
def group(self):
return self._settings_group |
fd4bc228c978019a7251fefe2c92899a16b8f95d | demosys/scene/shaders.py | demosys/scene/shaders.py | from pyrr import Matrix33
class MeshShader:
def __init__(self, shader):
self.shader = shader
def draw(self, mesh, proj_mat, view_mat):
"""Minimal draw function. Should be overridden"""
mesh.vao.bind(self.shader)
self.shader.uniform_mat4("m_proj", proj_mat)
self.shader... | from pyrr import Matrix33
class MeshShader:
def __init__(self, shader, **kwargs):
self.shader = shader
def draw(self, mesh, proj_mat, view_mat):
"""Minimal draw function. Should be overridden"""
mesh.vao.bind(self.shader)
self.shader.uniform_mat4("m_proj", proj_mat)
s... | Allow sending kwars to mesh shader | Allow sending kwars to mesh shader
| Python | isc | Contraz/demosys-py | ---
+++
@@ -3,7 +3,7 @@
class MeshShader:
- def __init__(self, shader):
+ def __init__(self, shader, **kwargs):
self.shader = shader
def draw(self, mesh, proj_mat, view_mat): |
83efb4c86ea34e9f51c231a3b7c96929d2ba5ee6 | bluebottle/utils/staticfiles_finders.py | bluebottle/utils/staticfiles_finders.py | from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in ... | from django.utils._os import safe_join
import os
from django.conf import settings
from django.contrib.staticfiles.finders import FileSystemFinder
from bluebottle.clients.models import Client
class TenantStaticFilesFinder(FileSystemFinder):
def find(self, path, all=False):
"""
Looks for files in ... | Fix static files finder errors | Fix static files finder errors
Conflicts:
bluebottle/utils/staticfiles_finders.py
| Python | bsd-3-clause | onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -19,6 +19,7 @@
matches = []
tenants = Client.objects.all()
tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None)
+
if not tenant_dir:
return matches
@@ -30,5 +31,7 @@
local_path = safe_join(tenant_dir, tenant_path)
prin... |
3cab4a8252d89c05895cc7a1715afa4ec14ce6e2 | utils/__init__.py | utils/__init__.py | import string
import struct
from collections import namedtuple
class NamedStruct(struct.Struct):
def __init__(self, fields, order='', size=0):
self.values = namedtuple("header", ' '.join(k for k, _ in fields))
format = order + ''.join([v for _, v in fields])
if size:
format +=... | import string
import struct
from collections import namedtuple
class NamedStruct(struct.Struct):
def __init__(self, fields, order='', size=0):
self.values = namedtuple("NamedStruct", ' '.join(k for k, _ in fields))
format = order + ''.join([v for _, v in fields])
if size:
form... | Make NamedStruct instance names less confusing | Make NamedStruct instance names less confusing
Ideally we'd want to make the name the same as the instance name,
but I'm not sure if it's possible without introducing an additional
constructor argument.
| Python | unlicense | tsudoko/98imgtools | ---
+++
@@ -5,7 +5,7 @@
class NamedStruct(struct.Struct):
def __init__(self, fields, order='', size=0):
- self.values = namedtuple("header", ' '.join(k for k, _ in fields))
+ self.values = namedtuple("NamedStruct", ' '.join(k for k, _ in fields))
format = order + ''.join([v for _, v in ... |
59691ed33347c60fe15014facee272e00f58ed3a | server/plugins/cryptstatus/cryptstatus.py | server/plugins/cryptstatus/cryptstatus.py | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Stat... | import requests
from collections import defaultdict
from requests.exceptions import RequestException
from django.conf import settings
from django.utils.dateparse import parse_datetime
import sal.plugin
import server.utils as utils
class CryptStatus(sal.plugin.DetailPlugin):
description = 'FileVault Escrow Stat... | Make sure `output` variable is in scope no matter what. | Make sure `output` variable is in scope no matter what.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal | ---
+++
@@ -31,6 +31,8 @@
verify = True
request_url = '{}/verify/{}/recovery_key/'.format(crypt_url, machine.serial)
+ output = None
+ machine_url = crypt_url
try:
response = requests.get(request_url, verify=verify)
i... |
0033a29537740592ea47b1e372a9aa3873120c35 | i18n/main.py | i18n/main.py | #!/usr/bin/env python
import importlib
import sys
def main():
try:
command = sys.argv[1]
except IndexError:
sys.stderr.write('must specify a command\n')
return -1
module = importlib.import_module('i18n.%s' % command)
module.main.args = sys.argv[2:]
return module.main()
if _... | #!/usr/bin/env python
import importlib
import sys
from path import path
def get_valid_commands():
modules = [m.basename().split('.')[0] for m in path(__file__).dirname().files('*.py')]
commands = []
for modname in modules:
if modname == 'main':
continue
mod = importlib.import_mo... | Add helpful list of subcommands. | Add helpful list of subcommands.
| Python | apache-2.0 | baxeico/i18n-tools,baxeico/i18n-tools,edx/i18n-tools | ---
+++
@@ -1,15 +1,38 @@
#!/usr/bin/env python
import importlib
import sys
+from path import path
+
+def get_valid_commands():
+ modules = [m.basename().split('.')[0] for m in path(__file__).dirname().files('*.py')]
+ commands = []
+ for modname in modules:
+ if modname == 'main':
+ con... |
1cc72b836e5b6feb76898192c886e9701fc34b8f | saylua/modules/users/views/recover.py | saylua/modules/users/views/recover.py | from ..forms.login import RecoveryForm, login_check
from saylua.utils.email import send_email
from flask import render_template, request, flash
def recover_login():
form = RecoveryForm(request.form)
if request.method == 'POST' and form.validate():
user = login_check.user
code = user.make_pass... | from ..forms.login import RecoveryForm, login_check
from saylua.utils import is_devserver
from saylua.utils.email import send_email
from flask import render_template, request, flash
def recover_login():
form = RecoveryForm(request.form)
if request.method == 'POST' and form.validate():
user = login_c... | Add devserver handling for password resets. | Add devserver handling for password resets.
| Python | agpl-3.0 | LikeMyBread/Saylua,saylua/SayluaV2,LikeMyBread/Saylua,LikeMyBread/Saylua,LikeMyBread/Saylua,saylua/SayluaV2,saylua/SayluaV2 | ---
+++
@@ -1,4 +1,6 @@
from ..forms.login import RecoveryForm, login_check
+
+from saylua.utils import is_devserver
from saylua.utils.email import send_email
from flask import render_template, request, flash
@@ -10,10 +12,12 @@
user = login_check.user
code = user.make_password_reset_code()
-... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.