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 |
|---|---|---|---|---|---|---|---|---|---|---|
d4274b32f283a056bec7048f1ab8b78bf1518bb6 | var/spack/repos/builtin/packages/bwa/package.py | var/spack/repos/builtin/packages/bwa/package.py | ##############################################################################
# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | Make flake8 happy (long lines) | Make flake8 happy (long lines)
| Python | lgpl-2.1 | matthiasdiener/spack,matthiasdiener/spack,TheTimmy/spack,skosukhin/spack,EmreAtes/spack,matthiasdiener/spack,mfherbst/spack,tmerrick1/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,lgarren/spack,lgarren/spack,skosukhin/spack,EmreAtes/spack,iulian787/spack,lgarren/spack,krafczyk/spack,TheTimmy/spack,iuli... | ---
+++
@@ -0,0 +1,52 @@
+##############################################################################
+# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.
+# Produced at the Lawrence Livermore National Laboratory.
+#
+# This file is part of Spack.
+# Created by Todd Gamblin, tgamblin@llnl.gov, Al... | |
a0cff25bdc493925ae750d6daa0bad0150677f2e | rdmo/projects/migrations/0032_data_migration.py | rdmo/projects/migrations/0032_data_migration.py | from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
def run_data_migration(apps, schema_editor):
Project = apps.get_model('projects', 'Project')
Task = apps.get_model('tasks', 'Task')
View = apps.get_model('views', 'View')
for project in ... | Add migration to add tasks and views to existing projects | Add migration to add tasks and views to existing projects
| Python | apache-2.0 | DMPwerkzeug/DMPwerkzeug,rdmorganiser/rdmo,rdmorganiser/rdmo,DMPwerkzeug/DMPwerkzeug,DMPwerkzeug/DMPwerkzeug,rdmorganiser/rdmo | ---
+++
@@ -0,0 +1,34 @@
+from __future__ import unicode_literals
+
+from django.conf import settings
+from django.db import migrations, models
+
+
+def run_data_migration(apps, schema_editor):
+ Project = apps.get_model('projects', 'Project')
+ Task = apps.get_model('tasks', 'Task')
+ View = apps.get_model(... | |
9867362ddc198ecdd095b6190936a683caed4aad | oneTimeEditedString.py | oneTimeEditedString.py | def isEditedOnce(stringOne,stringTwo):
stringOneLength = len(stringOne)
stringTwoLength = len(stringTwo)
totalChanges = 0
if abs(stringOneLength - stringTwoLength) > 1:
return False
else:
if stringOneLength == stringTwoLength:
for index in range(0,stringOneLen... | Verify String is edited only one time | Verify String is edited only one time
| Python | mit | arunkumarpalaniappan/algorithm_tryouts | ---
+++
@@ -0,0 +1,33 @@
+def isEditedOnce(stringOne,stringTwo):
+ stringOneLength = len(stringOne)
+ stringTwoLength = len(stringTwo)
+ totalChanges = 0
+ if abs(stringOneLength - stringTwoLength) > 1:
+ return False
+ else:
+ if stringOneLength == stringTwoLength:
+ ... | |
5d918622ca14c1d9eed88346c200eca60bccaa5f | yatsm/classification/roi.py | yatsm/classification/roi.py | """ Utilities for extracting training data from region of interests (ROI)
"""
import numpy as np
from rasterio.features import rasterize
from shapely.geometry import shape as geom_shape
def extract_roi(src, features, feature_prop=None, all_touched=False, fill=0):
""" Yield pixel data from ``src`` for ROIs in ``fe... | Add ROI extraction code for use w/ xarray | Add ROI extraction code for use w/ xarray
| Python | mit | valpasq/yatsm,c11/yatsm,valpasq/yatsm,c11/yatsm | ---
+++
@@ -0,0 +1,70 @@
+""" Utilities for extracting training data from region of interests (ROI)
+"""
+import numpy as np
+from rasterio.features import rasterize
+from shapely.geometry import shape as geom_shape
+
+
+def extract_roi(src, features, feature_prop=None, all_touched=False, fill=0):
+ """ Yield pixe... | |
f631b42aee7e144947236bcd55218cf0252e6ec8 | h2o-py/tests/testdir_algos/gam/pyunit_gam_train_metrics.py | h2o-py/tests/testdir_algos/gam/pyunit_gam_train_metrics.py | from __future__ import division
from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o
from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
import pandas as pd
import numpy as np
from tests import pyunit_utils
def gam_train_metrics_recalculate(family):
np.random.seed(... | Add test to show GAM metrics are correct | PUBDEV-8455: Add test to show GAM metrics are correct
We compare training metrics calculated in training and user-calculated
metrics.
| Python | apache-2.0 | h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3 | ---
+++
@@ -0,0 +1,67 @@
+from __future__ import division
+from __future__ import print_function
+import sys
+sys.path.insert(1,"../../../")
+import h2o
+from h2o.estimators.gam import H2OGeneralizedAdditiveEstimator
+import pandas as pd
+import numpy as np
+from tests import pyunit_utils
+
+
+def gam_train_metrics_r... | |
d21d5136351d92a384ea7d5b7db5224ec648ad0f | src/ggrc_risks/migrations/versions/20160513135106_47bf3f1f9be8_add_url_and_reference_url_columns.py | src/ggrc_risks/migrations/versions/20160513135106_47bf3f1f9be8_add_url_and_reference_url_columns.py | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: urban@reciprocitylabs.com
# Maintained By: urban@reciprocitylabs.com
"""
Add url and reference_url columns
Create Date: 2016-05-13 13:51:06.534663... | Add `url` and `reference_url` columns to risk object | Add `url` and `reference_url` columns to risk object
| Python | apache-2.0 | andrei-karalionak/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,NejcZupec/ggrc-core,andrei-karalionak/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,josthkko/ggrc-core,selahssea/ggrc-core,VinnieJohns... | ---
+++
@@ -0,0 +1,36 @@
+# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
+# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
+# Created By: urban@reciprocitylabs.com
+# Maintained By: urban@reciprocitylabs.com
+
+"""
+Add url and reference_url columns
+
+Cre... | |
1922197472b5afcacdae37da2c4e66856e74116e | storage/mongo_storage.py | storage/mongo_storage.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/
'''
Storage module to interact with MongoDB.
Provides a MongoStorage helper class with the following
functions:
setup:... | Add storage module for mongo DB | Add storage module for mongo DB | Python | mpl-2.0 | awest1339/multiscanner,mitre/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,awest1339/multiscanner | ---
+++
@@ -0,0 +1,74 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/
+'''
+Storage module to interact with MongoDB.
+Provides a MongoStorage helper class with th... | |
c050cbd0f13f34915854137dced4003b8836f451 | scripts/image_signing/security_test_artifact.py | scripts/image_signing/security_test_artifact.py | #!/usr/bin/env python3
# Copyright 2022 The ChromiumOS Authors.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run security tests on an artifact"""
import argparse
import os
from pathlib import Path
import subprocess
import sys
DIR = Path(__file__).resolve().... | Add general security test script | scripts/image_signing: Add general security test script
This commit adds a general security test script. This allows
some logic to be moved out of the signer as well as providing a single
entry point for the security tests run by the signer.
BRANCH=none
BUG=b:202397678
TEST=Verified that correct security tests ran wi... | Python | bsd-3-clause | coreboot/vboot,coreboot/vboot,coreboot/vboot,coreboot/vboot,coreboot/vboot | ---
+++
@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+# Copyright 2022 The ChromiumOS Authors.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Run security tests on an artifact"""
+
+import argparse
+import os
+from pathlib import Path
+import subprocess
+impo... | |
770da0f60ec4f80425334f281fcd0abb590e6b6b | test/snv/writers_test.py | test/snv/writers_test.py | '''
Created on 05/03/2010
@author: peio
'''
import unittest
from franklin.seq.seqs import SeqFeature, SeqWithQuality, Seq
from Bio.SeqFeature import FeatureLocation
from franklin.snv.snv_annotation import SNP, INVARIANT
from tempfile import NamedTemporaryFile
from franklin.snv.writers import VariantCallFormatWriter
... | Add vcf writer preliminary test | Add vcf writer preliminary test
| Python | agpl-3.0 | JoseBlanca/franklin,JoseBlanca/franklin | ---
+++
@@ -0,0 +1,46 @@
+'''
+Created on 05/03/2010
+
+@author: peio
+'''
+import unittest
+from franklin.seq.seqs import SeqFeature, SeqWithQuality, Seq
+from Bio.SeqFeature import FeatureLocation
+from franklin.snv.snv_annotation import SNP, INVARIANT
+from tempfile import NamedTemporaryFile
+from franklin.snv.wr... | |
2227619b0358db4f2d5f707248ab2fb19652021e | test/test_thin_client.py | test/test_thin_client.py | from unittest import TestCase
from pythinclient.client import *
from pythinclient.server import *
import time
__author__ = 'Alek Ratzloff <alekratz@gmail.com>'
DATEFMT = "%d/%m/%Y"
def today():
return time.strftime(DATEFMT)
def server_echo(msg, conn, addr):
# Echoes the message
conn.send((msg + '\n').en... | Add thin client tests. They don't work yet - they just kind of hang there. | Add thin client tests. They don't work yet - they just kind of hang there.
| Python | bsd-3-clause | alekratz/pythinclient | ---
+++
@@ -0,0 +1,59 @@
+from unittest import TestCase
+from pythinclient.client import *
+from pythinclient.server import *
+import time
+
+
+__author__ = 'Alek Ratzloff <alekratz@gmail.com>'
+
+DATEFMT = "%d/%m/%Y"
+def today():
+ return time.strftime(DATEFMT)
+
+def server_echo(msg, conn, addr):
+ # Echoes ... | |
80e7b007bdb731fb8f5d069230a3c5be09a0ec50 | mz-data.py | mz-data.py | # IPython log file
import numpy as np
import napari
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.figure import Figure
# load the data
cube = np.load('datacube.npy')
peaks = np.load('peaklist.npy')
mz = peaks[0]
thresh = np.load('hsr_thresholds.npy')
cubet = np.transpose(cube, (2, 0, 1... | Add script to view mass spec images | Add script to view mass spec images
| Python | bsd-3-clause | jni/useful-histories | ---
+++
@@ -0,0 +1,77 @@
+# IPython log file
+
+
+import numpy as np
+import napari
+from matplotlib.backends.backend_qt5agg import FigureCanvas
+from matplotlib.figure import Figure
+
+
+# load the data
+cube = np.load('datacube.npy')
+peaks = np.load('peaklist.npy')
+mz = peaks[0]
+thresh = np.load('hsr_thresholds.... | |
54c7d5704a148b703fb0db74eeeb66c187134faf | gratipay/utils/pricing.py | gratipay/utils/pricing.py | from decimal import Decimal as D, ROUND_HALF_EVEN
def suggested_payment(usage):
if usage >= 500:
percentage = D('0.02')
elif usage >= 20:
percentage = D('0.05')
else:
percentage = D('0.10')
suggestion = usage * percentage
if suggestion == 0:
rounded = suggestion
... | from decimal import Decimal as D, ROUND_HALF_EVEN
def suggested_payment(usage):
percentage = D('0.05')
suggestion = usage * percentage
rounded = suggestion.quantize(D('0'), ROUND_HALF_EVEN)
return rounded
def suggested_payment_low_high(usage):
# Above $500/wk we suggest 2%.
if usage >= 5000... | Change suggested payment to flat 5% | Change suggested payment to flat 5%
| Python | mit | eXcomm/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,studio666/gratipay.com | ---
+++
@@ -2,24 +2,9 @@
def suggested_payment(usage):
- if usage >= 500:
- percentage = D('0.02')
- elif usage >= 20:
- percentage = D('0.05')
- else:
- percentage = D('0.10')
-
+ percentage = D('0.05')
suggestion = usage * percentage
- if suggestion == 0:
- round... |
b97a5108c26f3e6b4f4a57c9148393e0ba13cfb4 | tests/test_redis/test_redis_ephemeral_tokens.py | tests/test_redis/test_redis_ephemeral_tokens.py | import pytest
from libs.redis_db import RedisEphemeralTokens
from tests.utils import BaseTest
@pytest.mark.redis_mark
class TestRedisEphemeralTokens(BaseTest):
def test_objects(self):
token = RedisEphemeralTokens()
assert token.key is not None
assert token.redis_key == RedisEphemeralToken... | Add ephemeral token redis tests | Add ephemeral token redis tests
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -0,0 +1,42 @@
+import pytest
+
+from libs.redis_db import RedisEphemeralTokens
+from tests.utils import BaseTest
+
+
+@pytest.mark.redis_mark
+class TestRedisEphemeralTokens(BaseTest):
+ def test_objects(self):
+ token = RedisEphemeralTokens()
+ assert token.key is not None
+ assert... | |
193e2d520ead6aef22997de2f7ebbcc9b7cec587 | pandachecker.py | pandachecker.py | """
Program will ping the list of website to see if they are online.
Will give an error message if the website is down.
"""
import subprocess
addressListA = ['baseness.com',
'npr.org',
'ucsc.edu',
'google.com',
'facebook.com',
'myeconlab.com',
'instagra... | Add python code for pinging | Add python code for pinging
| Python | unlicense | ahandsel/pandachecker | ---
+++
@@ -0,0 +1,26 @@
+"""
+Program will ping the list of website to see if they are online.
+Will give an error message if the website is down.
+"""
+import subprocess
+
+addressListA = ['baseness.com',
+ 'npr.org',
+ 'ucsc.edu',
+ 'google.com',
+ 'facebook.com',
+ ... | |
d16a3753d73714a51fbe846e45fe77d5e41cb2ab | examples/dup_and_replay.py | examples/dup_and_replay.py | from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True, run_scripthooks=False)
| from mitmproxy import ctx
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
ctx.master.replay_request(f, block=True)
| Remove dead run_scripthooks example reference. | Remove dead run_scripthooks example reference. | Python | mit | xaxa89/mitmproxy,Kriechi/mitmproxy,cortesi/mitmproxy,zlorb/mitmproxy,dwfreed/mitmproxy,ujjwal96/mitmproxy,vhaupert/mitmproxy,mosajjal/mitmproxy,laurmurclar/mitmproxy,ujjwal96/mitmproxy,Kriechi/mitmproxy,xaxa89/mitmproxy,MatthewShao/mitmproxy,dwfreed/mitmproxy,mosajjal/mitmproxy,mitmproxy/mitmproxy,ddworken/mitmproxy,mo... | ---
+++
@@ -4,4 +4,4 @@
def request(flow):
f = ctx.master.state.duplicate_flow(flow)
f.request.path = "/changed"
- ctx.master.replay_request(f, block=True, run_scripthooks=False)
+ ctx.master.replay_request(f, block=True) |
66ea7be70d37c8431d6daef976c6d5c9a7407ea0 | examples/example_injury.py | examples/example_injury.py | #!/usr/bin/env python
from tabulate import tabulate
from mlbgame import injury
import dateutil.parser
from datetime import datetime
team_id = 117 # Houston Astros
i = injury.Injury(team_id)
injuries = []
for inj in i.injuries:
team = inj.team_name
injury = ['{0}, {1} ({2})'.format(inj.name_last, inj.name_fir... | Add example for injury class | Add example for injury class
| Python | mit | panzarino/mlbgame,zachpanz88/mlbgame | ---
+++
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+
+from tabulate import tabulate
+from mlbgame import injury
+import dateutil.parser
+from datetime import datetime
+
+team_id = 117 # Houston Astros
+i = injury.Injury(team_id)
+injuries = []
+
+for inj in i.injuries:
+ team = inj.team_name
+ injury = ['{0}, {1} ... | |
68009fdf18081033609bc1f98afc1b7e6065c35d | examples/get_yara_rules.py | examples/get_yara_rules.py | import urllib2
import socket
from OTXv2 import OTXv2
from OTXv2 import OTXv2, IndicatorTypes
otx = OTXv2('API_KEY')
pulses = otx.getall()
for i in range(0,len(pulses)-1):
print ("// https://otx.alienvault.com/pulse/" + pulses[i]["id"])
indicators = pulses[i]["indicators"]
for ind in indicators:
i... | Add get yara rules script | Add get yara rules script
| Python | apache-2.0 | AlienVault-Labs/OTX-Python-SDK | ---
+++
@@ -0,0 +1,15 @@
+import urllib2
+import socket
+from OTXv2 import OTXv2
+from OTXv2 import OTXv2, IndicatorTypes
+
+otx = OTXv2('API_KEY')
+
+pulses = otx.getall()
+
+for i in range(0,len(pulses)-1):
+ print ("// https://otx.alienvault.com/pulse/" + pulses[i]["id"])
+ indicators = pulses[i]["indicators... | |
ddf8b393a0695b71400a35a1a218c734a9bc669c | regscrape/regs_common/data_import.py | regscrape/regs_common/data_import.py | import pymongo
import gridfs
import settings
def copy_data(source_db_name, dest_db_name, query):
source = pymongo.Connection(**settings.DB_SETTINGS)[source_db_name]
dest = pymongo.Connection(**settings.DB_SETTINGS)[dest_db_name]
source_gridfs = gridfs.GridFS(source, collection='files')
dest_gridfs = g... | Add a utility for copying data from one database to another. | Add a utility for copying data from one database to another.
| Python | bsd-3-clause | sunlightlabs/regulations-scraper,sunlightlabs/regulations-scraper,sunlightlabs/regulations-scraper | ---
+++
@@ -0,0 +1,64 @@
+import pymongo
+import gridfs
+import settings
+
+def copy_data(source_db_name, dest_db_name, query):
+ source = pymongo.Connection(**settings.DB_SETTINGS)[source_db_name]
+ dest = pymongo.Connection(**settings.DB_SETTINGS)[dest_db_name]
+
+ source_gridfs = gridfs.GridFS(source, col... | |
6354d6a7cbfa253562f983a9002827af2b3cc819 | csv_insert_script.py | csv_insert_script.py | #!/usr/bin/env python2.7
import csv
import sqlite3
conn = sqlite3.connect("twdb.db")
cur = conn.cursor()
file = open('stgcd_manual.csv', 'r')
reader = csv.reader(file)
readings = []
twdb_nums = []
for row in reader:
readings.append(row)
if (row[0] not in twdb_nums):
twdb_nums.append(row[0])
readi... | Add script to generate SQL script for STGCD manual readings. | Add script to generate SQL script for STGCD manual readings.
| Python | isc | wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/env python2.7
+
+import csv
+import sqlite3
+
+conn = sqlite3.connect("twdb.db")
+cur = conn.cursor()
+
+file = open('stgcd_manual.csv', 'r')
+
+reader = csv.reader(file)
+
+readings = []
+twdb_nums = []
+
+for row in reader:
+ readings.append(row)
+ if (row[0] not in twdb_n... | |
3f09462f3be6f7d59d36ffaf5e4dae4be74b623b | private/realclearpolitics-scraper/scraper.py | private/realclearpolitics-scraper/scraper.py | import sys, os
args = sys.argv
if (len(args) <= 1):
print("ERROR: Please provide source url")
print("Example : python scraper.py url output.csv")
else:
url = args[1]
if (len(args) == 2):
filename = url.split('/')[-1].split('.')[0]
output = filename + ".csv"
print("No output file... | import sys, os
args = sys.argv
if (len(args) <= 1):
raise ValueError('Please provide source url when calling scraper.py. Example : python scraper.py url output.csv')
else:
url = args[1]
if (len(args) == 2):
filename = url.split('/')[-1].split('.')[0]
output = filename + ".csv"
print... | Raise exception when script called with wrong args | Raise exception when script called with wrong args
(instead of just printing)
| Python | mit | Rumel/berniemetrics,Rumel/berniemetrics,Rumel/berniemetrics,dpxxdp/berniemetrics,Rumel/berniemetrics,fpagnoux/berniemetrics,fpagnoux/berniemetrics,fpagnoux/berniemetrics,dpxxdp/berniemetrics,fpagnoux/berniemetrics,dpxxdp/berniemetrics,dpxxdp/berniemetrics | ---
+++
@@ -2,8 +2,7 @@
args = sys.argv
if (len(args) <= 1):
- print("ERROR: Please provide source url")
- print("Example : python scraper.py url output.csv")
+ raise ValueError('Please provide source url when calling scraper.py. Example : python scraper.py url output.csv')
else:
url = args[1]
... |
f536adf23907282aa26c6b844dc6875d5412553d | raw2obj.py | raw2obj.py | import numpy as np
import scipy.misc
import mcubes
import argparse
from sklearn.neighbors import NearestNeighbors
parser = argparse.ArgumentParser(description='Visualise the 3D volume')
parser.add_argument('--image', dest='image',
help="The background image to display")
parser.add_argument('--volu... | Convert the raw data to obj file using PyMCubes. | Convert the raw data to obj file using PyMCubes.
| Python | mit | AaronJackson/vrn,AaronJackson/vrn,AaronJackson/vrn | ---
+++
@@ -0,0 +1,50 @@
+import numpy as np
+import scipy.misc
+import mcubes
+import argparse
+from sklearn.neighbors import NearestNeighbors
+
+
+parser = argparse.ArgumentParser(description='Visualise the 3D volume')
+parser.add_argument('--image', dest='image',
+ help="The background image to ... | |
5770dfc5b5df312dc15f0bc44437c0e62936d688 | events/migrations/0073_soft_delete_replaced_objects.py | events/migrations/0073_soft_delete_replaced_objects.py | # Generated by Django 2.2.9 on 2020-01-31 08:25
from django.db import migrations
def soft_delete_replaced_objects(Model, deleted_attr='deleted', replaced_by_attr='replaced_by'):
for obj in Model.objects.filter(**{f'{replaced_by_attr}__isnull': False, deleted_attr: False}):
print(f'Found an object that is... | Add data migration that deletes replaced objects | Add data migration that deletes replaced objects
| Python | mit | City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents | ---
+++
@@ -0,0 +1,33 @@
+# Generated by Django 2.2.9 on 2020-01-31 08:25
+
+from django.db import migrations
+
+
+def soft_delete_replaced_objects(Model, deleted_attr='deleted', replaced_by_attr='replaced_by'):
+ for obj in Model.objects.filter(**{f'{replaced_by_attr}__isnull': False, deleted_attr: False}):
+ ... | |
d08404d9589a0a61aba9eeb01231f5d7d6707bf3 | services/migrations/0026_auto_20150302_2222.py | services/migrations/0026_auto_20150302_2222.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import services.models
class Migration(migrations.Migration):
dependencies = [
('services', '0025_merge'),
]
operations = [
migrations.AlterField(
model_name='provider',
... | Add missing migration for provider name validators | Add missing migration for provider name validators
| Python | bsd-3-clause | theirc/ServiceInfo,theirc/ServiceInfo,theirc/ServiceInfo,theirc/ServiceInfo-ircdeploy,theirc/ServiceInfo | ---
+++
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+import services.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('services', '0025_merge'),
+ ]
+
+ operations = [
+ migrations.Alter... | |
f453221b89d21dc7350706fc707bb3a88012d5ba | src/simple_data_export.py | src/simple_data_export.py | from collections import defaultdict
import json
from math import floor
import sys
import database as db
from database.model import Team
from geotools import simple_distance
from geotools.routing import MapPoint
from webapp.cfg.config import DB_CONNECTION
if len(sys.argv) == 2:
MAX_TEAMS = sys.argv[1]
else:
MA... | Add a very simple script to export team data from the database as json files. | Add a very simple script to export team data from the database as json files.
| Python | bsd-3-clause | eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system | ---
+++
@@ -0,0 +1,79 @@
+from collections import defaultdict
+import json
+from math import floor
+import sys
+import database as db
+from database.model import Team
+from geotools import simple_distance
+from geotools.routing import MapPoint
+from webapp.cfg.config import DB_CONNECTION
+
+
+if len(sys.argv) == 2:
+... | |
b5a9c8e0c7ae377d9b1a3671170542f6a7fecde3 | ecommerce/extensions/catalogue/migrations/0034_add_on_campus_coupon_category.py | ecommerce/extensions/catalogue/migrations/0034_add_on_campus_coupon_category.py | """ Add 'On-Campus Learners' to the list of default coupon categories"""
from django.db import migrations
from oscar.apps.catalogue.categories import create_from_breadcrumbs
from oscar.core.loading import get_model
Category = get_model('catalogue', 'Category')
COUPON_CATEGORY_NAME = 'Coupons'
ON_CAMPUS_CATEGORY = '... | Create On-Campus Learner Coupon Category | REVE-183: Create On-Campus Learner Coupon Category
| Python | agpl-3.0 | edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce | ---
+++
@@ -0,0 +1,35 @@
+""" Add 'On-Campus Learners' to the list of default coupon categories"""
+
+from django.db import migrations
+from oscar.apps.catalogue.categories import create_from_breadcrumbs
+from oscar.core.loading import get_model
+
+Category = get_model('catalogue', 'Category')
+
+COUPON_CATEGORY_NAME... | |
9569ea1d7c3e91dc8f7ba63ca22aaddd2f3bcfca | djangae/contrib/auth/management/__init__.py | djangae/contrib/auth/management/__init__.py | from django.db import DEFAULT_DB_ALIAS, router
from django.db.models import get_model, get_models, signals, UnavailableApp
from django.contrib.auth import (models as auth_app, get_permission_codename,
get_user_model)
from django.contrib.auth.management import _get_all_permissions
def create_permissions(app, create... | Add an override for create_permissions which batches the lookups | Add an override for create_permissions which batches the lookups
| Python | bsd-3-clause | stucox/djangae,nealedj/djangae,SiPiggles/djangae,b-cannon/my_djae,armirusco/djangae,armirusco/djangae,martinogden/djangae,stucox/djangae,martinogden/djangae,kirberich/djangae,grzes/djangae,grzes/djangae,leekchan/djangae,potatolondon/djangae,martinogden/djangae,chargrizzle/djangae,chargrizzle/djangae,asendecka/djangae,S... | ---
+++
@@ -0,0 +1,64 @@
+from django.db import DEFAULT_DB_ALIAS, router
+from django.db.models import get_model, get_models, signals, UnavailableApp
+from django.contrib.auth import (models as auth_app, get_permission_codename,
+ get_user_model)
+from django.contrib.auth.management import _get_all_permissions
+
+... | |
5c2ed17e84f435380ded64e0b5d1703f8e3b54c9 | csunplugged/tests/infrastructure/test_deployment.py | csunplugged/tests/infrastructure/test_deployment.py | """Tests deployments."""
import os
import re
from tests.BaseTest import BaseTest
class DeploymentTest(BaseTest):
"""Tests for deployments."""
def test_dev_deploy_scripts_are_called(self):
# Create list of script files
FILES_TO_SKIP = (
'decrypt-dev-secrets.sh',
'load-... | Add test to check resource generation files are called | Add test to check resource generation files are called
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | ---
+++
@@ -0,0 +1,67 @@
+"""Tests deployments."""
+
+import os
+import re
+from tests.BaseTest import BaseTest
+
+
+class DeploymentTest(BaseTest):
+ """Tests for deployments."""
+
+ def test_dev_deploy_scripts_are_called(self):
+ # Create list of script files
+ FILES_TO_SKIP = (
+ 'de... | |
5ae4da11c2a98321864569b900338f3e78cd22d6 | flexx/app/tests/test_live.py | flexx/app/tests/test_live.py | """ Test a live app connection.
"""
from flexx import app, react
from flexx.util.testing import run_tests_if_main, raises
def runner(cls):
t = app.launch(cls, 'xul')
t.test_init()
app.run()
t.test_check()
class BaseTesterApp(app.Model):
@react.input
def input(v):
return v... | Add test for a life connection with a browser to test important code paths. | Add test for a life connection with a browser to test important code paths.
| Python | bsd-2-clause | JohnLunzer/flexx,jrversteegh/flexx,zoofIO/flexx,JohnLunzer/flexx,zoofIO/flexx,JohnLunzer/flexx,jrversteegh/flexx | ---
+++
@@ -0,0 +1,62 @@
+""" Test a live app connection.
+"""
+
+from flexx import app, react
+
+from flexx.util.testing import run_tests_if_main, raises
+
+
+def runner(cls):
+ t = app.launch(cls, 'xul')
+ t.test_init()
+ app.run()
+ t.test_check()
+
+
+class BaseTesterApp(app.Model):
+
+
+ @... | |
7a838753853f172078068ba37e3462e3093f32c6 | leetcode/289-Game-of-Life/GameofLife_001.py | leetcode/289-Game-of-Life/GameofLife_001.py | class Solution(object):
def gameOfLife(self, board):
"""
:type board: List[List[int]]
:rtype: void Do not return anything, modify board in-place instead.
"""
m, n = len(board), len(board[0])
for i in xrange(m):
for j in xrange(n):
cnt = 0
... | Add Game of Life for lc | Add Game of Life for lc
| Python | mit | cc13ny/Allin,cc13ny/algo,Chasego/cod,cc13ny/Allin,Chasego/cod,cc13ny/algo,Chasego/codirit,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/codi,Chasego/codi,Chasego/codi,cc13ny/Allin,Chasego/codirit,Chasego/cod,cc13ny/algo,Chasego/cod,Chasego/codi,cc13ny/Allin,Chasego/codirit,Chasego/codi,cc13ny/algo,Chasego/cod,cc... | ---
+++
@@ -0,0 +1,28 @@
+class Solution(object):
+ def gameOfLife(self, board):
+ """
+ :type board: List[List[int]]
+ :rtype: void Do not return anything, modify board in-place instead.
+ """
+ m, n = len(board), len(board[0])
+ for i in xrange(m):
+ for j in ... | |
a14ce43c2d318f864f70392eab16145ec6bc4733 | support/jenkins/buildAllModuleCombination.py | support/jenkins/buildAllModuleCombination.py | import os
from subprocess import call
from itertools import product, repeat
# To be called from the OpenSpace main folder
modules = os.listdir("modules")
modules.remove("base")
# Get 2**len(modules) combinatorical combinations of ON/OFF
settings = []
for args in product(*repeat(("ON", "OFF"), len(modules))):
sett... | Add Python script to build all combinations of modules | Add Python script to build all combinations of modules
| Python | mit | OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace | ---
+++
@@ -0,0 +1,28 @@
+import os
+from subprocess import call
+from itertools import product, repeat
+
+# To be called from the OpenSpace main folder
+modules = os.listdir("modules")
+modules.remove("base")
+
+# Get 2**len(modules) combinatorical combinations of ON/OFF
+settings = []
+for args in product(*repeat((... | |
e42f488ae779168c10d6a01bd04dfd2f6c3c311d | restalchemy/api/controllers.py | restalchemy/api/controllers.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | Add base class for API Controller | Add base class for API Controller
Change-Id: Idf28f395308be3416a95783d9c1ec1d6c2478487
| Python | apache-2.0 | phantomii/restalchemy | ---
+++
@@ -0,0 +1,46 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+#
+# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
+#
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# ... | |
8f13e16b904d71149321b4ae8f03db32a49cdf08 | iatidq/user_activity_types.py | iatidq/user_activity_types.py |
# IATI Data Quality, tools for Data QA on IATI-formatted publications
# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
#
# Copyright (C) 2013 Publish What You Fund
#
# This programme is free software; you may redistribute and/or modify
# it under the terms of the GNU Affero General Public License v3... | Add user activity types module | Add user activity types module
| Python | agpl-3.0 | pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality | ---
+++
@@ -0,0 +1,11 @@
+
+# IATI Data Quality, tools for Data QA on IATI-formatted publications
+# by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith
+#
+# Copyright (C) 2013 Publish What You Fund
+#
+# This programme is free software; you may redistribute and/or modify
+# it under the terms of the G... | |
48ec53343be7d7efc07bc1f66416d884be22b430 | Python/ds.py | Python/ds.py | """
This file includes several data structures used in LeetCode question.
"""
# Definition for a list node.
class ListNode(object):
def __init__(self, n):
self.val = n
self.next = None
def createLinkedList(nodelist):
#type nodelist: list[int/float]
#rtype: head of linked list
linkedList = ListNode(0)
head = ... | Add class file for linked list and binary tree | Add class file for linked list and binary tree
| Python | mit | comicxmz001/LeetCode,comicxmz001/LeetCode | ---
+++
@@ -0,0 +1,46 @@
+"""
+ This file includes several data structures used in LeetCode question.
+"""
+# Definition for a list node.
+class ListNode(object):
+ def __init__(self, n):
+ self.val = n
+ self.next = None
+
+def createLinkedList(nodelist):
+ #type nodelist: list[int/float]
+ #rtype: head of linked ... | |
4601244bea1c0b84679d90b0b368da7f39908759 | dakota_utils/tests/test_file.py | dakota_utils/tests/test_file.py | #! /usr/bin/env python
#
# Tests for dakota_utils.file.
#
# 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 *
def setup_module():
print('File tests:')
os.environ['_test_tmp_dir'] = tempfile.m... | Add unit tests for file module | Add unit tests for file module
| Python | mit | mcflugen/dakota-experiments,mcflugen/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments,mdpiper/dakota-experiments | ---
+++
@@ -0,0 +1,50 @@
+#! /usr/bin/env python
+#
+# Tests for dakota_utils.file.
+#
+# 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 *
+
+def setup_module():
+ print('File tests:')
... | |
cde2263c2084b8ce91e85face95e5e85439ab7ce | scripts/annotate_rsvps.py | scripts/annotate_rsvps.py | """Utilities for annotating workshop RSVP data.
Example ::
import pandas as pd
from scripts import annotate_rsvps
frame = pd.read_csv('workshop.csv')
annotated = annotate_rsvps.process(frame)
annotated.to_csv('workshop-annotated.csv')
"""
import re
import logging
from dateutil.parser import par... | Add script to annotate conference RSVP spreadsheets. | Add script to annotate conference RSVP spreadsheets.
Requested by @lbanner.
| Python | apache-2.0 | caneruguz/osf.io,CenterForOpenScience/osf.io,petermalcolm/osf.io,bdyetton/prettychart,asanfilippo7/osf.io,petermalcolm/osf.io,KAsante95/osf.io,ZobairAlijan/osf.io,cwisecarver/osf.io,Ghalko/osf.io,Johnetordoff/osf.io,cosenal/osf.io,DanielSBrown/osf.io,doublebits/osf.io,jnayak1/osf.io,MerlinZhang/osf.io,rdhyee/osf.io,dan... | ---
+++
@@ -0,0 +1,91 @@
+"""Utilities for annotating workshop RSVP data.
+
+Example ::
+
+ import pandas as pd
+ from scripts import annotate_rsvps
+ frame = pd.read_csv('workshop.csv')
+ annotated = annotate_rsvps.process(frame)
+ annotated.to_csv('workshop-annotated.csv')
+
+"""
+
+import re
+import... | |
1f17a2a4efaefa0b77eef123dd950e1c047fcb2d | scripts/copy_snippet.py | scripts/copy_snippet.py | #!/usr/bin/env python
"""Copy a snippet (in its latest version) from one party to another.
:Copyright: 2006-2018 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
import click
from byceps.services.snippet.models.snippet import SnippetType
from byceps.services.snippet import service as snippe... | Add script to copy a snippet from one party to another | Add script to copy a snippet from one party to another
| Python | bsd-3-clause | m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps | ---
+++
@@ -0,0 +1,61 @@
+#!/usr/bin/env python
+
+"""Copy a snippet (in its latest version) from one party to another.
+
+:Copyright: 2006-2018 Jochen Kupperschmidt
+:License: Modified BSD, see LICENSE for details.
+"""
+
+import click
+
+from byceps.services.snippet.models.snippet import SnippetType
+from byceps.se... | |
9991b40871ccd70ee4359b8e44e9a3a5aa15fd8a | migrations/versions/0243_another_letter_org.py | migrations/versions/0243_another_letter_org.py | """empty message
Revision ID: 0243_another_letter_org
Revises: 0242_template_folders
"""
# revision identifiers, used by Alembic.
revision = '0243_another_letter_org'
down_revision = '0242_template_folders'
from alembic import op
NEW_ORGANISATIONS = [
('516', 'Worcestershire County Council', 'worcestershire')... | Add Buckinghamshire and Worcestershire letter logos | Add Buckinghamshire and Worcestershire letter logos
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -0,0 +1,36 @@
+"""empty message
+
+Revision ID: 0243_another_letter_org
+Revises: 0242_template_folders
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '0243_another_letter_org'
+down_revision = '0242_template_folders'
+
+from alembic import op
+
+
+NEW_ORGANISATIONS = [
+ ('516', 'Worces... | |
ffd021e5effd8264bb8708cb52f17498f3969357 | scripts/update_names.py | scripts/update_names.py | from accounts.models import TimtecUser
import re
cont = 0
for user in TimtecUser.objects.all():
complete_name = user.first_name + " " + user.last_name
complete_name = re.sub(' +',' ', complete_name)
if (complete_name != ' '):
user.first_name = complete_name
user.last_name = ''
user... | Add script to update names | Add script to update names
| Python | agpl-3.0 | mupi/tecsaladeaula,mupi/tecsaladeaula,mupi/tecsaladeaula,mupi/tecsaladeaula | ---
+++
@@ -0,0 +1,14 @@
+from accounts.models import TimtecUser
+import re
+
+cont = 0
+for user in TimtecUser.objects.all():
+ complete_name = user.first_name + " " + user.last_name
+ complete_name = re.sub(' +',' ', complete_name)
+
+ if (complete_name != ' '):
+ user.first_name = complete_name
+ ... | |
b00d66ebe0248fcaff164997638c8890b5b5c17c | tensorflow/python/autograph/utils/compat_util.py | tensorflow/python/autograph/utils/compat_util.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Swap out modules in py2 mode in a cleaner fashion. | Swap out modules in py2 mode in a cleaner fashion.
PiperOrigin-RevId: 288526813
Change-Id: I86efd4d804c0c873856307cf4a969270eb7bbae8
| Python | apache-2.0 | annarev/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,annarev/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_on... | ---
+++
@@ -20,7 +20,6 @@
import importlib
import sys
-import types
import six
@@ -36,10 +35,4 @@
"""Swaps calling module with a Py2-specific implementation. Noop in Py3."""
if six.PY2:
legacy_module = importlib.import_module(module_name + '_deprecated_py2')
- current_module = sys.modules[modul... |
24fe675fa2cedb4cce6596ea46dbed24b31ee072 | python/fix-srt-subtitle/fix-srt-subtitle.py | python/fix-srt-subtitle/fix-srt-subtitle.py | #!/usr/bin/env python
import optparse
import sys
def main():
empty_subtitle = '''1
00:00:00,000 --> 00:00:00,001
'''
parser, infile_name, outfile_name = parse_options()
#if len(sys.argv) < 3:
# sys.exit('USAGE: {0} SRT_INFILE SRT_OUTFILE'.format(sys.argv[0]))
# TODO: with contextlib.clos... | Add script for fixing SRT subtitle files | Add script for fixing SRT subtitle files
| Python | mit | bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile,bmaupin/junkpile | ---
+++
@@ -0,0 +1,78 @@
+#!/usr/bin/env python
+
+import optparse
+import sys
+
+def main():
+ empty_subtitle = '''1
+00:00:00,000 --> 00:00:00,001
+
+'''
+
+ parser, infile_name, outfile_name = parse_options()
+
+ #if len(sys.argv) < 3:
+ # sys.exit('USAGE: {0} SRT_INFILE SRT_OUTFILE'.format(sys.... | |
deda54b8b97399019d1d7378d1e45b223436494e | mzalendo/core/management/commands/core_extend_party_memberships.py | mzalendo/core/management/commands/core_extend_party_memberships.py | # This command is intended to fix issue 550:
#
# https://github.com/mysociety/mzalendo/issues/550
#
# "As mentioned in #494 there are lots of party membership positions
# that have an end date of 2012 - meaning that on the site many
# positions are hidden by default. These party memberships should
# probab... | Add an admin command to fix party membership position end_dates | Add an admin command to fix party membership position end_dates
This is a fix for issue #550 - some party membership positions
were set to 2012, so they no longer appear as current
party memberships. Instead, we should set these to 'future'.
We will shortly be importing the new candidate data, in which
lots of these... | Python | agpl-3.0 | hzj123/56th,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,hzj123/56th,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,patricmutwiri/pombola,geoffkilpin/pombola,hzj123/56th,geoffkilpin/pombola,ken-muturi/pombola,patricmutwiri/pombola,pat... | ---
+++
@@ -0,0 +1,46 @@
+# This command is intended to fix issue 550:
+#
+# https://github.com/mysociety/mzalendo/issues/550
+#
+# "As mentioned in #494 there are lots of party membership positions
+# that have an end date of 2012 - meaning that on the site many
+# positions are hidden by default. These pa... | |
079df6a4908cb03dc5a6ca9b350ffc81b04bdac4 | smsgateway/factories.py | smsgateway/factories.py | # -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import factory
from smsgateway.models import SMS
class SMSFactory(factory.DjangoModelFactory):
FACTORY_FOR = SMS
content = 'This is a test'
sender = factory.Sequence(lambda n: u"+32476{0:06d}".format(n))
to = factory.Sequence(lambda n:... | Add factory for text messages | Add factory for text messages
| Python | bsd-3-clause | mvpoland/django-smsgateway,mvpoland/django-smsgateway,mvpoland/django-smsgateway | ---
+++
@@ -0,0 +1,12 @@
+# -*- encoding: utf-8 -*-
+from __future__ import unicode_literals
+import factory
+from smsgateway.models import SMS
+
+
+class SMSFactory(factory.DjangoModelFactory):
+ FACTORY_FOR = SMS
+
+ content = 'This is a test'
+ sender = factory.Sequence(lambda n: u"+32476{0:06d}".format(n... | |
8841ed6de25e1b5752ba6bcbd8527820526ccc22 | tests/test_regex.py | tests/test_regex.py | import unittest
import importlib
import sublime
from SublimeLinter.lint.linter import get_linter_settings
from SublimeLinter.tests.parameterized import parameterized as p
LinterModule = importlib.import_module('SublimeLinter-annotations.linter')
Linter = LinterModule.Annotations
class TestRegex(unittest.TestCase)... | Add basic test to prove the concept | Add basic test to prove the concept
| Python | mit | SublimeLinter/SublimeLinter-annotations | ---
+++
@@ -0,0 +1,57 @@
+import unittest
+import importlib
+
+import sublime
+from SublimeLinter.lint.linter import get_linter_settings
+
+from SublimeLinter.tests.parameterized import parameterized as p
+
+
+LinterModule = importlib.import_module('SublimeLinter-annotations.linter')
+Linter = LinterModule.Annotation... | |
82a8e092260d5768babc5d498ac0ddf40c7b3634 | tests/views/test_admin_committee_page.py | tests/views/test_admin_committee_page.py | from tests import PMGLiveServerTestCase
from pmg.models import db
from tests.fixtures import (
dbfixture, UserData, CommitteeData, MembershipData
)
class TestAdminCommitteePage(PMGLiveServerTestCase):
def setUp(self):
super(TestAdminCommitteePage, self).setUp()
self.fx = dbfixture.data(
... | Add admin committee view test | Add admin committee view test
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 | ---
+++
@@ -0,0 +1,36 @@
+from tests import PMGLiveServerTestCase
+from pmg.models import db
+from tests.fixtures import (
+ dbfixture, UserData, CommitteeData, MembershipData
+)
+
+
+class TestAdminCommitteePage(PMGLiveServerTestCase):
+ def setUp(self):
+ super(TestAdminCommitteePage, self).setUp()
+
+... | |
dfdbfa7f68a80cbf3976ce9c6d7cb8771e038209 | conf_site/proposals/migrations/0008_alter_urlfields.py | conf_site/proposals/migrations/0008_alter_urlfields.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-01-16 21:29
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proposals', '0007_add_urlfields'),
]
operations = [
migrations.AlterField(
... | Add DB migration for previous URL field changes. | Add DB migration for previous URL field changes.
See #214.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site | ---
+++
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.13 on 2018-01-16 21:29
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('proposals', '0007_add_urlfields'),
+ ]
+
+ opera... | |
6cbeab27628b83a0b075d344f46ad8f9207e335e | ikea-ota-download.py | ikea-ota-download.py | #!/usr/bin/env python
"""
Snipped to dowload current IKEA ZLL OTA files into ~/otau
Requires python 2.7, not compatible with python 3.
"""
import os
import json
import urllib
f = urllib.urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json")
data = f.read()
arr = json.loads(data)
otapath = '%s/otau' % os... | Add IKEA OTA download script | Add IKEA OTA download script
| Python | bsd-3-clause | dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin,dresden-elektronik/deconz-rest-plugin | ---
+++
@@ -0,0 +1,35 @@
+#!/usr/bin/env python
+"""
+Snipped to dowload current IKEA ZLL OTA files into ~/otau
+Requires python 2.7, not compatible with python 3.
+"""
+
+import os
+import json
+import urllib
+
+f = urllib.urlopen("http://fw.ota.homesmart.ikea.net/feed/version_info.json")
+data = f.read()
+
+arr = j... | |
52d312ad6bcfd68eb88202ef40574f10788eb70b | leetcode/reverse_string.py | leetcode/reverse_string.py | """
# Problem statement
https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
## Algorithm description
Traverse the given input until the middle of it.
Swap the extremes of the input until reach the middle of it.
Example:
input = "abcde"
len(input) = 5
middle = ceil(5 / 3) = 3
... | Add solution for Reverse String problem | Add solution for Reverse String problem
| Python | mit | julianespinel/training,julianespinel/training,julianespinel/training,julianespinel/trainning,julianespinel/trainning,julianespinel/training | ---
+++
@@ -0,0 +1,96 @@
+"""
+# Problem statement
+
+https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
+
+## Algorithm description
+
+Traverse the given input until the middle of it.
+Swap the extremes of the input until reach the middle of it.
+
+Example:
+
+input = "abcde"
+... | |
093c29e315ca0a1eb5efc3099892ceea016ffde1 | awx/main/management/commands/revoke_tokens.py | awx/main/management/commands/revoke_tokens.py | # Django
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
# AWX
from awx.main.models.oauth import OAuth2AccessToken
from oauth2_provider.models import RefreshToken
def revoke_tokens(token_list):
for ... | Add command to revoke tokens | Add command to revoke tokens
Signed-off-by: Cristian Vargas <87b43435284539b2f7f4e4dcab5e78251c243226@swapps.co>
| Python | apache-2.0 | wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx | ---
+++
@@ -0,0 +1,34 @@
+# Django
+from django.core.management.base import BaseCommand, CommandError
+from django.contrib.auth.models import User
+from django.core.exceptions import ObjectDoesNotExist
+
+# AWX
+from awx.main.models.oauth import OAuth2AccessToken
+from oauth2_provider.models import RefreshToken
+
+de... | |
2af5a573196d409cb70b58fe828de9515dc4088a | bin/fetch_mcgill_transcript.py | bin/fetch_mcgill_transcript.py | #!/usr/bin/env python
import argparse
import getpass
import sys
import StringIO
import mcgill
def parse_args():
parser = argparse.ArgumentParser(
description='fetch McGill transcript',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-a', '--auth', help='''email:password or... | Add a quick script to dump transcript to stdout. | Add a quick script to dump transcript to stdout.
| Python | mit | isbadawi/minerva | ---
+++
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+import argparse
+import getpass
+import sys
+import StringIO
+
+import mcgill
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(
+ description='fetch McGill transcript',
+ formatter_class=argparse.RawTextHelpFormatter)
+ parser.add_argument(... | |
d470e524e534a7a0d0b217a12777d6e18c45eb78 | nurseconnect/formfields.py | nurseconnect/formfields.py | from django.core.exceptions import ValidationError
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from phonenumber_field.formfields import PhoneNumberField as ImportedPhoneNumberField
from phonenumber_field.phonenumber import to_python
def validate_international_... | Add custom PhoneNumberField for use in NurseConnect | Add custom PhoneNumberField for use in NurseConnect
| Python | bsd-2-clause | praekelt/nurseconnect,praekelt/nurseconnect,praekelt/nurseconnect | ---
+++
@@ -0,0 +1,26 @@
+from django.core.exceptions import ValidationError
+from django.utils.encoding import force_text
+from django.utils.translation import ugettext_lazy as _
+
+from phonenumber_field.formfields import PhoneNumberField as ImportedPhoneNumberField
+from phonenumber_field.phonenumber import to_pyt... | |
c9f397162c131455ca2f8b63ab7ede126529c053 | 005.py | 005.py | """
Project Euler Problem 5
=======================
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest number that is evenly divisible by all of the numbers
from 1 to 20?
"""
from functools import reduce
from math import gcd
def divisible... | Add solution and unit tests for problem 5 | Add solution and unit tests for problem 5
| Python | mit | BeataBak/project-euler-problems | ---
+++
@@ -0,0 +1,34 @@
+"""
+Project Euler Problem 5
+=======================
+
+2520 is the smallest number that can be divided by each of the numbers
+from 1 to 10 without any remainder.
+
+What is the smallest number that is evenly divisible by all of the numbers
+from 1 to 20?
+"""
+
+from functools import redu... | |
e2d7b446cc290cda01709636e964f850cbef0532 | 17B-162/HI/analysis/convolve_and_match_iram30m.py | 17B-162/HI/analysis/convolve_and_match_iram30m.py |
'''
Create a cube that is spatially-matched and convolved to the IRAM 30-m
CO(2-1) cube.
'''
import os
from os.path import join as osjoin
from cube_analysis.reprojection import reproject_cube
from cube_analysis.run_pipe import run_pipeline
from paths import (seventeenB_HI_data_1kms_wGBT_path,
sev... | Make a 17B HI cube matched to the 30-m IRAM cube | Make a 17B HI cube matched to the 30-m IRAM cube
| Python | mit | e-koch/VLA_Lband,e-koch/VLA_Lband | ---
+++
@@ -0,0 +1,52 @@
+
+'''
+Create a cube that is spatially-matched and convolved to the IRAM 30-m
+CO(2-1) cube.
+'''
+
+import os
+from os.path import join as osjoin
+
+from cube_analysis.reprojection import reproject_cube
+from cube_analysis.run_pipe import run_pipeline
+
+from paths import (seventeenB_HI_dat... | |
126893b50e5d72998398dd1c3687fbf102e6b441 | app/feed.py | app/feed.py | #!/usr/bin/python
# Documentation: http://api.mongodb.org/python/
# A python script connecting to a MongoDB given a MongoDB Connection URI.
import sys
import pymongo
import os
### Create seed data
SEED_DATA = [
{
'decade': '1970s',
'artist': 'Debby Boone',
'song': 'You Light Up My Life',... | Set up mongodb addon to heroku app; created a test python script to connect to db | Set up mongodb addon to heroku app; created a test python script to connect to db
| Python | mit | hw3jung/Gucci,hw3jung/Gucci | ---
+++
@@ -0,0 +1,82 @@
+#!/usr/bin/python
+
+# Documentation: http://api.mongodb.org/python/
+# A python script connecting to a MongoDB given a MongoDB Connection URI.
+
+import sys
+import pymongo
+import os
+
+### Create seed data
+
+SEED_DATA = [
+ {
+ 'decade': '1970s',
+ 'artist': 'Debby Boone... | |
905f46ffba7f008a6f290cd5db9060ba62e6d576 | test/test_bezier_direct.py | test/test_bezier_direct.py | from __future__ import division
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
import cocos
from cocos.director import director
from cocos.actions import Bezier
from cocos.sprite import Sprite
import pyglet
from cocos import path
def direct_bezier(p0, p1, p2, p3):
'''G... | Test using bezier going through 4 specific points | Test using bezier going through 4 specific points
| Python | bsd-3-clause | google-code-export/los-cocos,google-code-export/los-cocos | ---
+++
@@ -0,0 +1,73 @@
+from __future__ import division
+
+import sys
+import os
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
+#
+
+
+import cocos
+from cocos.director import director
+from cocos.actions import Bezier
+from cocos.sprite import Sprite
+import pyglet
+
+from cocos import path
+
... | |
470b7313fa9b176fa4492ac9f355acd21542265d | tests/test_lib_fallback.py | tests/test_lib_fallback.py | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patch('tvrenamr.libraries.requests.get', new=invali... | from mock import patch
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
from .mock_requests import initially_bad_xml, invalid_xml
class TestLibrariesFallback(BaseTest):
@patc... | Test library fallback is overridden by setting a library | Test library fallback is overridden by setting a library
| Python | mit | wintersandroid/tvrenamr,ghickman/tvrenamr | ---
+++
@@ -2,6 +2,7 @@
from pytest import raises
from tvrenamr.errors import NoMoreLibrariesException
+from tvrenamr.libraries import TheTvDb, TvRage
from tvrenamr.main import Episode
from .base import BaseTest
@@ -19,3 +20,14 @@
episode = Episode(self._file, '8')
title = self.tv.retrieve_e... |
c41627f6eef6647a2b80e79b7cee860c4455daeb | utils/apply-fixit-edits.py | utils/apply-fixit-edits.py | #!/usr/bin/env python
#===--- apply-fixit-edits.py - Tool for applying edits from .remap files ---===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See htt... | Add a script for picking up all .remap files in a directory and applying the edits therein. | [utils] Add a script for picking up all .remap files in a directory and applying the edits therein.
Swift SVN r31773
| Python | apache-2.0 | deyton/swift,ahoppen/swift,IngmarStein/swift,MukeshKumarS/Swift,johnno1962d/swift,shajrawi/swift,harlanhaskins/swift,gmilos/swift,calebd/swift,austinzheng/swift,arvedviehweger/swift,lorentey/swift,sschiau/swift,codestergit/swift,kperryua/swift,jtbandes/swift,uasys/swift,OscarSwanros/swift,parkera/swift,xedin/swift,jtba... | ---
+++
@@ -0,0 +1,81 @@
+#!/usr/bin/env python
+
+#===--- apply-fixit-edits.py - Tool for applying edits from .remap files ---===#
+#
+# This source file is part of the Swift.org open source project
+#
+# Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
+# Licensed under Apache License v2.0 with Ru... | |
56ce529d115acfa9d7ae7d1cba574c26f68cb955 | py/diameter-of-binary-tree.py | py/diameter-of-binary-tree.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 dfs(self, cur):
if cur:
ldepth = self.dfs(cur.left)
rdepth = self.dfs(cur.right)
... | Add py solution for 543. Diameter of Binary Tree | Add py solution for 543. Diameter of Binary Tree
543. Diameter of Binary Tree: https://leetcode.com/problems/diameter-of-binary-tree/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,27 @@
+# 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 dfs(self, cur):
+ if cur:
+ ldepth = self.dfs(cur.left)
+ ... | |
f01ce359618e66163f280eb386d70e1350addbc6 | py/top-k-frequent-elements.py | py/top-k-frequent-elements.py | import heapq
from operator import itemgetter
from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
c = Counter(nums)
return map(itemgetter(1), heapq.nlargest(k, [(c... | Add py solution for 347. Top K Frequent Elements | Add py solution for 347. Top K Frequent Elements
347. Top K Frequent Elements: https://leetcode.com/problems/top-k-frequent-elements/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,12 @@
+import heapq
+from operator import itemgetter
+from collections import Counter
+class Solution(object):
+ def topKFrequent(self, nums, k):
+ """
+ :type nums: List[int]
+ :type k: int
+ :rtype: List[int]
+ """
+ c = Counter(nums)
+ return m... | |
eb84efd25b8c5e9ba06434ad78c9611b3f8350f0 | every_election/apps/elections/management/commands/add_tags.py | every_election/apps/elections/management/commands/add_tags.py | import json
from django.contrib.gis.gdal import DataSource
from django.core.management import BaseCommand
from django.db.models import Value
from core.mixins import ReadFromFileMixin
from core.models import JsonbSet
from elections.models import Election
def get_layer(data, layer_index=0):
data_source = DataSour... | Add command to add tags to Election model | Add command to add tags to Election model
| Python | bsd-3-clause | DemocracyClub/EveryElection,DemocracyClub/EveryElection,DemocracyClub/EveryElection | ---
+++
@@ -0,0 +1,76 @@
+import json
+
+from django.contrib.gis.gdal import DataSource
+from django.core.management import BaseCommand
+from django.db.models import Value
+
+from core.mixins import ReadFromFileMixin
+from core.models import JsonbSet
+from elections.models import Election
+
+
+def get_layer(data, lay... | |
cac06b93f257afa2760180074a978cffdc05c8c2 | examples/kiwilist.py | examples/kiwilist.py | import gtk
from kiwi.ui.widgets.list import Column, List, SequentialColumn
class Person:
"""The parameters need to be of the same name of the column headers"""
def __init__(self, name, age, city, present):
(self.name, self.age,
self.city, self.present) = name, age, city, present
def __re... | Add a small kiwi list example | Add a small kiwi list example | Python | lgpl-2.1 | stoq/kiwi | ---
+++
@@ -0,0 +1,50 @@
+import gtk
+
+from kiwi.ui.widgets.list import Column, List, SequentialColumn
+
+class Person:
+ """The parameters need to be of the same name of the column headers"""
+ def __init__(self, name, age, city, present):
+ (self.name, self.age,
+ self.city, self.present) = na... | |
dae41df9835a83a71b71b5e4b64561761c404bf5 | mp3-formatter/url_scrape_div.py | mp3-formatter/url_scrape_div.py | #!/usr/bin/python3
# sudo apt-get install python3-pip
# pip3 install requests
import lxml.html
import requests
import sys
def validate_url(url):
if not url:
raise SystemError("validate_url() was given an empty URL")
protocol = "http://"
protocol_error_message = ValueError("A URL beginning with "... | Add script to scrape tracklist from URL | MP3: Add script to scrape tracklist from URL
I didn't do this in separate commits because I had such a rough time
extracting the div I needed from the page.
| Python | mit | jleung51/scripts,jleung51/scripts,jleung51/scripts | ---
+++
@@ -0,0 +1,91 @@
+#!/usr/bin/python3
+
+# sudo apt-get install python3-pip
+# pip3 install requests
+
+import lxml.html
+import requests
+import sys
+
+def validate_url(url):
+ if not url:
+ raise SystemError("validate_url() was given an empty URL")
+
+ protocol = "http://"
+ protocol_error_me... | |
25fb55ed7d90834d36f0f536f4324facbb5db710 | examples/play_tvz.py | examples/play_tvz.py | import sc2
from sc2 import Race
from sc2.player import Human, Bot
from zerg_rush import ZergRushBot
def main():
sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
Human(Race.Terran),
Bot(Race.Zerg, ZergRushBot())
], realtime=True)
if __name__ == '__main__':
main()
| Add TvZ Human vs AI example | Add TvZ Human vs AI example
| Python | mit | Dentosal/python-sc2 | ---
+++
@@ -0,0 +1,14 @@
+import sc2
+from sc2 import Race
+from sc2.player import Human, Bot
+
+from zerg_rush import ZergRushBot
+
+def main():
+ sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
+ Human(Race.Terran),
+ Bot(Race.Zerg, ZergRushBot())
+ ], realtime=True)
+
+if __name__ == '__main__'... | |
b0b4cb81874f4e7d347baaf292b58dad1af6bbb3 | perftest.py | perftest.py | """
Simple peformance tests.
"""
import sys
import time
import couchdb
def main():
print 'sys.version : %r' % (sys.version,)
print 'sys.platform : %r' % (sys.platform,)
tests = [create_doc, create_bulk_docs]
if len(sys.argv) > 1:
tests = [test for test in tests if test.__name__ in sys.argv... | Add a very simple performance testing tool. | Add a very simple performance testing tool.
| Python | bsd-3-clause | erikdejonge/rabshakeh-couchdb-python-progress-attachments | ---
+++
@@ -0,0 +1,59 @@
+"""
+Simple peformance tests.
+"""
+
+import sys
+import time
+
+import couchdb
+
+
+def main():
+
+ print 'sys.version : %r' % (sys.version,)
+ print 'sys.platform : %r' % (sys.platform,)
+
+ tests = [create_doc, create_bulk_docs]
+ if len(sys.argv) > 1:
+ tests = [test f... | |
3c9fc8bbdbbcbca148a3b00c22a0e5fdaa9108aa | perftest.py | perftest.py | """
Simple peformance tests.
"""
import sys
import time
import couchdb
def main():
print 'sys.version : %r' % (sys.version,)
print 'sys.platform : %r' % (sys.platform,)
tests = [create_doc, create_bulk_docs]
if len(sys.argv) > 1:
tests = [test for test in tests if test.__name__ in sys.argv... | Add a very simple performance testing tool. | Add a very simple performance testing tool.
| Python | bsd-3-clause | gcarranza/couchdb-python,jur9526/couchdb-python | ---
+++
@@ -0,0 +1,59 @@
+"""
+Simple peformance tests.
+"""
+
+import sys
+import time
+
+import couchdb
+
+
+def main():
+
+ print 'sys.version : %r' % (sys.version,)
+ print 'sys.platform : %r' % (sys.platform,)
+
+ tests = [create_doc, create_bulk_docs]
+ if len(sys.argv) > 1:
+ tests = [test f... | |
216c9e937263838f126474a0728ed9d43797c3e5 | modify_wpr_delays.py | modify_wpr_delays.py | #!/usr/bin/env python
# TODO(cs): make cache hit ratio tunable.
# TODO(cs): two analyses: perfect cachability at proxy, and perfect
# cachability in browser. Use CC: private vs. CC: public to make distinction.
# TODO(cs): don't assume that cache is co-located with browser, i.e. insert
# delays between browser and perf... | Add a script for fingind cacheable responses and setting their delays to 0 | Add a script for fingind cacheable responses and setting their delays to 0
| Python | apache-2.0 | colin-scott/web-page-replay,colin-scott/web-page-replay | ---
+++
@@ -0,0 +1,75 @@
+#!/usr/bin/env python
+
+# TODO(cs): make cache hit ratio tunable.
+# TODO(cs): two analyses: perfect cachability at proxy, and perfect
+# cachability in browser. Use CC: private vs. CC: public to make distinction.
+# TODO(cs): don't assume that cache is co-located with browser, i.e. insert
... | |
7fea10691b8f8d15e31c30949d15a69e20ee4214 | scripts/identify-unpinned.py | scripts/identify-unpinned.py | import yaml
import glob
for file in glob.glob("*.yaml"):
print("Processing %s" % file)
with open(file, 'r') as handle:
w = yaml.load(handle)
for tool in w['tools']:
print(tool)
if 'changeset_revision' not in tool:
print(tool)
for file in glob.glob("*.yml"):
print("P... | Add script to identify unpinned repos | Add script to identify unpinned repos
| Python | mit | usegalaxy-eu/usegalaxy-eu-tools,usegalaxy-eu/usegalaxy-eu-tools | ---
+++
@@ -0,0 +1,21 @@
+import yaml
+import glob
+for file in glob.glob("*.yaml"):
+ print("Processing %s" % file)
+ with open(file, 'r') as handle:
+ w = yaml.load(handle)
+
+ for tool in w['tools']:
+ print(tool)
+ if 'changeset_revision' not in tool:
+ print(tool)
+
+for ... | |
cd27adc357655e9cd25c5d23a171920addd7c8f5 | jupyter_notebook_config.py | jupyter_notebook_config.py | # Based off of https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rst
import io
import os
from notebook.utils import to_api_path
_script_exporter = None
_html_exporter = None
def script_post_save(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after... | Add script to automatically save py file in jupyter. | Add script to automatically save py file in jupyter.
| Python | bsd-3-clause | daichi-yoshikawa/dnn | ---
+++
@@ -0,0 +1,32 @@
+# Based off of https://github.com/jupyter/notebook/blob/master/docs/source/extending/savehooks.rst
+
+import io
+import os
+from notebook.utils import to_api_path
+
+_script_exporter = None
+_html_exporter = None
+
+def script_post_save(model, os_path, contents_manager, **kwargs):
+ """co... | |
08e7dd7f9e1ee8d9ec57f2ec7b6a68caee1c8f0d | py/number-of-boomerangs.py | py/number-of-boomerangs.py | from collections import Counter
class Solution(object):
def numberOfBoomerangs(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
cs = [Counter() for _ in xrange(len(points))]
for i1, p1 in enumerate(points):
for i2 in range(i1 + 1, len(point... | Add py solution for 447. Number of Boomerangs | Add py solution for 447. Number of Boomerangs
447. Number of Boomerangs: https://leetcode.com/problems/number-of-boomerangs/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,19 @@
+from collections import Counter
+class Solution(object):
+ def numberOfBoomerangs(self, points):
+ """
+ :type points: List[List[int]]
+ :rtype: int
+ """
+ cs = [Counter() for _ in xrange(len(points))]
+ for i1, p1 in enumerate(points):
+ ... | |
1abdf4b669f9d5329c8e0895956af2b0ebf2bfdd | housemarket/housesales/migrations/0001_initial.py | housemarket/housesales/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='HouseSales',
fields=[
('id', models.AutoField(v... | Add initial db migration for HouseSales | Add initial db migration for HouseSales
| Python | mit | andreagrandi/sold-house-prices | ---
+++
@@ -0,0 +1,34 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name='HouseSales',
+ fields=[... | |
645cbafc95f69d9d8d70ce3438d3907fed1024a2 | pyVers/neuralnet.py | pyVers/neuralnet.py |
import numpy as np
class NeuralNEt(object):
def __init__(self, inputs, outputs, *hiddens):
self.shape = [inputs] + list(hiddens) + [outputs]
self.layers = len(self.shape)
self.weights = self.__randInitialize()
def __randInitialize(self):
"""Randomly initializes... | Work begun on neural network class. | Work begun on neural network class.
| Python | mit | m0baxter/tic-tac-toe-AI | ---
+++
@@ -0,0 +1,72 @@
+
+
+import numpy as np
+
+
+class NeuralNEt(object):
+
+ def __init__(self, inputs, outputs, *hiddens):
+
+ self.shape = [inputs] + list(hiddens) + [outputs]
+ self.layers = len(self.shape)
+ self.weights = self.__randInitialize()
+
+ def __randInitiali... | |
453174d7acb9156fda29e4192691ef2d14eda2bb | bookmarks/bookmarks/migrations/0005_rename_app.py | bookmarks/bookmarks/migrations/0005_rename_app.py | from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bookmarks', '0004_auto_20160901_2322'),
]
operations = [
migrations.RunSQL("DROP TABLE bookmarks_bookmark;"),
migrations.RunSQL("ALTER TABLE core_bookmark RENAME TO bookmarks_bookmark;"),
... | Add one-way migration from core to bookmarks | Add one-way migration from core to bookmarks
| Python | mit | tom-henderson/bookmarks,tom-henderson/bookmarks,tom-henderson/bookmarks | ---
+++
@@ -0,0 +1,14 @@
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('bookmarks', '0004_auto_20160901_2322'),
+ ]
+
+ operations = [
+ migrations.RunSQL("DROP TABLE bookmarks_bookmark;"),
+ migrations.RunSQL("ALTER TABLE core_book... | |
206d1d2eb2b1ead51621670dd3341baeb21ae271 | CodeFights/spiralNumbers.py | CodeFights/spiralNumbers.py | #!/usr/local/bin/python
# Code Fights Spiral Numbers Problem
def spiralNumbers(n):
r, c = 0, 0 # Starting location
# Delta for row or column increments: first direction is left to right
dr, dc = 0, 1
spiral = [[0] * n for _ in range(n)]
for i in range(1, n * n + 1):
spiral[r][c] = i
... | Solve Code Fights spiral numbers problem | Solve Code Fights spiral numbers problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,58 @@
+#!/usr/local/bin/python
+# Code Fights Spiral Numbers Problem
+
+
+def spiralNumbers(n):
+ r, c = 0, 0 # Starting location
+ # Delta for row or column increments: first direction is left to right
+ dr, dc = 0, 1
+ spiral = [[0] * n for _ in range(n)]
+ for i in range(1, n * n... | |
dae0ec0b70ed68a5fa6ae29225c4995256f4ec80 | CodeFights/isBeautifulString.py | CodeFights/isBeautifulString.py | #!/usr/local/bin/python
# Code Fights Is Beautiful String Problem
import string
def isBeautifulString(inputString):
keys = string.ascii_lowercase
for i in range(1, len(keys)):
if inputString.count(keys[i]) > inputString.count(keys[i - 1]):
return False
return True
def main():
t... | Solve Code Fights is beautiful string problem | Solve Code Fights is beautiful string problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,42 @@
+#!/usr/local/bin/python
+# Code Fights Is Beautiful String Problem
+
+import string
+
+
+def isBeautifulString(inputString):
+ keys = string.ascii_lowercase
+ for i in range(1, len(keys)):
+ if inputString.count(keys[i]) > inputString.count(keys[i - 1]):
+ return Fals... | |
f53e12b1e3d939d1c98037589da81c459a61616f | papermill/tests/test_hdfs.py | papermill/tests/test_hdfs.py | import unittest
from unittest.mock import MagicMock, patch
from ..iorw import HDFSHandler
class MockHadoopFileSystem(MagicMock):
def ls(self, path):
return ['test1.ipynb', 'test2.ipynb']
def open(self, path, *args):
return MockHadoopFile()
class MockHadoopFile(object):
def __init__(sel... | Add test for hdfs handler | Add test for hdfs handler
| Python | bsd-3-clause | nteract/papermill,nteract/papermill | ---
+++
@@ -0,0 +1,52 @@
+import unittest
+from unittest.mock import MagicMock, patch
+
+from ..iorw import HDFSHandler
+
+
+class MockHadoopFileSystem(MagicMock):
+ def ls(self, path):
+ return ['test1.ipynb', 'test2.ipynb']
+
+ def open(self, path, *args):
+ return MockHadoopFile()
+
+
+class Mo... | |
b5c9fffab5d0c2082d0fcd55967e033272c36acc | flickrest.py | flickrest.py | import md5, urllib
from twisted.internet import defer
from twisted.web import client
from elementtree import ElementTree
class FlickREST:
endpoint = "http://api.flickr.com/services/rest/?"
def __init__(self, api_key, secret, perms="read"):
self.api_key = api_key
self.secret = secret
... | Add prototype and incomplete REST interface | Add prototype and incomplete REST interface | Python | lgpl-2.1 | rossburton/flickrest | ---
+++
@@ -0,0 +1,45 @@
+import md5, urllib
+from twisted.internet import defer
+from twisted.web import client
+from elementtree import ElementTree
+
+class FlickREST:
+ endpoint = "http://api.flickr.com/services/rest/?"
+
+ def __init__(self, api_key, secret, perms="read"):
+ self.api_key = api_ke... | |
0343ecb6bbc239a3e2542cbb0257f66bfb34a2b1 | tests/test_rietveld.py | tests/test_rietveld.py | from __future__ import absolute_import, print_function
import unittest
import os
from addie.addiedriver import AddieDriver
from tests import DATA_DIR
TOF = 'TOF'
D_SPACING = 'dSpacing'
Q_SPACE = 'MomentumTransfer'
class BraggData(unittest.TestCase):
def setUp(self):
self.filename = os.path.join(DATA_DIR... | Add unit tests for loading gsas data | Add unit tests for loading gsas data
| Python | mit | neutrons/FastGR,neutrons/FastGR,neutrons/FastGR | ---
+++
@@ -0,0 +1,55 @@
+from __future__ import absolute_import, print_function
+import unittest
+import os
+
+from addie.addiedriver import AddieDriver
+from tests import DATA_DIR
+
+TOF = 'TOF'
+D_SPACING = 'dSpacing'
+Q_SPACE = 'MomentumTransfer'
+
+
+class BraggData(unittest.TestCase):
+ def setUp(self):
+ ... | |
ade6ab718b6fe29808e37aa9b852d502cc033980 | haml/util.py | haml/util.py |
def extract_haml(fileobj, keywords, comment_tags, options):
""" babel translation token extract function for haml files """
import haml
from mako import lexer, parsetree
from mako.ext.babelplugin import extract_nodes
encoding = options.get('input_encoding', options.get('encoding', None))
te... | Add babel translation string extractor function | Add babel translation string extractor function
haml.util.extract_haml adds ability for babel to
recognize and extract gettext translation tokens from haml files
| Python | bsd-3-clause | mikeboers/PyHAML | ---
+++
@@ -0,0 +1,14 @@
+
+
+def extract_haml(fileobj, keywords, comment_tags, options):
+ """ babel translation token extract function for haml files """
+
+ import haml
+ from mako import lexer, parsetree
+ from mako.ext.babelplugin import extract_nodes
+
+ encoding = options.get('input_encoding', ... | |
87179a4c040400aa7f5cc868744ffd298920caa6 | scripts/data_download/secex/create_all_files.py | scripts/data_download/secex/create_all_files.py | import os
import commands
import time
import logging
import sys
if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
print "ERROR! Use:\n python scripts/data_download/secex/create_files.py en/pt output_path\n"
exit()
logging.basicConfig(filename=os.path.abspath(os.path.join(sys.argv[2],str(sys.argv... | Add file to create all files to secex. | Add file to create all files to secex.
| Python | mit | DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site | ---
+++
@@ -0,0 +1,16 @@
+import os
+import commands
+import time
+import logging
+import sys
+
+if len(sys.argv) != 3 or (sys.argv[1:][0] not in ['pt', 'en']):
+ print "ERROR! Use:\n python scripts/data_download/secex/create_files.py en/pt output_path\n"
+ exit()
+
+logging.basicConfig(filename=os.path.abspath... | |
ce7994e255cd83d84259c369d1823aa7ac8c30cd | sahara/tests/unit/plugins/cdh/test_versionfactory.py | sahara/tests/unit/plugins/cdh/test_versionfactory.py | # Copyright (c) 2015 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Add test cases for CDH plugin versionfactory | Add test cases for CDH plugin versionfactory
Changes:
* add test cases for CDH plugin versionfactory
* add a function to get supported versions into utils
partially implements bp: cdh-plugin-refactoring
Change-Id: I3b60c65ab8a6bb7c296b2a8a1ebbfd4bacfbe6b4
| Python | apache-2.0 | openstack/sahara,egafford/sahara,tellesnobrega/sahara,openstack/sahara,tellesnobrega/sahara,egafford/sahara | ---
+++
@@ -0,0 +1,43 @@
+# Copyright (c) 2015 Mirantis Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by... | |
32bb59d990a00a288c083d23a32b179e61486aff | generic/test_client.py | generic/test_client.py | # Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | Fix discover command failed to read extension list issue | Fix discover command failed to read extension list issue
Fix the key error which caused discover command failed to read the
response body of extension list result. This change also added test
cases to cover the use case of generic client extension discovery.
Change-Id: Id687f8d73cead28f594de00d3b5ff9086558947b
Closes... | Python | apache-2.0 | varunarya10/keystonemiddleware | ---
+++
@@ -0,0 +1,67 @@
+# Copyright 2014 OpenStack Foundation
+# All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/lice... | |
e0fe2901e699ed4ac8ded58fed0793c495eec02e | conftest.py | conftest.py | # -*- coding: utf-8 -*-
import pytest
import os
import json
@pytest.fixture(scope="class",
params=os.listdir('test_fixtures'))
def story(request):
"""
Provides a detailed HPACK story to test with.
"""
path = os.path.join('test_fixtures', request.param)
with open(path, 'r', encoding=... | Create a py.test fixture to use the new stories. | Create a py.test fixture to use the new stories.
| Python | mit | plucury/hyper,masaori335/hyper,lawnmowerlatte/hyper,fredthomsen/hyper,irvind/hyper,jdecuyper/hyper,jdecuyper/hyper,masaori335/hyper,Lukasa/hyper,lawnmowerlatte/hyper,irvind/hyper,Lukasa/hyper,fredthomsen/hyper,plucury/hyper | ---
+++
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+import pytest
+import os
+import json
+
+@pytest.fixture(scope="class",
+ params=os.listdir('test_fixtures'))
+def story(request):
+ """
+ Provides a detailed HPACK story to test with.
+ """
+ path = os.path.join('test_fixtures', request.pa... | |
c694a5a5e5ba9403eeca57feb9fd21edccd95132 | scripts/get_bank_registry_hr.py | scripts/get_bank_registry_hr.py | #!/usr/bin/env python
import json
import xlrd
import requests
URL = (
"https://www.hnb.hr/documents/20182/121798/tf-pp-ds-vbb-xlsx-e-vbb.xlsx/"
"06982c63-13e3-4aa0-846d-afb7956ee731"
)
def process():
registry = []
book = xlrd.open_workbook(file_contents=requests.get(URL).content)
sheet = book.sh... | Add script to generate HR bic code registry | Add script to generate HR bic code registry
| Python | mit | figo-connect/schwifty | ---
+++
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+import json
+import xlrd
+import requests
+
+URL = (
+ "https://www.hnb.hr/documents/20182/121798/tf-pp-ds-vbb-xlsx-e-vbb.xlsx/"
+ "06982c63-13e3-4aa0-846d-afb7956ee731"
+)
+
+
+def process():
+ registry = []
+
+ book = xlrd.open_workbook(file_contents=requ... | |
bf059b8b781c786edb4b3ca7ef838e9b4d16d3a0 | tests/commands/test_lib.py | tests/commands/test_lib.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from os import listdir
from os.path import isdir, isfile, join
import re
from click.testing import CliRunner
from platformio.commands.lib import cli
from platformio import util
runner = CliRunner()
def validate_output(result):
assert r... | Cover "lib" commands with tests | Cover "lib" commands with tests
| Python | apache-2.0 | awong1900/platformio,platformio/platformio,ZachMassia/platformio,mplewis/platformio,bkudria/platformio,platformio/platformio-core,jrobeson/platformio,TimJay/platformio,jrobeson/platformio,valeros/platformio,atyenoria/platformio,jrobeson/platformio,bkudria/platformio,TimJay/platformio,mcanthony/platformio,mseroczynski/p... | ---
+++
@@ -0,0 +1,74 @@
+# Copyright (C) Ivan Kravets <me@ikravets.com>
+# See LICENSE for details.
+
+from os import listdir
+from os.path import isdir, isfile, join
+
+import re
+
+from click.testing import CliRunner
+
+from platformio.commands.lib import cli
+from platformio import util
+
+runner = CliRunner()
+
... | |
c9f2fcdb62856f112a17a51020c9cb215bb8620c | tests/test_gitlab_local.py | tests/test_gitlab_local.py | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import os
import pytest
import contextlib
pytestmark = [pytest.mark.asyncio,
pytest.mark.skipif(os.environ.get('TRAVIS') == 'true',
reason="rate-limited per IP")]
@contextlib.contextmanager
de... | Add local test for over limit check | tests: Add local test for over limit check
Signed-off-by: Xuanwo <60f7302bde66b4a81d2f70acbeb96280e4013e10@gmail.com>
| Python | mit | lilydjwg/nvchecker | ---
+++
@@ -0,0 +1,38 @@
+# MIT licensed
+# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
+
+import os
+import pytest
+import contextlib
+pytestmark = [pytest.mark.asyncio,
+ pytest.mark.skipif(os.environ.get('TRAVIS') == 'true',
+ reason="rate-limited per ... | |
3653ad1320d7624aa798d67031827056ddf64efd | pontoon/base/migrations/0095_pontoon_intro_permalink_prefix.py | pontoon/base/migrations/0095_pontoon_intro_permalink_prefix.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-28 23:15
from __future__ import unicode_literals
from django.db import migrations
def load_initial_data(apps, schema_editor):
Project = apps.get_model('base', 'Project')
repository = Project.objects.get(slug="pontoon-intro").repositories.first()... | Add required field data for the initial project | Add required field data for the initial project
The permalink_prefix field has been add to the Repository object and
made required, but we never added a data migration to populate it for
the initial project (Pontoon Intro). So let's do this now.
| Python | bsd-3-clause | mathjazz/pontoon,mathjazz/pontoon,jotes/pontoon,mozilla/pontoon,mastizada/pontoon,mozilla/pontoon,mastizada/pontoon,mastizada/pontoon,mozilla/pontoon,mastizada/pontoon,jotes/pontoon,mozilla/pontoon,jotes/pontoon,mathjazz/pontoon,jotes/pontoon,mozilla/pontoon,mathjazz/pontoon,mathjazz/pontoon | ---
+++
@@ -0,0 +1,25 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.7 on 2017-07-28 23:15
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def load_initial_data(apps, schema_editor):
+ Project = apps.get_model('base', 'Project')
+ repository = Project.objects.get(slug=... | |
c26498c9295ffca534d42d80d7d22e53c19822b2 | byceps/typing.py | byceps/typing.py | """
byceps.typing
~~~~~~~~~~~~~
BYCEPS-specific type aliases for PEP 484 type hints
:Copyright: 2006-2017 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from uuid import UUID
UserID = UUID
BrandID = str
PartyID = str
| Add module with BYCEPS-specific types for PEP 484 type hints | Add module with BYCEPS-specific types for PEP 484 type hints
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | ---
+++
@@ -0,0 +1,18 @@
+"""
+byceps.typing
+~~~~~~~~~~~~~
+
+BYCEPS-specific type aliases for PEP 484 type hints
+
+:Copyright: 2006-2017 Jochen Kupperschmidt
+:License: Modified BSD, see LICENSE for details.
+"""
+
+from uuid import UUID
+
+
+UserID = UUID
+
+BrandID = str
+
+PartyID = str | |
bf897cd1ee43cf970dc9b0b955db0c8c3a2dbbe4 | src/nodeconductor_openstack/tests/test_instance.py | src/nodeconductor_openstack/tests/test_instance.py | from rest_framework import status, test
from nodeconductor.structure.models import CustomerRole
from nodeconductor.structure.tests import factories as structure_factories
from ..apps import OpenStackConfig
from . import factories
class InstanceProvisionTest(test.APITransactionTestCase):
def setUp(self):
... | Add unit tests for provisioning instance with floating IP (NC-1470) | Add unit tests for provisioning instance with floating IP (NC-1470)
| Python | mit | opennode/nodeconductor-openstack | ---
+++
@@ -0,0 +1,65 @@
+from rest_framework import status, test
+
+from nodeconductor.structure.models import CustomerRole
+from nodeconductor.structure.tests import factories as structure_factories
+
+from ..apps import OpenStackConfig
+from . import factories
+
+
+class InstanceProvisionTest(test.APITransactionTe... | |
3bf6d6e13f7611b127582ab862d46228b2164a95 | st2common/bin/migrations/v2.1/st2-migrate-runners.py | st2common/bin/migrations/v2.1/st2-migrate-runners.py | #!/usr/bin/env python
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License... | Add migration script to register runners | Add migration script to register runners
| Python | apache-2.0 | peak6/st2,nzlosh/st2,Plexxi/st2,peak6/st2,tonybaloney/st2,StackStorm/st2,Plexxi/st2,tonybaloney/st2,lakshmi-kannan/st2,pixelrebel/st2,StackStorm/st2,nzlosh/st2,StackStorm/st2,lakshmi-kannan/st2,tonybaloney/st2,Plexxi/st2,pixelrebel/st2,pixelrebel/st2,nzlosh/st2,lakshmi-kannan/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2,pe... | ---
+++
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+# Licensed to the StackStorm, Inc ('StackStorm') under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache Lice... | |
5d741bb4a0f0cdab21a23951507e42b257acc2a6 | examples/timer_spinner.py | examples/timer_spinner.py | # -*- coding: utf-8 -*-
"""
examples.timer_spinner
~~~~~~~~~~~~~~~~~~~~~~
Show elapsed time at the end of the line.
"""
import time
from yaspin import yaspin
def main():
with yaspin(text="elapsed time", timer=True) as sp:
# Floats are rounded into two decimal digits in timer output
time.sleep(... | Add usage example for timer feature | Add usage example for timer feature
| Python | mit | pavdmyt/yaspin | ---
+++
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+
+"""
+examples.timer_spinner
+~~~~~~~~~~~~~~~~~~~~~~
+
+Show elapsed time at the end of the line.
+"""
+
+import time
+
+from yaspin import yaspin
+
+
+def main():
+ with yaspin(text="elapsed time", timer=True) as sp:
+ # Floats are rounded into two decima... | |
4223ed495639650a1b2ffdbc76546c8cbb7cc90f | moksha/tests/quickstarts/test_consumer.py | moksha/tests/quickstarts/test_consumer.py | import inspect
import pkg_resources
from datetime import timedelta
from moksha.api.hub import Consumer
from moksha.pastetemplate import MokshaConsumerTemplate
from base import QuickstartTester
class TestConsumerQuickstart(QuickstartTester):
def __init__(self,**options):
self.app = None
self.tem... | Add some tests for our consumer quickstart | Add some tests for our consumer quickstart
| Python | apache-2.0 | pombredanne/moksha,ralphbean/moksha,lmacken/moksha,mokshaproject/moksha,mokshaproject/moksha,ralphbean/moksha,lmacken/moksha,pombredanne/moksha,lmacken/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,pombredanne/moksha | ---
+++
@@ -0,0 +1,56 @@
+import inspect
+import pkg_resources
+
+from datetime import timedelta
+
+from moksha.api.hub import Consumer
+from moksha.pastetemplate import MokshaConsumerTemplate
+
+from base import QuickstartTester
+
+class TestConsumerQuickstart(QuickstartTester):
+
+ def __init__(self,**options):
... | |
6f74d7d1b95eb2b4b2b07e48fab7d935069a9c7c | generate-upload-stream.py | generate-upload-stream.py | #!/usr/bin/env python3
import fileinput
import hashlib
import itertools
import random
import re
import sys
import timer
import utils
"""
Generates an upload request stream from the data collected by file_counts.py.
The input is read from stdin and the compact, binary output is written to
stdout.
Usage:
cat <FILE_P... | Add script for generating upload request stream | Add script for generating upload request stream
| Python | apache-2.0 | sjakthol/dedup-simulator,sjakthol/dedup-simulator | ---
+++
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+
+import fileinput
+import hashlib
+import itertools
+import random
+import re
+import sys
+import timer
+import utils
+
+"""
+Generates an upload request stream from the data collected by file_counts.py.
+The input is read from stdin and the compact, binary output is... | |
27cc2a5fb13a9a45fd8af3b8bee1d0c66b7c8d91 | cardinal/test_decorators.py | cardinal/test_decorators.py | import pytest
import decorators
def test_command():
# ensure commands is a list with foo added
@decorators.command('foo')
def foo():
pass
assert foo.commands == ['foo']
# test that you can pass a list
@decorators.command(['foo', 'bar'])
def foo():
pass
assert foo.com... | Add first unit test using py.test | Add first unit test using py.test
Tests Cardinal's decorators
| Python | mit | BiohZn/Cardinal,JohnMaguire/Cardinal | ---
+++
@@ -0,0 +1,82 @@
+import pytest
+
+import decorators
+
+def test_command():
+ # ensure commands is a list with foo added
+ @decorators.command('foo')
+ def foo():
+ pass
+
+ assert foo.commands == ['foo']
+
+ # test that you can pass a list
+ @decorators.command(['foo', 'bar'])
+ d... | |
4ba1ea670b208a734aa3f36c694b20e4bb5d6dda | alembic/versions/14ef1fe33bd_add_checkpoint_evaluation_table.py | alembic/versions/14ef1fe33bd_add_checkpoint_evaluation_table.py | """Add checkpoint_evaluation table
Revision ID: 14ef1fe33bd
Revises: 3d0a468b38f
Create Date: 2015-07-10 02:35:06.655075
"""
# revision identifiers, used by Alembic.
revision = '14ef1fe33bd'
down_revision = '3d0a468b38f'
branch_labels = None
depends_on = None
from alembic import op
from bnd.models import Checkpoint... | Write an Alembic migration script | Write an Alembic migration script
| Python | mit | suminb/bnd,suminb/bnd,suminb/bnd | ---
+++
@@ -0,0 +1,31 @@
+"""Add checkpoint_evaluation table
+
+Revision ID: 14ef1fe33bd
+Revises: 3d0a468b38f
+Create Date: 2015-07-10 02:35:06.655075
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '14ef1fe33bd'
+down_revision = '3d0a468b38f'
+branch_labels = None
+depends_on = None
+
+from alembic i... | |
d0ac9b735694220f9d101358da1e51a335fad284 | smap-nepse/preprocessing/l1_regularization.py | smap-nepse/preprocessing/l1_regularization.py | import numpy as np
import pandas as pd
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("NABIL.csv")
df.drop(df.columns[[0,1,9,13,14]], axis=1, inplace=True)
#print(df.columns)
df.drop(df.index[:19],inplace=True)
scaler = StandardScaler()
#df['Price']=df['... | Select features using l1 regularization | Select features using l1 regularization
| Python | mit | samshara/Stock-Market-Analysis-and-Prediction | ---
+++
@@ -0,0 +1,31 @@
+import numpy as np
+import pandas as pd
+
+from sklearn.linear_model import Lasso
+
+from sklearn.preprocessing import StandardScaler
+
+
+
+
+df = pd.read_csv("NABIL.csv")
+df.drop(df.columns[[0,1,9,13,14]], axis=1, inplace=True)
+#print(df.columns)
+df.drop(df.index[:19],inplace=True)
+sc... | |
899d432b87397368f53010493a3cd67506bbe5a5 | hooks/post_gen_project.py | hooks/post_gen_project.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('post_gen_project')
import shutil
import os
{% if cookiecutter.docs_tool == "mkdocs" %}
logger.info('Moving files for mkdocs.')
os.rename('mkdocs/mkdocs.yml', 'mkdocs.yml')
shutil.move('... | Implement a post gen hook to rename mkdocs files | Implement a post gen hook to rename mkdocs files
| Python | mit | pytest-dev/cookiecutter-pytest-plugin,luzfcb/cookiecutter-pytest-plugin,s0undt3ch/cookiecutter-pytest-plugin | ---
+++
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import logging
+logging.basicConfig(level=logging.DEBUG)
+logger = logging.getLogger('post_gen_project')
+
+import shutil
+import os
+
+
+{% if cookiecutter.docs_tool == "mkdocs" %}
+
+logger.info('Moving files for mkdocs.')
+os.rename('mkdoc... | |
0b8dc2afb3b3b9b9988e04586ca6c732cd4c7b98 | test/misc/test_commands.py | test/misc/test_commands.py | import json
import datetime
from simplekv import fs
from test.base import ApiTestCase
from zou.app.utils import commands
def totimestamp(dt, epoch=datetime.datetime(1970, 1, 1)):
td = dt - epoch
return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6
class CommandsTestCase(ApiTestCase):... | Add tests for commands module | Add tests for commands module
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -0,0 +1,63 @@
+import json
+import datetime
+
+from simplekv import fs
+
+from test.base import ApiTestCase
+
+from zou.app.utils import commands
+
+
+def totimestamp(dt, epoch=datetime.datetime(1970, 1, 1)):
+ td = dt - epoch
+ return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**... | |
71723aecd5466dc7ad9bd27b2f1d2d267e695ff5 | tests/test_kernel_execution.py | tests/test_kernel_execution.py | from parcels import Grid, ScipyParticle, JITParticle, KernelOp
import numpy as np
import pytest
ptype = {'scipy': ScipyParticle, 'jit': JITParticle}
def DoNothing(particle, grid, time, dt):
return KernelOp.SUCCESS
@pytest.fixture
def grid(xdim=20, ydim=20):
""" Standard unit mesh grid """
lon = np.lin... | Add test to verify timestepping and endtimes after execute | Particle: Add test to verify timestepping and endtimes after execute
| Python | mit | OceanPARCELS/parcels,OceanPARCELS/parcels | ---
+++
@@ -0,0 +1,58 @@
+from parcels import Grid, ScipyParticle, JITParticle, KernelOp
+import numpy as np
+import pytest
+
+
+ptype = {'scipy': ScipyParticle, 'jit': JITParticle}
+
+
+def DoNothing(particle, grid, time, dt):
+ return KernelOp.SUCCESS
+
+
+@pytest.fixture
+def grid(xdim=20, ydim=20):
+ """ St... | |
ad9f701c9e601a0678ee92e980a15bdbd8d18828 | src/metamodels/nig_normal.py | src/metamodels/nig_normal.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, MIT Probabilistic Computing Project
#
# 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... | Add a starting skeleton for NIG-Normal, by copying IID-Normal, mutatis mutandis. | Add a starting skeleton for NIG-Normal, by copying IID-Normal, mutatis mutandis.
| Python | apache-2.0 | probcomp/bayeslite,probcomp/bayeslite | ---
+++
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2015, MIT Probabilistic Computing Project
+#
+# 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:/... | |
46c17b1aeba9b4928df0c9f0c9057e5bbaf77378 | dp/lcs.py | dp/lcs.py | def lcslen(x, y):
# Allocate extra row and column for the empty sequence case.
# Extra row and column is appended to the end and exploit
# Python's ability of negative indices: x[-1] is the last elem.
c = [[0 for _ in range(len(y) + 1)] for _ in range(len(x) + 1)]
for i, xi in enumerate(x):
... | Add Longest Common Subsequent implementation | Add Longest Common Subsequent implementation
| Python | mit | dzeban/cs,dzeban/cs,dzeban/cs,dzeban/cs | ---
+++
@@ -0,0 +1,28 @@
+def lcslen(x, y):
+ # Allocate extra row and column for the empty sequence case.
+ # Extra row and column is appended to the end and exploit
+ # Python's ability of negative indices: x[-1] is the last elem.
+ c = [[0 for _ in range(len(y) + 1)] for _ in range(len(x) + 1)]
+
+ ... | |
db45d34db6e4c14be226f33a383a4034cc6f7048 | lib/utils.py | lib/utils.py | import re
def find_memtions(content):
regex = re.compile(r"@(?P<username>)(\s|$)", re.I)
return [m.group("username") for m in regex.finditer(content)]
| Add the method for finding names using regular expression matching. | Add the method for finding names using regular expression matching.
| Python | mit | yiyangyi/cc98-tornado | ---
+++
@@ -0,0 +1,6 @@
+import re
+
+def find_memtions(content):
+ regex = re.compile(r"@(?P<username>)(\s|$)", re.I)
+ return [m.group("username") for m in regex.finditer(content)]
+ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.