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 |
|---|---|---|---|---|---|---|---|---|---|---|
57e32770422981160e6de515f0a79e4075c101ef | server/data_updates/00006_20190201-125213_archive.py | server/data_updates/00006_20190201-125213_archive.py | # -*- coding: utf-8; -*-
# This file is part of Superdesk.
# 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
#
# Creation: 2018-11-14 10:31
from superdesk.commands.data_updates import Da... | Set status in-progress for existing pictures | chore(pictures): Set status in-progress for existing pictures
| Python | agpl-3.0 | ioanpocol/superdesk,ioanpocol/superdesk,ioanpocol/superdesk | ---
+++
@@ -0,0 +1,39 @@
+# -*- coding: utf-8; -*-
+# This file is part of Superdesk.
+# 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
+#
+# Creation: 2018-11-14 10:31
+
+from super... | |
4501160aff2cef3f6da66862d1c7524bc26420b4 | samples/bulk_update.py | samples/bulk_update.py | import requests
from orionsdk import SwisClient
npm_server = 'localhost'
username = 'admin'
password = ''
verify = False
if not verify:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
swis = SwisClient(npm_server, user... | Add bulk custom property example | Add bulk custom property example
| Python | apache-2.0 | solarwinds/orionsdk-python | ---
+++
@@ -0,0 +1,32 @@
+import requests
+from orionsdk import SwisClient
+
+npm_server = 'localhost'
+username = 'admin'
+password = ''
+
+verify = False
+if not verify:
+ from requests.packages.urllib3.exceptions import InsecureRequestWarning
+ requests.packages.urllib3.disable_warnings(InsecureRequestWarnin... | |
6b0d48f87f56b9485903f7422dbb9ece4d96d329 | python/minimum_absolute_difference_in_an_array.py | python/minimum_absolute_difference_in_an_array.py | #!/bin/python3
import sys
def minimum_absolute_difference(array):
sorted_pairs = zip(sorted(array)[:-1], sorted(array)[1:])
differences = [abs(a - b) for a, b in sorted_pairs]
return min(differences)
if __name__ == "__main__":
_ = int(input().strip())
array = list(map(int, input().strip().split... | Solve Minimum Absolute Difference in an Array | Solve Minimum Absolute Difference in an Array
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | ---
+++
@@ -0,0 +1,15 @@
+#!/bin/python3
+
+import sys
+
+
+def minimum_absolute_difference(array):
+ sorted_pairs = zip(sorted(array)[:-1], sorted(array)[1:])
+ differences = [abs(a - b) for a, b in sorted_pairs]
+ return min(differences)
+
+
+if __name__ == "__main__":
+ _ = int(input().strip())
+ ar... | |
bdaa2fbf4147ce645a93921366953b3a93143899 | test_AcmeTinyHelperConsole.py | test_AcmeTinyHelperConsole.py | from AcmeTinyHelperConsole import AcmeTinyHelperConsole
class TestAcmeTinyHelper:
def test_run(self, capsys):
console = AcmeTinyHelperConsole()
opts = [('--path', '/etc/letsencrypt/example.com'),
('--domains', 'example.com'),
('--acme-tiny-path', '/usr/src/acme-tin... | Add some basic console tests | Add some basic console tests
| Python | mit | mariano-dagostino/AcmeTinyHelper | ---
+++
@@ -0,0 +1,30 @@
+from AcmeTinyHelperConsole import AcmeTinyHelperConsole
+
+class TestAcmeTinyHelper:
+
+ def test_run(self, capsys):
+ console = AcmeTinyHelperConsole()
+
+ opts = [('--path', '/etc/letsencrypt/example.com'),
+ ('--domains', 'example.com'),
+ ('... | |
beb7d6ab2472c173528002be9f7190346884ce56 | radar/radar/models/fetal_anomaly_scans.py | radar/radar/models/fetal_anomaly_scans.py | from sqlalchemy import Column, Integer, Date, Index, Boolean, String
from radar.database import db
from radar.models.common import MetaModelMixin, uuid_pk_column, patient_id_column, patient_relationship
class FetalAnomalyScan(db.Model, MetaModelMixin):
__tablename__ = 'fetal_anomaly_scans'
id = uuid_pk_colu... | Add fetal anomaly scan model | Add fetal anomaly scan model
| Python | agpl-3.0 | renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar | ---
+++
@@ -0,0 +1,23 @@
+from sqlalchemy import Column, Integer, Date, Index, Boolean, String
+
+from radar.database import db
+from radar.models.common import MetaModelMixin, uuid_pk_column, patient_id_column, patient_relationship
+
+
+class FetalAnomalyScan(db.Model, MetaModelMixin):
+ __tablename__ = 'fetal_an... | |
9131040b8115bffc3e852c3507d128a2060f463d | astropy_helpers/tests/test_ah_bootstrap.py | astropy_helpers/tests/test_ah_bootstrap.py | import os
from setuptools.sandbox import run_setup
from . import run_cmd
TEST_SETUP_PY = """\
#!/usr/bin/env python
from __future__ import print_function
import os
import sys
for k in list(sys.modules):
if k == 'astropy_helpers' or k.startswith('astropy_helpers.'):
del sys.modules[k]
import ah_bootstr... | Add the first test that actually tests ah_bootstrap.use_astropy_helpers directly. Will be adding more tests soon following the same general pattern. | Add the first test that actually tests ah_bootstrap.use_astropy_helpers directly. Will be adding more tests soon following the same general pattern.
| Python | bsd-3-clause | bsipocz/astropy-helpers,larrybradley/astropy-helpers,bsipocz/astropy-helpers,larrybradley/astropy-helpers,dpshelio/astropy-helpers,embray/astropy_helpers,Cadair/astropy-helpers,embray/astropy_helpers,Cadair/astropy-helpers,dpshelio/astropy-helpers,astropy/astropy-helpers,bsipocz/astropy-helpers,embray/astropy_helpers,e... | ---
+++
@@ -0,0 +1,74 @@
+import os
+
+from setuptools.sandbox import run_setup
+
+from . import run_cmd
+
+
+TEST_SETUP_PY = """\
+#!/usr/bin/env python
+from __future__ import print_function
+
+import os
+import sys
+for k in list(sys.modules):
+ if k == 'astropy_helpers' or k.startswith('astropy_helpers.'):
+ ... | |
7be3c1c7d1a881683ff8f0a27b6d6dae0a093b20 | main.py | main.py | import sys
if __name__ == '__main__':
print 'Hello world'
print 'Your current version is', sys.version
print 'Your current version should be 2.7.6'
print "Let's get started, shall we?"
| Revert "Revert "Added version printing"" | Revert "Revert "Added version printing""
This reverts commit 7f392958bc8d4327e0e9d6dc169eee26ea80c279.
| Python | bsd-3-clause | rkawauchi/IHK,rkawauchi/IHK | ---
+++
@@ -0,0 +1,7 @@
+import sys
+
+if __name__ == '__main__':
+ print 'Hello world'
+ print 'Your current version is', sys.version
+ print 'Your current version should be 2.7.6'
+ print "Let's get started, shall we?" | |
920e20ea689e62e86f2adbf905db168063be00db | main.py | main.py | import urllib
import yaml
from datetime import datetime
from icalendar import Calendar
# Load configuration data
with open('config.yaml', 'r') as f:
config = yaml.load(f)
calendar = config['calendar']
topic_format = config['irc']['topic']
date_format = config['date_format']
def next_event(ical_url):
raw_ics ... | Create a script for printing the chatroom topic with the next event. | Create a script for printing the chatroom topic with the next event.
| Python | mit | thisgeek/topiCal | ---
+++
@@ -0,0 +1,40 @@
+import urllib
+import yaml
+from datetime import datetime
+from icalendar import Calendar
+
+# Load configuration data
+with open('config.yaml', 'r') as f:
+ config = yaml.load(f)
+
+calendar = config['calendar']
+topic_format = config['irc']['topic']
+date_format = config['date_format']
... | |
18a166e0831cccd0a08f859a3533ed01d810c4ee | binarycalcs.py | binarycalcs.py | import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.constants import G, M_sun, au
from astropy.units.core import UnitConversionError
def keplerian_binary(givenquant):
'''Return equivalency for Keplerian binary orbit.
Parameters
----------
givenquant : `~astropy.un... | Convert between period, semimajor axis, and total mass for Keplerian orbit. | Convert between period, semimajor axis, and total mass for Keplerian orbit.
For cases where a quick and easy conversion between period and semimajor axis
is needed for some sort of binary system, this function will be able to do the
conversion relatively quickly by taking one aspect to be fixed, and doing the
rest of ... | Python | bsd-3-clause | cactaur/astropy-utils | ---
+++
@@ -0,0 +1,77 @@
+import numpy as np
+import matplotlib.pyplot as plt
+import astropy.units as u
+from astropy.constants import G, M_sun, au
+from astropy.units.core import UnitConversionError
+
+def keplerian_binary(givenquant):
+ '''Return equivalency for Keplerian binary orbit.
+
+ Parameters
+ --... | |
960b95dc666753f59eff1b449124490fbec10184 | kivy/_version.py | kivy/_version.py | # This file is imported from __init__.py and exec'd from setup.py
MAJOR = 2
MINOR = 1
MICRO = 0
RELEASE = False
__version__ = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
if not RELEASE:
# if it's a rcx release, it's not proceeded by a period. If it is a
# devx release, it must start with a period
__version__ += '... | # This file is imported from __init__.py and exec'd from setup.py
MAJOR = 2
MINOR = 1
MICRO = 0
RELEASE = False
__version__ = '%d.%d.%d' % (MAJOR, MINOR, MICRO)
if not RELEASE:
# if it's a rcx release, it's not proceeded by a period. If it is a
# devx release, it must start with a period
__version__ += '... | Revert to 2.1.0.dev0 for test release. | Revert to 2.1.0.dev0 for test release.
| Python | mit | akshayaurora/kivy,kivy/kivy,kivy/kivy,akshayaurora/kivy,kivy/kivy,akshayaurora/kivy | ---
+++
@@ -10,7 +10,7 @@
if not RELEASE:
# if it's a rcx release, it's not proceeded by a period. If it is a
# devx release, it must start with a period
- __version__ += 'rc1'
+ __version__ += '.dev0'
_kivy_git_hash = '' |
47e6c52f0c2bf058c5d099dd2993192e0978e172 | tests/cpydiff/core_function_moduleattr.py | tests/cpydiff/core_function_moduleattr.py | """
categories: Core,Functions
description: Function objects do not have the ``__module__`` attribute
cause: MicroPython is optimized for reduced code size and RAM usage.
workaround: Use ``sys.modules[function.__globals__['__name__']]`` for non-builtin modules.
"""
def f():
pass
print(f.__module__)
| Add test and workaround for function.__module__ attr. | tests/cpydiff: Add test and workaround for function.__module__ attr.
MicroPython does not store any reference from a function object to the
module it was defined in, but there is a way to use function.__globals__ to
indirectly get the module.
See issue #7259.
Signed-off-by: Damien George <99e6b749acbfbe2a596df99e91d... | Python | mit | bvernoux/micropython,adafruit/circuitpython,bvernoux/micropython,adafruit/circuitpython,adafruit/circuitpython,henriknelson/micropython,henriknelson/micropython,bvernoux/micropython,henriknelson/micropython,bvernoux/micropython,adafruit/circuitpython,henriknelson/micropython,adafruit/circuitpython,bvernoux/micropython,... | ---
+++
@@ -0,0 +1,13 @@
+"""
+categories: Core,Functions
+description: Function objects do not have the ``__module__`` attribute
+cause: MicroPython is optimized for reduced code size and RAM usage.
+workaround: Use ``sys.modules[function.__globals__['__name__']]`` for non-builtin modules.
+"""
+
+
+def f():
+ pa... | |
753c7cad0fa93a7472f3210705be45f0e3917f6c | tests/test_utils.py | tests/test_utils.py | from cartolafc.util import json_default
from datetime import datetime
def test_json_default():
date = datetime(
year=2019,
month=10,
day=10,
hour=0,
minute=0,
second=0,
microsecond=0,
)
result = json_default(date)
assert isinstance(result, dict) | Add test to json default | Add test to json default
| Python | mit | vicenteneto/python-cartolafc | ---
+++
@@ -0,0 +1,15 @@
+from cartolafc.util import json_default
+from datetime import datetime
+
+def test_json_default():
+ date = datetime(
+ year=2019,
+ month=10,
+ day=10,
+ hour=0,
+ minute=0,
+ second=0,
+ microsecond=0,
+ )
+ result = json_default(da... | |
24f5c0371ca59c9d7f0d86b6635ea263d456ca2f | alembic/versions/534f7c1fb55f_create_address_colum.py | alembic/versions/534f7c1fb55f_create_address_colum.py | """Create address column in person table
Revision ID: 534f7c1fb55f
Revises: 13d42d50c79a
Create Date: 2013-05-12 14:33:19.490150
"""
# revision identifiers, used by Alembic.
revision = '534f7c1fb55f'
down_revision = '13d42d50c79a'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgr... | Create address column on person table | Create address column on person table
| Python | apache-2.0 | teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr,teampopong/pokr.kr | ---
+++
@@ -0,0 +1,30 @@
+"""Create address column in person table
+
+Revision ID: 534f7c1fb55f
+Revises: 13d42d50c79a
+Create Date: 2013-05-12 14:33:19.490150
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '534f7c1fb55f'
+down_revision = '13d42d50c79a'
+
+from alembic import op
+import sqlalchemy as ... | |
1f103880e2c6652dcfb999158b74aa7c12a1b536 | set1/challenge-3.py | set1/challenge-3.py | from __future__ import division
import base64
import collections
import string
expected_frequency = {
'e': .12702,
't': .9056,
'a': .8167,
'o': .7507,
'i': .6966,
'n': .6749,
's': .6327,
'h': .6094,
'r': .5987,
'd': .4253,
'l': .4025,
'c': .2782,
'u': .2758,
'm':... | Add solution to challenge 3. | Add solution to challenge 3.
| Python | mit | ericnorris/cryptopals-solutions | ---
+++
@@ -0,0 +1,67 @@
+from __future__ import division
+import base64
+import collections
+import string
+
+expected_frequency = {
+ 'e': .12702,
+ 't': .9056,
+ 'a': .8167,
+ 'o': .7507,
+ 'i': .6966,
+ 'n': .6749,
+ 's': .6327,
+ 'h': .6094,
+ 'r': .5987,
+ 'd': .4253,
+ 'l': .40... | |
75a4434a88a57c39df41dafbb798f0e6814d763c | interview-questions/conversion.py | interview-questions/conversion.py | '''
Task: Convert a non-negative integer to a hex value for printing
Copyright 2017, Dave Cuthbert. License MIT
'''
def int_to_hex(number):
"""
Check 0
>>> int_to_hex(0)
'0'
Value less than 10
>>> int_to_hex(9)
'9'
Value requiring letter digits
>>> int_to_hex(15)
'F'
... | Print an int as a hex value | Print an int as a hex value
| Python | mit | daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various,daveinnyc/various | ---
+++
@@ -0,0 +1,59 @@
+'''
+
+Task: Convert a non-negative integer to a hex value for printing
+
+
+Copyright 2017, Dave Cuthbert. License MIT
+'''
+
+
+def int_to_hex(number):
+ """
+ Check 0
+ >>> int_to_hex(0)
+ '0'
+
+ Value less than 10
+ >>> int_to_hex(9)
+ '9'
+
+ Value requiring le... | |
e9bb81fced105d41aed1a6069e31b41891cea41c | tests/test_web_service.py | tests/test_web_service.py | # -*- coding: UTF-8 -*-
from expects import *
import xml.dom.minidom
from sii.resource import SII
from dicttoxml import dicttoxml
class Period():
def __init__(self, name):
self.name = name
class Partner():
def __init__(self, name, nif):
self.name = name
self.nif = nif
class Invoice... | Add first version of tests file | Add first version of tests file
| Python | mit | gisce/sii | ---
+++
@@ -0,0 +1,55 @@
+# -*- coding: UTF-8 -*-
+
+from expects import *
+import xml.dom.minidom
+from sii.resource import SII
+from dicttoxml import dicttoxml
+
+class Period():
+ def __init__(self, name):
+ self.name = name
+
+
+class Partner():
+ def __init__(self, name, nif):
+ self.name = n... | |
4243b04eb6568f8fccab31509557bd7b7c6783a5 | logistic-regression-performance.py | logistic-regression-performance.py | # IPython log file
# Run this in the NewEM data folder
from gala import classify
X, y = classify.load_training_data_from_disk('training-data-0.h5',
names=['data', 'labels'])
train_idxs = np.random.randint(0, X.shape[0], size=10_000)
y = y[:, 0]
Xtr, ytr = X[train_idxs], y[train_idxs]
test_idxs = np.r... | Add logistic regression experiment; matching RF performance | Add logistic regression experiment; matching RF performance
| Python | bsd-3-clause | jni/useful-histories | ---
+++
@@ -0,0 +1,44 @@
+# IPython log file
+# Run this in the NewEM data folder
+
+
+from gala import classify
+X, y = classify.load_training_data_from_disk('training-data-0.h5',
+ names=['data', 'labels'])
+
+train_idxs = np.random.randint(0, X.shape[0], size=10_000)
+y = y[:, 0]
+Xtr, ytr = X[train... | |
3de26996fcd56b0371e73583d880f96c0f55b906 | clusterCompanies.py | clusterCompanies.py | import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import finance
from matplotlib.collections import LineCollection
from sklearn import cluster, covariance, manifold
def clusterCompanies():
###############################################################################
# Retrieve the... | Add function to return list of stocks | Add function to return list of stocks
| Python | mit | dankolbman/MarketCents | ---
+++
@@ -0,0 +1,67 @@
+import datetime
+import numpy as np
+import matplotlib.pyplot as plt
+from matplotlib import finance
+from matplotlib.collections import LineCollection
+from sklearn import cluster, covariance, manifold
+
+def clusterCompanies():
+ ###########################################################... | |
f84e0b83eb1abf84104ba3de7c845be147ffabe5 | tests/units/test_release.py | tests/units/test_release.py | import pytest
from magnate import release
def test_release_info():
assert hasattr(release, 'AUTHOR')
assert hasattr(release, 'MAINTAINER')
assert hasattr(release, 'PROGRAM_NAME')
assert hasattr(release, 'COPYRIGHT_YEAR')
assert hasattr(release, 'LICENSE')
def test_version_correct():
assert ... | Add simple tests that the release information exists | Add simple tests that the release information exists
| Python | agpl-3.0 | abadger/stellarmagnate | ---
+++
@@ -0,0 +1,15 @@
+import pytest
+
+from magnate import release
+
+
+def test_release_info():
+ assert hasattr(release, 'AUTHOR')
+ assert hasattr(release, 'MAINTAINER')
+ assert hasattr(release, 'PROGRAM_NAME')
+ assert hasattr(release, 'COPYRIGHT_YEAR')
+ assert hasattr(release, 'LICENSE')
+
+... | |
38c8901aafdfedc2263bd5fd1cce6bf322525f38 | samples/plasma.py | samples/plasma.py | from asciimatics.renderers import Plasma
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from asciimatics.effects import Print
from asciimatics.exceptions import ResizeScreenError
import sys
def demo(screen):
scenes = []
effects = [
Print(screen,
Plasma(screen.... | Add sample for Plasma effect. | Add sample for Plasma effect.
| Python | apache-2.0 | peterbrittain/asciimatics,peterbrittain/asciimatics | ---
+++
@@ -0,0 +1,29 @@
+from asciimatics.renderers import Plasma
+from asciimatics.scene import Scene
+from asciimatics.screen import Screen
+from asciimatics.effects import Print
+from asciimatics.exceptions import ResizeScreenError
+import sys
+
+
+def demo(screen):
+ scenes = []
+
+ effects = [
+ Pr... | |
e1be51d2a7bf9bd0b6244c8c4d10557c068fad6a | src/01_pre_processing/cutter.py | src/01_pre_processing/cutter.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Utility functions for spatial processing."""
import click
import fiona
import logging
import numpy as np
import numpy.ma as ma
import os
import rasterio
import sys
def cookie_cut(infile, clipfile, field, outfile, verbose=False):
""
# Read in the clipfile and... | Add script for cookie cutting | Add script for cookie cutting
| Python | mit | VUEG/bdes_to,VUEG/bdes_to,VUEG/bdes_to | ---
+++
@@ -0,0 +1,66 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+""" Utility functions for spatial processing."""
+import click
+import fiona
+import logging
+import numpy as np
+import numpy.ma as ma
+import os
+import rasterio
+import sys
+
+
+def cookie_cut(infile, clipfile, field, outfile, verbose=False... | |
87aecd71db9ec9872374f6f6807cd3ee43b95a83 | examples/translations/portuguese_test_1.py | examples/translations/portuguese_test_1.py | # Portuguese Language Test - Python 3 Only!
from seleniumbase.translate.portuguese import CasoDeTeste
class MinhaClasseDeTeste(CasoDeTeste):
def test_exemplo_1(self):
self.abrir_url("https://pt.wikipedia.org/wiki/")
self.verificar_texto("Wikipédia")
self.verificar_elemento('[title="Visita... | Add an example test in Portuguese | Add an example test in Portuguese
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | ---
+++
@@ -0,0 +1,22 @@
+# Portuguese Language Test - Python 3 Only!
+from seleniumbase.translate.portuguese import CasoDeTeste
+
+
+class MinhaClasseDeTeste(CasoDeTeste):
+
+ def test_exemplo_1(self):
+ self.abrir_url("https://pt.wikipedia.org/wiki/")
+ self.verificar_texto("Wikipédia")
+ se... | |
b26bb24d09691189d2d079a052c99a2c29bf51d5 | myDevices/test/systeminfo_test.py | myDevices/test/systeminfo_test.py | import unittest
from myDevices.os.systeminfo import SystemInfo
from myDevices.utils.logger import setInfo, info
class SystemInfoTest(unittest.TestCase):
def setUp(self):
setInfo()
system_info = SystemInfo()
self.info = system_info.getSystemInformation()
def testCpuInfo(self):
... | Add system info test script. | Add system info test script.
| Python | mit | myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent | ---
+++
@@ -0,0 +1,53 @@
+import unittest
+from myDevices.os.systeminfo import SystemInfo
+from myDevices.utils.logger import setInfo, info
+
+
+class SystemInfoTest(unittest.TestCase):
+ def setUp(self):
+ setInfo()
+ system_info = SystemInfo()
+ self.info = system_info.getSystemInformation()... | |
984fa4639d73132799589963fe33ed2f213ca9ed | numba/tests/test_nopython_math.py | numba/tests/test_nopython_math.py | import math
import numpy as np
import unittest
#import logging; logging.getLogger().setLevel(1)
from numba import *
def test_exp(a):
return math.exp(a)
def test_sqrt(a):
return math.sqrt(a)
def test_log(a):
return math.log(a)
class TestNoPythonMath(unittest.TestCase):
def test_sqrt(self):
s... | Add test for math functions in nopython context. | Add test for math functions in nopython context.
| Python | bsd-2-clause | numba/numba,pombredanne/numba,IntelLabs/numba,stonebig/numba,pombredanne/numba,gdementen/numba,IntelLabs/numba,cpcloud/numba,seibert/numba,jriehl/numba,stonebig/numba,GaZ3ll3/numba,stuartarchibald/numba,shiquanwang/numba,gmarkall/numba,ssarangi/numba,numba/numba,gmarkall/numba,stefanseefeld/numba,IntelLabs/numba,jriehl... | ---
+++
@@ -0,0 +1,35 @@
+import math
+import numpy as np
+import unittest
+#import logging; logging.getLogger().setLevel(1)
+
+from numba import *
+
+def test_exp(a):
+ return math.exp(a)
+
+def test_sqrt(a):
+ return math.sqrt(a)
+
+def test_log(a):
+ return math.log(a)
+
+class TestNoPythonMath(unittest.T... | |
59a0255babaef772ad72e36c688e72b3385b0db4 | test/pointfree_test.py | test/pointfree_test.py | import os, sys, unittest
from pointfree import *
class CurryingTest(unittest.TestCase):
def testCurrying1(self):
@curryable
def add(a, b):
return a + b
@curryable
def mult(a, b):
return a * b
add1 = add(1)
mult2 = mult(2)
self.asse... | Add simple unit test module | Add simple unit test module
| Python | apache-2.0 | markshroyer/pointfree,markshroyer/pointfree | ---
+++
@@ -0,0 +1,21 @@
+import os, sys, unittest
+from pointfree import *
+
+class CurryingTest(unittest.TestCase):
+ def testCurrying1(self):
+ @curryable
+ def add(a, b):
+ return a + b
+
+ @curryable
+ def mult(a, b):
+ return a * b
+
+ add1 = add(1)
+... | |
64d4e5939fbfa325b57149a73c4bf12c54b6f2bf | tests/maptools_test.py | tests/maptools_test.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import unittest as ut
import stripeline.maptools as mt
import numpy as np
class TestMaptools(ut.TestCase):
def test_condmatr(self):
matr = np.zeros((2, 9), dtype='float64', order='F')
mt.update_condmatr(numpix=2,
pixidx... | Add a test for update_condmatr | Add a test for update_condmatr
| Python | mit | ziotom78/stripeline,ziotom78/stripeline | ---
+++
@@ -0,0 +1,32 @@
+#!/usr/bin/env python3
+# -*- encoding: utf-8 -*-
+
+import unittest as ut
+
+import stripeline.maptools as mt
+import numpy as np
+
+
+class TestMaptools(ut.TestCase):
+
+ def test_condmatr(self):
+ matr = np.zeros((2, 9), dtype='float64', order='F')
+ mt.update_condmatr(nu... | |
94cc15125fa4d8990de50b7c3c39effe6a5e5d93 | tools/dev/wc-format.py | tools/dev/wc-format.py | #!/usr/bin/env python
import os
import sqlite3
import sys
# helper
def usage():
sys.stderr.write("USAGE: %s [PATH]\n" + \
"\n" + \
"Prints to stdout the format of the working copy at PATH.\n")
# parse argv
wc = (sys.argv[1:] + ['.'])[0]
# main()
entries = os.path.join(wc, '.s... | Add a helper script, ported to Python. | Add a helper script, ported to Python.
* tools/dev/wc-format.py: New.
Prints the working copy format of a given directory.
git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@995260 13f79535-47bb-0310-9956-ffa450edef68
| Python | apache-2.0 | YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+
+import os
+import sqlite3
+import sys
+
+# helper
+def usage():
+ sys.stderr.write("USAGE: %s [PATH]\n" + \
+ "\n" + \
+ "Prints to stdout the format of the working copy at PATH.\n")
+
+# parse argv
+wc = (sys.argv[1:] + ['.'])[0]... | |
c9b3178a9ac222d0536b0500452ae6a56672fba7 | documents/tests/document_test.py | documents/tests/document_test.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from documents.models import Document, Page
from users.models import User
import pytest
import mock
from documents.models import process_document
pytestmark = pytest.mark.django_db
def create_doc(name):
user = User.objects.create(netid='test_user... | Add tests for documents models | Add tests for documents models
| Python | agpl-3.0 | UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/beta402,UrLab/DocHub,UrLab/DocHub | ---
+++
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from documents.models import Document, Page
+from users.models import User
+import pytest
+import mock
+
+from documents.models import process_document
+
+
+pytestmark = pytest.mark.django_db
+
+
+def create_doc(name):
+ ... | |
aa06ca147741d8f931acaf95ffe482b4abb11ac4 | tests/base/io.py | tests/base/io.py | import steel
import io
import unittest
class SeekIO(io.BytesIO):
"""
A variation of BytesIO that keeps track of all .seek() activity.
This can test whether files are accessed as efficiently as possible.
"""
def __init__(self, *args, **kwargs):
super(SeekIO, self).__init__(*args, **kwargs)
... | Add some tests to make sure we're seeking efficiently | Add some tests to make sure we're seeking efficiently
| Python | bsd-3-clause | gulopine/steel-experiment | ---
+++
@@ -0,0 +1,52 @@
+import steel
+import io
+import unittest
+
+
+class SeekIO(io.BytesIO):
+ """
+ A variation of BytesIO that keeps track of all .seek() activity.
+ This can test whether files are accessed as efficiently as possible.
+ """
+ def __init__(self, *args, **kwargs):
+ super(S... | |
30c25249f7c76dd20422a73832fd8f26ee3a9f1d | tests/test_bip32_vector.py | tests/test_bip32_vector.py | import json
from unittest import TestCase
from bitmerchant.network import BitcoinMainNet
from bitmerchant.wallet import Wallet
class TestBIP32(TestCase):
def _test_wallet(self, wallet, data):
self.assertEqual(
wallet.serialize_b58(private=True), data['private_key'])
self.assertEqual(
... | Add test for the new bip32 test vectors | Add test for the new bip32 test vectors
| Python | mit | sbuss/bitmerchant,mflaxman/bitmerchant | ---
+++
@@ -0,0 +1,34 @@
+import json
+from unittest import TestCase
+
+from bitmerchant.network import BitcoinMainNet
+from bitmerchant.wallet import Wallet
+
+
+class TestBIP32(TestCase):
+ def _test_wallet(self, wallet, data):
+ self.assertEqual(
+ wallet.serialize_b58(private=True), data['pri... | |
197e3910f64fc34aec71c1788f4e944c33e05422 | tests/test_dgim_quality.py | tests/test_dgim_quality.py | import unittest
import random
from dgim.dgim import Dgim
class ExactAlgorithm(object):
"""Exact algorithm to count the number of ones
in the last N elements of a stream."""
def __init__(self, N):
"""Constructor
:param N: size of the sliding window
:type N: int
"""
se... | Add tests to assess algorithm quality. | Add tests to assess algorithm quality.
To test the quality, implement an exact algorithm to count the number
of ones in the last N elements of a stream.
Then compare the dgim result with the exact result and check that the
dgim estimates is in the expected bounds.
| Python | bsd-3-clause | simondolle/dgim,simondolle/dgim | ---
+++
@@ -0,0 +1,77 @@
+import unittest
+import random
+from dgim.dgim import Dgim
+
+class ExactAlgorithm(object):
+ """Exact algorithm to count the number of ones
+ in the last N elements of a stream."""
+ def __init__(self, N):
+ """Constructor
+ :param N: size of the sliding window
+ ... | |
40ae8895be108e14ec1673cfd88031f82b4cf6f4 | tools/recover.py | tools/recover.py | #!/usr/bin/python
import sys
import re
import socket
import binascii
if len(sys.argv) < 2:
sys.exit("log file is not provided")
path = sys.argv[1]
p = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} DEBUG: \[([0-9a-fA-F]{8}): (\d+) < [\d.]+] HEX: ([0-9a-fA-F]+)")
ports = {}
messages = {}
for line in open(path... | Implement a script to re-send data from log | Implement a script to re-send data from log
| Python | apache-2.0 | AnshulJain1985/Roadcast-Tracker,stalien/traccar_test,joseant/traccar-1,orcoliver/traccar,tananaev/traccar,jssenyange/traccar,ninioe/traccar,5of9/traccar,orcoliver/traccar,5of9/traccar,duke2906/traccar,tsmgeek/traccar,tananaev/traccar,ninioe/traccar,jon-stumpf/traccar,tsmgeek/traccar,tananaev/traccar,renaudallard/tracca... | ---
+++
@@ -0,0 +1,35 @@
+#!/usr/bin/python
+
+import sys
+import re
+import socket
+import binascii
+
+if len(sys.argv) < 2:
+ sys.exit("log file is not provided")
+
+path = sys.argv[1]
+p = re.compile(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} DEBUG: \[([0-9a-fA-F]{8}): (\d+) < [\d.]+] HEX: ([0-9a-fA-F]+)")
+
+ports ... | |
d0c65c221fd6e14b3ec6251ec3eb0b8ec424dced | flexget/plugins/urlrewrite_cinemageddon.py | flexget/plugins/urlrewrite_cinemageddon.py | from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
from flexget import plugin
from flexget.event import event
log = logging.getLogger('cinemageddon')
class UrlRewriteCinemageddon(object):
"""Cinemageddon urlrewriter."""
def url_rewritable(self, task, entry):
... | from __future__ import unicode_literals, division, absolute_import
import logging
import urllib
from flexget import plugin
from flexget.event import event
log = logging.getLogger('cinemageddon')
class UrlRewriteCinemageddon(object):
"""Cinemageddon urlrewriter."""
def url_rewritable(self, task, entry):
... | Remove extra unneeded empty line. | Remove extra unneeded empty line.
| Python | mit | drwyrm/Flexget,thalamus/Flexget,qk4l/Flexget,Danfocus/Flexget,OmgOhnoes/Flexget,jawilson/Flexget,poulpito/Flexget,ZefQ/Flexget,jawilson/Flexget,vfrc2/Flexget,JorisDeRieck/Flexget,jawilson/Flexget,Danfocus/Flexget,tobinjt/Flexget,LynxyssCZ/Flexget,cvium/Flexget,sean797/Flexget,tvcsantos/Flexget,oxc/Flexget,malkavi/Flexg... | ---
+++
@@ -15,7 +15,6 @@
return entry['url'].startswith('http://cinemageddon.net/details.php?id=')
def url_rewrite(self, task, entry):
-
entry['url'] = entry['url'].replace('details.php?id=', 'download.php?id=')
entry['url'] += '&name=%s.torrent' % (urllib.quote(entry['title'], safe... |
0b07192262dc251344c11027b59751501fc6e4a9 | iroha_files.py | iroha_files.py | # Script to create tar.gz package. This will replace automake based "make dist".
import os
PACKAGE="iroha"
VERSION="0.1.0"
ARCHIVE=PACKAGE + "-" + VERSION
EXTRA = ["configure.ac", "configure", "ltmain.sh", "depcomp", "Makefile.in", "config.sub", "lib/cxx-rt.h", "missing", "config.guess", "install-sh", "aclocal.m4", ... | Add script to collect files. | Add script to collect files.
| Python | bsd-3-clause | nlsynth/iroha,nlsynth/iroha | ---
+++
@@ -0,0 +1,48 @@
+# Script to create tar.gz package. This will replace automake based "make dist".
+import os
+
+PACKAGE="iroha"
+VERSION="0.1.0"
+
+ARCHIVE=PACKAGE + "-" + VERSION
+
+EXTRA = ["configure.ac", "configure", "ltmain.sh", "depcomp", "Makefile.in", "config.sub", "lib/cxx-rt.h", "missing", "config.... | |
7872d42b99235a681e52f0e5bec83600b14345c5 | svm_10folds_cv.py | svm_10folds_cv.py | import csv
from os.path import dirname, join
import time
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.svm import LinearSVC
from modules.cleaner import clean
categories = ['traffic', 'non_traffic']
count... | Add k-folds CV with SVM | Add k-folds CV with SVM
| Python | mit | dwiajik/twit-macet-mining-v3 | ---
+++
@@ -0,0 +1,47 @@
+import csv
+from os.path import dirname, join
+import time
+
+import numpy as np
+from sklearn.feature_extraction.text import CountVectorizer
+from sklearn.model_selection import cross_val_score, StratifiedKFold
+from sklearn.svm import LinearSVC
+
+from modules.cleaner import clean
+categor... | |
266ae3aa0a00f8b8872cd90a631196ff4a7afb38 | st2common/st2common/constants/secrets.py | st2common/st2common/constants/secrets.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... | Add st2_auth_token to masked attributes list. | Add st2_auth_token to masked attributes list.
| Python | apache-2.0 | StackStorm/st2,alfasin/st2,punalpatel/st2,pixelrebel/st2,Plexxi/st2,dennybaa/st2,lakshmi-kannan/st2,emedvedev/st2,Plexxi/st2,dennybaa/st2,armab/st2,StackStorm/st2,lakshmi-kannan/st2,armab/st2,punalpatel/st2,StackStorm/st2,pixelrebel/st2,nzlosh/st2,peak6/st2,Plexxi/st2,nzlosh/st2,emedvedev/st2,dennybaa/st2,alfasin/st2,p... | ---
+++
@@ -26,7 +26,8 @@
'auth_token',
'token',
'secret',
- 'credentials'
+ 'credentials',
+ 'st2_auth_token'
]
# Value with which the masked attribute values are replaced |
a7fedf571935bccf10b3002427afe2070ad0666b | tagcache/utils.py | tagcache/utils.py | # -*- encoding: utf-8 -*-
import os
import errno
def ensure_intermediate_dir(path):
"""
Basiclly equivalent to command `mkdir -p`
"""
try:
os.makedirs(os.path.dirname(path))
except OSError, e:
if e.errno != errno.EEXIST:
raise e
def open_file(filename, flag, mo... | Add some file utility functions. | Add some file utility functions.
| Python | mit | huangjunwen/tagcache | ---
+++
@@ -0,0 +1,83 @@
+# -*- encoding: utf-8 -*-
+
+import os
+import errno
+
+
+def ensure_intermediate_dir(path):
+ """
+ Basiclly equivalent to command `mkdir -p`
+
+ """
+
+ try:
+
+ os.makedirs(os.path.dirname(path))
+
+ except OSError, e:
+
+ if e.errno != errno.EEXIST:
+
+ ... | |
81b4cd41198edd388d68bf49dfa2a87c43f3357e | joblib/test/test_func_inspect.py | joblib/test/test_func_inspect.py | """
Test the func_inspect module.
"""
# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
import nose
import tempfile
from ..func_inspect import filter_args, get_func_name
from ..memory import Memory
##############################... | Add tests checking that we get the names right. | TEST: Add tests checking that we get the names right.
| Python | bsd-3-clause | tomMoral/joblib,karandesai-96/joblib,aabadie/joblib,joblib/joblib,aabadie/joblib,karandesai-96/joblib,lesteve/joblib,joblib/joblib,tomMoral/joblib,lesteve/joblib | ---
+++
@@ -0,0 +1,39 @@
+"""
+Test the func_inspect module.
+"""
+
+# Author: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
+# Copyright (c) 2009 Gael Varoquaux
+# License: BSD Style, 3 clauses.
+
+import nose
+import tempfile
+
+from ..func_inspect import filter_args, get_func_name
+from ..memory impor... | |
8b16282fe0e9332c6224ff83c9236eb9e8780fdb | txircd/ircbase.py | txircd/ircbase.py | from twisted.protocols.basic.LineOnlyReceiver
class IRCBase(LineOnlyReceiver):
delimiter = "\n" # Default to splitting by \n, and then we'll also split \r in the handler
def lineReceived(self, data):
for line in data.split("\r"):
command, params, prefix, tags = self._parseLine(line)
if command:
self.ha... | Create an IRC parser base to replace the Twisted one | Create an IRC parser base to replace the Twisted one
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd | ---
+++
@@ -0,0 +1,71 @@
+from twisted.protocols.basic.LineOnlyReceiver
+
+class IRCBase(LineOnlyReceiver):
+ delimiter = "\n" # Default to splitting by \n, and then we'll also split \r in the handler
+
+ def lineReceived(self, data):
+ for line in data.split("\r"):
+ command, params, prefix, tags = self._parseLi... | |
4c90aa6581b3c26a3da1cd83fd92e82ab9e70d68 | _tests/test_feed.py | _tests/test_feed.py | # -*- encoding: utf-8
import feedvalidator
from feedvalidator import compatibility
from feedvalidator.formatter.text_plain import Formatter
def test_feed_passes_validation():
events = feedvalidator.validateStream(
open('_site/feeds/all.atom.xml'),
firstOccurrenceOnly=1
)['loggedEvents']
... | Add a test that the feed passes validation | Add a test that the feed passes validation
| Python | mit | alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net | ---
+++
@@ -0,0 +1,16 @@
+# -*- encoding: utf-8
+
+import feedvalidator
+from feedvalidator import compatibility
+from feedvalidator.formatter.text_plain import Formatter
+
+
+def test_feed_passes_validation():
+ events = feedvalidator.validateStream(
+ open('_site/feeds/all.atom.xml'),
+ firstOccurr... | |
f2a889564b3a215902622b040a1247af38cb8203 | tests/basics/gc1.py | tests/basics/gc1.py | # basic tests for gc module
try:
import gc
except ImportError:
print("SKIP")
import sys
sys.exit()
print(gc.isenabled())
gc.disable()
print(gc.isenabled())
gc.enable()
print(gc.isenabled())
gc.collect()
if hasattr(gc, 'mem_free'):
# uPy has these extra functions
# just test they execute and ... | Add basics test for gc module. | tests: Add basics test for gc module.
| Python | mit | MrSurly/micropython-esp32,MrSurly/micropython-esp32,AriZuu/micropython,Peetz0r/micropython-esp32,praemdonck/micropython,chrisdearman/micropython,drrk/micropython,HenrikSolver/micropython,slzatz/micropython,PappaPeppar/micropython,vitiral/micropython,adafruit/circuitpython,mpalomer/micropython,drrk/micropython,lbattraw/... | ---
+++
@@ -0,0 +1,22 @@
+# basic tests for gc module
+
+try:
+ import gc
+except ImportError:
+ print("SKIP")
+ import sys
+ sys.exit()
+
+print(gc.isenabled())
+gc.disable()
+print(gc.isenabled())
+gc.enable()
+print(gc.isenabled())
+
+gc.collect()
+
+if hasattr(gc, 'mem_free'):
+ # uPy has these ext... | |
5df72792a708adb17969dcad4dcbbe60212dcad7 | tests/test_login.py | tests/test_login.py | from . import TheInternetTestCase
from helium.api import Text, write, press, ENTER, click
class BasicAuthTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/login"
def test_valid_credentials(self):
self._login("tomsmith", "SuperSecretPassword!")
self.assertTrue(Text("Secure... | Add test case for login form. | Add test case for login form.
| Python | mit | bugfree-software/the-internet-solution-python | ---
+++
@@ -0,0 +1,23 @@
+from . import TheInternetTestCase
+from helium.api import Text, write, press, ENTER, click
+
+class BasicAuthTest(TheInternetTestCase):
+ def get_page(self):
+ return "http://the-internet.herokuapp.com/login"
+ def test_valid_credentials(self):
+ self._login("tomsmith", "SuperSecretPasswor... | |
aa40b9ceb0d0af4fd37490e2c2f5aabbed40d5df | web_widget_darkroom/__init__.py | web_widget_darkroom/__init__.py | # -*- coding: utf-8 -*-
# © 2016-TODAY LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
| Add missing init in web_widget_darkroom | Add missing init in web_widget_darkroom
| Python | agpl-3.0 | laslabs/odoo-web,laslabs/odoo-web,laslabs/odoo-web | ---
+++
@@ -0,0 +1,3 @@
+# -*- coding: utf-8 -*-
+# © 2016-TODAY LasLabs Inc.
+# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). | |
4260746d6d266f63d17de2727d7b51145603c97b | python/connected_cell_in_a_grid.py | python/connected_cell_in_a_grid.py | class Grid(object):
def __init__(self, grid):
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0])
def largest_region(self):
return max([self.region_size(row, col)
for row in range(self.rows)
for col in range(self.cols)])
... | Solve connected cell in a grid | Solve connected cell in a grid
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | ---
+++
@@ -0,0 +1,58 @@
+class Grid(object):
+
+ def __init__(self, grid):
+ self.grid = grid
+ self.rows = len(grid)
+ self.cols = len(grid[0])
+
+ def largest_region(self):
+ return max([self.region_size(row, col)
+ for row in range(self.rows)
+ ... | |
dcc8af2b9147d00a40d972c20a37b5d3ab92a26f | test/__init__.py | test/__init__.py | """
Copyright (C) 2016 STFC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distribu... | Allow 'setup.py test' to see the test package | Allow 'setup.py test' to see the test package
| Python | apache-2.0 | tofu-rocketry/ssm,apel/ssm,stfc/ssm,tofu-rocketry/ssm,apel/ssm,stfc/ssm | ---
+++
@@ -0,0 +1,15 @@
+"""
+Copyright (C) 2016 STFC.
+
+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 ag... | |
bb8301e66c243b18eada71c4c8338f8eaa47a597 | 284_peeking_iterator.py | 284_peeking_iterator.py | # https://leetcode.com/problems/peeking-iterator/
# We just need to buffer the current object of the iterator. When peek(), return the buffered object. When next(), return the buffered object, update the buffer to the next object.
# Below is the interface for Iterator, which is already defined for you.
#
# class Itera... | Add a solution for ploblem 284: Peeking Iterator. | Add a solution for ploblem 284: Peeking Iterator.
| Python | apache-2.0 | shen-yang/leetcode_solutions,shen-yang/leetcode_solutions,shen-yang/leetcode_solutions | ---
+++
@@ -0,0 +1,68 @@
+# https://leetcode.com/problems/peeking-iterator/
+# We just need to buffer the current object of the iterator. When peek(), return the buffered object. When next(), return the buffered object, update the buffer to the next object.
+
+# Below is the interface for Iterator, which is already d... | |
d417e5a874cd2912e7787b85304683b12ea5fbbc | tools/fitsevt.py | tools/fitsevt.py | #! /usr/bin/python3
import sys
import os
import math
from astropy.io import fits
inputFolder = sys.argv[1]
outputFolder = sys.argv[2]
eLo = int(sys.argv[3])
eHi = int(sys.argv[4])
binSize = int(sys.argv[5])
fnames = os.listdir(inputFolder)
for fname in fnames:
print(fname)
hdulist = fits.open(inputFolder+"/"+fna... | Add file to convert IUCAA FITS *.evt file to txt format suitable for input to feature extraction program | Add file to convert IUCAA FITS *.evt file to txt format suitable for input to feature extraction program
| Python | mit | fauzanzaid/IUCAA-GRB-detection-Feature-extraction | ---
+++
@@ -0,0 +1,37 @@
+#! /usr/bin/python3
+
+import sys
+import os
+import math
+from astropy.io import fits
+
+inputFolder = sys.argv[1]
+outputFolder = sys.argv[2]
+eLo = int(sys.argv[3])
+eHi = int(sys.argv[4])
+binSize = int(sys.argv[5])
+
+
+fnames = os.listdir(inputFolder)
+
+for fname in fnames:
+ print(fn... | |
8bc6fddeb1232e7973d76bef05252f8228070ab7 | plata/shop/templatetags/plata_product_tags.py | plata/shop/templatetags/plata_product_tags.py | from django import template
import plata
register = template.Library()
@register.simple_tag
def featured_products_for_categories(category_list, variable_name='featured_product'):
"""
{% featured_products_for_categories category_list "variable_name" %}
"""
category_list = list(category_list)
f... | Add template tag to get featured products for a list of categories | Add template tag to get featured products for a list of categories
| Python | bsd-3-clause | allink/plata,armicron/plata,stefanklug/plata,armicron/plata,armicron/plata | ---
+++
@@ -0,0 +1,23 @@
+from django import template
+
+import plata
+
+
+register = template.Library()
+
+
+@register.simple_tag
+def featured_products_for_categories(category_list, variable_name='featured_product'):
+ """
+ {% featured_products_for_categories category_list "variable_name" %}
+ """
+
+ ... | |
bd0d8099d8d6ef36fa111c91667bf9700cfdd844 | scikits/talkbox/misc/tests/test_find_peaks.py | scikits/talkbox/misc/tests/test_find_peaks.py | import numpy as np
from numpy.testing import TestCase, assert_array_equal, \
assert_array_almost_equal, dec
from scikits.talkbox.misc.peak_picking import find_peaks
class TestFindPeaks(TestCase):
def test_simple(self):
x = np.sin(np.linspace(0, 6 * np.pi, 256))
p = find_p... | Add simple test for find_peaks. | Add simple test for find_peaks.
| Python | mit | cournape/talkbox,cournape/talkbox | ---
+++
@@ -0,0 +1,14 @@
+import numpy as np
+from numpy.testing import TestCase, assert_array_equal, \
+ assert_array_almost_equal, dec
+
+from scikits.talkbox.misc.peak_picking import find_peaks
+
+class TestFindPeaks(TestCase):
+ def test_simple(self):
+ x = np.sin(np.linspace(0,... | |
ad2bc4f97bf267415e425463e6980ac865a20f24 | scripts/02-web_collect/01_get_weather_data.py | scripts/02-web_collect/01_get_weather_data.py | #!/usr/bin/python3
'''
script that collects weather data from
'''
import urllib.request
import sys
import os
import time
from datetime import date, timedelta, datetime
from calendar import monthrange
def main():
# path for files to be saved
dir_path = '..' + os.sep + '..' + os.sep + 'data' + os.sep + 'weath... | Add script that collects weather data from worldweatheronline.com | Add script that collects weather data from worldweatheronline.com
| Python | apache-2.0 | jayBana/InventoryMan,jayBana/InventoryMan,jayBana/InventoryMan,jayBana/InventoryMan | ---
+++
@@ -0,0 +1,69 @@
+#!/usr/bin/python3
+
+'''
+script that collects weather data from
+'''
+
+import urllib.request
+import sys
+import os
+import time
+from datetime import date, timedelta, datetime
+from calendar import monthrange
+
+
+def main():
+ # path for files to be saved
+ dir_path = '..' + os.se... | |
d6866c6f2bbf14d9904aacfa2c84b3499b2b093d | make_toponym_xml.py | make_toponym_xml.py | #Make Annotation Files
import os
docgeo_directory = "/Users/grant/devel/GeoAnnotate/docgeo_spans_dloaded_103115"
toponym_directory = "/Users/grant/devel/GeoAnnotate/toponym_annotated_103115"
for f in os.listdir(docgeo_directory):
fp = os.path.join(docgeo_directory, f)
vol = fp.split('-')[1].split('.')[0]
vol_sto... | Add a python scrip that stitches together annotated toponym json | Add a python scrip that stitches together annotated toponym json
| Python | apache-2.0 | utcompling/GeoAnnotate,utcompling/GeoAnnotate,utcompling/GeoAnnotate,utcompling/GeoAnnotate,utcompling/GeoAnnotate | ---
+++
@@ -0,0 +1,21 @@
+#Make Annotation Files
+import os
+
+
+
+docgeo_directory = "/Users/grant/devel/GeoAnnotate/docgeo_spans_dloaded_103115"
+toponym_directory = "/Users/grant/devel/GeoAnnotate/toponym_annotated_103115"
+
+for f in os.listdir(docgeo_directory):
+ fp = os.path.join(docgeo_directory, f)
+ vol = f... | |
ebcc2e9d4295b1e85e43c7b7a01c69a7f28193a5 | hera_mc/tests/test_utils.py | hera_mc/tests/test_utils.py | import nose.tools as nt
from .. import utils
def test_reraise_context():
with nt.assert_raises(ValueError) as cm:
try:
raise ValueError('Initial Exception message.')
except ValueError:
utils._reraise_context('Add some info')
ex = cm.exception
nt.assert_equal(ex.arg... | Add testing for reraise function | Add testing for reraise function
| Python | bsd-2-clause | HERA-Team/hera_mc,HERA-Team/hera_mc,HERA-Team/Monitor_and_Control | ---
+++
@@ -0,0 +1,29 @@
+import nose.tools as nt
+
+from .. import utils
+
+
+def test_reraise_context():
+ with nt.assert_raises(ValueError) as cm:
+ try:
+ raise ValueError('Initial Exception message.')
+ except ValueError:
+ utils._reraise_context('Add some info')
+ ex = ... | |
158b38bdeff8b38c31766968f3fb5bdb73a85b6a | CodeFights/areEquallyStrong.py | CodeFights/areEquallyStrong.py | #!/usr/local/bin/python
# Code Fights Are Equally Strong Problem
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
s = {yourLeft, yourRight, friendsLeft, friendsRight}
return (
len(s) <= 2 and
max(yourLeft, yourRight) == max(friendsLeft, friendsRight)
)
def main():
... | Solve Code Fights are equally strong problem | Solve Code Fights are equally strong problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,41 @@
+#!/usr/local/bin/python
+# Code Fights Are Equally Strong Problem
+
+
+def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
+ s = {yourLeft, yourRight, friendsLeft, friendsRight}
+ return (
+ len(s) <= 2 and
+ max(yourLeft, yourRight) == max(friendsLeft, ... | |
859bc842da554e7e85b3684ade024ee533142d0b | modules/__init__.py | modules/__init__.py | import botconfig
from settings import wolfgame as var
# Todo: Allow game modes to be set via config
# Carry over settings from botconfig into settings/wolfgame.py
for setting, value in botconfig.__dict__.items():
if not setting.isupper():
continue # Not a setting
if not setting in var.__dict__.keys()... | Add ability to carry settings from botconfig to var. | Add ability to carry settings from botconfig to var.
| Python | bsd-2-clause | Cr0wb4r/lykos,billion57/lykos,Diitto/lykos,Agent-Isai/lykos | ---
+++
@@ -0,0 +1,15 @@
+import botconfig
+from settings import wolfgame as var
+
+# Todo: Allow game modes to be set via config
+
+# Carry over settings from botconfig into settings/wolfgame.py
+
+for setting, value in botconfig.__dict__.items():
+ if not setting.isupper():
+ continue # Not a setting
+ ... | |
dc2040c1e30a21224145f02ec339e600a53bc823 | test/buildings.py | test/buildings.py | from django.test import TestCase
from django.conf import settings
from django.test.client import Client
from spotseeker_server.models import Spot, SpotExtendedInfo
from spotseeker_server import models
from django.core import cache
from mock import patch
from django.test.utils import override_settings
import simplejson ... | Add unit test for building API v1 | SPOT-1101: Add unit test for building API v1
| Python | apache-2.0 | uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server,uw-it-aca/spotseeker_server | ---
+++
@@ -0,0 +1,43 @@
+from django.test import TestCase
+from django.conf import settings
+from django.test.client import Client
+from spotseeker_server.models import Spot, SpotExtendedInfo
+from spotseeker_server import models
+from django.core import cache
+from mock import patch
+from django.test.utils import o... | |
ed92a8932dc0647643a79b53fa0f5885a59d31a5 | LiSE/LiSE/tests/test_examples.py | LiSE/LiSE/tests/test_examples.py | from LiSE.examples import college, kobold, polygons, sickle
def test_college(engy):
college.install(engy)
engy.turn = 10 # wake up the students
engy.next_turn()
def test_kobold(engy):
kobold.inittest(engy, shrubberies=20, kobold_sprint_chance=.9)
for i in range(10):
engy.next_turn()
d... | Add tests to make sure the examples run | Add tests to make sure the examples run
| Python | agpl-3.0 | LogicalDash/LiSE,LogicalDash/LiSE | ---
+++
@@ -0,0 +1,25 @@
+from LiSE.examples import college, kobold, polygons, sickle
+
+
+def test_college(engy):
+ college.install(engy)
+ engy.turn = 10 # wake up the students
+ engy.next_turn()
+
+
+def test_kobold(engy):
+ kobold.inittest(engy, shrubberies=20, kobold_sprint_chance=.9)
+ for i in ... | |
18d5005f4255b0d0c9687c4ae535a652da6a6b31 | bin/utils/removePasswords.py | bin/utils/removePasswords.py | import sys
from MaKaC.common.db import DBMgr
from MaKaC.user import AvatarHolder
from MaKaC.authentication import AuthenticatorMgr
from MaKaC.authentication.LocalAuthentication import LocalIdentity
print('This script will remove all local identities from users.')
print('This will remove passwords from the database and... | Add script to remove all local identities | [ADD] Add script to remove all local identities
| Python | mit | mvidalgarcia/indico,indico/indico,OmeGak/indico,mvidalgarcia/indico,ThiefMaster/indico,pferreir/indico,DirkHoffmann/indico,mic4ael/indico,OmeGak/indico,mic4ael/indico,OmeGak/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,indico/indico,pferreir/indico,ThiefMaster/indico,pferreir/indico,mic4ael/indico,mvidalgarc... | ---
+++
@@ -0,0 +1,28 @@
+import sys
+from MaKaC.common.db import DBMgr
+from MaKaC.user import AvatarHolder
+from MaKaC.authentication import AuthenticatorMgr
+from MaKaC.authentication.LocalAuthentication import LocalIdentity
+
+print('This script will remove all local identities from users.')
+print('This will rem... | |
a9a74a1ff2e118c76abebf1738d1c6bb75b4589a | Python_Data/smpl4.py | Python_Data/smpl4.py | '''
2.1 - Numpy Array library
'''
import numpy as np
def main():
n = 10
a = [x**2 for x in range(n)]
b = [x**3 for x in range(n)]
v = plainVectorAddition(a, b)
print(v)
def plainVectorAddition(a, b):
v = list()
for i,j,k in zip(a, b, len(a)):
v[k] = i + j
return v
if __name__... | Add new file for numpy library usage | Add new file for numpy library usage
| Python | unlicense | robotenique/RandomAccessMemory,robotenique/RandomAccessMemory,robotenique/RandomAccessMemory | ---
+++
@@ -0,0 +1,21 @@
+'''
+2.1 - Numpy Array library
+'''
+import numpy as np
+
+def main():
+ n = 10
+ a = [x**2 for x in range(n)]
+ b = [x**3 for x in range(n)]
+ v = plainVectorAddition(a, b)
+ print(v)
+
+
+def plainVectorAddition(a, b):
+ v = list()
+ for i,j,k in zip(a, b, len(a)):
+ ... | |
35c2c26ba379c4fc33465c11bb77a5cc8b4a7d2d | data/process_bigrams.py | data/process_bigrams.py | # Intended to be used with count_2w.txt which has the following format:
# A B\tFREQENCY
# Sometimes "A" is "<S>" for start and "</S>" for end.
# Output is similar with all output lower-cased (including "<S>" and "</S>").
import collections
from src.data import data
all_results = collections.defaultdict(int)
for line... | Reformat words_2w.txt to sort and remove caps. | Reformat words_2w.txt to sort and remove caps.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge | ---
+++
@@ -0,0 +1,17 @@
+# Intended to be used with count_2w.txt which has the following format:
+# A B\tFREQENCY
+# Sometimes "A" is "<S>" for start and "</S>" for end.
+# Output is similar with all output lower-cased (including "<S>" and "</S>").
+import collections
+
+from src.data import data
+
+all_results = co... | |
0b1266eb66fd02e8513b1f36d52b699bfa152285 | build/android/test_runner.py | build/android/test_runner.py | #!/usr/bin/env python
# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All c... | Add Android test runner script for WebRTC. | Add Android test runner script for WebRTC.
The Android test execution toolchain scripts in Chromium
has been causing headaches for us several times. Mostly
because they're tailored at running Chrome tests only.
Wrapping their script in our own avoids the pain of
upstreaming new test names to Chromium and rolling them... | Python | bsd-3-clause | svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758,svn2github/webrtc-Revision-8758 | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+# Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
+#
+# Use of this source code is governed by a BSD-style license
+# that can be found in the LICENSE file in the root of the source
+# tree. An additional intellectual property rights grant can be fo... | |
8e2e666f22c83ca17484eaef54566ec7213bc0d3 | RpiAir/mqttsender.py | RpiAir/mqttsender.py | # coding=utf-8
import sys
import time
import paho.mqtt.client as paho
def on_connect(client, userdata, flags, rc):
print("MQTT CONNACK received with code %d." % (rc))
client.subscribe("#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
msg_... | Add very simple MQTT sender setup | Add very simple MQTT sender setup
| Python | mit | aapris/VekotinVerstas,aapris/VekotinVerstas | ---
+++
@@ -0,0 +1,40 @@
+# coding=utf-8
+
+import sys
+import time
+import paho.mqtt.client as paho
+
+
+def on_connect(client, userdata, flags, rc):
+ print("MQTT CONNACK received with code %d." % (rc))
+ client.subscribe("#")
+
+
+# The callback for when a PUBLISH message is received from the server.
+def on... | |
5de30944c3348bde0f3cbf6c6105894142e194fb | cmdline.py | cmdline.py | class Command:
"""
The definition of a command line command, allows specification of the command itself
the options it expects and also optional arguments
"""
def __init__(self, description):
self.description = description
class CommandNotFoundError(Exception):
pass
class CommandPars... | Migrate existing code to new project. | Migrate existing code to new project.
| Python | mit | nathanroys/commandlineparser | ---
+++
@@ -0,0 +1,40 @@
+class Command:
+ """
+ The definition of a command line command, allows specification of the command itself
+ the options it expects and also optional arguments
+ """
+ def __init__(self, description):
+ self.description = description
+
+
+class CommandNotFoundError(Exc... | |
43a4fa21ce8cf8176efc79f84474f3dd4c08fd44 | python/robotics/examples/aizek_remote.py | python/robotics/examples/aizek_remote.py | from robotics.robots.factory import RobotFactory
from robotics.robots.proxy import AizekProxy
from zmq import zmq_server
def main():
robot = RobotFactory.createAizekRobot()
robot.start()
proxy = AizekProxy(robot)
zmq_server.run_zmq_server(proxy)
robot.stop()
if __name__ == '__main__':
main()... | Add Aizek remote control example | Add Aizek remote control example
Change-Id: I713c0cce94ca0f312c3f6eb14c69c44b31751eaa
| Python | mit | asydorchuk/robotics,asydorchuk/robotics | ---
+++
@@ -0,0 +1,14 @@
+from robotics.robots.factory import RobotFactory
+from robotics.robots.proxy import AizekProxy
+from zmq import zmq_server
+
+
+def main():
+ robot = RobotFactory.createAizekRobot()
+ robot.start()
+ proxy = AizekProxy(robot)
+ zmq_server.run_zmq_server(proxy)
+ robot.stop()
+... | |
5dac625970d647fa7c28a77b319bed00153cc59d | testbed_image.py | testbed_image.py | #!/usr/bin/env python3
"""A script for downloading the current FMI Testbed image and sending
it to a storage backend."""
import argparse
import base64
import sys
import requests
from bs4 import BeautifulSoup
def download_image():
"""Downloads the latest FMI Testbed image. Returns the image data on success
a... | Add Python script for fetching the latest FMI Testbed image | Add Python script for fetching the latest FMI Testbed image
| Python | mit | terop/env-logger,terop/env-logger,terop/env-logger,terop/env-logger,terop/env-logger,terop/env-logger,terop/env-logger | ---
+++
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""A script for downloading the current FMI Testbed image and sending
+it to a storage backend."""
+
+import argparse
+import base64
+import sys
+
+import requests
+from bs4 import BeautifulSoup
+
+
+def download_image():
+ """Downloads the latest FMI Testbed image... | |
93e861c49ccd84f8b50661b491fad62d38b75421 | rally/cmd/manage.py | rally/cmd/manage.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013: Mirantis Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | Add CLI utils for DB recreate | Add CLI utils for DB recreate
We should be able to init DB for rally from CLI
blueprint db-task-track
Change-Id: I52804e86b24d0e9334687d2545ada9a6a00595de
| Python | apache-2.0 | eayunstack/rally,vganapath/rally,paboldin/rally,pandeyop/rally,varunarya10/rally,yeming233/rally,amit0701/rally,eayunstack/rally,openstack/rally,vganapath/rally,vganapath/rally,cernops/rally,amit0701/rally,openstack/rally,gluke77/rally,shdowofdeath/rally,pyKun/rally,eonpatapon/rally,pandeyop/rally,vponomaryov/rally,eon... | ---
+++
@@ -0,0 +1,46 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+# Copyright 2013: Mirantis Inc.
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at... | |
592732019b37c1ea72d503fa5a6498f46ae023e1 | scripts/add_acceptable_subjects_to_provider.py | scripts/add_acceptable_subjects_to_provider.py | from modularodm import Q
from website.app import init_app
from website.models import Subject, PreprintProvider
def find_child_and_grandchild(grandpa, childIndex=0):
parent = Subject.find('parents', 'eq', grandpa)[childIndex]
try:
child = Subject.find(Q('parents', 'eq', parent))[0]
except IndexErro... | Add acceptable subjects to provider script | Add acceptable subjects to provider script
| Python | apache-2.0 | monikagrabowska/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,caneruguz/osf.io,CenterForOpenScience/osf.io,alexschiller/osf.io,chennan47/osf.io,adlius/osf.io,hmoco/osf.io,mluo613/osf.io,cslzchen/osf.io,rdhyee/osf.io,brianjgeiger/osf.io,acshi/osf.io,chennan47/osf.io,mattclark/osf.io,aaxelb/osf.io,chrisseto/osf.io,chr... | ---
+++
@@ -0,0 +1,41 @@
+from modularodm import Q
+
+from website.app import init_app
+from website.models import Subject, PreprintProvider
+
+def find_child_and_grandchild(grandpa, childIndex=0):
+ parent = Subject.find('parents', 'eq', grandpa)[childIndex]
+ try:
+ child = Subject.find(Q('parents', 'e... | |
0db90f8cd74661a973578f393163125eabeefb7e | src/info/name_table_util.py | src/info/name_table_util.py |
_name_ids = {
0: { 'short': 'Copyright', 'name': 'Copyright notice' },
1: { 'short': 'Family', 'name': 'Font Family name' },
2: { 'short': 'Subfamily', 'name': 'Font Subfamily name' },
3: { 'short': 'Unique ID', 'name': 'Unique font identifier' },
4: { 'short': 'Full name', 'name': 'Full font n... | Add ability to display the name table. | Add ability to display the name table.
| Python | apache-2.0 | googlei18n/fontuley,googlei18n/fontuley,wskplho/fontuley,wskplho/fontuley,googlei18n/fontuley | ---
+++
@@ -0,0 +1,35 @@
+
+_name_ids = {
+ 0: { 'short': 'Copyright', 'name': 'Copyright notice' },
+ 1: { 'short': 'Family', 'name': 'Font Family name' },
+ 2: { 'short': 'Subfamily', 'name': 'Font Subfamily name' },
+ 3: { 'short': 'Unique ID', 'name': 'Unique font identifier' },
+ 4: { 'short':... | |
ffca8058de944543cf25606ec1989da8f206e4bb | takeout_inspector/tests/__init__.py | takeout_inspector/tests/__init__.py | """takeout_inspector/tests/__init__.py
Tests for the main Takeout Inspector module.
Copyright (c) 2016 Christopher Charbonneau Wells
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restr... | Create base files for adding tests to the project. | Create base files for adding tests to the project.
| Python | mit | cdubz/takeout-inspector | ---
+++
@@ -0,0 +1,28 @@
+"""takeout_inspector/tests/__init__.py
+
+Tests for the main Takeout Inspector module.
+
+Copyright (c) 2016 Christopher Charbonneau Wells
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to... | |
5d9e624b69a38e826a5591b0976a29c61ebd20f3 | tests/smoketests/test_components.py | tests/smoketests/test_components.py | """
Create an actual instance of one of the client/server components and make sure
we can talk to it.
"""
from twisted.internet import reactor, task
from twisted.internet.defer import Deferred
from src.client.backend import Backend as ClientBackend
from src.shared.message_infrastructure import deserializeMessage
from... | Add a test that interacts with the client backend. | Add a test that interacts with the client backend.
| Python | mit | CheeseLord/warts,CheeseLord/warts | ---
+++
@@ -0,0 +1,87 @@
+"""
+Create an actual instance of one of the client/server components and make sure
+we can talk to it.
+"""
+
+from twisted.internet import reactor, task
+from twisted.internet.defer import Deferred
+
+from src.client.backend import Backend as ClientBackend
+from src.shared.message_infrastr... | |
eb3d5c78255e3b9d60f7b1f1a1379017058c0417 | migrations/versions/190_eas_add_device_retirement.py | migrations/versions/190_eas_add_device_retirement.py | """eas_add_device_retirement
Revision ID: 246a6bf050bc
Revises: 3b093f2d7419
Create Date: 2015-07-17 02:46:47.842573
"""
# revision identifiers, used by Alembic.
revision = '246a6bf050bc'
down_revision = '3b093f2d7419'
from alembic import op
import sqlalchemy as sa
def upgrade():
from inbox.ignition import ma... | Add migration for Exchange bookkeeping. | Add migration for Exchange bookkeeping.
| Python | agpl-3.0 | wakermahmud/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,closeio/nylas,jobscore/sync-engine,gale320/sync-engine,ErinCall/sync-engine,nylas/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,nylas/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,ErinCall/sync... | ---
+++
@@ -0,0 +1,33 @@
+"""eas_add_device_retirement
+
+Revision ID: 246a6bf050bc
+Revises: 3b093f2d7419
+Create Date: 2015-07-17 02:46:47.842573
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '246a6bf050bc'
+down_revision = '3b093f2d7419'
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def ... | |
24d4c412d7655d2f8c5d98c80741864fc1068418 | quickstats/tests/test_query.py | quickstats/tests/test_query.py | import time
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone
from quickstats import models, shortcuts
class SamplesTest(TestCase):
def setUp(self):
self.user = User.objects.create(username="SamplesTest")
self.date = "2019-11-06T11:42:... | Add test for our manager and shortcut | Add test for our manager and shortcut
| Python | mit | kfdm/django-simplestats,kfdm/django-simplestats | ---
+++
@@ -0,0 +1,56 @@
+import time
+
+from django.contrib.auth.models import User
+from django.test import TestCase
+from django.utils import timezone
+
+from quickstats import models, shortcuts
+
+
+class SamplesTest(TestCase):
+ def setUp(self):
+ self.user = User.objects.create(username="SamplesTest")... | |
534558d30b5afb2d14dd119cf27c42ae3d6aed39 | starter_project/normalize_breton_test.py | starter_project/normalize_breton_test.py | import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
if __name__ == '__main__':
unittest.main()
| Add example unit test for the Breton starter project. | Add example unit test for the Breton starter project.
| Python | apache-2.0 | googleinterns/text-norm-for-low-resource-languages,googleinterns/text-norm-for-low-resource-languages | ---
+++
@@ -0,0 +1,9 @@
+import unittest
+
+class TestStringMethods(unittest.TestCase):
+
+ def test_upper(self):
+ self.assertEqual('foo'.upper(), 'FOO')
+
+if __name__ == '__main__':
+ unittest.main() | |
0505061e9fef8120a02443d5e8dabcdaadc08c56 | stateMessageParser/stateMessageParser.py | stateMessageParser/stateMessageParser.py | #!/usr/bin/env python3
description = """State Message Parser
Parses all the code in the MINDS-i-Drone project looking for comments formatted
to contain /*# followed by a state name (no spaces). All text following the
first space after the state name is considered the description.
/*#STATE_NAME ...description...*/
Th... | Implement doc comment => XML DB script for state message descriptions | Implement doc comment => XML DB script for state message descriptions
| Python | apache-2.0 | MINDS-i/Dashboard,MINDS-i/Dashboard,MINDS-i/Dashboard | ---
+++
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+
+description = """State Message Parser
+
+Parses all the code in the MINDS-i-Drone project looking for comments formatted
+to contain /*# followed by a state name (no spaces). All text following the
+first space after the state name is considered the description.
+/*... | |
e4b8275a745d88ec8763e94ea7fa06c3cf152388 | examples/tornado.py | examples/tornado.py | import tornado.web
from tornado.ioloop import IOLoop
from pushka import AmazonSESService
# NOTE: make sure your Amazon SES user has `ses:SendEmail` permission!
# Here's user policy example:
#
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Effect": "Allow",
# "Action": [
... | Add examples dir with Tornado example source | Add examples dir with Tornado example source
| Python | apache-2.0 | rudyryk/pushka | ---
+++
@@ -0,0 +1,56 @@
+import tornado.web
+from tornado.ioloop import IOLoop
+from pushka import AmazonSESService
+
+# NOTE: make sure your Amazon SES user has `ses:SendEmail` permission!
+# Here's user policy example:
+#
+# {
+# "Version": "2012-10-17",
+# "Statement": [
+# {
+# "Effec... | |
d5609f7110f31a5d046fd09106a6d143c88ac54d | scripts/renew_user_sessions.py | scripts/renew_user_sessions.py | #!/usr/bin/env python
"""Log out users by renewing their session tokens.
This is meant to be used when new terms of service are published so
users have to log in again and are presented the form to accept the new
terms of service.
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for det... | Add script to renew user sessions | Add script to renew user sessions
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+
+"""Log out users by renewing their session tokens.
+
+This is meant to be used when new terms of service are published so
+users have to log in again and are presented the form to accept the new
+terms of service.
+
+:Copyright: 2006-2018 Jochen Kupperschmidt
+:Licen... | |
4a405d5884dee29604cdc0f8908a0c2a6c74168e | classes/killmails_cache.py | classes/killmails_cache.py | # -*- coding: utf-8 -*-
import sqlite3
import json
from classes.sitecfg import SiteConfig
class KillMailsCache:
def __init__(self, siteconfig: SiteConfig):
self._conn = sqlite3.connect(siteconfig.ZKB_CACHE_DIR + '/killmails.db', check_same_thread=False)
self.check_tables()
def check_tables(se... | Add new class to cache killmails indefinitely, forever | Add new class to cache killmails indefinitely, forever
| Python | mit | minlexx/whdbx_web,minlexx/whdbx_web,minlexx/whdbx_web,minlexx/whdbx_web,minlexx/whdbx_web | ---
+++
@@ -0,0 +1,48 @@
+# -*- coding: utf-8 -*-
+import sqlite3
+import json
+from classes.sitecfg import SiteConfig
+
+
+class KillMailsCache:
+ def __init__(self, siteconfig: SiteConfig):
+ self._conn = sqlite3.connect(siteconfig.ZKB_CACHE_DIR + '/killmails.db', check_same_thread=False)
+ self.ch... | |
dcf8d5dc9e36043e27e207a308da1e6a1f0d00d6 | memefarm/fontutil.py | memefarm/fontutil.py | """ PIL doesn't have a built-in method for drawing text with a border """
from PIL import ImageFont
def drawTextWithBorder(draw, text, coords,
fontname="Impact", fontsize=80, strokewidth=3,
color="#fff", strokecolor="#000"):
""" Draw text with a border. Although PIL d... | Add function for drawing font with border | Add function for drawing font with border
| Python | mit | The-Penultimate-Defenestrator/memefarm | ---
+++
@@ -0,0 +1,29 @@
+""" PIL doesn't have a built-in method for drawing text with a border """
+from PIL import ImageFont
+
+
+def drawTextWithBorder(draw, text, coords,
+ fontname="Impact", fontsize=80, strokewidth=3,
+ color="#fff", strokecolor="#000"):
+ """ Draw... | |
4ee0f8776b4bf74b20df5f0a69e68f8aa1d82a6d | tests/unit/express_checkout/facade_tests.py | tests/unit/express_checkout/facade_tests.py | from decimal import Decimal as D
from unittest.mock import patch
from django.test import TestCase
from paypalhttp.http_response import construct_object
from paypal.express_checkout.facade import refund_order
from paypal.express_checkout.models import ExpressCheckoutTransaction
from .mocked_data import REFUND_ORDER_D... | Add test for `refund_order` function of `facade` module | Add test for `refund_order` function of `facade` module
| Python | bsd-3-clause | lpakula/django-oscar-paypal,lpakula/django-oscar-paypal,django-oscar/django-oscar-paypal,st8st8/django-oscar-paypal,st8st8/django-oscar-paypal,django-oscar/django-oscar-paypal,lpakula/django-oscar-paypal,evonove/django-oscar-paypal,evonove/django-oscar-paypal,st8st8/django-oscar-paypal,evonove/django-oscar-paypal,djang... | ---
+++
@@ -0,0 +1,37 @@
+from decimal import Decimal as D
+from unittest.mock import patch
+
+from django.test import TestCase
+from paypalhttp.http_response import construct_object
+
+from paypal.express_checkout.facade import refund_order
+from paypal.express_checkout.models import ExpressCheckoutTransaction
+
+fr... | |
8f078438c34f845c71b45571d02d09a34bd04ded | dimagi/utils/rate_limit.py | dimagi/utils/rate_limit.py | from dimagi.utils.couch.cache.cache_core import get_redis_client
def rate_limit(key, actions_allowed=60, how_often=60):
"""
A simple util to be used for rate limiting, using redis as a backend.
key - a unique key which describes the action you are rate limiting
actions_allowed - the number of action... | Add simple rate limiting util | Add simple rate limiting util
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,41 @@
+from dimagi.utils.couch.cache.cache_core import get_redis_client
+
+
+def rate_limit(key, actions_allowed=60, how_often=60):
+ """
+ A simple util to be used for rate limiting, using redis as a backend.
+
+ key - a unique key which describes the action you are rate limiting
+
+ a... | |
520146d0aac1adf6f377e02b4412c9f7f0619bf7 | guess_language.py | guess_language.py | import click
import os
import codecs
import pandas as pd
from xtas.tasks.single import guess_language
@click.command()
@click.argument('input_dir', type=click.Path(exists=True))
@click.argument('output_file', type=click.Path())
def guess(input_dir, output_file):
output_dir = os.path.dirname(output_file)
if n... | Add script to guess the language of all documents | Add script to guess the language of all documents
Input: directory with text files
Output: csv file that specifies the language of each document in
the input dir
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln | ---
+++
@@ -0,0 +1,30 @@
+import click
+import os
+import codecs
+import pandas as pd
+
+from xtas.tasks.single import guess_language
+
+@click.command()
+@click.argument('input_dir', type=click.Path(exists=True))
+@click.argument('output_file', type=click.Path())
+
+def guess(input_dir, output_file):
+ output_dir... | |
b487df165bb257b327fdaf0588240f48f0ded0db | ipython_config.py | ipython_config.py | c = get_config()
# Kernel config
c.IPKernelApp.pylab = 'inline' # if you want plotting support always
# Notebook config
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8080
c.NotebookApp.notebook_dir = '/work'
c.NotebookApp.trust_xheaders = True
c.NotebookApp.tornado_settings = {
... | Add ipython config file with notebook dir set to /work | Add ipython config file with notebook dir set to /work
| Python | mit | louisdorard/bml-base,louisdorard/bml-base | ---
+++
@@ -0,0 +1,18 @@
+c = get_config()
+
+# Kernel config
+c.IPKernelApp.pylab = 'inline' # if you want plotting support always
+
+# Notebook config
+c.NotebookApp.ip = '*'
+c.NotebookApp.open_browser = False
+c.NotebookApp.port = 8080
+c.NotebookApp.notebook_dir = '/work'
+
+c.NotebookApp.trust_xheaders = True
... | |
59f8b80d6a5e37b9d91ee53fd900d9499f0391ca | src/collectors/KVMCollector/KVMCollector.py | src/collectors/KVMCollector/KVMCollector.py |
from diamond import *
import diamond.collector
import os
class KVMCollector(diamond.collector.Collector):
"""
Collects /sys/kernel/debug/kvm/*
"""
PROC = '/sys/kernel/debug/kvm'
def get_default_config(self):
"""
Returns the default collector settings
"""
... | Add in a kvm collector that collects the same stats as kvm_stat does | Add in a kvm collector that collects the same stats as kvm_stat does
| Python | mit | Netuitive/Diamond,skbkontur/Diamond,hamelg/Diamond,joel-airspring/Diamond,hamelg/Diamond,tuenti/Diamond,CYBERBUGJR/Diamond,Slach/Diamond,MediaMath/Diamond,tusharmakkar08/Diamond,anandbhoraskar/Diamond,mzupan/Diamond,disqus/Diamond,tuenti/Diamond,datafiniti/Diamond,mfriedenhagen/Diamond,jumping/Diamond,anandbhoraskar/Di... | ---
+++
@@ -0,0 +1,31 @@
+
+from diamond import *
+import diamond.collector
+import os
+
+class KVMCollector(diamond.collector.Collector):
+ """
+ Collects /sys/kernel/debug/kvm/*
+ """
+
+ PROC = '/sys/kernel/debug/kvm'
+
+
+ def get_default_config(self):
+ """
+ Returns the ... | |
309df37b7381027bcd2691a86b935e2ea0f8ffce | python_scripts/WordCount.py | python_scripts/WordCount.py | #!/usr/bin/python
import re
# this one in honor of 4th July, or pick text file you have!!!!!!!
filename = 'out.txt'
# create list of lower case words, \s+ --> match any whitespace(s)
# you can replace file(filename).read() with given string
word_list = re.split('\s+', file(filename).read().lower())
print 'Words in text... | Add initial word counting file. | Add initial word counting file.
| Python | agpl-3.0 | AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter... | ---
+++
@@ -0,0 +1,29 @@
+#!/usr/bin/python
+import re
+# this one in honor of 4th July, or pick text file you have!!!!!!!
+filename = 'out.txt'
+# create list of lower case words, \s+ --> match any whitespace(s)
+# you can replace file(filename).read() with given string
+word_list = re.split('\s+', file(filename).re... | |
b2dceb40d8e04771098a3aad47c7656071c00b74 | rxpy-test.py | rxpy-test.py | #!/usr/bin/env python3
from auth_tokens import *
from rx import Observable
try:
import json
except ImportError:
import simplejson as json
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
twitter_stream = TwitterSt... | Add sample use of RxPy. | Add sample use of RxPy.
| Python | mit | Pysellus/streaming-api-test,Pysellus/streaming-api-test | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python3
+
+from auth_tokens import *
+from rx import Observable
+
+
+try:
+ import json
+except ImportError:
+ import simplejson as json
+
+from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
+
+oauth = OAuth(ACCESS_TOKEN, ACCESS_SECRET, CONSUMER_KEY, CON... | |
c95869f3438268c757638ac1d857360e80070ccf | sksos/cli.py | sksos/cli.py | #!/usr/bin/env python
import argparse
import logging
import sys
import numpy as np
from sos import SOS
def get_stdout():
if sys.version_info.major < 3:
return sys.stdout
else:
return sys.stdout.buffer
def main():
parser = argparse.ArgumentParser(description="Stochastic Outlier Selecti... | Put command-line code into separate file | Put command-line code into separate file
| Python | bsd-3-clause | jeroenjanssens/sos | ---
+++
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+
+import argparse
+import logging
+import sys
+
+import numpy as np
+
+from sos import SOS
+
+def get_stdout():
+
+ if sys.version_info.major < 3:
+ return sys.stdout
+ else:
+ return sys.stdout.buffer
+
+
+def main():
+ parser = argparse.Argumen... | |
84a6465b5b36989091245e2039912867a27c2773 | migrations/versions/760_brief_response_submitted_at.py | migrations/versions/760_brief_response_submitted_at.py | """brief response submitted at
Revision ID: 760
Revises: 750
Create Date: 2016-10-24 14:16:29.951023
"""
# revision identifiers, used by Alembic.
revision = '760'
down_revision = '750'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.add_column('brief_responses', sa.Column('submitted_at', sa.D... | Add `submitted_at` migration to `brief_responses` table | Add `submitted_at` migration to `brief_responses` table
Represents when a brief response has been submitted and is therefore
a complete response, as opposed to one that may be in a draft form.
Note, we choose not to use the word "published" as a brief response
is not published publicly.
| Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | ---
+++
@@ -0,0 +1,22 @@
+"""brief response submitted at
+
+Revision ID: 760
+Revises: 750
+Create Date: 2016-10-24 14:16:29.951023
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '760'
+down_revision = '750'
+
+from alembic import op
+import sqlalchemy as sa
+
+
+def upgrade():
+ op.add_column('bri... | |
a8eaee817f91dec66b186bf9e8ac94084b2e4190 | nagios/check_b548_temps.py | nagios/check_b548_temps.py | """
Gateway for B548 temps to nagios, this way I can setup alerts via it
Array("In Air Handler", "Out Air Handler", "Out Rack", "In Rack")
0 70.25
1 57.88
2 88.25
3 62.04
"""
import sys
data = open('/tmp/onewire.txt', 'r').readlines()
if len(data) != 4:
print 'WARNING - Could not read file!'
sys.exit(1)
v = ... | Add nagios script for room temps | Add nagios script for room temps | Python | mit | akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem | ---
+++
@@ -0,0 +1,38 @@
+"""
+Gateway for B548 temps to nagios, this way I can setup alerts via it
+
+Array("In Air Handler", "Out Air Handler", "Out Rack", "In Rack")
+0 70.25
+1 57.88
+2 88.25
+3 62.04
+"""
+import sys
+
+data = open('/tmp/onewire.txt', 'r').readlines()
+if len(data) != 4:
+ print 'WARNING - Co... | |
46af9016a2a349c0ea7c1f2aec6a3d67eeef3c86 | tests/st/calicoctl/test_convert.py | tests/st/calicoctl/test_convert.py | # Copyright (c) 2015-2017 Tigera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Add ST to run manifest convert tests | Add ST to run manifest convert tests
| Python | apache-2.0 | Metaswitch/calico-docker,projectcalico/calico-docker,projectcalico/calico-containers,insequent/calico-docker,insequent/calico-docker,projectcalico/calico-containers,projectcalico/calico-containers,projectcalico/calico-docker,Metaswitch/calico-docker | ---
+++
@@ -0,0 +1,67 @@
+# Copyright (c) 2015-2017 Tigera, Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.... | |
3cbc45e6496770bb16d3eac01897f23fbc001491 | turbopump_test.py | turbopump_test.py | import unittest
import turbopump
class TestStringMethods(unittest.TestCase):
def test_m_dot2gpm(self):
# 100 kg s**-1, 1000 kg m**-3 --> 1584 gal min**-1
self.assertAlmostEqual(1584, turbopump.m_dot2gpm(100, 1000), delta=2)
def test_gpm_m_dot_inverse(self):
for m_dot in [1, 100, 1000... | Add unit tests for turbopump. | Add unit tests for turbopump.
| Python | mit | mvernacc/proptools | ---
+++
@@ -0,0 +1,54 @@
+import unittest
+import turbopump
+
+class TestStringMethods(unittest.TestCase):
+
+ def test_m_dot2gpm(self):
+ # 100 kg s**-1, 1000 kg m**-3 --> 1584 gal min**-1
+ self.assertAlmostEqual(1584, turbopump.m_dot2gpm(100, 1000), delta=2)
+
+
+ def test_gpm_m_dot_inverse(sel... | |
28c2e89343db336723b3f36bccd9bca5d6e1dfc7 | trex/settings_production.py | trex/settings_production.py | from trex.settings_global import *
DEBUG = False
REST_FRAMEWORK = {
# don't use BrowsableAPIRenderer
"DEFAULT_RENDERER_CLASSES": {
"rest_framework.renderers.JSONRenderer"
},
# deactivate "browser enhancements"
"FORM_CONTENT_OVERRIDE": None,
"FORM_METHOD_OVERRIDE": None,
"FORM_CONTE... | Add a settings module for production | Add a settings module for production
| Python | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -0,0 +1,14 @@
+from trex.settings_global import *
+
+DEBUG = False
+
+REST_FRAMEWORK = {
+ # don't use BrowsableAPIRenderer
+ "DEFAULT_RENDERER_CLASSES": {
+ "rest_framework.renderers.JSONRenderer"
+ },
+ # deactivate "browser enhancements"
+ "FORM_CONTENT_OVERRIDE": None,
+ "FORM_... | |
29519614965e6629debcd2d08fd1fe2e0debe08f | test/test_paramval.py | test/test_paramval.py | import logging
import luigi
import sciluigi as sl
import os
import time
import unittest
log = logging.getLogger('sciluigi-interface')
log.setLevel(logging.WARNING)
class IntParamTask(sl.Task):
an_int_param = luigi.IntParameter()
def out_int_val(self):
return sl.TargetInfo(self, '/tmp/intparamtask_in... | Add test for non-string (integer) parameter value | Add test for non-string (integer) parameter value
| Python | mit | pharmbio/sciluigi,pharmbio/sciluigi,samuell/sciluigi | ---
+++
@@ -0,0 +1,46 @@
+import logging
+import luigi
+import sciluigi as sl
+import os
+import time
+import unittest
+
+log = logging.getLogger('sciluigi-interface')
+log.setLevel(logging.WARNING)
+
+
+class IntParamTask(sl.Task):
+ an_int_param = luigi.IntParameter()
+
+ def out_int_val(self):
+ retur... | |
828a12547380091d4183bdf2ae247e6df8574fe7 | tests/test_filters.py | tests/test_filters.py | import unittest
from pypercube.filters import Filter
from pypercube.filters import EQ
from pypercube.filters import LT
from pypercube.filters import LE
from pypercube.filters import GT
from pypercube.filters import GE
from pypercube.filters import NE
from pypercube.filters import RE
from pypercube.filters import IN
fr... | Add Filter tests. Regular expressions are broken. | Add Filter tests. Regular expressions are broken.
| Python | bsd-3-clause | sbuss/pypercube | ---
+++
@@ -0,0 +1,68 @@
+import unittest
+
+from pypercube.filters import Filter
+from pypercube.filters import EQ
+from pypercube.filters import LT
+from pypercube.filters import LE
+from pypercube.filters import GT
+from pypercube.filters import GE
+from pypercube.filters import NE
+from pypercube.filters import R... | |
113673a78c633ceffe40b071a8c164bd631255fa | tests/test_weekday.py | tests/test_weekday.py | import pytest
from recurrence import Weekday
def test_init():
assert repr(Weekday(3)) == 'TH'
assert repr(Weekday(3, -2)) == '-2TH'
assert repr(Weekday(3, 3)) == '3TH'
with pytest.raises(ValueError):
Weekday(8)
with pytest.raises(ValueError):
Weekday('fish')
def test_call():
... | Add tests to show what the Weekday object does | Add tests to show what the Weekday object does
| Python | bsd-3-clause | Nikola-K/django-recurrence,linux2400/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,FrankSalad/django-recurrence,django-recurrence/django-recurrence,django-recurrence/django-recurrence,linux2400/django-recurrence | ---
+++
@@ -0,0 +1,24 @@
+import pytest
+from recurrence import Weekday
+
+
+def test_init():
+ assert repr(Weekday(3)) == 'TH'
+ assert repr(Weekday(3, -2)) == '-2TH'
+ assert repr(Weekday(3, 3)) == '3TH'
+
+ with pytest.raises(ValueError):
+ Weekday(8)
+
+ with pytest.raises(ValueError):
+ ... | |
857750c5f2fba568c9ad3320d06b4178457be612 | uwsgi/hello.py | uwsgi/hello.py | import ujson
def application(environ, start_response):
response = {
"message": "Hello, World!"
}
data = ujson.dumps(response)
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response('200 OK', response_headers)
return [d... | import ujson
def application(environ, start_response):
response = {
"message": "Hello, World!"
}
data = ujson.dumps(response)
response_headers = [
('Content-type', 'application/json'),
('Content-Length', str(len(data)))
]
start_response('200 OK', response_headers)
ret... | Fix test to use proper Content-type for json test | uwsgi: Fix test to use proper Content-type for json test
| Python | bsd-3-clause | nbrady-techempower/FrameworkBenchmarks,zhuochenKIDD/FrameworkBenchmarks,hamiltont/FrameworkBenchmarks,actframework/FrameworkBenchmarks,jeevatkm/FrameworkBenchmarks,lcp0578/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,jetty-project/FrameworkBenchmarks,marko-asplund/FrameworkBenchmarks,zloster/FrameworkBenchmarks,Di... | ---
+++
@@ -7,7 +7,7 @@
}
data = ujson.dumps(response)
response_headers = [
- ('Content-type', 'text/plain'),
+ ('Content-type', 'application/json'),
('Content-Length', str(len(data)))
]
start_response('200 OK', response_headers) |
212aaed11103a9442745715ae88573fa8fcf3a2c | trac/upgrades/db43.py | trac/upgrades/db43.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.com/license.html.
#
# This software consists of vo... | Add upgrade script missing from r15749 | 1.3.2dev: Add upgrade script missing from r15749
Refs #12719.
git-svn-id: 0d96b0c1a6983ccc08b3732614f4d6bfcf9cbb42@15765 af82e41b-90c4-0310-8c96-b1721e28e2e2
| Python | bsd-3-clause | rbaumg/trac,rbaumg/trac,rbaumg/trac,rbaumg/trac | ---
+++
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2017 Edgewall Software
+# All rights reserved.
+#
+# This software is licensed as described in the file COPYING, which
+# you should have received as part of this distribution. The terms
+# are also available at http://trac.edgewall.com/license.htm... | |
d5bc55e4e643247d959c0e6035f184473c600346 | pydump.py | pydump.py | import ConfigParser
import os
import time
import getpass
def get_dump():
print "Enter user:"
user = raw_input()
print "Password will not be visible:"
password = getpass.getpass()
print "Enter host:"
host = raw_input()
print "Enter database name:"
database = raw_input()
filestam... | Add script for taking mysqldump | Add script for taking mysqldump | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | ---
+++
@@ -0,0 +1,26 @@
+import ConfigParser
+import os
+import time
+import getpass
+
+def get_dump():
+ print "Enter user:"
+ user = raw_input()
+
+ print "Password will not be visible:"
+ password = getpass.getpass()
+
+ print "Enter host:"
+ host = raw_input()
+
+ print "Enter database name:... | |
4510eccddc5fbb7fef16a4702112545346d171f3 | heat/utils.py | heat/utils.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 applicab... | Add back catch_error which is used for CLI errors | Add back catch_error which is used for CLI errors
Change-Id: Ib8b975d22950d5ba6aa9d5f150403a64356a8aa3
Signed-off-by: Jeff Peeler <d776211e63e47e40d00501ffdb86a800e0782fea@redhat.com>
| Python | apache-2.0 | srznew/heat,dims/heat,noironetworks/heat,JioCloud/heat,rh-s/heat,pshchelo/heat,Triv90/Heat,dims/heat,miguelgrinberg/heat,pratikmallya/heat,dragorosson/heat,NeCTAR-RC/heat,rickerc/heat_audit,steveb/heat,cwolferh/heat-scratch,JioCloud/heat,ntt-sic/heat,varunarya10/heat,cryptickp/heat,redhat-openstack/heat,openstack/heat,... | ---
+++
@@ -0,0 +1,57 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+
+#
+# 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... | |
6ac27ccc4a23b9af6555b624c16bc270aaf849ed | ntm/test/test_layers.py | ntm/test/test_layers.py | import pytest
import theano
import theano.tensor as T
import numpy as np
from lasagne.layers import InputLayer, ReshapeLayer, DenseLayer
from lasagne.layers import get_output, get_all_param_values, set_all_param_values
from ntm.layers import NTMLayer
from ntm.heads import WriteHead, ReadHead
from ntm.controllers impo... | Add test for size of batches | Add test for size of batches
| Python | mit | snipsco/ntm-lasagne | ---
+++
@@ -0,0 +1,57 @@
+import pytest
+
+import theano
+import theano.tensor as T
+import numpy as np
+
+from lasagne.layers import InputLayer, ReshapeLayer, DenseLayer
+from lasagne.layers import get_output, get_all_param_values, set_all_param_values
+from ntm.layers import NTMLayer
+from ntm.heads import WriteHea... | |
97e5a157a56caf7a71ec7b51ecbbfef840bf24c7 | Program1/Program1-NoLoops.py | Program1/Program1-NoLoops.py | #
# Explain what this program does
#
numberOne = int(input("Number? "))
action = input("Action (+, -, / or *)? ")
numberTwo = int(input("Number? "))
if action == "+":
print()
print(numberOne + numberTwo)
print()
elif action == "-":
print()
print(numberOne - numberTwo)
print()
elif action == "/"... | Add no loop version of Program1 | Add no loop version of Program1 | Python | mit | Mrcomputer1/SimplePythonPrograms | ---
+++
@@ -0,0 +1,27 @@
+#
+# Explain what this program does
+#
+
+numberOne = int(input("Number? "))
+action = input("Action (+, -, / or *)? ")
+numberTwo = int(input("Number? "))
+if action == "+":
+ print()
+ print(numberOne + numberTwo)
+ print()
+elif action == "-":
+ print()
+ print(numberOne - ... | |
e47264d3bd45034e22923f793b9466114af6a32c | gmmp/management/commands/fix_countries.py | gmmp/management/commands/fix_countries.py | from django.core.management.base import BaseCommand
from django.db.models import F
from forms.models import sheet_models
class Command(BaseCommand):
def handle(self, *args, **options):
for name, model in sheet_models.iteritems():
country_errors_sheets = model.objects.exclude(monitor__country__i... | Add management command to fix sheet countries | Add management command to fix sheet countries
| Python | apache-2.0 | Code4SA/gmmp,Code4SA/gmmp,Code4SA/gmmp | ---
+++
@@ -0,0 +1,12 @@
+from django.core.management.base import BaseCommand
+from django.db.models import F
+from forms.models import sheet_models
+
+class Command(BaseCommand):
+ def handle(self, *args, **options):
+ for name, model in sheet_models.iteritems():
+ country_errors_sheets = model.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.