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 |
|---|---|---|---|---|---|---|---|---|---|---|
4eb81354583902e95a41affd0f0bb6572cf8bde8 | examples/hello.py | examples/hello.py | from toil.common import Toil
from toil.job import Job
class HelloWorld(Job):
def __init__(self, message):
Job.__init__(self, memory="2G", cores=2, disk="3G")
self.message = message
def run(self, fileStore):
return "Hello, world!, here's a message: %s" % self.message
if __name__=="__m... | Add a tiny example workflow to support manual testing | Add a tiny example workflow to support manual testing
| Python | apache-2.0 | BD2KGenomics/slugflow,BD2KGenomics/slugflow | ---
+++
@@ -0,0 +1,19 @@
+from toil.common import Toil
+from toil.job import Job
+
+class HelloWorld(Job):
+ def __init__(self, message):
+ Job.__init__(self, memory="2G", cores=2, disk="3G")
+ self.message = message
+
+ def run(self, fileStore):
+ return "Hello, world!, here's a message: ... | |
7d18daa13b16a64d56b06e19d9f2966a79e75755 | tests/test_lesson_3_calculator.py | tests/test_lesson_3_calculator.py | import unittest
from lessons.lesson_3_calculator import calculator
class AddTestCase(unittest.TestCase):
def test_add_returns_sum_of_two_numbers(self):
five = calculator.add(2, 3)
self.assertEqual(five, 5)
ten = calculator.add(7, 3)
self.assertEqual(ten, 10)
def test_position... | Add unit test file for lesson 3: calculator. | Add unit test file for lesson 3: calculator.
| Python | mit | thejessleigh/test_driven_python,thejessleigh/test_driven_python,thejessleigh/test_driven_python | ---
+++
@@ -0,0 +1,55 @@
+import unittest
+
+from lessons.lesson_3_calculator import calculator
+
+
+class AddTestCase(unittest.TestCase):
+ def test_add_returns_sum_of_two_numbers(self):
+ five = calculator.add(2, 3)
+ self.assertEqual(five, 5)
+ ten = calculator.add(7, 3)
+ self.asser... | |
887413520fa06433e19bed093b466ec1282fbbc1 | CycleOpsFluid2PowerCalculator.py | CycleOpsFluid2PowerCalculator.py | from AbstractPowerCalculator import AbstractPowerCalculator
'''
Linear interpolation. Numpy could be used here,
but the app should be kept thin
'''
def interp(x_arr, y_arr, x):
for i, xi in enumerate(x_arr):
if xi >= x:
break
else:
return 611
x_min = x_arr[i - 1]
y_min = y... | Add CycleOps Fluid2 power calculator | Add CycleOps Fluid2 power calculator | Python | mit | dhague/vpower,dhague/vpower | ---
+++
@@ -0,0 +1,46 @@
+from AbstractPowerCalculator import AbstractPowerCalculator
+
+
+'''
+Linear interpolation. Numpy could be used here,
+but the app should be kept thin
+'''
+def interp(x_arr, y_arr, x):
+ for i, xi in enumerate(x_arr):
+ if xi >= x:
+ break
+ else:
+ return 611... | |
46731933b2146bcac81c85cbae711d163a8758dc | Genotype_Matrix_To_Fasta.py | Genotype_Matrix_To_Fasta.py | #!/usr/bin/env python
"""A script to take a genotyping matrix with population assignment and produce
FASTA files for each population. This was written with K. Thornton's
libsequence tools in mind. This script will also remove monomorphic sites.
Assumes that samples are rows and markers are columns. The first column ha... | Add script for converting genotype matrix to libsequence-friendly FASTA | Add script for converting genotype matrix to libsequence-friendly FASTA
| Python | unlicense | MeeshCompBio/Misc_Utils,MeeshCompBio/Misc_Utils,TomJKono/Misc_Utils,MeeshCompBio/Misc_Utils,TomJKono/Misc_Utils,TomJKono/Misc_Utils | ---
+++
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+"""A script to take a genotyping matrix with population assignment and produce
+FASTA files for each population. This was written with K. Thornton's
+libsequence tools in mind. This script will also remove monomorphic sites.
+
+Assumes that samples are rows and markers... | |
350f88747c15e08fc7c58f431ea5a93eb650e789 | ibmcnx/config/addNode.py | ibmcnx/config/addNode.py | ######
# Create Cluster Servers for an additional Node
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-13
#
# License: Apache 2.0
#
def selectNode( nodelist ):
result = ... | Test all scripts on Windows | 10: Test all scripts on Windows
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/10 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 | ---
+++
@@ -0,0 +1,55 @@
+######
+# Create Cluster Servers for an additional Node
+#
+# Author: Christoph Stoettner
+# Mail: christoph.stoettner@stoeps.de
+# Documentation: http://scripting101.stoeps.de
+#
+# Version: 2.0
+# Date: 2014-06-13
+#
+# License: Apache 2.0
+#
+
+... | |
e6369a2b4954356ed6b43cb83fb0aba41c6abc16 | py/house-robber-iii.py | py/house-robber-iii.py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def do_rob(self, cur):
if not cur:
return 0, 0
else:
robl, no_robl = self.do_rob(... | Add py solution for 337. House Robber III | Add py solution for 337. House Robber III
337. House Robber III: https://leetcode.com/problems/house-robber-iii/
Approach:
Observe the first item remaining in each step. The value will be added
1 << step either the remaining count is odd or it's a left-to-right
step. Hence the n | 0x55555.. is the key.
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,24 @@
+# Definition for a binary tree node.
+# class TreeNode(object):
+# def __init__(self, x):
+# self.val = x
+# self.left = None
+# self.right = None
+
+class Solution(object):
+ def do_rob(self, cur):
+ if not cur:
+ return 0, 0
+ else:
+... | |
a5dda3d167d460fd60defe2debc0460d577c008d | src/ifd.blog/ifd/blog/subjects.py | src/ifd.blog/ifd/blog/subjects.py | # -*- coding: UTF-8 -*-
from collective.z3cform.widgets.token_input_widget import TokenInputFieldWidget
from plone.app.dexterity.behaviors.metadata import ICategorization
from plone.app.z3cform.interfaces import IPloneFormLayer
from z3c.form.interfaces import IFieldWidget
from z3c.form.util import getSpecification
from... | Add categorization behavior adaptor for better widget | Add categorization behavior adaptor for better widget
| Python | mit | potzenheimer/buildout.ifd,potzenheimer/buildout.ifd | ---
+++
@@ -0,0 +1,16 @@
+# -*- coding: UTF-8 -*-
+from collective.z3cform.widgets.token_input_widget import TokenInputFieldWidget
+from plone.app.dexterity.behaviors.metadata import ICategorization
+from plone.app.z3cform.interfaces import IPloneFormLayer
+from z3c.form.interfaces import IFieldWidget
+from z3c.form.... | |
e947e9b0a5c3804d50bc6a602433861cca10debb | rwt/tests/test_deps.py | rwt/tests/test_deps.py | import pytest
import pkg_resources
from rwt import deps
@pytest.mark.xfail(reason="Technique fails to load entry points")
def test_entry_points():
"""
Ensure entry points are visible after making packages visible
"""
with deps.on_sys_path('jaraco.mongodb'):
eps = pkg_resources.iter_entry_points('pytest11')
as... | Add test capturing expectation that entry points will be visible after installing packages. | Add test capturing expectation that entry points will be visible after installing packages.
| Python | mit | jaraco/rwt | ---
+++
@@ -0,0 +1,13 @@
+import pytest
+import pkg_resources
+
+from rwt import deps
+
+@pytest.mark.xfail(reason="Technique fails to load entry points")
+def test_entry_points():
+ """
+ Ensure entry points are visible after making packages visible
+ """
+ with deps.on_sys_path('jaraco.mongodb'):
+ eps = pkg_resou... | |
769f982d58c75e4c3f07d68d93a3dd549d548efa | scripts/get-instances.py | scripts/get-instances.py | import sys
from boto import ec2
def get_instances(conn, environment):
for reservation in conn.get_all_reservations():
env_suffix = '-{}'.format(environment)
if reservation.instances[0].tags['Name'].endswith(env_suffix):
yield reservation.instances[0]
if __name__ == '__main__':
en... | Add a script to list instances | Add a script to list instances
This is a quick and dirty script to list out instances from an
environment.
| Python | mit | alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws | ---
+++
@@ -0,0 +1,19 @@
+import sys
+from boto import ec2
+
+
+def get_instances(conn, environment):
+ for reservation in conn.get_all_reservations():
+ env_suffix = '-{}'.format(environment)
+ if reservation.instances[0].tags['Name'].endswith(env_suffix):
+ yield reservation.instances[0]... | |
046bacdc8e7a92785f12bf8e3b3a6c698df3f86f | bin/benchmark_embed.py | bin/benchmark_embed.py | import nltk
import plac
import os
from os import path
import io
import gzip
from collections import defaultdict
import cProfile
import pstats
from thinc.neural.eeap import Embed
from thinc.neural.eeap import NumpyOps
def iter_files(giga_dir):
i = 0
for subdir in os.listdir(giga_dir):
if not path.isdi... | Add existing script to benchmark embed | Add existing script to benchmark embed
| Python | mit | explosion/thinc,spacy-io/thinc,explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc | ---
+++
@@ -0,0 +1,56 @@
+import nltk
+import plac
+import os
+from os import path
+import io
+import gzip
+from collections import defaultdict
+import cProfile
+import pstats
+
+from thinc.neural.eeap import Embed
+from thinc.neural.eeap import NumpyOps
+
+
+def iter_files(giga_dir):
+ i = 0
+ for subdir in os... | |
a68760976cfbfa276b16ed465d6312783407dc8c | examples/flask_context.py | examples/flask_context.py | from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from flask import Flask
from flask_apscheduler import APScheduler
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
... | Add example to show how to get a flask context within a task. | Add example to show how to get a flask context within a task.
| Python | apache-2.0 | viniciuschiele/flask-apscheduler | ---
+++
@@ -0,0 +1,49 @@
+from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
+from flask import Flask
+from flask_apscheduler import APScheduler
+from flask_sqlalchemy import SQLAlchemy
+
+
+db = SQLAlchemy()
+
+
+class User(db.Model):
+ id = db.Column(db.Integer, primary_key=True)
+ username = db.... | |
f9b4544b359c48be3bcae9fd2d6e3a99c8a18e44 | t3f/shapes_test.py | t3f/shapes_test.py | import tensorflow as tf
from t3f import initializers
from t3f import shapes
class ShapesTest(tf.test.TestCase):
def testLazyShapeOverflow(self):
large_shape = [10] * 20
tensor = initializers.random_matrix_batch([large_shape, large_shape], batch_size=5)
self.assertAllEqual([5, 10 ** 20, 10 ** 20], shap... | Test lazy shape as well | Test lazy shape as well
| Python | mit | Bihaqo/t3f | ---
+++
@@ -0,0 +1,16 @@
+import tensorflow as tf
+
+from t3f import initializers
+from t3f import shapes
+
+
+class ShapesTest(tf.test.TestCase):
+
+ def testLazyShapeOverflow(self):
+ large_shape = [10] * 20
+ tensor = initializers.random_matrix_batch([large_shape, large_shape], batch_size=5)
+ self.asser... | |
561d9db2693c4bd63dd8fce32192f43d92a67b36 | job-logs/python/check_log.py | job-logs/python/check_log.py | import sys
import argparse
import csv
def examine_log(filename, save_raw=False):
"""
Download job log files from Amazon EC2 machines
parameters:
filename - beginning date to start downloading from
work_directory - directory to download files to
"""
input_file =- open(filename, 'r')
c... | Add script for checking csv files | Add script for checking csv files
| Python | apache-2.0 | DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs,DHTC-Tools/logstash-confs | ---
+++
@@ -0,0 +1,34 @@
+import sys
+import argparse
+import csv
+
+
+def examine_log(filename, save_raw=False):
+ """
+ Download job log files from Amazon EC2 machines
+
+ parameters:
+ filename - beginning date to start downloading from
+ work_directory - directory to download files to
+ """
+ ... | |
567e3c57762e13e0d43138940bc0b8d4cc15b08b | tests/unit/dataactcore/test_models_userModel.py | tests/unit/dataactcore/test_models_userModel.py | from dataactcore.models.domainModels import CGAC
from dataactcore.models.lookups import PERMISSION_TYPE_DICT
from dataactcore.models.userModel import User, UserAffiliation
from tests.unit.dataactcore.factories.domain import CGACFactory
from tests.unit.dataactcore.factories.user import UserFactory
def test_user_affili... | Add FK tests for user affiliations | Add FK tests for user affiliations
cc @nmonga91
| Python | cc0-1.0 | fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend | ---
+++
@@ -0,0 +1,42 @@
+from dataactcore.models.domainModels import CGAC
+from dataactcore.models.lookups import PERMISSION_TYPE_DICT
+from dataactcore.models.userModel import User, UserAffiliation
+from tests.unit.dataactcore.factories.domain import CGACFactory
+from tests.unit.dataactcore.factories.user import Us... | |
ab08b50774170f4d3df6cfb58c447878ff646465 | create-vm-opensteak.py | create-vm-opensteak.py | #!/usr/bin/python
import os
import pprint
import novaclient.v1_1.client as novaclient
pp = pprint.PrettyPrinter(indent=4)
def p(value):
"""Shortcut for pretty printing"""
pp.pprint(value)
def print_title(title):
"""Print title of things"""
print "\n"+"#"*32+"\n# "+title+"\n"+"#"*32+"\n"
def get_creds... | Add back create vm on opensteak | Add back create vm on opensteak
| Python | apache-2.0 | arnaudmorin/instantserver,arnaudmorin/instantserver,arnaudmorin/instantserver | ---
+++
@@ -0,0 +1,52 @@
+#!/usr/bin/python
+import os
+import pprint
+import novaclient.v1_1.client as novaclient
+pp = pprint.PrettyPrinter(indent=4)
+
+def p(value):
+ """Shortcut for pretty printing"""
+ pp.pprint(value)
+
+def print_title(title):
+ """Print title of things"""
+ print "\n"+"#"*32+"\n#... | |
f6fce37d3121a27e9ddb0a78cc17926ac7062f94 | osf/migrations/0142_auto_20181029_1701.py | osf/migrations/0142_auto_20181029_1701.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-10-29 17:01
from __future__ import unicode_literals
from django.db import migrations
from django.db.models import OuterRef, Subquery
from osf.models import NodeLog, Node
from django_bulk_update.helper import bulk_update
def untransfer_forked_date(state, s... | Add a data migration to iterate over forks and find where the last log is a fork log and set the last_logged date on the node to the date of that log. | Add a data migration to iterate over forks and find where the last log is a fork log and set the last_logged date on the node to the date of that log.
| Python | apache-2.0 | mfraezz/osf.io,CenterForOpenScience/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,mattclark/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,felliott/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,pattisdr/osf.io,brianjgeiger/osf.io,baylee-d/osf.io,mfraezz/osf.io,mat... | ---
+++
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.15 on 2018-10-29 17:01
+from __future__ import unicode_literals
+
+from django.db import migrations
+from django.db.models import OuterRef, Subquery
+from osf.models import NodeLog, Node
+from django_bulk_update.helper import bulk_update
+
... | |
9e2f770c560f35cb67aac96596d92cd2d1cc1d30 | examples/geoms.py | examples/geoms.py |
from shapely.geometry import Point, LineString, Polygon
polygon = Polygon(((-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (1.0, -1.0)))
point_r = Point(-1.5, 1.2)
point_g = Point(-1.0, 1.0)
point_b = Point(-0.5, 0.5)
line_r = LineString(((-0.5, 0.5), (0.5, 0.5)))
line_g = LineString(((1.0, -1.0), (1.8, 0.5)))
line_b = Line... | Add tutorial geometries, with plot | Add tutorial geometries, with plot
git-svn-id: 30e8e193f18ae0331cc1220771e45549f871ece9@871 b426a367-1105-0410-b9ff-cdf4ab011145
| Python | bsd-3-clause | abali96/Shapely,jdmcbr/Shapely,mouadino/Shapely,mindw/shapely,abali96/Shapely,jdmcbr/Shapely,mindw/shapely,mouadino/Shapely | ---
+++
@@ -0,0 +1,41 @@
+
+from shapely.geometry import Point, LineString, Polygon
+
+polygon = Polygon(((-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (1.0, -1.0)))
+
+point_r = Point(-1.5, 1.2)
+point_g = Point(-1.0, 1.0)
+point_b = Point(-0.5, 0.5)
+
+line_r = LineString(((-0.5, 0.5), (0.5, 0.5)))
+line_g = LineString(((... | |
84c4097caf0db678859252c58c1822d12d11c924 | polly/plugins/publish/upload_avalon_asset.py | polly/plugins/publish/upload_avalon_asset.py | from pyblish import api
from avalon.api import Session
class UploadAvalonAsset(api.InstancePlugin):
"""Write to files and metadata
This plug-in exposes your data to others by encapsulating it
into a new version.
"""
label = "Upload"
order = api.IntegratorOrder + 0.1
depends = ["Integrat... | Implement automatic upload, enabled via AVALON_UPLOAD | Implement automatic upload, enabled via AVALON_UPLOAD
| Python | mit | mindbender-studio/config | ---
+++
@@ -0,0 +1,64 @@
+from pyblish import api
+from avalon.api import Session
+
+
+class UploadAvalonAsset(api.InstancePlugin):
+ """Write to files and metadata
+
+ This plug-in exposes your data to others by encapsulating it
+ into a new version.
+
+ """
+
+ label = "Upload"
+ order = api.Integ... | |
ec31a66014c00a916eb49d78557e6ddb0c4dbb50 | dakota_utils/tests/test_write.py | dakota_utils/tests/test_write.py | #!/usr/bin/env python
#
# Tests for dakota_utils.write.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (mark.piper@colorado.edu)
from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.file import touch, remove
from dakota_utils.write import *
nonfile = 'fbwiBVBVFVBvVB.txt'
def setup_mo... | Add unit tests for write module | Add unit tests for write module
| Python | mit | mdpiper/dakota-experiments,mdpiper/dakota-experiments,mcflugen/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+#
+# Tests for dakota_utils.write.
+#
+# Call with:
+# $ nosetests -sv
+#
+# Mark Piper (mark.piper@colorado.edu)
+
+from nose.tools import *
+import os
+import tempfile
+import shutil
+from dakota_utils.file import touch, remove
+from dakota_utils.write import *
+
+... | |
5afb810c19923ff7edeb41ba084b1d7b85925840 | markov/markov2.py | markov/markov2.py | #!python3
import string
import random
import time
import re
import sys
'''
This is an implementation of a markov chain used for text generation.
Just pass a file name as an argument and it should load it up, build a markov
chain with a state for each word(s), and start walking through the chain, writing
incoherent t... | Add second markov text generator v2 with order parameter | Add second markov text generator v2 with order parameter
| Python | mit | tmerr/trevornet | ---
+++
@@ -0,0 +1,99 @@
+#!python3
+
+import string
+import random
+import time
+import re
+import sys
+
+
+'''
+This is an implementation of a markov chain used for text generation.
+Just pass a file name as an argument and it should load it up, build a markov
+chain with a state for each word(s), and start walking... | |
05306ceea2d33c8732f339e26655927474b8f9c7 | deploy.py | deploy.py | #!/usr/bin/python
from subprocess import check_output, call
import argparse
def main():
args = process_args()
output = check_output(['git', 'status', '--porcelain', '-uno'])
filelist = output.split('\n')
for staged_file in filelist:
if staged_file:
deploy_code(staged_file, args)
de... | Deploy staged files by using scp | Deploy staged files by using scp
| Python | mit | csterryliu/deploy-changed-code | ---
+++
@@ -0,0 +1,43 @@
+#!/usr/bin/python
+from subprocess import check_output, call
+import argparse
+
+def main():
+ args = process_args()
+ output = check_output(['git', 'status', '--porcelain', '-uno'])
+ filelist = output.split('\n')
+ for staged_file in filelist:
+ if staged_file:
+ ... | |
fbc2642b0361d48579c6556817fab02e9a7cfda8 | gen/azure/calc.py | gen/azure/calc.py | import pkg_resources
import yaml
entry = {
'must': {
'resolvers': '["168.63.129.16"]',
'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/aws.sh').decode()),
'master_discovery': 'static',
'exhibitor_storage_backend': 'azure',
'master_cloud_confi... | import pkg_resources
import yaml
entry = {
'must': {
'resolvers': '["168.63.129.16"]',
'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/azure.sh').decode()),
'master_discovery': 'static',
'exhibitor_storage_backend': 'azure',
'master_cloud_con... | Fix Azure to use it's ip-detect script rather than AWS' | Fix Azure to use it's ip-detect script rather than AWS'
| Python | apache-2.0 | surdy/dcos,kensipe/dcos,xinxian0458/dcos,mnaboka/dcos,darkonie/dcos,dcos/dcos,lingmann/dcos,mesosphere-mergebot/dcos,mellenburg/dcos,jeid64/dcos,kensipe/dcos,mnaboka/dcos,vishnu2kmohan/dcos,amitaekbote/dcos,kensipe/dcos,kensipe/dcos,xinxian0458/dcos,vishnu2kmohan/dcos,darkonie/dcos,dcos/dcos,dcos/dcos,xinxian0458/dcos,... | ---
+++
@@ -5,7 +5,7 @@
entry = {
'must': {
'resolvers': '["168.63.129.16"]',
- 'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/aws.sh').decode()),
+ 'ip_detect_contents': yaml.dump(pkg_resources.resource_string('gen', 'ip-detect/azure.sh').decode()),
... |
91b63107a77bc9153151c2aede3e834374aa775b | backend/scripts/copyproj.py | backend/scripts/copyproj.py | #!/usr/bin/env python
from optparse import OptionParser
import rethinkdb as r
import sys
import shutil
import os
import errno
def mkdirp(path):
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
... | Add script to copy over project files to a directory tree. | Add script to copy over project files to a directory tree.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -0,0 +1,64 @@
+#!/usr/bin/env python
+
+from optparse import OptionParser
+import rethinkdb as r
+import sys
+import shutil
+import os
+import errno
+
+
+def mkdirp(path):
+ try:
+ os.makedirs(path)
+ except OSError as exc:
+ if exc.errno == errno.EEXIST and os.path.isdir(path):
+ ... | |
5684db6e73de6a3358c4f669facbdd47fb0d0b9e | setup.py | setup.py | #!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version... | #!/usr/bin/env python
import os
import sys
import skosprovider
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
packages = [
'skosprovider',
]
requires = [
'language-tags',
'rfc3987',
'pyld',
'html5lib'
]
setup(
name='skosprovider',
version... | Add long description content type. | Add long description content type.
| Python | mit | koenedaele/skosprovider | ---
+++
@@ -26,6 +26,7 @@
version='0.8.0',
description='Abstraction layer for SKOS vocabularies.',
long_description=open('README.rst').read(),
+ long_description_content_type='text/x-rst',
author='Koen Van Daele',
author_email='koen_van_daele@telenet.be',
url='http://github.com/koened... |
9f36fa84c2357e829d7820c1d4024decf702f04f | test/test_ViewLogin.py | test/test_ViewLogin.py | import pytest
from controller import db
from model.user import User
from test import C3BottlesTestCase, NAME, PASSWORD
class LoginViewTestCase(C3BottlesTestCase):
def test_login(self):
self.create_test_user()
resp = self.c3bottles.post('/login', data=dict(
username=NAME,
... | Add a simple login test case | test: Add a simple login test case
| Python | mit | der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles,der-michik/c3bottles | ---
+++
@@ -0,0 +1,26 @@
+import pytest
+
+from controller import db
+from model.user import User
+
+from test import C3BottlesTestCase, NAME, PASSWORD
+
+
+class LoginViewTestCase(C3BottlesTestCase):
+
+ def test_login(self):
+ self.create_test_user()
+
+ resp = self.c3bottles.post('/login', data=di... | |
7efea7644cdb567742532f4edd24f528badef21b | pandas_rs/rs.py | pandas_rs/rs.py | import psycopg2
import pandas as pd
def create_engine(dbname, user, password, host, port):
return Redshift.create_engine(dbname, user, password, host, port)
class Redshift(object):
"""
Redshift client which connect to redshfit database.
Furthermore, you can read sql from Redshift and
returns the r... | Add Reshift class which connect to redshift | Add Reshift class which connect to redshift
| Python | mit | SamuraiT/pandas-rs | ---
+++
@@ -0,0 +1,75 @@
+import psycopg2
+import pandas as pd
+
+def create_engine(dbname, user, password, host, port):
+ return Redshift.create_engine(dbname, user, password, host, port)
+
+class Redshift(object):
+ """
+ Redshift client which connect to redshfit database.
+ Furthermore, you can read sq... | |
3ede8da88dc0a368fed45b696f66168898f6363e | tests/test_tip_json.py | tests/test_tip_json.py | import json
from nose.tools import assert_equal
from gittip.testing import TestClient
from gittip import db
CREATE_ACCOUNT = "INSERT INTO participants (id) VALUES (%s);"
def test_get_amount_and_total_back_from_api():
"Test that we get correct amounts and totals back on POSTs to tip.json"
client = TestClien... | Add test for tip.json view. | Add test for tip.json view.
| Python | cc0-1.0 | mccolgst/www.gittip.com,bountysource/www.gittip.com,bountysource/www.gittip.com,eXcomm/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,bountysource/www.gittip.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,bountysource... | ---
+++
@@ -0,0 +1,41 @@
+import json
+from nose.tools import assert_equal
+
+from gittip.testing import TestClient
+from gittip import db
+
+
+CREATE_ACCOUNT = "INSERT INTO participants (id) VALUES (%s);"
+
+
+def test_get_amount_and_total_back_from_api():
+ "Test that we get correct amounts and totals back on PO... | |
296fdb0bd202ea39d73d421ee4aa51efb079d297 | src/waldur_core/core/migrations/0019_drop_zabbix_tables.py | src/waldur_core/core/migrations/0019_drop_zabbix_tables.py | from django.db import migrations
TABLES = (
'monitoring_resourceitem',
'monitoring_resourcesla',
'monitoring_resourceslastatetransition',
'waldur_zabbix_usergroup',
'waldur_zabbix_item',
'waldur_zabbix_trigger',
'waldur_zabbix_host_templates',
'waldur_zabbix_template',
'waldur_zabbi... | Add migration for zabbix tables | Add migration for zabbix tables
| Python | mit | opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur | ---
+++
@@ -0,0 +1,32 @@
+from django.db import migrations
+
+TABLES = (
+ 'monitoring_resourceitem',
+ 'monitoring_resourcesla',
+ 'monitoring_resourceslastatetransition',
+ 'waldur_zabbix_usergroup',
+ 'waldur_zabbix_item',
+ 'waldur_zabbix_trigger',
+ 'waldur_zabbix_host_templates',
+ 'wald... | |
a284f097b388c0cbdd92af0a28cf5fe78fd03986 | hackerrank_hello_world.py | hackerrank_hello_world.py | # Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
inputString = raw_input()
# Print a string literal saying "Hello, World." to stdout.
print 'Hello, World.'
print inputString
| Print Hello, World on the first line, and the contents of input on the second line. | Print Hello, World on the first line, and the contents of input on the second line.
| Python | mit | kumarisneha/practice_repo | ---
+++
@@ -0,0 +1,8 @@
+# Read a full line of input from stdin and save it to our dynamically typed variable, input_string.
+inputString = raw_input()
+
+# Print a string literal saying "Hello, World." to stdout.
+print 'Hello, World.'
+print inputString
+
+ | |
df2dc6cad36851e2b7aaf1d3ace98483a00b51c7 | altair/vegalite/v2/examples/simple_line_chart_with_markers.py | altair/vegalite/v2/examples/simple_line_chart_with_markers.py | """
Simple Line Chart with Markers
------------------------------
This chart shows the most basic line chart with markers, made from a dataframe with two
columns.
"""
# category: simple charts
import altair as alt
import numpy as np
import pandas as pd
x = np.arange(100)
data = pd.DataFrame({'x': x,
... | Add simple line chart with markers example | DOC: Add simple line chart with markers example
| Python | bsd-3-clause | altair-viz/altair,jakevdp/altair | ---
+++
@@ -0,0 +1,20 @@
+"""
+Simple Line Chart with Markers
+------------------------------
+This chart shows the most basic line chart with markers, made from a dataframe with two
+columns.
+"""
+# category: simple charts
+
+import altair as alt
+import numpy as np
+import pandas as pd
+
+x = np.arange(100)
+data ... | |
3ad97790d078d50839d8a0c50775d8a75e04ff9e | py/longest-palindromic-subsequence.py | py/longest-palindromic-subsequence.py | class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
prev2 = [0] * len(s)
prev = [1] * len(s)
for l in xrange(2, len(s) + 1):
nxt = [0] * (len(s) - l + 1)
for i in xrange(len(s) - l + 1):
... | Add py solution for 516. Longest Palindromic Subsequence | Add py solution for 516. Longest Palindromic Subsequence
516. Longest Palindromic Subsequence: https://leetcode.com/problems/longest-palindromic-subsequence/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,17 @@
+class Solution(object):
+ def longestPalindromeSubseq(self, s):
+ """
+ :type s: str
+ :rtype: int
+ """
+ prev2 = [0] * len(s)
+ prev = [1] * len(s)
+ for l in xrange(2, len(s) + 1):
+ nxt = [0] * (len(s) - l + 1)
+ f... | |
ca716b34fa0e320f8f3684fdba2e124ebf79a534 | compileJSX.py | compileJSX.py | from react import jsx
# For a single file, you can use a shortcut method.
jsx.transform('website/public/js/riverComponents.jsx', js_path='website/public/js/riverComponents.js')
| Add script to translate riverComponents jsx => js | Add script to translate riverComponents jsx => js
| Python | agpl-3.0 | 1self/api,1self/api,1self/api,1self/api | ---
+++
@@ -0,0 +1,4 @@
+from react import jsx
+
+# For a single file, you can use a shortcut method.
+jsx.transform('website/public/js/riverComponents.jsx', js_path='website/public/js/riverComponents.js') | |
c15ca56c170fe13ef6a7b016de812f57d613c0bb | python--learnings/class_functionality.py | python--learnings/class_functionality.py | #!/usr/bin/env python
#
# Topics: Classes, Inheritance, and Related
#
# Background: Use of classes, including inheritance, instance variables, etc.
#
# Sources:
# - https://www.python-course.eu/object_oriented_programming.php
# - https://realpython.com/python3-object-oriented-programming
import unittest
class... | Add Python Class Test Functionality | Add Python Class Test Functionality
Add some refreshers around Python classes.
| Python | mit | jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox,jekhokie/scriptbox | ---
+++
@@ -0,0 +1,57 @@
+#!/usr/bin/env python
+#
+# Topics: Classes, Inheritance, and Related
+#
+# Background: Use of classes, including inheritance, instance variables, etc.
+#
+# Sources:
+# - https://www.python-course.eu/object_oriented_programming.php
+# - https://realpython.com/python3-object-oriented... | |
fb7e95444136b1e8461b4cd246df1b81f4767f1e | tests/test_runnable.py | tests/test_runnable.py | import glob
import os
import unittest
from chainer import testing
class TestRunnable(unittest.TestCase):
def test_runnable(self):
cwd = os.path.dirname(__file__)
for path in glob.iglob(os.path.join(cwd, '**', '*.py')):
with open(path) as f:
source = f.read()
... | Add test to check if all tests are runnable | Add test to check if all tests are runnable
| Python | mit | keisuke-umezawa/chainer,jnishi/chainer,wkentaro/chainer,t-abe/chainer,t-abe/chainer,cupy/cupy,okuta/chainer,okuta/chainer,niboshi/chainer,chainer/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,ktnyt/chainer,laysakura/chainer,masia02/chainer,wavelets/chainer,jnishi/chainer,jnishi/chainer,sinhrks/chainer,baye... | ---
+++
@@ -0,0 +1,21 @@
+import glob
+import os
+import unittest
+
+from chainer import testing
+
+
+class TestRunnable(unittest.TestCase):
+
+ def test_runnable(self):
+ cwd = os.path.dirname(__file__)
+ for path in glob.iglob(os.path.join(cwd, '**', '*.py')):
+ with open(path) as f:
+ ... | |
4db37770ab2378822b91316e56ca0618912231ac | demo/scripts/random-build-graph.py | demo/scripts/random-build-graph.py | #!/usr/bin/env python3
# Copyright 2016 Codethink Ltd.
# Apache 2.0 license
'''Generate a random build graph in 'node-link' JSON format.'''
import networkx
import networkx.readwrite.json_graph
import json
import sys
INPUT_NAMES = '/usr/share/dict/words'
N_NODES = 1000
N_EDGES = 2000
# Return a random graph wit... | Add random build graph generator | Add random build graph generator
| Python | apache-2.0 | ssssam/generic-concourse-ui,ssssam/generic-concourse-ui | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env python3
+# Copyright 2016 Codethink Ltd.
+# Apache 2.0 license
+
+'''Generate a random build graph in 'node-link' JSON format.'''
+
+
+import networkx
+import networkx.readwrite.json_graph
+
+import json
+import sys
+
+
+INPUT_NAMES = '/usr/share/dict/words'
+
+N_NODES = 1000
... | |
0f06ade09a339f99789b3b4e9ae9ac7db2c1f22d | genoome/disease/migrations/0017_remove_allelecolor_color.py | genoome/disease/migrations/0017_remove_allelecolor_color.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('disease', '0016_auto_20151007_0824'),
]
operations = [
migrations.RemoveField(
model_name='allelecolor',
... | Remove field color from allelecolor | Remove field color from allelecolor
| Python | mit | jiivan/genoomy,jiivan/genoomy,jiivan/genoomy,jiivan/genoomy | ---
+++
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('disease', '0016_auto_20151007_0824'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ ... | |
6a889eea6953e8ecb89c0cbac0656f5d7e274669 | project/creditor/management/commands/update_membershipfees.py | project/creditor/management/commands/update_membershipfees.py | # -*- coding: utf-8 -*-
import datetime
import dateutil.parser
from creditor.models import RecurringTransaction, TransactionTag
from creditor.tests.fixtures.recurring import MembershipfeeFactory
from django.core.management.base import BaseCommand, CommandError
from members.models import Member
class Command(BaseComm... | Add initial version of membership fee updater | Add initial version of membership fee updater
| Python | mit | jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,jautero/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,hacklab-fi/asylum,rambo/asylum,HelsinkiHacklab/asylum,jautero/asylum,jautero/asylum,HelsinkiHacklab/asylum,rambo/asylum,rambo/asylum,rambo/asylum,hacklab-fi/asylum | ---
+++
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+import datetime
+import dateutil.parser
+
+from creditor.models import RecurringTransaction, TransactionTag
+from creditor.tests.fixtures.recurring import MembershipfeeFactory
+from django.core.management.base import BaseCommand, CommandError
+from members.models imp... | |
71a3fc92f947aa4ae2041829f47b9dad617b3532 | pylearn2/scripts/tests/test_show_weights.py | pylearn2/scripts/tests/test_show_weights.py | """
Tests for the show_weights.py script
"""
import cPickle
import os
from pylearn2.testing.skip import skip_if_no_matplotlib
from pylearn2.models.mlp import MLP, Linear
from pylearn2.scripts.show_weights import show_weights
def test_show_weights():
"""
Create a pickled model and show the weights
"""
... | Add unit test for show_weights.py | Add unit test for show_weights.py
| Python | bsd-3-clause | mclaughlin6464/pylearn2,lamblin/pylearn2,KennethPierce/pylearnk,lamblin/pylearn2,pkainz/pylearn2,caidongyun/pylearn2,hyqneuron/pylearn2-maxsom,woozzu/pylearn2,kastnerkyle/pylearn2,sandeepkbhat/pylearn2,matrogers/pylearn2,lunyang/pylearn2,alexjc/pylearn2,fishcorn/pylearn2,ddboline/pylearn2,pkainz/pylearn2,pombredanne/py... | ---
+++
@@ -0,0 +1,29 @@
+"""
+Tests for the show_weights.py script
+"""
+import cPickle
+import os
+
+from pylearn2.testing.skip import skip_if_no_matplotlib
+from pylearn2.models.mlp import MLP, Linear
+from pylearn2.scripts.show_weights import show_weights
+
+
+def test_show_weights():
+ """
+ Create a pickl... | |
7c2b2fca21424dda2633b152a49d8b2350eff3de | moniker/tests/test_api/test_auth.py | moniker/tests/test_api/test_auth.py | # Copyright 2012 Managed I.T.
#
# Author: Kiall Mac Innes <kiall@managedit.ie>
#
# 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 r... | Add tests for KeystoneContextMiddleware and NoAuthMiddleware | Add tests for KeystoneContextMiddleware and NoAuthMiddleware
Change-Id: I3fa40ae111c48810f1f2c5774925c1460c958163
| Python | apache-2.0 | ramsateesh/designate,cneill/designate,melodous/designate,ramsateesh/designate,richm/designate,NeCTAR-RC/designate,melodous/designate,openstack/designate,cneill/designate,richm/designate,kiall/designate-py3,kiall/designate-py3,cneill/designate-testing,ramsateesh/designate,grahamhayes/designate,muraliselva10/designate,gr... | ---
+++
@@ -0,0 +1,78 @@
+# Copyright 2012 Managed I.T.
+#
+# Author: Kiall Mac Innes <kiall@managedit.ie>
+#
+# 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.o... | |
06294648da65a1303601a3bc69bc341c59eab9a9 | setup.py | setup.py | from distutils.core import setup
setup(
name='udiskie',
version='0.4.1',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name',
url='http://bitbucket.org/byronclark/udiskie',
license='MIT',
packages=[
'udiskie',
]... | from distutils.core import setup
setup(
name='udiskie',
version='0.4.2',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name',
url='http://bitbucket.org/byronclark/udiskie',
license='MIT',
packages=[
'udiskie',
]... | Prepare for next development cycle. | Prepare for next development cycle.
| Python | mit | coldfix/udiskie,khardix/udiskie,coldfix/udiskie,mathstuf/udiskie,pstray/udiskie,pstray/udiskie | ---
+++
@@ -2,7 +2,7 @@
setup(
name='udiskie',
- version='0.4.1',
+ version='0.4.2',
description='Removable disk automounter for udisks',
author='Byron Clark',
author_email='byron@theclarkfamily.name', |
7468494e5a604c138c8a9ad777eed9c9550c354f | docker_test/network_test.py | docker_test/network_test.py | # coding=utf-8
import unittest
import json
from docker import session
from docker import network
from docker_test import base_test
class NetworkTest(unittest.TestCase):
def setUp(self):
self.c_session = session.get_session(base_test.session_url)
self.n = network.Network(self.c_session)
... | Add network api test case | Add network api test case | Python | apache-2.0 | interhui/docker-api,PinaeCloud/docker-api | ---
+++
@@ -0,0 +1,51 @@
+# coding=utf-8
+
+import unittest
+import json
+from docker import session
+from docker import network
+
+from docker_test import base_test
+
+class NetworkTest(unittest.TestCase):
+
+ def setUp(self):
+ self.c_session = session.get_session(base_test.session_url)
+ self.... | |
aa985e9a686c4f333f64f6f39759f1cd0cc0f8c2 | oscar/apps/offer/managers.py | oscar/apps/offer/managers.py | from django.utils.timezone import now
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating offers within their date range
"""
def get_query_set(self):
cutoff = now()
return super(ActiveOfferManager, self).get_query_set().filter(
... | from django.utils.timezone import now
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating offers within their date range
"""
def get_query_set(self):
cutoff = now()
return super(ActiveOfferManager, self).get_query_set().filter(
... | Fix bug with date filtering of offers | Fix bug with date filtering of offers
Offers with no end date were not being picked up.
| Python | bsd-3-clause | kapt/django-oscar,itbabu/django-oscar,eddiep1101/django-oscar,dongguangming/django-oscar,manevant/django-oscar,ahmetdaglarbas/e-commerce,DrOctogon/unwash_ecom,anentropic/django-oscar,mexeniz/django-oscar,binarydud/django-oscar,taedori81/django-oscar,jinnykoo/wuyisj,WillisXChen/django-oscar,QLGu/django-oscar,itbabu/djan... | ---
+++
@@ -10,4 +10,5 @@
def get_query_set(self):
cutoff = now()
return super(ActiveOfferManager, self).get_query_set().filter(
- start_datetime__lte=cutoff, end_datetime__gte=cutoff)
+ models.Q(end_date__gte=today) | models.Q(end_date=None),
+ start_date__lte=... |
4d47aef2b91e77cd8bc295d4166b49d3bfc78b8d | watson/apps.py | watson/apps.py | from django.apps import AppConfig
class WatsonAppConfig(AppConfig):
"""App configuration for watson."""
name = 'watson'
default_auto_field = 'django.db.models.AutoField'
| Add AppConfig with default_auto_field set | Add AppConfig with default_auto_field set
| Python | bsd-3-clause | etianen/django-watson,etianen/django-watson | ---
+++
@@ -0,0 +1,7 @@
+from django.apps import AppConfig
+
+
+class WatsonAppConfig(AppConfig):
+ """App configuration for watson."""
+ name = 'watson'
+ default_auto_field = 'django.db.models.AutoField' | |
28b49417a46659a2e64ee91eea497f674d42dde5 | tests/test_integration.py | tests/test_integration.py | from pandarus import intersect
import fiona
import json
import numpy as np
import os
import tempfile
dirpath = os.path.abspath(os.path.join(os.path.dirname(__file__), "data"))
grid = os.path.join(dirpath, "grid.geojson")
square = os.path.join(dirpath, "square.geojson")
range_raster = os.path.join(dirpath, "range.tif")... | Add first intersection integration test | Add first intersection integration test
| Python | bsd-3-clause | cmutel/pandarus | ---
+++
@@ -0,0 +1,82 @@
+from pandarus import intersect
+import fiona
+import json
+import numpy as np
+import os
+import tempfile
+
+dirpath = os.path.abspath(os.path.join(os.path.dirname(__file__), "data"))
+grid = os.path.join(dirpath, "grid.geojson")
+square = os.path.join(dirpath, "square.geojson")
+range_raste... | |
a6bd9c0b2b552347d540b2b05b7d7ed31d84a47b | remove_nth_node_from_end_of_list.py | remove_nth_node_from_end_of_list.py | '''
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
... | Remove Nth Node From End of List problem | Remove Nth Node From End of List problem
| Python | apache-2.0 | zsmountain/leetcode,zsmountain/leetcode,zsmountain/leetcode | ---
+++
@@ -0,0 +1,64 @@
+'''
+Given a linked list, remove the nth node from the end of list and return its head.
+
+For example,
+
+ Given linked list: 1->2->3->4->5, and n = 2.
+
+ After removing the second node from the end, the linked list becomes 1->2->3->5.
+ Note:
+ Given n will always be vali... | |
f25d4cc39d5a6b4f9463ad4abfbfc722b0ab74af | tests/kafka_consumer_manager/test_list_groups.py | tests/kafka_consumer_manager/test_list_groups.py | import contextlib
import sys
import mock
from kazoo.exceptions import NoNodeError
from yelp_kafka_tool.kafka_consumer_manager. \
commands.list_groups import ListGroups
class TestListGroups(object):
@contextlib.contextmanager
def mock_kafka_info(self, topics_partitions):
with mock.patch.object(
... | Add unit tests for list_groups command. | KAFKA-797: Add unit tests for list_groups command.
| Python | apache-2.0 | anthonysandrin/kafka-utils,Yelp/kafka-utils,Yelp/kafka-utils,anthonysandrin/kafka-utils | ---
+++
@@ -0,0 +1,76 @@
+import contextlib
+import sys
+
+import mock
+from kazoo.exceptions import NoNodeError
+
+from yelp_kafka_tool.kafka_consumer_manager. \
+ commands.list_groups import ListGroups
+
+
+class TestListGroups(object):
+
+ @contextlib.contextmanager
+ def mock_kafka_info(self, topics_part... | |
30d26f76e76ee760ec72ce95f6845891cd6ed3b0 | examples/asmleds.py | examples/asmleds.py | """
This script uses the inline assembler to make the LEDs light up
in a pattern based on how they are multiplexed in rows/cols.
"""
# row pins: 13, 14, 15
# col pins: 4..12 inclusive
# GPIO words starting at 0x50000500:
# RESERVED, OUT, OUTSET, OUTCLR, IN, DIR, DIRSET, DIRCLR
@micropython.asm_thumb
def led_cycle()... | Add example using the inline assembler. | Add example using the inline assembler.
| Python | mit | JoeGlancy/micropython,JoeGlancy/micropython,JoeGlancy/micropython | ---
+++
@@ -0,0 +1,57 @@
+"""
+This script uses the inline assembler to make the LEDs light up
+in a pattern based on how they are multiplexed in rows/cols.
+"""
+
+# row pins: 13, 14, 15
+# col pins: 4..12 inclusive
+# GPIO words starting at 0x50000500:
+# RESERVED, OUT, OUTSET, OUTCLR, IN, DIR, DIRSET, DIRCLR
+
+... | |
bae0360435a42b0298c0728f0c718d415b12938d | socket_server.py | socket_server.py | #!/usr/bin/env python
import socket
from datetime import datetime
def req_ok(content):
time= datetime.now()
length= len(bytearray(content))
response= "HTTP/1.1 200 OK\r\nDate: {t}\r\nContent-Length: {l}\r\n\r\n".format(t=time, l=length)
return bytearray(response)
def req_notok(content):
return byt... | Add first attempt at http server assignment. | Add first attempt at http server assignment.
| Python | mit | charlieRode/network_tools | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+import socket
+from datetime import datetime
+
+def req_ok(content):
+ time= datetime.now()
+ length= len(bytearray(content))
+ response= "HTTP/1.1 200 OK\r\nDate: {t}\r\nContent-Length: {l}\r\n\r\n".format(t=time, l=length)
+ return bytearray(response)
+
+... | |
efd5fd08833d562d90f0dc8008af368665a054b8 | worker.py | worker.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
zhihu_crawler.worker
~~~~~~~~~~~~~~~~
Use rq module to support distributed crawler task assigment,
deploy this file to a machine cluster.
"""
import os
import redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('RE... | Add rq module to support distributed cluster. | Add rq module to support distributed cluster.
| Python | mit | cpselvis/zhihu-crawler | ---
+++
@@ -0,0 +1,27 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""
+zhihu_crawler.worker
+~~~~~~~~~~~~~~~~
+
+Use rq module to support distributed crawler task assigment,
+deploy this file to a machine cluster.
+
+"""
+
+import os
+
+import redis
+from rq import Worker, Queue, Connection
+
+listen = ['high',... | |
97e4d80bbd5b0b5ad03d51b72083174402f183f6 | learning_automata.py | learning_automata.py | # Learning_automata.py is a module containing some learning automata.
# For now it only contains a Tsetlin 2N,2 automaton.
# Write a Tsetlin automaton.
# A Tsetlin automaton is defined by N memory states, R actions,
# and c penalties.
#
# N is expected to be a whole number indicating memory depth.
# R is expected to b... | Add a module to contain learning automata with an empty function for the Tsetlin automata. | Add a module to contain learning automata with an empty function for the Tsetlin automata.
| Python | mit | 0xSteve/learning_automata_simulator | ---
+++
@@ -0,0 +1,18 @@
+# Learning_automata.py is a module containing some learning automata.
+# For now it only contains a Tsetlin 2N,2 automaton.
+
+# Write a Tsetlin automaton.
+# A Tsetlin automaton is defined by N memory states, R actions,
+# and c penalties.
+#
+# N is expected to be a whole number indicating... | |
69884909800ac468b7ad7d1fc9491facec9e79b6 | zephyr/management/commands/update_permissions.py | zephyr/management/commands/update_permissions.py | from __future__ import absolute_import
from django.core.management.base import BaseCommand
from django.db.models import get_app, get_models
from django.contrib.auth.management import create_permissions
class Command(BaseCommand):
help = "Sync newly created object permissions to the database"
def handle(self,... | Add a management command to create objects for newly defined permissions | Add a management command to create objects for newly defined permissions
This script does not remove permissions that already exist.
(imported from commit 15d18266a05a84b9cac6cc7d2104668b41b48f35)
| Python | apache-2.0 | nicholasbs/zulip,shrikrishnaholla/zulip,tiansiyuan/zulip,arpith/zulip,arpitpanwar/zulip,kokoar/zulip,brainwane/zulip,bastianh/zulip,qq1012803704/zulip,aliceriot/zulip,yuvipanda/zulip,vikas-parashar/zulip,natanovia/zulip,mahim97/zulip,he15his/zulip,dwrpayne/zulip,hengqujushi/zulip,Batterfii/zulip,EasonYi/zulip,hafeez300... | ---
+++
@@ -0,0 +1,12 @@
+from __future__ import absolute_import
+
+from django.core.management.base import BaseCommand
+from django.db.models import get_app, get_models
+from django.contrib.auth.management import create_permissions
+
+class Command(BaseCommand):
+ help = "Sync newly created object permissions to ... | |
ecced598c7048739dd25bfa027939975f94d6950 | src/import_to_elastic.py | src/import_to_elastic.py | import sys
import os
def get_file_names(dir_path):
return None
def transform_data(data):
return data
def import_json(dir_path):
file_names = get_file_names(dir_path)
for file in file_names:
# TODO: Read json files and do manipulations
# Maybe have a passed in function to do this? t... | Add intial dummy skeleton structure | Add intial dummy skeleton structure
| Python | mit | PinPinIre/slack-scripts | ---
+++
@@ -0,0 +1,36 @@
+import sys
+import os
+
+
+def get_file_names(dir_path):
+ return None
+
+
+def transform_data(data):
+ return data
+
+
+def import_json(dir_path):
+ file_names = get_file_names(dir_path)
+ for file in file_names:
+ # TODO: Read json files and do manipulations
+ # M... | |
ec9ed86353070a6523c3bc6833a708422e28664e | CodeFights/phoneCall.py | CodeFights/phoneCall.py | #!/usr/local/bin/python
# Code Fights Phone Call Problem
def phoneCall(min1, min2_10, min11, s):
money_left = s
talking = 0
while money_left > 0:
if talking < 1:
if money_left - min1 < 0:
return talking
else:
money_left -= min1
... | Solve Code Fights phone call problem | Solve Code Fights phone call problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/local/bin/python
+# Code Fights Phone Call Problem
+
+
+def phoneCall(min1, min2_10, min11, s):
+ money_left = s
+ talking = 0
+ while money_left > 0:
+ if talking < 1:
+ if money_left - min1 < 0:
+ return talking
+ else:
+ ... | |
56ce986d4f203f1b8187615a42a6ac0ecf25f9f8 | tests/test_db.py | tests/test_db.py |
from socket import inet_aton
import tempfile
from whip.db import Database
from whip.json import loads as json_loads
from whip.util import ipv4_str_to_int
def test_db_loading():
snapshot_1 = [
dict(begin='1.0.0.0', end='1.255.255.255', x=1, datetime='2010'),
dict(begin='3.0.0.0', end='3.255.255.... | Add some tests for the whip.db module | Add some tests for the whip.db module
| Python | bsd-3-clause | wbolster/whip | ---
+++
@@ -0,0 +1,59 @@
+
+from socket import inet_aton
+import tempfile
+
+from whip.db import Database
+from whip.json import loads as json_loads
+from whip.util import ipv4_str_to_int
+
+
+def test_db_loading():
+
+ snapshot_1 = [
+ dict(begin='1.0.0.0', end='1.255.255.255', x=1, datetime='2010'),
+ ... | |
1755f2bc99b2e0e42496fbfc2cb439db0251608a | tsa/lib/cache.py | tsa/lib/cache.py | import os
import cPickle
import logging
logger = logging.getLogger(__name__)
def pickleable(file_pattern):
'''A function helper. Use like:
@pickle('tmp/longrunner-%(hashtag)s-%(limit)d.pyckle')
def get_tweets(hashtag='hcr', limit=1000):
... go get some tweets and return them as a plain dict or l... | Add general pickle decorator that interpolates a string with the function's **kw | Add general pickle decorator that interpolates a string with the function's **kw
| Python | mit | chbrown/tsa,chbrown/tsa,chbrown/tsa | ---
+++
@@ -0,0 +1,39 @@
+import os
+import cPickle
+
+import logging
+logger = logging.getLogger(__name__)
+
+
+def pickleable(file_pattern):
+ '''A function helper. Use like:
+
+ @pickle('tmp/longrunner-%(hashtag)s-%(limit)d.pyckle')
+ def get_tweets(hashtag='hcr', limit=1000):
+ ... go get some twe... | |
294e3251cff159e08bcb28820720c1de41534ea1 | passenger_wsgi.py | passenger_wsgi.py | import sys, os
sys.path.append(os.getcwd())
sys.path.append(os.getcwd() + '/huxley')
INTERP = os.path.join(os.getcwd(), 'env/bin/python')
if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
sys.path.insert(0, os.path.join(os.getcwd(), 'env/bin'))
sys.path.insert(0, os.path.join(os.getcwd(), 'env/lib/pyt... | Add production-specific passenger wsgi file | Add production-specific passenger wsgi file
| Python | bsd-3-clause | ctmunwebmaster/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley,ctmunwebmaster/huxley | ---
+++
@@ -0,0 +1,20 @@
+import sys, os
+sys.path.append(os.getcwd())
+sys.path.append(os.getcwd() + '/huxley')
+
+INTERP = os.path.join(os.getcwd(), 'env/bin/python')
+
+if sys.executable != INTERP: os.execl(INTERP, INTERP, *sys.argv)
+
+sys.path.insert(0, os.path.join(os.getcwd(), 'env/bin'))
+sys.path.insert(0, o... | |
8ef5a7105f23a3c3050aa0df0ec5aca5b738dc7d | directions.py | directions.py | #!/usr/bin/python
import googlemaps
#api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
class Directions(object):
"""
"""
api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
def __init__(self):
self.gmaps = googlemaps.Client(self.api_key)
pass
def getData(self, orig, dest):
... | Create new Direction class. Calculates distance and time from two addresses with Google Maps API | Create new Direction class. Calculates distance and time from two addresses with Google Maps API
| Python | mit | LibriCerule/Cerulean_Tracking,LibriCerule/Cerulean_Tracking,LibriCerule/Cerulean_Tracking,LibriCerule/Cerulean_Tracking,LibriCerule/Cerulean_Tracking | ---
+++
@@ -0,0 +1,21 @@
+#!/usr/bin/python
+import googlemaps
+#api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
+
+class Directions(object):
+ """
+
+ """
+ api_key = "AIzaSyBhOIJ_Ta2QrnO2jllAy4sd5dGCzUOA4Hw"
+ def __init__(self):
+ self.gmaps = googlemaps.Client(self.api_key)
+ pass
+
... | |
998303eff5fc4fecfa26d32a9920a6726a275ae3 | tests/test_billion.py | tests/test_billion.py | from numpy.testing import assert_raises
from fuel.datasets.billion import OneBillionWord
class TestOneBillionWord(object):
def setUp(self):
all_chars = ([chr(ord('a') + i) for i in range(26)] +
[chr(ord('0') + i) for i in range(10)] +
[',', '.', '!', '?', '<UNK>'... | Increase test coverage for OneBillonWord | Increase test coverage for OneBillonWord
| Python | mit | glewis17/fuel,bouthilx/fuel,dhruvparamhans/fuel,hantek/fuel,lamblin/fuel,udibr/fuel,bouthilx/fuel,dwf/fuel,laurent-dinh/fuel,hantek/fuel,dribnet/fuel,capybaralet/fuel,dmitriy-serdyuk/fuel,janchorowski/fuel,markusnagel/fuel,dmitriy-serdyuk/fuel,aalmah/fuel,harmdevries89/fuel,rodrigob/fuel,EderSantana/fuel,jbornschein/fu... | ---
+++
@@ -0,0 +1,25 @@
+from numpy.testing import assert_raises
+
+from fuel.datasets.billion import OneBillionWord
+
+
+class TestOneBillionWord(object):
+ def setUp(self):
+ all_chars = ([chr(ord('a') + i) for i in range(26)] +
+ [chr(ord('0') + i) for i in range(10)] +
+ ... | |
b084ca332c34103139078e2e9956b757bfed190f | tests/test_filters.py | tests/test_filters.py | import pytest
import vtki
from vtki import examples
def test_uniform_grid_filters():
"""This tests all avaialble filters"""
dataset = examples.load_uniform()
dataset.set_active_scalar('Spatial Point Data')
# Threshold
thresh = dataset.threshold([100, 500])
assert thresh is not None
# Slic... | Add simple test case to make sure the filters work | Add simple test case to make sure the filters work
| Python | mit | akaszynski/vtkInterface | ---
+++
@@ -0,0 +1,22 @@
+import pytest
+
+import vtki
+from vtki import examples
+
+
+def test_uniform_grid_filters():
+ """This tests all avaialble filters"""
+ dataset = examples.load_uniform()
+ dataset.set_active_scalar('Spatial Point Data')
+ # Threshold
+ thresh = dataset.threshold([100, 500])
+... | |
777b7d32ea71a09429caef492ace61074b84dd91 | private_storage/storage/s3boto3.py | private_storage/storage/s3boto3.py | from storages.backends.s3boto3 import S3Boto3Storage
from storages.utils import setting
class PrivateS3BotoStorage(S3Boto3Storage):
"""
Private storage bucket for S3
"""
# Since this class inherits the default storage, it shares many parameters with the base class.
# Thus, redefine the setting nam... | Add new S3 storage class, PrivateS3BotoStorage and PrivateEncryptedS3BotoStorage | Add new S3 storage class, PrivateS3BotoStorage and PrivateEncryptedS3BotoStorage
This class can now be selected with the new `PRIVATE_STORAGE_CLASS` setting.
| Python | apache-2.0 | edoburu/django-private-storage | ---
+++
@@ -0,0 +1,44 @@
+from storages.backends.s3boto3 import S3Boto3Storage
+from storages.utils import setting
+
+
+class PrivateS3BotoStorage(S3Boto3Storage):
+ """
+ Private storage bucket for S3
+ """
+ # Since this class inherits the default storage, it shares many parameters with the base class.
... | |
b736ae17f17aa4034f1722a6a3c449aed07fd8cd | hanzifreqs.py | hanzifreqs.py | import sys
from hanzidefs import get_all_hanzi
if __name__ == "__main__":
chars = get_all_hanzi(sys.stdin.read())
for ch, ct in chars:
print("%s\t%s" % (ch, ct))
| Add separate script to print out frequencies only | Add separate script to print out frequencies only
| Python | agpl-3.0 | erjiang/hanzidefs | ---
+++
@@ -0,0 +1,10 @@
+import sys
+
+from hanzidefs import get_all_hanzi
+
+if __name__ == "__main__":
+
+ chars = get_all_hanzi(sys.stdin.read())
+
+ for ch, ct in chars:
+ print("%s\t%s" % (ch, ct)) | |
f962333ab52c0041f4873ff27da4185a51df7795 | demo/apps/catalogue/migrations/0011_remove_category_name.py | demo/apps/catalogue/migrations/0011_remove_category_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('catalogue', '0010_auto_20160616_1048'),
]
operations = [
migrations.RemoveField(
model_name='category',
... | Add remove cat name migration | Add remove cat name migration
| Python | mit | pgovers/oscar-wagtail-demo,pgovers/oscar-wagtail-demo | ---
+++
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('catalogue', '0010_auto_20160616_1048'),
+ ]
+
+ operations = [
+ migrations.RemoveField(
+ ... | |
5cb11884e953a734afab55a4548753fe99a16d5b | {{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py | {{cookiecutter.repo_name}}/tests/test_{{cookiecutter.repo_name}}.py | # -*- coding: utf-8 -*-
import pytest
@pytest.fixture
def basic_app():
"""Fixture for a default app.
Returns:
:class:`{{cookiecutter.app_class_name}}`: App instance
"""
from {{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}}
return {{cookiecutter.app_class_name}}()
def tes... | Create simple test module for the app title | Create simple test module for the app title
| Python | mit | hackebrot/cookiedozer,hackebrot/cookiedozer | ---
+++
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+
+import pytest
+
+
+@pytest.fixture
+def basic_app():
+ """Fixture for a default app.
+
+ Returns:
+ :class:`{{cookiecutter.app_class_name}}`: App instance
+ """
+ from {{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}}
+ return {{... | |
c245bd90dd8f1fd90da45e737ff3cbfba43707fa | run_tests.py | run_tests.py | #!/usr/bin/env python
#
# Copyright 2012 Ezox Systems LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Add simple unit test runner to setup environment. | Add simple unit test runner to setup environment.
The test runner performs setup like configuring paths and setting up App
Engine stubs needed to run tests.
| Python | apache-2.0 | andreleblanc-wf/furious,beaulyddon-wf/furious,rosshendrickson-wf/furious,mattsanders-wf/furious,Workiva/furious,beaulyddon-wf/furious,rosshendrickson-wf/furious,mattsanders-wf/furious,Workiva/furious,andreleblanc-wf/furious,robertkluin/furious | ---
+++
@@ -0,0 +1,117 @@
+#!/usr/bin/env python
+#
+# Copyright 2012 Ezox Systems LLC
+#
+# 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... | |
aa36823abcd2371519ab2e6c195c6ffb2f7af27a | abstract_soup.py | abstract_soup.py | # import sys
from bs4 import BeautifulSoup
fn = "/Users/ajh/Code/openssr-parser/sample-data/wb-abstract-2770053.html"
soup = BeautifulSoup(
open(fn),
"html.parser")
print("Ready. Beautiful Soup object available as soup.")
| Add interactive script for parsing abstracts | Add interactive script for parsing abstracts
Run with `python3 -i abstract_soup.py`
| Python | agpl-3.0 | OpenSSR/openssr-parser,OpenSSR/openssr-parser | ---
+++
@@ -0,0 +1,9 @@
+# import sys
+from bs4 import BeautifulSoup
+
+fn = "/Users/ajh/Code/openssr-parser/sample-data/wb-abstract-2770053.html"
+soup = BeautifulSoup(
+ open(fn),
+ "html.parser")
+
+print("Ready. Beautiful Soup object available as soup.") | |
6eeaaedb0a15dbecac93e649b456a7adfdbbc919 | tests/thrift/test_multiple_services.py | tests/thrift/test_multiple_services.py | # Copyright (c) 2015 Uber Technologies, Inc.
#
# 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 restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | Verify Thrift service name used for inherited methods | Test: Verify Thrift service name used for inherited methods
| Python | mit | uber/tchannel-python,uber/tchannel-python | ---
+++
@@ -0,0 +1,59 @@
+# Copyright (c) 2015 Uber Technologies, Inc.
+#
+# 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 restriction, including without limitation the rights
+# ... | |
db1b12b26ee6136198cdc51ca12c7ab17977bc05 | rajab_roza/__init__.py | rajab_roza/__init__.py | from datetime import timedelta
import yaml
from hijri_date import HijriDate
from usno_data import USNO_Data
class RajabRoza:
def __init__(self, lat, lng, start_year, end_year):
self.lat = lat
self.lng = lng
self.start_year = start_year
self.end_year = end_year
self.usno_dat... | Add class to accumulate and load/save roza durations. | Add class to accumulate and load/save roza durations.
| Python | mit | mygulamali/rajab_roza | ---
+++
@@ -0,0 +1,69 @@
+from datetime import timedelta
+import yaml
+
+from hijri_date import HijriDate
+from usno_data import USNO_Data
+
+class RajabRoza:
+ def __init__(self, lat, lng, start_year, end_year):
+ self.lat = lat
+ self.lng = lng
+ self.start_year = start_year
+ self.en... | |
e94f83ea8f409b83f27fc4682c81706f3003bbba | bin/merge_apis.py | bin/merge_apis.py | #!/usr/bin/env python
import sys
import json
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger()
data = sys.argv[1:]
merged_data = {'data': []}
for path, tag in zip(data[0::2], data[1::2]):
with open(path, 'r') as handle:
ldata = json.load(handle)
for element in ldata[... | Add script to merge json files | Add script to merge json files
| Python | mit | gregvonkuster/cargo-port,gregvonkuster/cargo-port,erasche/community-package-cache,erasche/community-package-cache,erasche/community-package-cache,galaxyproject/cargo-port,gregvonkuster/cargo-port,galaxyproject/cargo-port | ---
+++
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+import sys
+import json
+import logging
+logging.basicConfig(level=logging.INFO)
+log = logging.getLogger()
+
+data = sys.argv[1:]
+merged_data = {'data': []}
+
+for path, tag in zip(data[0::2], data[1::2]):
+ with open(path, 'r') as handle:
+ ldata = json.lo... | |
c5c4f619fcc6052782e7f68968656ef3de8b5489 | shoop/core/migrations/0007_product_media.py | shoop/core/migrations/0007_product_media.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('shoop', '0006_shop_add_logo_and_public_name'),
]
operations = [
migrations.AlterField(
model_name='productmedia'... | Add missing migration for product media external_url | Core: Add missing migration for product media external_url
| Python | agpl-3.0 | suutari/shoop,hrayr-artunyan/shuup,jorge-marques/shoop,suutari/shoop,hrayr-artunyan/shuup,suutari-ai/shoop,taedori81/shoop,shoopio/shoop,shawnadelic/shuup,shoopio/shoop,suutari-ai/shoop,shawnadelic/shuup,suutari-ai/shoop,taedori81/shoop,jorge-marques/shoop,jorge-marques/shoop,suutari/shoop,akx/shoop,akx/shoop,taedori81... | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('shoop', '0006_shop_add_logo_and_public_name'),
+ ]
+
+ operations = [
+ migrations.AlterFie... | |
95ca8cdbd46dba984774cf5eb484642f2c007de3 | src/p2.py | src/p2.py | from itertools import takewhile
def fib(n):
if n == 0:
return 1
elif n == 1:
return 2
else:
return fib(n-2) + fib(n-1)
def fib_iter():
n = 0
while True:
yield fib(n)
n += 1
def calc():
values = takewhile(lambda x: x <= 4000000, fib_iter())
return su... | Add solution to second problem | Add solution to second problem
| Python | mit | gsnedders/projecteuler | ---
+++
@@ -0,0 +1,22 @@
+from itertools import takewhile
+
+def fib(n):
+ if n == 0:
+ return 1
+ elif n == 1:
+ return 2
+ else:
+ return fib(n-2) + fib(n-1)
+
+def fib_iter():
+ n = 0
+ while True:
+ yield fib(n)
+ n += 1
+
+def calc():
+ values = takewhile(lamb... | |
0b5d508f0c8c04443de7858b1c3af2f05ad8a6f0 | traittypes/tests/test_validators.py | traittypes/tests/test_validators.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import pytest
from traitlets import HasTraits, TraitError
from ..traittypes import SciType
def test_coercion_validator():
# Test with a squeeze coercion
def truncate(t... | Add tests for SciType validators | Add tests for SciType validators
| Python | bsd-3-clause | jupyter-incubator/traittypes,SylvainCorlay/traittypes | ---
+++
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+# coding: utf-8
+
+# Copyright (c) Jupyter Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import pytest
+
+from traitlets import HasTraits, TraitError
+
+from ..traittypes import SciType
+
+
+def test_coercion_validator():
+ # Test ... | |
ace3ea15bc99cb384a59cc27d38a98d7aa7a2948 | tests/pytests/unit/auth/test_rest.py | tests/pytests/unit/auth/test_rest.py | import pytest
import salt.auth.rest as rest
from tests.support.mock import MagicMock, patch
@pytest.fixture
def configure_loader_modules():
"""
Rest module configuration
"""
return {
rest: {
"__opts__": {
"external_auth": {
"rest": {"^url": "http... | Add tests for REST eauth | Add tests for REST eauth
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,99 @@
+import pytest
+import salt.auth.rest as rest
+from tests.support.mock import MagicMock, patch
+
+
+@pytest.fixture
+def configure_loader_modules():
+ """
+ Rest module configuration
+ """
+ return {
+ rest: {
+ "__opts__": {
+ "external_auth": {
+... | |
2c17cb829516d0a3856d870b12f25271efb296ce | examples/kde_joyplot.py | examples/kde_joyplot.py | """
Overlapping KDEs ('Joy Division plot')
======================================
"""
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
# Create the data
rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.ti... | Add an example script to make a Joy Division plot | Add an example script to make a Joy Division plot
| Python | bsd-3-clause | phobson/seaborn,lukauskas/seaborn,anntzer/seaborn,arokem/seaborn,phobson/seaborn,anntzer/seaborn,arokem/seaborn,mwaskom/seaborn,lukauskas/seaborn,petebachant/seaborn,mwaskom/seaborn,sauliusl/seaborn | ---
+++
@@ -0,0 +1,43 @@
+"""
+Overlapping KDEs ('Joy Division plot')
+======================================
+
+
+"""
+import numpy as np
+import pandas as pd
+import seaborn as sns
+import matplotlib.pyplot as plt
+sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})
+
+# Create the data
+rs = np.random.Rand... | |
cdfc702741a0209fe55c8aff5ac6c61ed81cb332 | scripts/patches/fsx.py | scripts/patches/fsx.py | patches = [
# Rename AWS::FSx::Volume.OntapConfiguration to AWS::FSx::Volume.VolumeOntapConfiguration - duplicate property name
{
"op": "move",
"from": "/PropertyTypes/AWS::FSx::Volume.OntapConfiguration",
"path": "/PropertyTypes/AWS::FSx::Volume.VolumeOntapConfiguration",
},
{
... | Fix duplicate resource names due to FSx::Volume | Fix duplicate resource names due to FSx::Volume
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -0,0 +1,24 @@
+patches = [
+ # Rename AWS::FSx::Volume.OntapConfiguration to AWS::FSx::Volume.VolumeOntapConfiguration - duplicate property name
+ {
+ "op": "move",
+ "from": "/PropertyTypes/AWS::FSx::Volume.OntapConfiguration",
+ "path": "/PropertyTypes/AWS::FSx::Volume.VolumeOn... | |
7893e7c268a8ae144b47cf6d2d9eed44696b17a2 | tests/test_widgets_simple.py | tests/test_widgets_simple.py | from controlcenter.widgets.contrib import simple
from . import TestCase
FAKE_VALUE_LIST = ['Label 1', 'Label 2']
FAKE_KEY_VALUE_LIST = {'Key 1': 'Value 1', 'Key 2': 'Value 2'}
class SimpleWidgetTest(TestCase):
def setUp(self):
self.widget = simple.SimpleWidget(request=None)
def test_get_data_rais... | Add tests for simple data widgets | Add tests for simple data widgets
| Python | bsd-3-clause | byashimov/django-controlcenter,byashimov/django-controlcenter,byashimov/django-controlcenter | ---
+++
@@ -0,0 +1,61 @@
+from controlcenter.widgets.contrib import simple
+
+from . import TestCase
+
+
+FAKE_VALUE_LIST = ['Label 1', 'Label 2']
+FAKE_KEY_VALUE_LIST = {'Key 1': 'Value 1', 'Key 2': 'Value 2'}
+
+
+class SimpleWidgetTest(TestCase):
+
+ def setUp(self):
+ self.widget = simple.SimpleWidget(r... | |
5b94733fb2983a923e31ec00fe05ec8614bd56f4 | tests/buildurl_test.py | tests/buildurl_test.py | from ass2m.storage import Storage
from ass2m.server import Server
from ass2m.template import build_url, build_root_url
from ass2m.filters import quote_url
from unittest import TestCase
from webtest import TestApp
from tempfile import mkdtemp
import shutil
class BuildURLTest(TestCase):
def setUp(self):
s... | Add tests for URL building | Add tests for URL building
| Python | agpl-3.0 | laurentb/assnet,laurentb/assnet | ---
+++
@@ -0,0 +1,35 @@
+from ass2m.storage import Storage
+from ass2m.server import Server
+from ass2m.template import build_url, build_root_url
+from ass2m.filters import quote_url
+
+from unittest import TestCase
+from webtest import TestApp
+
+from tempfile import mkdtemp
+import shutil
+
+
+class BuildURLTest(T... | |
e81f0407a5514a0216b731077d8def7e30d708b0 | ovp_users/migrations/0016_auto_20170216_1930.py | ovp_users/migrations/0016_auto_20170216_1930.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-16 19:30
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('ovp_users', '0015_userprof... | Set UserProfile.user to OneToOne instead o ForeignKey | Set UserProfile.user to OneToOne instead o ForeignKey
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users | ---
+++
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.5 on 2017-02-16 19:30
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies =... | |
299ab440ff8b783d66d67d02c3510eccac4ccbf9 | server/cli.py | server/cli.py | # coding=UTF-8
#
# thickishstring server
# Copyright © 2013 David Given
#
# This software is redistributable under the terms of the Simplified BSD
# open source license. Please see the COPYING file in the distribution for
# the full text.
from ws4py.client.threadedclient import WebSocketClient
import anyjson as json
... | Add very very basic CLI test app. | Add very very basic CLI test app. | Python | bsd-2-clause | davidgiven/gruntle,davidgiven/gruntle | ---
+++
@@ -0,0 +1,33 @@
+# coding=UTF-8
+#
+# thickishstring server
+# Copyright © 2013 David Given
+#
+# This software is redistributable under the terms of the Simplified BSD
+# open source license. Please see the COPYING file in the distribution for
+# the full text.
+
+from ws4py.client.threadedclient import Web... | |
416a12561ffb65705d80a62de22ddeac3c46d8ec | devicecloud/test/test_conditions.py | devicecloud/test/test_conditions.py | import unittest
import datetime
from devicecloud.conditions import Attribute
class TestConditions(unittest.TestCase):
def test_gt(self):
a = Attribute("a")
self.assertEqual((a > 21).compile(), "a>'21'")
def test_lt(self):
a = Attribute("a")
self.assertEqual((a < 25).compile()... | Add test coverage for conditions logic | PYTHONDC-6: Add test coverage for conditions logic
| Python | mpl-2.0 | michaelcho/python-devicecloud,ctrlaltdel/python-devicecloud,ctrlaltdel/python-devicecloud,michaelcho/python-devicecloud,brucetsao/python-devicecloud,brucetsao/python-devicecloud,digidotcom/python-devicecloud,digidotcom/python-devicecloud | ---
+++
@@ -0,0 +1,47 @@
+import unittest
+import datetime
+from devicecloud.conditions import Attribute
+
+
+class TestConditions(unittest.TestCase):
+
+ def test_gt(self):
+ a = Attribute("a")
+ self.assertEqual((a > 21).compile(), "a>'21'")
+
+ def test_lt(self):
+ a = Attribute("a")
+ ... | |
ce799933ef7a15bfb70f9ab681f7ba47270cbed8 | docs/src/examples/over_available.py | docs/src/examples/over_available.py | from scikits.audiolab import available_file_formats, available_encodings
for format in available_file_formats():
print "File format %s is supported; available encodings are:" % format
for enc in available_encodings(format):
print "\t%s" % enc
print ""
| Add example of usage for available_* funcs. | Add example of usage for available_* funcs.
| Python | lgpl-2.1 | cournape/audiolab,cournape/audiolab,cournape/audiolab | ---
+++
@@ -0,0 +1,7 @@
+from scikits.audiolab import available_file_formats, available_encodings
+
+for format in available_file_formats():
+ print "File format %s is supported; available encodings are:" % format
+ for enc in available_encodings(format):
+ print "\t%s" % enc
+ print "" | |
0e0105d6e5a5583432d39d019569483bf28dc860 | imageio/plugins/feisem.py | imageio/plugins/feisem.py | # -*- coding: utf-8 -*-
# Copyright (c) 2016, imageio contributors
# imageio is distributed under the terms of the (new) BSD License.
from __future__ import absolute_import, unicode_literals
from .tifffile import TiffFormat
class FEISEMFormat(TiffFormat):
"""Provide read support for TIFFs produced by an FEI SEM... | Add FEI-SEM plugin based on TIFF | Add FEI-SEM plugin based on TIFF
| Python | bsd-2-clause | imageio/imageio | ---
+++
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2016, imageio contributors
+# imageio is distributed under the terms of the (new) BSD License.
+
+from __future__ import absolute_import, unicode_literals
+
+from .tifffile import TiffFormat
+
+
+class FEISEMFormat(TiffFormat):
+ """Provide read su... | |
69c449b0bd90f59e578e35ab9475b54ce6c8f0ce | backend/breach/tests/test_sniffer.py | backend/breach/tests/test_sniffer.py | from mock import patch
from django.test import TestCase
from breach.sniffer import Sniffer
class SnifferTest(TestCase):
def setUp(self):
self.endpoint = 'http://localhost'
self.sniffer = Sniffer(self.endpoint)
self.source_ip = '147.102.239.229'
self.destination_host = 'dionyziz.c... | Add basic sniffer client test | Add basic sniffer client test
| Python | mit | dionyziz/rupture,dionyziz/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,esarafianou/rupture,dimriou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimkarakostas/rupture,e... | ---
+++
@@ -0,0 +1,28 @@
+from mock import patch
+
+from django.test import TestCase
+from breach.sniffer import Sniffer
+
+
+class SnifferTest(TestCase):
+ def setUp(self):
+ self.endpoint = 'http://localhost'
+ self.sniffer = Sniffer(self.endpoint)
+
+ self.source_ip = '147.102.239.229'
+ ... | |
be75470198065f6d66f179e52d96908f11275222 | tests/rules_tests/grammarManipulation_tests/__init__.py | tests/rules_tests/grammarManipulation_tests/__init__.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
""" | Add directory for tests responsible rule - grammar manipulations | Add directory for tests responsible rule - grammar manipulations
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,8 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 23.06.2017 16:39
+:Licence GNUv3
+Part of grammpy
+
+""" | |
fba553b19585c26ba6eed73c71519b882a57add5 | test_hash.py | test_hash.py | from hash import HashTable
import io
words = []
with io.open('/usr/share/dict/words', 'r') as word_file:
words = word_file.readlines()
def test_hash():
t = HashTable()
t.set('coffee', 'coffee')
assert t.get('coffee') == 'coffee'
def test_duplicate_hash_val():
t = HashTable()
t.set('bob', ... | Add tests for hash table | Add tests for hash table
| Python | mit | nbeck90/data_structures_2 | ---
+++
@@ -0,0 +1,31 @@
+from hash import HashTable
+import io
+
+
+words = []
+
+with io.open('/usr/share/dict/words', 'r') as word_file:
+ words = word_file.readlines()
+
+
+def test_hash():
+ t = HashTable()
+ t.set('coffee', 'coffee')
+ assert t.get('coffee') == 'coffee'
+
+
+def test_duplicate_hash_... | |
678dd502ef3d8c044c2915ed6a55bb10857f653a | zephyr/management/commands/profile_request.py | zephyr/management/commands/profile_request.py | from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from confirmation.models import Confirmation
from zephyr.models import get_user_profile_by_email, UserMessage
from zephyr.views import get_old_messages_backend
import cProfile
import time
import ... | Add command-line tool to profile get_old_messages requests. | Add command-line tool to profile get_old_messages requests.
(imported from commit bd7fc27b0c6fc1ae4f82bb74763736f9163b90bf)
| Python | apache-2.0 | LeeRisk/zulip,mansilladev/zulip,guiquanz/zulip,swinghu/zulip,stamhe/zulip,adnanh/zulip,mahim97/zulip,tbutter/zulip,johnny9/zulip,isht3/zulip,so0k/zulip,dxq-git/zulip,mdavid/zulip,samatdav/zulip,guiquanz/zulip,wangdeshui/zulip,Batterfii/zulip,dhcrzf/zulip,mohsenSy/zulip,dattatreya303/zulip,zulip/zulip,bowlofstew/zulip,c... | ---
+++
@@ -0,0 +1,52 @@
+from __future__ import absolute_import
+
+from optparse import make_option
+from django.core.management.base import BaseCommand
+from confirmation.models import Confirmation
+from zephyr.models import get_user_profile_by_email, UserMessage
+from zephyr.views import get_old_messages_backend
+... | |
bba6f8aad17719ff909281a62f6d449ebb08d859 | tests/cmp_mkpy.py | tests/cmp_mkpy.py | #!/usr/bin/env python
"""Determine which tests are in the directory which should be added to the makefile."""
import os
import sys
import re
import glob
def main():
"""Compare the tests in this directory to the tests in the makefile."""
tests_cwd = set(glob.glob('*.py'))
tests_mk = _get_makefile_tests()
... | Determine if tests are in test dir, but not in test/makefile | Determine if tests are in test dir, but not in test/makefile
| Python | bsd-2-clause | lileiting/goatools,tanghaibao/goatools,tanghaibao/goatools,lileiting/goatools | ---
+++
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+"""Determine which tests are in the directory which should be added to the makefile."""
+
+import os
+import sys
+import re
+import glob
+
+def main():
+ """Compare the tests in this directory to the tests in the makefile."""
+ tests_cwd = set(glob.glob('*.py'))
... | |
039001c71ce5b4eb4eb7796e5ee56e0ee459687b | tests/conftest.py | tests/conftest.py | def pytest_configure():
from django.conf import settings
settings.configure(
DEBUG_PROPAGATE_EXCEPTIONS=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
},
SITE_ID=1,
SECRE... | Add conf test for django settings | Add conf test for django settings
| Python | mit | NorakGithub/django-excel-tools | ---
+++
@@ -0,0 +1,48 @@
+def pytest_configure():
+ from django.conf import settings
+
+ settings.configure(
+ DEBUG_PROPAGATE_EXCEPTIONS=True,
+ DATABASES={
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': ':memory:'
+ }
+ ... | |
a3d35b7e654a3cfd84a442396b470d19212d9b26 | src/proposals/management/commands/loadproposals.py | src/proposals/management/commands/loadproposals.py | import json
from django.apps import apps
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
User = get_user_model()
class Command(BaseCommand):
help = 'Load talk proposals from data dumped by `manage.py dumpdata`.'
def add_arguments(self, parser):
p... | Add command to load proposals from dumped data | Add command to load proposals from dumped data
| Python | mit | pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 | ---
+++
@@ -0,0 +1,31 @@
+import json
+
+from django.apps import apps
+from django.contrib.auth import get_user_model
+from django.core.management.base import BaseCommand
+
+
+User = get_user_model()
+
+
+class Command(BaseCommand):
+
+ help = 'Load talk proposals from data dumped by `manage.py dumpdata`.'
+
+ ... | |
ce5fbcfdac8e8ba5bf85f48ed9a87553a621b34a | scripts/remove_duplicate_preprint_logs.py | scripts/remove_duplicate_preprint_logs.py | import sys
import logging
from modularodm import Q
from framework.transactions.context import TokuTransaction
from scripts import utils as script_utils
from website.app import init_app
from website.project.model import Node, NodeLog
logger = logging.getLogger(__name__)
# This is where all your migration log will ... | Add script to remove duplicate preprint logs. | Add script to remove duplicate preprint logs.
| Python | apache-2.0 | mluo613/osf.io,mfraezz/osf.io,Nesiehr/osf.io,pattisdr/osf.io,mattclark/osf.io,felliott/osf.io,cwisecarver/osf.io,HalcyonChimera/osf.io,icereval/osf.io,baylee-d/osf.io,mfraezz/osf.io,caseyrollins/osf.io,cslzchen/osf.io,mfraezz/osf.io,TomBaxter/osf.io,acshi/osf.io,laurenrevere/osf.io,mattclark/osf.io,Nesiehr/osf.io,patti... | ---
+++
@@ -0,0 +1,73 @@
+import sys
+import logging
+
+from modularodm import Q
+
+from framework.transactions.context import TokuTransaction
+from scripts import utils as script_utils
+from website.app import init_app
+from website.project.model import Node, NodeLog
+
+
+logger = logging.getLogger(__name__)
+
+
+# ... | |
ff459ece8deb05e141cc1055421f88721b16f7d1 | securedrop/tests/test_unit_crypto_util.py | securedrop/tests/test_unit_crypto_util.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import unittest
# Set environment variable so config.py uses a test environment
os.environ['SECUREDROP_ENV'] = 'test'
import config
import common
import crypto_util
class TestCryptoUtil(unittest.TestCase):
"""The set of tests for crypto_util.py."""
def... | Add coverage of clean function in crypto_util | Add coverage of clean function in crypto_util
| Python | agpl-3.0 | conorsch/securedrop,heartsucker/securedrop,conorsch/securedrop,micahflee/securedrop,ehartsuyker/securedrop,micahflee/securedrop,ehartsuyker/securedrop,heartsucker/securedrop,garrettr/securedrop,micahflee/securedrop,ageis/securedrop,heartsucker/securedrop,garrettr/securedrop,ageis/securedrop,garrettr/securedrop,conorsch... | ---
+++
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import os
+import unittest
+# Set environment variable so config.py uses a test environment
+os.environ['SECUREDROP_ENV'] = 'test'
+import config
+import common
+import crypto_util
+
+
+class TestCryptoUtil(unittest.TestCase):
+
+ """The set... | |
3ac4d3aeee4308d7db09151e340ec02ab4da1403 | challenge1.py | challenge1.py | #!/usr/bin/python
file = open("story.txt", "r+")
words = 0
unique = 0
paragraphs = 0
sentences = 0
for word in file.read().split():
words += 1
print words
| Add challenge word count fragment | Add challenge word count fragment
| Python | mit | Stahpware/rlp_weekly_challenge_1 | ---
+++
@@ -0,0 +1,12 @@
+#!/usr/bin/python
+
+file = open("story.txt", "r+")
+
+words = 0
+unique = 0
+paragraphs = 0
+sentences = 0
+
+for word in file.read().split():
+ words += 1
+ print words | |
e87864550eb6d4cee1dc2149e89274d7c6c63a29 | aids/strings/is_anagram.py | aids/strings/is_anagram.py | '''
In this module, we determine if two given strings are anagrams
'''
def is_anagram_sort(string_1, string_2):
'''
Return True if the two given strings are anagrams using sorting
'''
return sorted(string_1) == sorted(string_2)
def is_anagram_counter(string_1, string_2):
'''
Return True if the two given strin... | Add function to determine if two strings are anagrams | Add function to determine if two strings are anagrams
| Python | mit | ueg1990/aids | ---
+++
@@ -0,0 +1,40 @@
+'''
+In this module, we determine if two given strings are anagrams
+
+'''
+
+def is_anagram_sort(string_1, string_2):
+ '''
+ Return True if the two given strings are anagrams using sorting
+
+ '''
+ return sorted(string_1) == sorted(string_2)
+
+def is_anagram_counter(string_1, string_2):
... | |
cd24a6de4d7b17105370bf142b5237f9ab90aa09 | candidates/management/commands/candidates_find_max_person_id.py | candidates/management/commands/candidates_find_max_person_id.py | from candidates.popit import PopItApiMixin, popit_unwrap_pagination
from django.core.management.base import BaseCommand
class Command(PopItApiMixin, BaseCommand):
def handle(self, **options):
max_person_id = -1
for person in popit_unwrap_pagination(
self.api.persons,
... | Add a helper command to find the maximum person ID | Add a helper command to find the maximum person ID
This is useful if by deleting and reimporting data directly in MongoDB
the maximum person ID in the YNMP database gets out of sync: this
command returns the maximum ID, and it's then your reponsibility what to
do about that. (i.e. It doesn't update it in the database ... | Python | agpl-3.0 | DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/your... | ---
+++
@@ -0,0 +1,15 @@
+from candidates.popit import PopItApiMixin, popit_unwrap_pagination
+
+from django.core.management.base import BaseCommand
+
+class Command(PopItApiMixin, BaseCommand):
+
+ def handle(self, **options):
+ max_person_id = -1
+ for person in popit_unwrap_pagination(
+ ... | |
124b0ae0b1eb1e7e1e4e4dec9b5af8870c0de270 | oedb_datamodels/versions/46fb02acc3b1_add_meta_tables.py | oedb_datamodels/versions/46fb02acc3b1_add_meta_tables.py | """Add meta tables
Revision ID: 46fb02acc3b1
Revises:
Create Date: 2017-11-23 11:08:50.199160
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '46fb02acc3b1'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
... | Add meta tables to alembic migrations | Add meta tables to alembic migrations
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | ---
+++
@@ -0,0 +1,49 @@
+"""Add meta tables
+
+Revision ID: 46fb02acc3b1
+Revises:
+Create Date: 2017-11-23 11:08:50.199160
+
+"""
+from alembic import op
+import sqlalchemy as sa
+
+
+# revision identifiers, used by Alembic.
+revision = '46fb02acc3b1'
+down_revision = None
+branch_labels = None
+depends_on = None
... | |
1b90326eac82dc73195363d4c57c3095ab3e90bc | dynamic_dynamodb/tests/test_dynamodb.py | dynamic_dynamodb/tests/test_dynamodb.py | # -*- coding: utf-8 -*-
""" Test dynamodb utils """
import unittest
from moto import mock_dynamodb2
from boto.dynamodb2.fields import HashKey
from boto.dynamodb2.table import Table
from dynamic_dynamodb.aws import dynamodb
class TestDynamodb(unittest.TestCase):
@mock_dynamodb2
def setUp(self):
supe... | Add basic test to check moto is working as expected | Add basic test to check moto is working as expected
| Python | apache-2.0 | tellybug/dynamic-dynamodb | ---
+++
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+""" Test dynamodb utils """
+import unittest
+
+from moto import mock_dynamodb2
+
+from boto.dynamodb2.fields import HashKey
+from boto.dynamodb2.table import Table
+
+from dynamic_dynamodb.aws import dynamodb
+
+class TestDynamodb(unittest.TestCase):
+
+ @mock_dy... | |
ed96c1c5d0e80f86e18c5fd555bad4cfafbd8e5e | kolibri/core/content/migrations/0020_le_utils_0_20_upgrade_migration.py | kolibri/core/content/migrations/0020_le_utils_0_20_upgrade_migration.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.23 on 2019-08-22 17:32
from __future__ import unicode_literals
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [("content", "0019_contentnode_slideshow_options")]
operations = [
mi... | Add content migrations for latest le_utils update. | Add content migrations for latest le_utils update.
| Python | mit | mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,learningequality/kolibri | ---
+++
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.23 on 2019-08-22 17:32
+from __future__ import unicode_literals
+
+from django.db import migrations
+from django.db import models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("content", "0019_contentnode_slideshow_opt... | |
dd01830cf9be3672d4223cdb37ed8bb410730b62 | devil/devil/android/tools/adb_run_shell_cmd.py | devil/devil/android/tools/adb_run_shell_cmd.py | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import json
import logging
import sys
from devil.android import device_blacklist
from devil.android import device_erro... | Add util for running adb shell commands on device. | [Android] Add util for running adb shell commands on device.
BUG=543257
Review URL: https://codereview.chromium.org/1498113002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#365301}
| Python | bsd-3-clause | sahiljain/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,sahiljain/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult-csm,sahiljain/catapult,SummerLW/Perf-Insight-Report,catapult-project/catap... | ---
+++
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+# Copyright 2015 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+import argparse
+import json
+import logging
+import sys
+
+from devil.android import device_blacklist... | |
308d5dec656a17c2dba97be0ad641fe8d390636d | thinc/neural/tests/unit/Params/test_params.py | thinc/neural/tests/unit/Params/test_params.py | import pytest
from ....params import Params
from ....ops import NumpyOps
@pytest.fixture
def ops():
return NumpyOps()
@pytest.mark.parametrize('size', [0, 10, 1000, 7, 12])
def test_init_allocates_mem(ops, size):
params = Params(ops, size)
assert params._mem.size == size
assert params._i == 0
@pytes... | Add unit tests for Params class | Add unit tests for Params class
| Python | mit | explosion/thinc,spacy-io/thinc,explosion/thinc,explosion/thinc,spacy-io/thinc,spacy-io/thinc,explosion/thinc | ---
+++
@@ -0,0 +1,74 @@
+import pytest
+
+from ....params import Params
+from ....ops import NumpyOps
+
+@pytest.fixture
+def ops():
+ return NumpyOps()
+
+@pytest.mark.parametrize('size', [0, 10, 1000, 7, 12])
+def test_init_allocates_mem(ops, size):
+ params = Params(ops, size)
+ assert params._mem.size =... | |
77d4dcd43fbc8caf3d9b727fea75b35339ed936e | utilities/src/d1_util/strip_xml_whitespace.py | utilities/src/d1_util/strip_xml_whitespace.py | #!/usr/bin/env python
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (t... | Add utility/example that strips problematic whitespace from XML doc | Add utility/example that strips problematic whitespace from XML doc
| Python | apache-2.0 | DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python | ---
+++
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+
+# This work was created by participants in the DataONE project, and is
+# jointly copyrighted by participating institutions in DataONE. For
+# more information on DataONE, see our web site at http://dataone.org.
+#
+# Copyright 2009-2019 DataONE
+#
+# Licensed unde... | |
74a4023c3d9e02d13456fca285e8f64eb8358434 | elasticsearch_flex/analysis_utils.py | elasticsearch_flex/analysis_utils.py | import logging
from elasticsearch_dsl.analysis import CustomAnalyzer
logger = logging.getLogger(__name__)
class AnalysisDefinition(object):
'''
This defines a helper class for registering search analyzers.
Analyzers can be defined as callables, hence ensuring io/cpu bound analysis
configuration can ... | Add AnalysisDefinition helper for configuring analyzers | Add AnalysisDefinition helper for configuring analyzers
| Python | mit | prashnts/dj-elasticsearch-flex,prashnts/dj-elasticsearch-flex | ---
+++
@@ -0,0 +1,40 @@
+import logging
+
+from elasticsearch_dsl.analysis import CustomAnalyzer
+
+logger = logging.getLogger(__name__)
+
+
+class AnalysisDefinition(object):
+ '''
+ This defines a helper class for registering search analyzers.
+ Analyzers can be defined as callables, hence ensuring io/cpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.