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 |
|---|---|---|---|---|---|---|---|---|---|---|
59372a01d2178616796379f4fe1cb76d9083eced | babybuddy/migrations/0020_update_language_en_to_en_us.py | babybuddy/migrations/0020_update_language_en_to_en_us.py | # Generated by Django 3.2.9 on 2021-12-13 21:25
from django.db import migrations
def update_language_en_to_en_us(apps, schema_editor):
Settings = apps.get_model('babybuddy', 'Settings')
for settings in Settings.objects.all():
if settings.language == 'en':
settings.language = 'en-US'
... | Add migration for `en` to `en-US` language setting | Add migration for `en` to `en-US` language setting
Fixes #337
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy | ---
+++
@@ -0,0 +1,30 @@
+# Generated by Django 3.2.9 on 2021-12-13 21:25
+
+from django.db import migrations
+
+
+def update_language_en_to_en_us(apps, schema_editor):
+ Settings = apps.get_model('babybuddy', 'Settings')
+ for settings in Settings.objects.all():
+ if settings.language == 'en':
+ ... | |
e4eee76998a6dc957889d4cf6d5750303bca0968 | numba-plsa/numba-plsa.py | numba-plsa/numba-plsa.py | import numpy as np
def normalize_basic(p):
p /= p.sum(axis=p.size[-1], keepdims=True)
def plsa(doc_term, n_topics, n_iter, method='basic'):
# Get size
n_docs, n_terms = doc_term.size
# Initialize distributions
topic_doc = np.random.rand(n_docs, n_topics)
normalize_basic(topic_doc)
term_t... | Add basic numpy pLSA implementation | Add basic numpy pLSA implementation
| Python | mit | henryre/numba-plsa | ---
+++
@@ -0,0 +1,51 @@
+import numpy as np
+
+def normalize_basic(p):
+ p /= p.sum(axis=p.size[-1], keepdims=True)
+
+def plsa(doc_term, n_topics, n_iter, method='basic'):
+ # Get size
+ n_docs, n_terms = doc_term.size
+
+ # Initialize distributions
+ topic_doc = np.random.rand(n_docs, n_topics)
+ ... | |
459cdc5c8f11510bd30f4a6553759bd778ad559f | mrequests/examples/get_deflate.py | mrequests/examples/get_deflate.py | import zlib
import mrequests as requests
host = "http://httpbin.org/"
#host = "http://localhost/"
url = host + "deflate"
r = requests.get(url, headers={"TE": "deflate"})
if r.status_code == 200:
print("Response body length: %i" % len(r.content))
text = zlib.decompress(r.content).decode("utf-8")
print("De... | Add example script for 'deflate' transfer encoding | Add example script for 'deflate' transfer encoding
Signed-off-by: Christopher Arndt <711c73f64afdce07b7e38039a96d2224209e9a6c@chrisarndt.de>
| Python | mit | SpotlightKid/micropython-stm-lib | ---
+++
@@ -0,0 +1,19 @@
+import zlib
+import mrequests as requests
+
+
+host = "http://httpbin.org/"
+#host = "http://localhost/"
+url = host + "deflate"
+r = requests.get(url, headers={"TE": "deflate"})
+
+if r.status_code == 200:
+ print("Response body length: %i" % len(r.content))
+ text = zlib.decompress(r... | |
baccda23c78fe8d4ec52ed3d912742f62b163aa5 | osf/migrations/0130_merge_20180913_1438.py | osf/migrations/0130_merge_20180913_1438.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-09-13 14:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('osf', '0129_merge_20180910_1926'),
('osf', '0129_merge_20180906_2006'),
]
operatio... | Add mergemigration for recent update with develop | Add mergemigration for recent update with develop
| Python | apache-2.0 | Johnetordoff/osf.io,felliott/osf.io,Johnetordoff/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,pattisdr/osf.io,baylee-d/osf.io,mattclark/osf.io,baylee-d/osf.io,CenterForOpenScience/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,felliott/osf.io,mfraezz/osf.io,adlius/osf.io,aaxelb/osf.... | ---
+++
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.13 on 2018-09-13 14:38
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('osf', '0129_merge_20180910_1926'),
+ ('osf', '0129_mer... | |
de08545d699d2be9c1ee917bd208364ff902138b | wagtail/tests/testapp/migrations/0022_pagewithexcludedcopyfield.py | wagtail/tests/testapp/migrations/0022_pagewithexcludedcopyfield.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-02 01:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0040_page_draft_title'),
('tests', '... | Add testapp migratin for PageWithExcludedCopyField | Add testapp migratin for PageWithExcludedCopyField
| Python | bsd-3-clause | mikedingjan/wagtail,kaedroho/wagtail,mikedingjan/wagtail,wagtail/wagtail,timorieber/wagtail,kaedroho/wagtail,torchbox/wagtail,gasman/wagtail,mixxorz/wagtail,mixxorz/wagtail,thenewguy/wagtail,nealtodd/wagtail,mixxorz/wagtail,gasman/wagtail,wagtail/wagtail,nealtodd/wagtail,mikedingjan/wagtail,thenewguy/wagtail,takeflight... | ---
+++
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.6 on 2017-11-02 01:03
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('wagtailcore', '0040_... | |
85373313233dfad0183d52ba44235a5131cc0f7d | readthedocs/builds/migrations/0016_migrate_protected_versions_to_hidden.py | readthedocs/builds/migrations/0016_migrate_protected_versions_to_hidden.py | # Generated by Django 2.2.11 on 2020-03-18 18:27
from django.db import migrations
def forwards_func(apps, schema_editor):
"""Migrate all protected versions to be hidden."""
Version = apps.get_model('builds', 'Version')
Version.objects.filter(privacy_level='protected').update(hidden=True)
class Migratio... | Migrate protected versions to be hidden | Migrate protected versions to be hidden
| Python | mit | rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org | ---
+++
@@ -0,0 +1,20 @@
+# Generated by Django 2.2.11 on 2020-03-18 18:27
+
+from django.db import migrations
+
+
+def forwards_func(apps, schema_editor):
+ """Migrate all protected versions to be hidden."""
+ Version = apps.get_model('builds', 'Version')
+ Version.objects.filter(privacy_level='protected').... | |
3cbd840a96628282e8ab99c2dc2cf4e7e711fa82 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/views.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/views.py | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView, RedirectView, UpdateView
User = get_user_model... | from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import DetailView, RedirectView, UpdateView
User = get_user_model... | Use self.request.user instead of second query | Use self.request.user instead of second query | Python | bsd-3-clause | trungdong/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-djang... | ---
+++
@@ -27,7 +27,7 @@
return reverse("users:detail", kwargs={"username": self.request.user.username})
def get_object(self):
- return User.objects.get(username=self.request.user.username)
+ return self.request.user
def form_valid(self, form):
messages.add_message( |
1d1627a98d206f002afaa4595ad6c8f332bc1e31 | tests/unit/utils/test_utils.py | tests/unit/utils/test_utils.py | # coding=utf-8
'''
Test case for utils/__init__.py
'''
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
try:
import pytest
except ImportError:
pytest = None
import salt.utils
@skipIf(pytest is None, 'PyTest is missing... | Add test case init commit | Add test case init commit
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,31 @@
+# coding=utf-8
+'''
+Test case for utils/__init__.py
+'''
+from tests.support.unit import TestCase, skipIf
+from tests.support.mock import (
+ NO_MOCK,
+ NO_MOCK_REASON,
+ MagicMock,
+ patch
+)
+
+try:
+ import pytest
+except ImportError:
+ pytest = None
+import salt.utils
... | |
e03bc6a462eca76a0b963a9c01b72aa474d6dd68 | scripts/different_features.py | scripts/different_features.py | # different_features.py
# Invoke on the command line like: python common_features.py pbtd aui
# Creates a set of features common to both groups and then outputs the
# difference between these sets.
from tabulate import tabulate
import csv
import sys
import os.path as path
base_directory = path.dirname(path.dirname(p... | Add script to isolate differences between two groups of segments | Add script to isolate differences between two groups of segments
| Python | mit | kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve | ---
+++
@@ -0,0 +1,67 @@
+# different_features.py
+# Invoke on the command line like: python common_features.py pbtd aui
+# Creates a set of features common to both groups and then outputs the
+# difference between these sets.
+
+
+from tabulate import tabulate
+import csv
+import sys
+import os.path as path
+
+base_... | |
c23c9d562fc7f3fb99b1f57832db2efd2441d992 | new_equation.py | new_equation.py | #! /usr/bin/env python
from __future__ import print_function
import datetime
import os
import sys
import json
import uuid
if len(sys.argv) > 1:
sys.stderr.write("Usage: python "+sys.argv[0]+" 'command-invocation'"+'\n')
sys.exit(1)
def get_year():
now = datetime.datetime.now()
return now.year
def ge... | Add an equation generator script. | Add an equation generator script.
| Python | mit | nbeaver/equajson | ---
+++
@@ -0,0 +1,91 @@
+#! /usr/bin/env python
+from __future__ import print_function
+
+import datetime
+import os
+import sys
+import json
+import uuid
+
+if len(sys.argv) > 1:
+ sys.stderr.write("Usage: python "+sys.argv[0]+" 'command-invocation'"+'\n')
+ sys.exit(1)
+
+def get_year():
+ now = datetime.... | |
374117742479ce7d0d31a5c059faa94a94a8b398 | gv.py | gv.py | #!/usr/bin/python
import sys
import argparse
from graphviz import Digraph
parser = argparse.ArgumentParser(
description="Generates a GraphViz file from *.graph and *.data files."
)
parser.add_argument("--data", type=argparse.FileType("r"),
help="Data input file.")
parser.add_argument("--graph", type=argpa... | Add script to generate GraphViz files from .graph and .data files. | Add script to generate GraphViz files from .graph and .data files.
| Python | mit | ucsb-igert/slice-tree,ucsb-igert/slice-tree,ucsb-igert/slice-tree,ucsb-igert/slice-tree | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/python
+
+import sys
+import argparse
+from graphviz import Digraph
+
+parser = argparse.ArgumentParser(
+ description="Generates a GraphViz file from *.graph and *.data files."
+ )
+parser.add_argument("--data", type=argparse.FileType("r"),
+ help="Data input file.")
+pa... | |
cd61764cfd3f8cd188a2650508fe3216a231d5a7 | plugins/misc.py | plugins/misc.py | # Copyright (c) 2013-2014 Molly White
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use, copy, modify, merge, publish,
# di... | Allow command settings to be saved | Allow command settings to be saved
| Python | mit | molly/GorillaBot,quanticle/GorillaBot,molly/GorillaBot,quanticle/GorillaBot | ---
+++
@@ -0,0 +1,28 @@
+# Copyright (c) 2013-2014 Molly White
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+# and associated documentation files (the "Software"), to deal in the Software without
+# restriction, including without limitation the rights to use, co... | |
da71a95586f17de48cb1067a8809da1e583b42cf | other/wrapping-cpp/swig/cpointerproblem/test_examples.py | other/wrapping-cpp/swig/cpointerproblem/test_examples.py | """
The code this example is all based on is from http://tinyurl.com/pmmnbxv
Some notes on this in the oommf-devnotes repo
"""
import os
os.system('make all')
import example1
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.sys... | """
The code this example is all based on is from http://tinyurl.com/pmmnbxv
Some notes on this in the oommf-devnotes repo
"""
import os
import pytest
#print("pwd:")
#os.system('pwd')
#import subprocess
#subprocess.check_output('pwd')
os.system('make all')
import example1
def test_f():
assert example1.f(1) -... | Add pytest.raises for test that fails on purpose. | Add pytest.raises for test that fails on purpose.
| Python | bsd-2-clause | ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python | ---
+++
@@ -5,14 +5,27 @@
import os
+import pytest
+
+#print("pwd:")
+#os.system('pwd')
+#import subprocess
+#subprocess.check_output('pwd')
+
+
os.system('make all')
import example1
+
+
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
- assert example1.myfun(example1.f, 2.0) ... |
644038ee51fa4219b96ef7a8edbebe9e6310cedf | plot_scores.py | plot_scores.py | import argparse
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def main():
parser = argparse.ArgumentParser()
parser.add_argument('dir', type=str)
args = parser.parse_args()
scores_path = os.path.join(args.dir, 'scores.txt')
scores = pd.read_csv(scores_path, names... | Add a script to plot scores | Add a script to plot scores
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | ---
+++
@@ -0,0 +1,19 @@
+import argparse
+import os
+
+import numpy as np
+import matplotlib.pyplot as plt
+import pandas as pd
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('dir', type=str)
+ args = parser.parse_args()
+ scores_path = os.path.join(args.dir, 'scores.txt')
+ ... | |
1ddd0c97059301614d4043fc3f749f3247f19599 | utilities/duplicate_cleaner.py | utilities/duplicate_cleaner.py | """Removes duplicate entries from dictionaries"""
import sys
import argparse
sys.path.append('../')
import namealizer
def main(dict_path, stat_path):
dictionary = namealizer.import_dictionary(dict_path)
sorted_words = []
updated = {}
running_total = 0
statistics = {
"old": {},
"new... | Add script to remove duplicates from dictionaries | Add script to remove duplicates from dictionaries
| Python | mit | LeonardMH/namealizer | ---
+++
@@ -0,0 +1,56 @@
+"""Removes duplicate entries from dictionaries"""
+import sys
+import argparse
+sys.path.append('../')
+import namealizer
+
+def main(dict_path, stat_path):
+ dictionary = namealizer.import_dictionary(dict_path)
+ sorted_words = []
+ updated = {}
+ running_total = 0
+
+ statis... | |
e7da5713a676c48248e51c0f8692d0ef5630df4f | png/makepng.py | png/makepng.py | #!/usr/bin/python
import png
device_size = [0]
chunks = []
width = 1200
height = 800
num_pixels = width * height
pixels = [[] for x in xrange(num_pixels)]
lines = open('output').read().splitlines()
for line in lines:
fields = line.split()
if fields[0] == 'chunk':
chunks.append({
'type':... | Convert output into png image | Convert output into png image
| Python | mit | knorrie/btrfs-heatmap | ---
+++
@@ -0,0 +1,72 @@
+#!/usr/bin/python
+
+import png
+
+device_size = [0]
+chunks = []
+
+width = 1200
+height = 800
+num_pixels = width * height
+
+pixels = [[] for x in xrange(num_pixels)]
+
+lines = open('output').read().splitlines()
+for line in lines:
+ fields = line.split()
+ if fields[0] == 'chunk':... | |
4536fe1df5081c69ac736d217721557e7a182ba7 | skyfield/tests/test_io_parsing.py | skyfield/tests/test_io_parsing.py | """Tests of how well we parse various file formats."""
from skyfield.functions import BytesIO
from skyfield.iokit import parse_celestrak_tle
sample_celestrak_text = b"""\
ISS (ZARYA) \n\
1 25544U 98067A 18135.61844383 .00002728 00000-0 48567-4 0 9998
2 25544 51.6402 181.0633 0004018 88.8954 22.22... | Add a test for our existing Celestrak parsing | Add a test for our existing Celestrak parsing
| Python | mit | skyfielders/python-skyfield,skyfielders/python-skyfield | ---
+++
@@ -0,0 +1,20 @@
+"""Tests of how well we parse various file formats."""
+
+from skyfield.functions import BytesIO
+from skyfield.iokit import parse_celestrak_tle
+
+sample_celestrak_text = b"""\
+ISS (ZARYA) \n\
+1 25544U 98067A 18135.61844383 .00002728 00000-0 48567-4 0 9998
+2 25544 51.6... | |
28787be24b1c251200c52ff8d2abc70b356811d8 | src/Scripts/sum-cachelines.py | src/Scripts/sum-cachelines.py | import csv
with open("/tmp/int/QueryPipelineStatistics.csv") as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['query',
'rows',
'matches',
'quadwords',
'cachelines',
'parse',
... | Add quick script for cacheline counting. | Add quick script for cacheline counting.
| Python | mit | BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel | ---
+++
@@ -0,0 +1,17 @@
+import csv
+
+with open("/tmp/int/QueryPipelineStatistics.csv") as f:
+ reader = csv.reader(f)
+ header = next(reader)
+ assert header == ['query',
+ 'rows',
+ 'matches',
+ 'quadwords',
+ 'cachelines... | |
b03476b85c94bdba0258f555b9e89b6e7c84f7e1 | foobargoogle1.py | foobargoogle1.py | import math
def check_prime(number, primes):
limit = math.sqrt(number)
for prime in primes:
if prime > limit:
return True
if number % prime == 0:
return False
return True
def solution(i):
primes = []
number = 2
while len(primes) < (i + 5):
is_p... | Add Google foobar question 1 | Add Google foobar question 1
| Python | mit | ismailsunni/scripts | ---
+++
@@ -0,0 +1,28 @@
+import math
+
+
+def check_prime(number, primes):
+ limit = math.sqrt(number)
+ for prime in primes:
+ if prime > limit:
+ return True
+ if number % prime == 0:
+ return False
+ return True
+
+
+def solution(i):
+ primes = []
+ number = 2
+ ... | |
03b24e97b1239f28cdaa4311f5d51c7974308bce | postgres2redis.py | postgres2redis.py | #!/usr/bin/env python
import ConfigParser
import json
import psycopg2
import redis
import time
def main():
config = ConfigParser.RawConfigParser()
config.read(('default.cfg', 'local.cfg',))
db_host = config.get('Database', 'host')
db_user = config.get('Database', 'user')
db_pass = config.get('Dat... | Add a simple script to prefill Redis with the old postgres data | Add a simple script to prefill Redis with the old postgres data
| Python | mit | rtyler/urlenco.de | ---
+++
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+
+import ConfigParser
+import json
+import psycopg2
+import redis
+import time
+
+
+def main():
+ config = ConfigParser.RawConfigParser()
+ config.read(('default.cfg', 'local.cfg',))
+ db_host = config.get('Database', 'host')
+ db_user = config.get('Databas... | |
2cdd4ac059dd21dcde654dd4d775d07dffb7a53e | test/test_cli.py | test/test_cli.py | import unittest
import subprocess
import tempfile
import fuchsia
from sage.all import SR
def sh(*cmd):
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise Exception("Command %s exited with code %s" % (cmd, p.retur... | Add a simple CLI test | Add a simple CLI test
| Python | isc | gituliar/fuchsia,gituliar/fuchsia | ---
+++
@@ -0,0 +1,38 @@
+import unittest
+import subprocess
+import tempfile
+
+import fuchsia
+from sage.all import SR
+
+def sh(*cmd):
+ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ stdout, stderr = p.communicate()
+ if p.returncode != 0:
+ raise Exception("Command ... | |
dcdc91d890fc96e76f21e0ee51fccb6b9d0bac52 | nodeconductor/structure/migrations/0022_init_global_count_quotas.py | nodeconductor/structure/migrations/0022_init_global_count_quotas.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from uuid import uuid4
from django.db import migrations
def create_quotas(apps, schema_editor):
Project = apps.get_model('structure', 'Project')
Customer = apps.get_model('structure', 'Customer')
ProjectGroup = apps.get_model('structure', '... | Add global count quotas calculation migration | Add global count quotas calculation migration
- nc-860
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from uuid import uuid4
+
+from django.db import migrations
+
+
+def create_quotas(apps, schema_editor):
+ Project = apps.get_model('structure', 'Project')
+ Customer = apps.get_model('structure', 'Customer')
+ Proje... | |
117809ed43c6c0cab4525ca4207764b9909020af | migrations/versions/910_delete_copied_from_brief_id_column.py | migrations/versions/910_delete_copied_from_brief_id_column.py | """Remove copied_from_brief_id column from briefs table as it has been superseded with 'is_a-copy' boolaean column
to fix a bug. The bug made it impossible to delete a draft brief if a copy was made from it. Reason for this is
that the original and the copy were bound by a parent-child database relationship.
Revision... | Delete 'copied_from_brief_id' column and create a correspnding migration | Delete 'copied_from_brief_id' column and create a correspnding migration
This is done because this field has been superseded with 'is_a-copy' boolaean column
to fix a bug. The bug made it impossible to delete a draft brief if a copy was made
from it. Reason for this is that the original and the copy were bound by
a p... | Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api | ---
+++
@@ -0,0 +1,31 @@
+"""Remove copied_from_brief_id column from briefs table as it has been superseded with 'is_a-copy' boolaean column
+to fix a bug. The bug made it impossible to delete a draft brief if a copy was made from it. Reason for this is
+that the original and the copy were bound by a parent-child da... | |
02b3548b557c4a10de8bd14ce609f924009baaf2 | core/migrations/0002_auto_20170522_0640.py | core/migrations/0002_auto_20170522_0640.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-05-22 10:40
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migra... | Make migrations for invoice changes | Make migrations for invoice changes
| Python | bsd-2-clause | overshard/timestrap,cdubz/timestrap,muhleder/timestrap,cdubz/timestrap,overshard/timestrap,muhleder/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap | ---
+++
@@ -0,0 +1,36 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.1 on 2017-05-22 10:40
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0001_initial'),
... | |
b0f0beae34de0a1fb5ddc704cba5ae9346e92341 | set_offline.py | set_offline.py | import asyncio
import os
import discord
from discord.ext import commands
import SLA_bot.channelupdater as ChannelUpdater
import SLA_bot.config as cf
curr_dir = os.path.dirname(__file__)
default_config = os.path.join(curr_dir, 'default_config.ini'),
user_config = os.path.join(curr_dir, 'config.ini')
cf.load_configs... | Add script to set an offline message on channels | Add script to set an offline message on channels
| Python | mit | EsqWiggles/SLA-bot,EsqWiggles/SLA-bot | ---
+++
@@ -0,0 +1,34 @@
+import asyncio
+import os
+
+import discord
+from discord.ext import commands
+
+import SLA_bot.channelupdater as ChannelUpdater
+import SLA_bot.config as cf
+
+curr_dir = os.path.dirname(__file__)
+default_config = os.path.join(curr_dir, 'default_config.ini'),
+user_config = os.path.join(... | |
15a05b3639c47014642cf962bc8a4da1c991b30b | script/upload-windows-pdb.py | script/upload-windows-pdb.py | #!/usr/bin/env python
import os
from lib.util import execute, rm_rf, safe_mkdir
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
SYMBOLS_DIR = 'dist\\symbols'
PDB_LIST = [
'out\\Release\\atom.exe.pdb',
'vendor\\brightray\\vendor\\download\\libchromiumcontent\\Release\\chromiumcontent.dl... | Add script to call symstore | Add script to call symstore
| Python | mit | carsonmcdonald/electron,mirrh/electron,kazupon/electron,trigrass2/electron,Evercoder/electron,jhen0409/electron,icattlecoder/electron,jtburke/electron,seanchas116/electron,vipulroxx/electron,fritx/electron,jlhbaseball15/electron,posix4e/electron,chrisswk/electron,mubassirhayat/electron,posix4e/electron,deed02392/electr... | ---
+++
@@ -0,0 +1,31 @@
+#!/usr/bin/env python
+
+import os
+
+from lib.util import execute, rm_rf, safe_mkdir
+
+
+SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
+SYMBOLS_DIR = 'dist\\symbols'
+PDB_LIST = [
+ 'out\\Release\\atom.exe.pdb',
+ 'vendor\\brightray\\vendor\\download\\libchrom... | |
44922934f55cb1cb8a64eba4afabb66563d66349 | tests/basics/for_else.py | tests/basics/for_else.py | # test for-else statement
# test optimised range with simple else
for i in range(2):
print(i)
else:
print('else')
# test optimised range with break over else
for i in range(2):
print(i)
break
else:
print('else')
# test nested optimised range with continue in the else
for i in range(4):
print(... | Add tests for for-else statement. | tests/basics: Add tests for for-else statement.
| Python | mit | selste/micropython,pfalcon/micropython,Timmenem/micropython,MrSurly/micropython,Timmenem/micropython,infinnovation/micropython,HenrikSolver/micropython,bvernoux/micropython,torwag/micropython,pfalcon/micropython,pozetroninc/micropython,micropython/micropython-esp32,SHA2017-badge/micropython-esp32,henriknelson/micropyth... | ---
+++
@@ -0,0 +1,43 @@
+# test for-else statement
+
+# test optimised range with simple else
+for i in range(2):
+ print(i)
+else:
+ print('else')
+
+# test optimised range with break over else
+for i in range(2):
+ print(i)
+ break
+else:
+ print('else')
+
+# test nested optimised range with continu... | |
dad157bdeb548a101a8ed5bb629539e8bcf4a686 | corehq/apps/hqadmin/management/commands/stale_cases_in_es.py | corehq/apps/hqadmin/management/commands/stale_cases_in_es.py |
import inspect
from django.core.management.base import BaseCommand
from datetime import datetime
from dimagi.utils.chunked import chunked
from casexml.apps.case.models import CommCareCase
from corehq.apps.es import CaseES
from corehq.elastic import ES_EXPORT_INSTANCE
from corehq.util.dates import iso_string_to_datet... | Add management command to get couch cases non updated in ES | Add management command to get couch cases non updated in ES
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,58 @@
+
+import inspect
+
+from django.core.management.base import BaseCommand
+from datetime import datetime
+from dimagi.utils.chunked import chunked
+
+from casexml.apps.case.models import CommCareCase
+from corehq.apps.es import CaseES
+from corehq.elastic import ES_EXPORT_INSTANCE
+from corehq... | |
35baf55e36c55222bc93b1e6d24b34c051dca4b1 | scripts/delete_all_models.py | scripts/delete_all_models.py | import importlib
import logging
import os
import shutil
mainapp_database = importlib.import_module('third_party.3dmr.mainapp.database')
mainapp_upload = getattr(mainapp_database, 'upload')
mainapp_models = importlib.import_module('third_party.3dmr.mainapp.models')
mainapp_model = getattr(mainapp_models, 'Model')
maina... | Add admin script to clear all models on disk and flush mainapp_model, mainapp_latestmodel and mainapp_location tables. | Add admin script to clear all models on disk and flush mainapp_model, mainapp_latestmodel and mainapp_location tables.
| Python | apache-2.0 | kartta-labs/reservoir,kartta-labs/reservoir | ---
+++
@@ -0,0 +1,46 @@
+import importlib
+import logging
+import os
+import shutil
+
+mainapp_database = importlib.import_module('third_party.3dmr.mainapp.database')
+mainapp_upload = getattr(mainapp_database, 'upload')
+mainapp_models = importlib.import_module('third_party.3dmr.mainapp.models')
+mainapp_model = ge... | |
0670cc4510b7049b29d716a2485487390f975095 | polling_stations/apps/data_collection/management/commands/import_stockton.py | polling_stations/apps/data_collection/management/commands/import_stockton.py | from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E06000004"
addresses_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019_Stockton.tsv"
stations_name = "local.2019-05-02/Version 1/Democracy_Club__02... | Add import script for Stockton-upon-Tees | Add import script for Stockton-upon-Tees
Closes #1484
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations | ---
+++
@@ -0,0 +1,9 @@
+from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
+
+
+class Command(BaseXpressDemocracyClubCsvImporter):
+ council_id = "E06000004"
+ addresses_name = "local.2019-05-02/Version 1/Democracy_Club__02May2019_Stockton.tsv"
+ stations_name = "local.2019-0... | |
ffdead34416dc9b2de52242503e4364d257ea619 | tests/test_fetch_http.py | tests/test_fetch_http.py | # coding=utf-8
from __future__ import unicode_literals
import simplemediawiki
import sys
import unittest
try:
import simplejson as json
except ImportError:
import json
if sys.version_info[0] == 3:
import http.cookiejar as cookielib
elif sys.version_info[0] == 2:
import cookielib
UNICODE_TEST = 'κόσμε... | Add first test suite (in progress) | Add first test suite (in progress)
| Python | lgpl-2.1 | lahwaacz/python-simplemediawiki,YSelfTool/python-simplemediawiki,ianweller/python-simplemediawiki | ---
+++
@@ -0,0 +1,80 @@
+# coding=utf-8
+from __future__ import unicode_literals
+
+import simplemediawiki
+import sys
+import unittest
+try:
+ import simplejson as json
+except ImportError:
+ import json
+
+if sys.version_info[0] == 3:
+ import http.cookiejar as cookielib
+elif sys.version_info[0] == 2:
+ ... | |
1ae25b4c129e156cad3d0ff18f37bdcd121be207 | tests/contrib/test_mobile.py | tests/contrib/test_mobile.py | from django.test import TestCase
from django.test.client import RequestFactory
from opps.contrib.mobile import template
from opps.contrib.mobile.middleware import (
MobileDetectionMiddleware, MobileRedirectMiddleware
)
class TestMobileTemplatesDir(TestCase):
def setUp(self):
self.detection_middlewar... | Test if mobile users get the right templates directory | Test if mobile users get the right templates directory
| Python | mit | jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps | ---
+++
@@ -0,0 +1,60 @@
+from django.test import TestCase
+from django.test.client import RequestFactory
+
+from opps.contrib.mobile import template
+from opps.contrib.mobile.middleware import (
+ MobileDetectionMiddleware, MobileRedirectMiddleware
+)
+
+
+class TestMobileTemplatesDir(TestCase):
+
+ def setUp(... | |
ac1dac3638b40f4ecdf5f82e52b5f93d4e74f9ef | tests/list_files_requests.py | tests/list_files_requests.py | import os
import requests
from time import time
from typing import Iterator
import dropbox
def t():
"""Return string of elapsed time since start in seconds."""
return '{:.2f}:'.format(time() - start)
def list_files(token: str,
member_id: str) -> Iterator[dropbox.files.Metadata]:
"""Recur... | Test for using HTTP API for recusive folder listing | Test for using HTTP API for recusive folder listing
| Python | apache-2.0 | blokeley/dfb,blokeley/backup_dropbox | ---
+++
@@ -0,0 +1,59 @@
+import os
+import requests
+from time import time
+from typing import Iterator
+
+import dropbox
+
+
+def t():
+ """Return string of elapsed time since start in seconds."""
+ return '{:.2f}:'.format(time() - start)
+
+
+def list_files(token: str,
+ member_id: str) -> Iter... | |
b4cd1a63148e0fca75781a05ed11541d1e6c87fa | django_lightweight_queue/management/commands/queue_worker.py | django_lightweight_queue/management/commands/queue_worker.py | import sys
import logging
import argparse
from django.core.management.base import BaseCommand, CommandError
from ...worker import Worker
class Command(BaseCommand):
help = "Run an individual queue worker"
def add_arguments(self, parser):
parser.add_argument(
'queue',
help="q... | Add basic individual queue worker command | Add basic individual queue worker command
| Python | bsd-3-clause | thread/django-lightweight-queue,thread/django-lightweight-queue | ---
+++
@@ -0,0 +1,64 @@
+import sys
+import logging
+import argparse
+
+from django.core.management.base import BaseCommand, CommandError
+
+from ...worker import Worker
+
+
+class Command(BaseCommand):
+ help = "Run an individual queue worker"
+
+ def add_arguments(self, parser):
+ parser.add_argument(... | |
a86f31954ffbb5708d5a4d0608bc4611f80ff2ff | tsparser/tests/parser/imu.py | tsparser/tests/parser/imu.py | from tsparser.parser import imu
from tsparser.tests.parser import ParserTestCase, DEFAULT_TIMESTAMP
class TestIMU(ParserTestCase):
ex_data = {'timestamp': DEFAULT_TIMESTAMP, 'pressure': 3981106,
'gyro_x': -413, 'gyro_y': -1286, 'gyro_z': -2545,
'accel_x': 14400, 'accel_y': 3328, 'acc... | Add unit tests to IMUParser | Add unit tests to IMUParser
| Python | mit | m4tx/techswarm-receiver | ---
+++
@@ -0,0 +1,36 @@
+from tsparser.parser import imu
+from tsparser.tests.parser import ParserTestCase, DEFAULT_TIMESTAMP
+
+
+class TestIMU(ParserTestCase):
+ ex_data = {'timestamp': DEFAULT_TIMESTAMP, 'pressure': 3981106,
+ 'gyro_x': -413, 'gyro_y': -1286, 'gyro_z': -2545,
+ 'acc... | |
ec59ed5c360d0d455c4623425271df3fffecbf82 | test/test_cs.py | test/test_cs.py | import pytest
from pml import cs
class InvalidControlSystem(cs.ControlSystem):
"""
Extends ControlSystem without implementing required methods.
"""
def __init__(self):
pass
def test_ControlSystem_throws_NotImplememtedError():
with pytest.raises(NotImplementedError):
cs.ControlSys... | Add simple tests for pml/cs.py. | Add simple tests for pml/cs.py.
| Python | apache-2.0 | willrogers/pml,willrogers/pml | ---
+++
@@ -0,0 +1,29 @@
+import pytest
+from pml import cs
+
+
+class InvalidControlSystem(cs.ControlSystem):
+ """
+ Extends ControlSystem without implementing required methods.
+ """
+ def __init__(self):
+ pass
+
+
+def test_ControlSystem_throws_NotImplememtedError():
+ with pytest.raises(No... | |
37c0719c6a82657d9796d39e7cd217d694de504b | bluebottle/payouts/migrations/0017_delete_in_review_accounts.py | bluebottle/payouts/migrations/0017_delete_in_review_accounts.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-12-19 15:21
from __future__ import unicode_literals
from django.db import migrations
def remove_accounts(apps, schema_editor):
PayoutAccount = apps.get_model('payouts', 'PayoutAccount')
ProjectPhase = apps.get_model('bb_projects', 'ProjectPhase')
... | Make sure we delete all payoutaccounts from new projects so that they will need submit a stripeaccount. | Make sure we delete all payoutaccounts from new projects so that they
will need submit a stripeaccount.
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.8 on 2018-12-19 15:21
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+def remove_accounts(apps, schema_editor):
+ PayoutAccount = apps.get_model('payouts', 'PayoutAccount')
+ ProjectPhase = apps.get_m... | |
bfba1d3c4c7dce98bb718666e0f3c232a0c4479f | mq/plugins/cloudtrailFixup.py | mq/plugins/cloudtrailFixup.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/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Brandon Myers bmyers@mozilla.com
class message(object):
... | Add apiVersion mapping fix for cloudtrail | Add apiVersion mapping fix for cloudtrail
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mpl-2.0 | ameihm0912/MozDef,jeffbryner/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,Phrozyn/MozDef,ameihm0912/MozDef,gdestuynder/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,jeffbryner/MozDef,Phrozyn/MozDef,ameihm0912/MozD... | ---
+++
@@ -0,0 +1,28 @@
+# 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/.
+# Copyright (c) 2014 Mozilla Corporation
+#
+# Contributors:
+# Brandon Myers bmyers@mozil... | |
2cb89fd366a014c27d5c5f44e35cc34a0eb967cf | hotline/db/db_abstract.py | hotline/db/db_abstract.py | from abc import ABCMeta, abstractmethod
class AbstractClient(metaclass=ABCMeta):
@abstractmethod
def connect(self):
pass
@abstractmethod
def get(self, **kwargs):
pass
@abstractmethod
def set(self, **kwargs):
pass
@abstractmethod
def update(self, **kwargs):
... | Add Abstract class that will inhertied in different database clients | Add Abstract class that will inhertied in different database clients
| Python | mit | wearhacks/hackathon_hotline | ---
+++
@@ -0,0 +1,23 @@
+from abc import ABCMeta, abstractmethod
+
+class AbstractClient(metaclass=ABCMeta):
+
+ @abstractmethod
+ def connect(self):
+ pass
+
+ @abstractmethod
+ def get(self, **kwargs):
+ pass
+
+ @abstractmethod
+ def set(self, **kwargs):
+ pass
+
+ @abstr... | |
17a9c1154ef41f7b3276be73d255a95c2e616cb0 | spec/bottling_specs/factory_specs/BottleSingletonAppLoader_specs.py | spec/bottling_specs/factory_specs/BottleSingletonAppLoader_specs.py | import fudge
from bottling.factory import BottleSingletonAppLoader
class describe_init:
def it_initializes_with_given_options(self):
ref = 'my_module:app'
kind = None
loader = BottleSingletonAppLoader(ref, kind)
assert loader.ref == ref
assert loader.kind == None... | Add loader for singleton apps | Add loader for singleton apps
| Python | mit | datamora/datamora,datamora/datamora | ---
+++
@@ -0,0 +1,30 @@
+import fudge
+from bottling.factory import BottleSingletonAppLoader
+
+
+class describe_init:
+
+ def it_initializes_with_given_options(self):
+ ref = 'my_module:app'
+ kind = None
+
+ loader = BottleSingletonAppLoader(ref, kind)
+
+ assert loader.ref =... | |
f60aa33b10268394b66e88b2b262b6ed821f05a6 | CodeFights/pagesNumberingWithInk.py | CodeFights/pagesNumberingWithInk.py | #!/usr/local/bin/python
# Code Fights Pages Numbering With Ink Problem
import math
def pagesNumberingWithInk(current, numberOfDigits):
num = current
digits = (int(math.log(num, 10)) + 1)
available = numberOfDigits - digits
while available >= digits:
digits = int(math.log(num + 1, 10)) + 1
... | Solve Code Fights pages numbering with ink problem | Solve Code Fights pages numbering with ink problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/local/bin/python
+# Code Fights Pages Numbering With Ink Problem
+
+import math
+
+
+def pagesNumberingWithInk(current, numberOfDigits):
+ num = current
+ digits = (int(math.log(num, 10)) + 1)
+ available = numberOfDigits - digits
+ while available >= digits:
+ digi... | |
76578869caaa79f7958ace74eeab82c9af9f4207 | metaci/cumulusci/migrations/0009_remove_org_management_group.py | metaci/cumulusci/migrations/0009_remove_org_management_group.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-10-19 14:47
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cumulusci', '0008_org_management_group'),
]
operations = [
migrations.RemoveField(... | Remove Org.management_group since org access is now controlled through the org_login perm on PlanRepository objects via guardian. | Remove Org.management_group since org access is now controlled through
the org_login perm on PlanRepository objects via guardian.
| Python | bsd-3-clause | SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.10 on 2018-10-19 14:47
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('cumulusci', '0008_org_management_group'),
+ ]
+
+ opera... | |
39b1ce81adedbff4099e2931d7379bc1281ee4b2 | scripts/make_ast_classes.py | scripts/make_ast_classes.py | """Build src/py_ast.js from the documentation of Python ast module."""
import os
import re
import json
import urllib.request
ast_url = "https://raw.githubusercontent.com/python/cpython/main/Doc/library/ast.rst"
f = urllib.request.urlopen(ast_url)
classes = {}
def add_class(line):
line = line[len(starter):].stri... | Add script to generate src/py_ast.js (classes for Python Abstract Syntax Tree) | Add script to generate src/py_ast.js (classes for Python Abstract Syntax Tree)
| Python | bsd-3-clause | brython-dev/brython,brython-dev/brython,brython-dev/brython | ---
+++
@@ -0,0 +1,43 @@
+"""Build src/py_ast.js from the documentation of Python ast module."""
+
+import os
+import re
+import json
+
+import urllib.request
+
+ast_url = "https://raw.githubusercontent.com/python/cpython/main/Doc/library/ast.rst"
+f = urllib.request.urlopen(ast_url)
+
+classes = {}
+
+def add_class(... | |
2fbd3cc8d903aff06588d9ed74edece8b0ecc41f | python/opencv/opencv_2/image_precessing/changing_colorspaces.py | python/opencv/opencv_2/image_precessing/changing_colorspaces.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
"""
OpenCV - Changing colorspaces: convert images from one color-space to another
Required: opencv library (Debian: aptitude install python-opencv)
See: https://opencv-python-tutroals.readthedocs.org/en/latest/py... | Add a snippet (Python OpenCV). | Add a snippet (Python OpenCV).
| Python | mit | jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets | ---
+++
@@ -0,0 +1,50 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
+
+"""
+OpenCV - Changing colorspaces: convert images from one color-space to another
+
+Required: opencv library (Debian: aptitude install python-opencv)
+
+See: https://opencv-python... | |
ff246189bcf5168222ff1231ec1028d2c4dd182c | simple_text_editor/kevin.py | simple_text_editor/kevin.py | #!/usr/bin/python3
# Kevin Boyette
# 1/11/2017
class Stack(object):
def __init__(self):
self.stack = []
def __str__(self):
return str(self.stack)
def __len__(self):
return len(self.stack)
def is_empty(self):
return self.stack == []
def push(self, element):
self.stack.append(element)
def pop(self... | Add Kevin's take on the TextEditor Problem | Add Kevin's take on the TextEditor Problem
| Python | mit | PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank,PlattsSEC/HackerRank | ---
+++
@@ -0,0 +1,80 @@
+#!/usr/bin/python3
+# Kevin Boyette
+# 1/11/2017
+
+
+
+class Stack(object):
+ def __init__(self):
+ self.stack = []
+
+ def __str__(self):
+ return str(self.stack)
+
+ def __len__(self):
+ return len(self.stack)
+
+ def is_empty(self):
+ return self.stack == []
+
+ def push(self, elemen... | |
3189a4db76c4ca49d1a51d1df05eb6b7bee0d817 | scripts/make_routes_json.py | scripts/make_routes_json.py | #!/usr/bin/env python
import os
import sys
import json
SCRIPTS_DIR = '/usr/src/scripts'
BUS_ROUTES_FILE = os.path.join(SCRIPTS_DIR, 'routes.txt')
result = []
with open(BUS_ROUTES_FILE, 'r') as fp:
for line in fp:
route_num = line.strip()
result.append(route_num)
json.dump(result, sys.stdout)
| Create helper script to generate bus routes JSON | Create helper script to generate bus routes JSON
| Python | mit | kdeloach/septa-viz,kdeloach/septa-viz,kdeloach/septa-viz,kdeloach/septa-viz | ---
+++
@@ -0,0 +1,16 @@
+#!/usr/bin/env python
+import os
+import sys
+import json
+
+SCRIPTS_DIR = '/usr/src/scripts'
+BUS_ROUTES_FILE = os.path.join(SCRIPTS_DIR, 'routes.txt')
+
+result = []
+
+with open(BUS_ROUTES_FILE, 'r') as fp:
+ for line in fp:
+ route_num = line.strip()
+ result.append(rout... | |
8351814c8eb645b50f92a498cb25d6af349d9a27 | scripts/upload_2_crowdai.py | scripts/upload_2_crowdai.py | #!/usr/bin/env python
try:
import crowdai
except:
raise Exception("Please install the `crowdai` python client by : pip install crowdai")
import argparse
parser = argparse.ArgumentParser(description='Upload saved docker environments to crowdai for grading')
parser.add_argument('--api_key', dest='api_key', action... | Add a sample uploader script | Add a sample uploader script
| Python | mit | vzhuang/osim-rl,stanfordnmbl/osim-rl | ---
+++
@@ -0,0 +1,15 @@
+#!/usr/bin/env python
+try:
+ import crowdai
+except:
+ raise Exception("Please install the `crowdai` python client by : pip install crowdai")
+import argparse
+parser = argparse.ArgumentParser(description='Upload saved docker environments to crowdai for grading')
+parser.add_argument(... | |
2d4431d7bc6b7ab362ce2cf084b901be45c51c2f | quantum/db/migration/alembic_migrations/versions/1d76643bcec4_nvp_netbinding.py | quantum/db/migration/alembic_migrations/versions/1d76643bcec4_nvp_netbinding.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
... | Add migration for network bindings in NVP plugin | Add migration for network bindings in NVP plugin
Bug 1099895
Ensures the table nvp_network_bindings is created when upgrading
database to head, by adding an appropriate alembic migration
Change-Id: I4a794ed0ec6866d657cb2470d5aa67828e81aa75
| Python | apache-2.0 | blueboxgroup/neutron,vbannai/neutron,swdream/neutron,mattt416/neutron,ykaneko/quantum,yamahata/neutron,apporc/neutron,vivekanand1101/neutron,openstack/neutron,mattt416/neutron,mandeepdhami/neutron,Comcast/neutron,miyakz1192/neutron,dims/neutron,vbannai/neutron,JianyuWang/neutron,Brocade-OpenSource/OpenStack-DNRM-Neutro... | ---
+++
@@ -0,0 +1,63 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+#
+# Copyright 2013 OpenStack LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://ww... | |
0ff0e770babe4c1e1d07f5b8f0722774d5bcb2b0 | benchexec/tools/kissat.py | benchexec/tools/kissat.py | # This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.result as result
import benchexec.tools.template
class Tool(benchexec.t... | Add a tool-info module for Kissat SAT solver | Add a tool-info module for Kissat SAT solver
| Python | apache-2.0 | sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,ultimate-pa/benchexec,dbeyer/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec | ---
+++
@@ -0,0 +1,48 @@
+# This file is part of BenchExec, a framework for reliable benchmarking:
+# https://github.com/sosy-lab/benchexec
+#
+# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
+#
+# SPDX-License-Identifier: Apache-2.0
+
+import benchexec.result as result
+import benchexec.too... | |
0c065daa5eef7868cf1825c247cf9628907b86a0 | tests/test_vector2_isclose.py | tests/test_vector2_isclose.py | from ppb_vector import Vector2
from utils import vectors
from hypothesis import assume, given, note, example
from hypothesis.strategies import floats
@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
def test_isclose_to_self(x, abs_tol, rel_tol):
assert x.isclose(x, abs_tol=abs_tol, re... | Add a test for Vector2.isclose | Add a test for Vector2.isclose
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector | ---
+++
@@ -0,0 +1,9 @@
+from ppb_vector import Vector2
+from utils import vectors
+from hypothesis import assume, given, note, example
+from hypothesis.strategies import floats
+
+
+@given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0))
+def test_isclose_to_self(x, abs_tol, rel_tol):
+ asse... | |
c7ef4887d06b47d64dad9fc989e9eadb1b9d16ef | tests/test_with_hypothesis.py | tests/test_with_hypothesis.py | from hypothesis import given
from aead import AEAD
@given(bytes, bytes)
def test_round_trip_encrypt_decrypt(plaintext, associated_data):
cryptor = AEAD(AEAD.generate_key())
ct = cryptor.encrypt(plaintext, associated_data)
assert plaintext == cryptor.decrypt(ct, associated_data)
| Add roundtrip encrypt-decrypt test using hypothesis. | Add roundtrip encrypt-decrypt test using hypothesis.
| Python | apache-2.0 | Ayrx/python-aead,Ayrx/python-aead | ---
+++
@@ -0,0 +1,10 @@
+from hypothesis import given
+
+from aead import AEAD
+
+
+@given(bytes, bytes)
+def test_round_trip_encrypt_decrypt(plaintext, associated_data):
+ cryptor = AEAD(AEAD.generate_key())
+ ct = cryptor.encrypt(plaintext, associated_data)
+ assert plaintext == cryptor.decrypt(ct, associ... | |
7997b8ad33736cdc436325cda3ed65db3223f75c | get_email_body_using_imap.py | get_email_body_using_imap.py | import email
from imaplib import IMAP4_SSL
import quopri
# Called recursively.
def get_email_content(message):
if not message.is_multipart():
return message.get_payload()
parts = [get_email_content(payload) for payload in message.get_payload()]
return ''.join(parts)
server = 'imap.example.com'
username = 'mat... | Add get email body using IMAP example | Add get email body using IMAP example
| Python | mit | MattMS/Python_3_examples | ---
+++
@@ -0,0 +1,41 @@
+import email
+from imaplib import IMAP4_SSL
+import quopri
+
+
+# Called recursively.
+def get_email_content(message):
+ if not message.is_multipart():
+ return message.get_payload()
+
+ parts = [get_email_content(payload) for payload in message.get_payload()]
+ return ''.join(parts)
+
+
+s... | |
535d8330427db8ddcb5bef832b8c7ae6ea3f6583 | stack/331.py | stack/331.py | class Solution:
def isValidSerialization(self, preorder):
"""
:type preorder: str
:rtype: bool
"""
arr_pre_order = preorder.split(',')
stack = []
for node in arr_pre_order:
stack.append(node)
while len(stack) > 1 and stack[-1] ... | Verify Preorder Serialization of a Binary Tree | Verify Preorder Serialization of a Binary Tree
| Python | apache-2.0 | MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode | ---
+++
@@ -0,0 +1,21 @@
+class Solution:
+ def isValidSerialization(self, preorder):
+ """
+ :type preorder: str
+ :rtype: bool
+ """
+ arr_pre_order = preorder.split(',')
+
+ stack = []
+ for node in arr_pre_order:
+ stack.append(node)
+ ... | |
825d2c053e7fa744f1d9c07748da358cba8d0d3b | tests/query_test/test_kudu.py | tests/query_test/test_kudu.py | # Copyright 2012 Cloudera 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 writing, so... | Add boilerplate code for Kudu end-to-end test | Add boilerplate code for Kudu end-to-end test
Change-Id: I568719afe5c172ac7e4ac98f9fe030f9710f26f1
Reviewed-on: http://gerrit.sjc.cloudera.com:8080/7038
Reviewed-by: David Alves <33ea948168c114d220e0372a903be6ee60f6396e@cloudera.com>
Tested-by: jenkins
| Python | apache-2.0 | ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC,ibmsoe/ImpalaPPC | ---
+++
@@ -0,0 +1,43 @@
+# Copyright 2012 Cloudera 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 applic... | |
5eee235af2bc145af5a9d476054da12f8cb095e2 | svir/test/unit/test_dumb.py | svir/test/unit/test_dumb.py | # -*- coding: utf-8 -*-
#/***************************************************************************
# Irmt
# A QGIS plugin
# OpenQuake Integrated Risk Modelling Toolkit
# -------------------
# begin : 2013-10-24
# copyright ... | Add a dumb test, to investigate segfault [skip CI] | Add a dumb test, to investigate segfault [skip CI]
| Python | agpl-3.0 | gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis | ---
+++
@@ -0,0 +1,45 @@
+# -*- coding: utf-8 -*-
+#/***************************************************************************
+# Irmt
+# A QGIS plugin
+# OpenQuake Integrated Risk Modelling Toolkit
+# -------------------
+# begin : ... | |
1e17a5297d2b02035088a1c6218e3b5d1796848f | datasets/management/commands/load_freesound_false_examples.py | datasets/management/commands/load_freesound_false_examples.py | from django.core.management.base import BaseCommand
from datasets.models import *
import json
from datasets.models import Taxonomy, Dataset, Sound, TaxonomyNode
class Command(BaseCommand):
help = 'Load false examples from json taxonomy file. Use it as python manage.py load_freesound_false_examples ' \
... | Add command load freesound false examples | Add command load freesound false examples
| Python | agpl-3.0 | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | ---
+++
@@ -0,0 +1,28 @@
+from django.core.management.base import BaseCommand
+from datasets.models import *
+import json
+from datasets.models import Taxonomy, Dataset, Sound, TaxonomyNode
+
+
+class Command(BaseCommand):
+ help = 'Load false examples from json taxonomy file. Use it as python manage.py load_frees... | |
bcada138526fc8ff4d07297802074d45b417d075 | dplace_app/migrations/0077_increase_max_length_for_Society_id.py | dplace_app/migrations/0077_increase_max_length_for_Society_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-28 20:53
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dplace_app', '0076_society_original_name'),
]
operations = [
migrations.Alte... | Increase length of society ID | Increase length of society ID
| Python | mit | stefelisabeth/dplace,NESCent/dplace,stefelisabeth/dplace,NESCent/dplace,D-PLACE/dplace,D-PLACE/dplace,stefelisabeth/dplace,stefelisabeth/dplace,shh-dlce/dplace,NESCent/dplace,NESCent/dplace,D-PLACE/dplace,D-PLACE/dplace,shh-dlce/dplace,shh-dlce/dplace,shh-dlce/dplace | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.2 on 2016-02-28 20:53
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('dplace_app', '0076_society_original_name'),
+ ]
+
+ ... | |
d3dab028d3d91c5144489e3826753a1a1579a0e6 | tests/testvdf.py | tests/testvdf.py | import unittest
from steam import vdf
class SyntaxTestCase(unittest.TestCase):
UNQUOTED_VDF = """
node
{
key value
}
"""
QUOTED_VDF = """
"node"
{
"key" "value"
}
"""
MACRO_UNQUOTED_VDF = """
node
{
key value [$MACRO]
}
"""
MACR... | Add initial vdf test fixture | Add initial vdf test fixture
| Python | isc | miedzinski/steamodd,Lagg/steamodd | ---
+++
@@ -0,0 +1,79 @@
+import unittest
+from steam import vdf
+
+class SyntaxTestCase(unittest.TestCase):
+ UNQUOTED_VDF = """
+ node
+ {
+ key value
+ }
+ """
+
+ QUOTED_VDF = """
+ "node"
+ {
+ "key" "value"
+ }
+ """
+
+ MACRO_UNQUOTED_VDF = """
+ node
+ {
+ ... | |
fdf820d731a31e39861fe0f9b3dbbf2da225116c | tests/test_pipeline_wgbs.py | tests/test_pipeline_wgbs.py | """
.. Copyright 2017 EMBL-European Bioinformatics Institute
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 applic... | Test the pipeline code for the WGBS pipeline | Test the pipeline code for the WGBS pipeline
| Python | apache-2.0 | Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq,Multiscale-Genomics/mg-process-fastq | ---
+++
@@ -0,0 +1,77 @@
+"""
+.. Copyright 2017 EMBL-European Bioinformatics Institute
+
+ 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/LICENS... | |
11695a26b7ca7f364d4464331965189ebd6357bc | backend/django/core/base_viewset.py | backend/django/core/base_viewset.py | from rest_framework import status, viewsets
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
class BaseViewSet(viewsets.ModelViewSet):
true = True
false = False
none = None
authentication_classes = Allow... | Create default BaseViewSet for all the common actions | Create default BaseViewSet for all the common actions
| Python | mit | slavpetroff/sweetshop,slavpetroff/sweetshop | ---
+++
@@ -0,0 +1,82 @@
+from rest_framework import status, viewsets
+from rest_framework.exceptions import ValidationError
+from rest_framework.response import Response
+from rest_framework.permissions import AllowAny
+
+
+class BaseViewSet(viewsets.ModelViewSet):
+ true = True
+ false = False
+ none = Non... | |
af2c7febc2feaad2d46b4b7ea818e39eac89ec66 | app/api/tests/test_weekday.py | app/api/tests/test_weekday.py | from django.test import Client, TestCase
class WeekdayApiTest(TestCase):
"""Tests for Weekday API."""
def setUp(self):
self.client = Client()
self.endpoint = '/api'
def create_weekday(self, name):
query = '''
mutation{
createWeekday(input: {nam... | Set up test for weekday api | Set up test for weekday api
| Python | mit | teamtaverna/core | ---
+++
@@ -0,0 +1,39 @@
+from django.test import Client, TestCase
+
+
+class WeekdayApiTest(TestCase):
+ """Tests for Weekday API."""
+
+ def setUp(self):
+ self.client = Client()
+ self.endpoint = '/api'
+
+ def create_weekday(self, name):
+ query = '''
+ mutation{
+ ... | |
8a21a8741d152a4040f42b57b4d21d483a6367fb | adhocracy/migration/versions/037_proposal_variants_fix_pickle.py | adhocracy/migration/versions/037_proposal_variants_fix_pickle.py | '''
Fix an error in the previous migration where wie pickled the versions
into a string that was pickled again by sqlalchemy.
'''
from datetime import datetime
from pickle import loads
from sqlalchemy import (MetaData, Column, ForeignKey, DateTime, Integer,
PickleType, Table)
metadata = MetaDa... | Add migration for double pickled values | Selection.variants: Add migration for double pickled values
| Python | agpl-3.0 | DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/vcv,alkadis/vcv,SysTheron/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,phihag/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,alkadis/vcv,phihag/adhocracy,SysTheron/adhocracy,SysTheron/adhocracy,liqd/adhocracy,DanielNeugebauer/a... | ---
+++
@@ -0,0 +1,57 @@
+'''
+Fix an error in the previous migration where wie pickled the versions
+into a string that was pickled again by sqlalchemy.
+'''
+from datetime import datetime
+from pickle import loads
+
+from sqlalchemy import (MetaData, Column, ForeignKey, DateTime, Integer,
+ P... | |
56c9d8dc45c27b8d86f17be4a88dd1c574874460 | nova/tests/virt_unittest.py | nova/tests/virt_unittest.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2010 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0... | Add new libvirt_type option "uml" for user-mode-linux.. This switches the libvirt URI to uml:///system and uses a different template for the libvirt xml. | Add new libvirt_type option "uml" for user-mode-linux.. This switches the libvirt URI to uml:///system and uses a different template for the libvirt xml. | Python | apache-2.0 | n0ano/ganttclient | ---
+++
@@ -0,0 +1,69 @@
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
+#
+# Copyright 2010 OpenStack LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http:/... | |
e3d0bcb91f59616eb0aa8cc56f72315c362493cf | utils/webhistory/epiphany-history-to-ttl.py | utils/webhistory/epiphany-history-to-ttl.py | import xml.dom.minidom
from xml.dom.minidom import Node
import time
import sys, os
PROPERTIES = {2: ("nie:title", str),
3: ("nfo:uri", str),
4: ("nie:usageCounter", int),
6: ("nie:lastRefreshed", time.struct_time)}
# Use time.struct_time as type for dates, even when the format... | Add util to generate real webhistory | Add util to generate real webhistory
Added program that reads epiphany web browsing history and print it
in turtle format.
| Python | lgpl-2.1 | hoheinzollern/tracker,hoheinzollern/tracker,outofbits/tracker,outofbits/tracker,outofbits/tracker,hoheinzollern/tracker,outofbits/tracker,hoheinzollern/tracker,outofbits/tracker,hoheinzollern/tracker,outofbits/tracker,hoheinzollern/tracker,hoheinzollern/tracker,outofbits/tracker | ---
+++
@@ -0,0 +1,53 @@
+import xml.dom.minidom
+from xml.dom.minidom import Node
+import time
+import sys, os
+
+PROPERTIES = {2: ("nie:title", str),
+ 3: ("nfo:uri", str),
+ 4: ("nie:usageCounter", int),
+ 6: ("nie:lastRefreshed", time.struct_time)}
+# Use time.struct_time as... | |
52ab2b852a9e4df8783818743396c565c8355547 | jacquard/storage/commands.py | jacquard/storage/commands.py | import pprint
from jacquard.commands import BaseCommand
class StorageDump(BaseCommand):
help = "dump all objects in storage"
def add_arguments(self, parser):
pass
def handle(self, config, options):
with config['storage'].transaction() as store:
for key, value in store.items()... | Add command to dump contents of storage | Add command to dump contents of storage
| Python | mit | prophile/jacquard,prophile/jacquard | ---
+++
@@ -0,0 +1,17 @@
+import pprint
+
+from jacquard.commands import BaseCommand
+
+class StorageDump(BaseCommand):
+ help = "dump all objects in storage"
+
+ def add_arguments(self, parser):
+ pass
+
+ def handle(self, config, options):
+ with config['storage'].transaction() as store:
+ ... | |
f18626a190ac967db2a30b9929bc055a93a370e6 | appium-demo/tt.py | appium-demo/tt.py | import os
from appium import webdriver
# capabilities for built-in email app
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = 'Android Emulator'
desired_caps['appPackage'] = 'com.android.email'
desired_caps['appActivity'] = 'com.android.ema... | Add demo app for appium | Add demo app for appium
| Python | mpl-2.0 | zapion/working-scripts,zapion/working-scripts,zapion/working-scripts,zapion/working-scripts | ---
+++
@@ -0,0 +1,52 @@
+import os
+from appium import webdriver
+
+# capabilities for built-in email app
+desired_caps = {}
+desired_caps['platformName'] = 'Android'
+desired_caps['platformVersion'] = '5.1'
+desired_caps['deviceName'] = 'Android Emulator'
+desired_caps['appPackage'] = 'com.android.email'
+desired_c... | |
89deb13c54957c10ab94c384fb58ca569fdb5cd2 | python/dataset_converter.py | python/dataset_converter.py | # converts article and user name to article id and user id
import csv
with open('cbdata-feedback.csv', 'rb') as f:
reader = csv.reader(f)
next(reader, None) # skip header
out_file = open('cbdata-feedback-anon.csv', 'wb')
writer = csv.writer(out_file, delimiter=',')
user_id = 0
item_id = 0
user_dict = {}
item... | Convert claypool dataset to anonymous claypool dataset | Convert claypool dataset to anonymous claypool dataset
| Python | mit | ntnu-smartmedia/goldfish,monsendag/goldfish,monsendag/goldfish,monsendag/goldfish,ntnu-smartmedia/goldfish,ntnu-smartmedia/goldfish | ---
+++
@@ -0,0 +1,44 @@
+# converts article and user name to article id and user id
+import csv
+
+with open('cbdata-feedback.csv', 'rb') as f:
+ reader = csv.reader(f)
+ next(reader, None) # skip header
+ out_file = open('cbdata-feedback-anon.csv', 'wb')
+ writer = csv.writer(out_file, delimiter=',')
+
+ user_id = ... | |
e095f5f3dd155877d2280862905ba5bb0c01d928 | bundle_to_yaml.py | bundle_to_yaml.py | #!/usr/bin/env python
import os
import sys
import unitypack
import yaml
from argparse import ArgumentParser
def handle_asset(asset):
for id, obj in asset.objects.items():
d = obj.read()
print(yaml.dump(d))
def asset_representer(dumper, data):
return dumper.represent_scalar("!asset", data.name)
yaml.add_repre... | Add a yaml dumper for asset bundles | Add a yaml dumper for asset bundles
| Python | mit | andburn/python-unitypack | ---
+++
@@ -0,0 +1,72 @@
+#!/usr/bin/env python
+import os
+import sys
+import unitypack
+import yaml
+from argparse import ArgumentParser
+
+
+def handle_asset(asset):
+ for id, obj in asset.objects.items():
+ d = obj.read()
+
+ print(yaml.dump(d))
+
+
+def asset_representer(dumper, data):
+ return dumper.represen... | |
55fc4153ece6e47dc799fd447356e54434475c77 | scripts/officediff/pptx-dump.py | scripts/officediff/pptx-dump.py | import sys
from pptx import Presentation
for slide in Presentation(sys.argv[1]).slides:
for shape in slide.shapes:
if not shape.has_text_frame:
continue
for paragraph in shape.text_frame.paragraphs:
for run in paragraph.runs:
print(run.text) | Add Python script for Excel file diffs | Add Python script for Excel file diffs
| Python | mit | Stratus3D/dotfiles,Stratus3D/dotfiles,Stratus3D/dotfiles | ---
+++
@@ -0,0 +1,13 @@
+import sys
+
+from pptx import Presentation
+
+
+for slide in Presentation(sys.argv[1]).slides:
+ for shape in slide.shapes:
+ if not shape.has_text_frame:
+ continue
+
+ for paragraph in shape.text_frame.paragraphs:
+ for run in paragraph.runs:
+ ... | |
6425c20b536e8952b062ccb8b470ea615ebc0fa2 | conman/routes/migrations/0002_simplify_route_slug_help_text.py | conman/routes/migrations/0002_simplify_route_slug_help_text.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('routes', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='route',
name='slug',
... | Add missing migration to routes app | Add missing migration to routes app
| Python | bsd-2-clause | meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('routes', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ mode... | |
678672d72accb773a3080394d4fd6936459c9f11 | bio/subs_matrix.py | bio/subs_matrix.py | from __future__ import division
def load_subs_matrix(matrix_name):
import Bio.SubsMat.MatrixInfo as matrix_info
# Try to get the requested substitution matrix from biopython, and
# complain if no such matrix exists.
try:
half_matrix = getattr(matrix_info, matrix_name)
except AttributeErr... | Add a module for working with PAM, BLOSUM, etc. | Add a module for working with PAM, BLOSUM, etc.
| Python | mit | Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab,Kortemme-Lab/klab | ---
+++
@@ -0,0 +1,42 @@
+from __future__ import division
+
+def load_subs_matrix(matrix_name):
+ import Bio.SubsMat.MatrixInfo as matrix_info
+
+ # Try to get the requested substitution matrix from biopython, and
+ # complain if no such matrix exists.
+
+ try:
+ half_matrix = getattr(matrix_info,... | |
764e0b742351c07dda5657fb2dc46f45dce4a3ef | migrations/versions/86b41c3dbd00_add_indexes_on_driver_for_licence_and_.py | migrations/versions/86b41c3dbd00_add_indexes_on_driver_for_licence_and_.py | """Add indexes on driver for licence and departement
Revision ID: 86b41c3dbd00
Revises: ccd5b0142a76
Create Date: 2019-10-21 15:55:35.965422
"""
# revision identifiers, used by Alembic.
revision = '86b41c3dbd00'
down_revision = 'ccd5b0142a76'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects i... | Add migration to create index on driver for departement and licence | Add migration to create index on driver for departement and licence
| Python | agpl-3.0 | openmaraude/APITaxi,openmaraude/APITaxi | ---
+++
@@ -0,0 +1,24 @@
+"""Add indexes on driver for licence and departement
+
+Revision ID: 86b41c3dbd00
+Revises: ccd5b0142a76
+Create Date: 2019-10-21 15:55:35.965422
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '86b41c3dbd00'
+down_revision = 'ccd5b0142a76'
+
+from alembic import op
+import sq... | |
4a382bcf4ab0022c7cf24d3e1ef187dd9a5d388b | test/test_sclopf_scigrid.py | test/test_sclopf_scigrid.py | from __future__ import print_function, division
from __future__ import absolute_import
import pypsa
import numpy as np
def test_sclopf():
csv_folder_name = "../examples/scigrid-de/scigrid-with-load-gen-trafos/"
network = pypsa.Network(csv_folder_name=csv_folder_name)
#test results were generated wit... | Include unit test of Security-Constrained LOPF | Include unit test of Security-Constrained LOPF
| Python | mit | PyPSA/PyPSA | ---
+++
@@ -0,0 +1,51 @@
+from __future__ import print_function, division
+from __future__ import absolute_import
+
+import pypsa
+
+import numpy as np
+
+
+def test_sclopf():
+
+
+ csv_folder_name = "../examples/scigrid-de/scigrid-with-load-gen-trafos/"
+
+ network = pypsa.Network(csv_folder_name=csv_folder_na... | |
f0d9944ccb7838bf438f6e4ff36ddd69941830f6 | scripts/kmeans_generator.py | scripts/kmeans_generator.py | import random
D = 5
K = 5
N = 10
means = [[j * 10 for i in range(D)] for j in range(-2, 3)]
for i in range(N):
mean = random.choice(means)
point = [random.gauss(c, 2.5) for c in mean]
print(','.join("{:0.8f}".format(i) for i in point))
| Add simple script to generate K-Means points. | Add simple script to generate K-Means points.
The data generated by this script is _very_ nice.
| Python | apache-2.0 | yliu120/K3,DaMSL/K3,DaMSL/K3 | ---
+++
@@ -0,0 +1,12 @@
+import random
+
+D = 5
+K = 5
+N = 10
+
+means = [[j * 10 for i in range(D)] for j in range(-2, 3)]
+
+for i in range(N):
+ mean = random.choice(means)
+ point = [random.gauss(c, 2.5) for c in mean]
+ print(','.join("{:0.8f}".format(i) for i in point)) | |
38fff5dec5a39fab6ab67c92854c9e2843cb49fc | syslog-logger.py | syslog-logger.py | import logging
import logging.handlers
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = logging.handlers.SysLogHandler(address = '/dev/log')
formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
def hello():
log.debug... | Add script logging to syslog example | Add script logging to syslog example | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | ---
+++
@@ -0,0 +1,21 @@
+import logging
+import logging.handlers
+
+log = logging.getLogger(__name__)
+
+log.setLevel(logging.DEBUG)
+
+handler = logging.handlers.SysLogHandler(address = '/dev/log')
+
+formatter = logging.Formatter('%(module)s.%(funcName)s: %(message)s')
+handler.setFormatter(formatter)
+
+log.addHa... | |
2e7866be517bb66907b4bba85f0a45c5310c0ddc | mini-project.py | mini-project.py | # Load the machine
import pkg_resources
pkg_resources.require('aphla')
import aphla as ap
# Other stuff
from cothread.catools import caget, caput, ca_nothing
# Load the machine
ap.machines.load('SRI21')
# First task
BPMS = ap.getElements('BPM')
print('There are {} BPM elements in the machine.'.format(len(BPMS)))
# S... | Print values of both setpoint and readback currents | Print values of both setpoint and readback currents
| Python | apache-2.0 | razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects,razvanvasile/Work-Mini-Projects | ---
+++
@@ -0,0 +1,29 @@
+# Load the machine
+import pkg_resources
+pkg_resources.require('aphla')
+import aphla as ap
+# Other stuff
+from cothread.catools import caget, caput, ca_nothing
+
+# Load the machine
+ap.machines.load('SRI21')
+
+# First task
+BPMS = ap.getElements('BPM')
+print('There are {} BPM elements ... | |
e7f0198684faf5c38d78a6ced7f0ff765f1ec17e | language/visualize.py | language/visualize.py | #!/usr/bin/env python
# Copyright 2016 Stanford University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | Add visualization script for RDIR flow graphs. | regent: Add visualization script for RDIR flow graphs.
| Python | apache-2.0 | StanfordLegion/legion,chuckatkins/legion,sdalton1/legion,StanfordLegion/legion,sdalton1/legion,StanfordLegion/legion,sdalton1/legion,StanfordLegion/legion,chuckatkins/legion,sdalton1/legion,StanfordLegion/legion,sdalton1/legion,chuckatkins/legion,chuckatkins/legion,StanfordLegion/legion,StanfordLegion/legion,StanfordLe... | ---
+++
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+
+# Copyright 2016 Stanford University
+#
+# 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-... | |
a72d75648c32e1c221c42a6024d92a92fe9e82ec | orchestra/migrations/0027_create_time_entries_for_snapshots.py | orchestra/migrations/0027_create_time_entries_for_snapshots.py | # -*- coding: utf-8 -*-
# Manually written
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
import dateutil
def create_time_entries(apps, schema_editor):
TaskAssignment = apps.get_model('orchestra', 'TaskAssignment')
TimeEntry = apps.get_model('orchestra', 'Ti... | Migrate task assignment snapshots to TimeEntry | Migrate task assignment snapshots to TimeEntry | Python | apache-2.0 | unlimitedlabs/orchestra,b12io/orchestra,b12io/orchestra,b12io/orchestra,unlimitedlabs/orchestra,b12io/orchestra,b12io/orchestra,unlimitedlabs/orchestra | ---
+++
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+# Manually written
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+import datetime
+import dateutil
+
+
+def create_time_entries(apps, schema_editor):
+ TaskAssignment = apps.get_model('orchestra', 'TaskAssignment')
+ Tim... | |
2f8e0d6c70160f646f374ef2431d819c3af6e5f3 | orcalib/autoscaling.py | orcalib/autoscaling.py | import boto3
from aws_config import AwsConfig
from aws_config import OrcaConfig
class AwsAppAutoscaling(object):
'''
The class provides a simpler abstraction to the AWS boto3
Autoscaling client interface
'''
def __init__(self,
profile_names=None,
access_key_id=Non... | Add `list_scaling_policies` for App Autoscaling service | Add `list_scaling_policies` for App Autoscaling service
Note: current AWS orca user has no permissions to list scaling policies.
| Python | apache-2.0 | bdastur/orca,bdastur/orca | ---
+++
@@ -0,0 +1,63 @@
+import boto3
+from aws_config import AwsConfig
+from aws_config import OrcaConfig
+
+
+class AwsAppAutoscaling(object):
+ '''
+ The class provides a simpler abstraction to the AWS boto3
+ Autoscaling client interface
+ '''
+ def __init__(self,
+ profile_names=N... | |
eac082bff13b660a15dfcd00d73f1a0e89c292dd | polling_stations/apps/data_collection/management/commands/import_neath-pt.py | polling_stations/apps/data_collection/management/commands/import_neath-pt.py | """
Import Neath Port Talbot
note: this script takes quite a long time to run
"""
from django.contrib.gis.geos import Point
from data_collection.management.commands import (
BaseAddressCsvImporter,
import_polling_station_shapefiles
)
class Command(BaseAddressCsvImporter):
"""
Imports the Polling Stati... | Add import script for Neath Port Talbot | Add import script for Neath Port Talbot
There are a small number of duplicate rows in the address file
so this intentionally imports a slightly smaller number of
ResidentialAddress records than the number of rows in the csv.
Apart from that, all good.
| Python | bsd-3-clause | chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations,chris48s/UK-Polling-Stations | ---
+++
@@ -0,0 +1,72 @@
+"""
+Import Neath Port Talbot
+
+note: this script takes quite a long time to run
+"""
+from django.contrib.gis.geos import Point
+from data_collection.management.commands import (
+ BaseAddressCsvImporter,
+ import_polling_station_shapefiles
+)
+
+class Command(BaseAddressCsvImporter)... | |
eac05b2e29b667fe80ba925b723d8133970725ac | molo/profiles/migrations/0002_userprofile_auth_service_uuid.py | molo/profiles/migrations/0002_userprofile_auth_service_uuid.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-17 16:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0001_squashed_0021_remove_uuid_null'),
]
operations = [
migrat... | Add migration for UserProfile.auth_service_uuid field | Add migration for UserProfile.auth_service_uuid field
| Python | bsd-2-clause | praekelt/molo,praekelt/molo,praekelt/molo,praekelt/molo | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.13 on 2018-05-17 16:42
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('profiles', '0001_squashed_0021_remove_uuid_null'),
+ ... | |
46eb5dc81ff0c26b2c9ff785a8b9aadea07b6aaa | py/next-greater-element-i.py | py/next-greater-element-i.py | from collections import defaultdict
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
next_greater = defaultdict(lambda: -1)
stack = []
for n in nums:
... | Add py solution for 496. Next Greater Element I | Add py solution for 496. Next Greater Element I
496. Next Greater Element I: https://leetcode.com/problems/next-greater-element-i/
| Python | apache-2.0 | ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode | ---
+++
@@ -0,0 +1,17 @@
+from collections import defaultdict
+class Solution(object):
+ def nextGreaterElement(self, findNums, nums):
+ """
+ :type findNums: List[int]
+ :type nums: List[int]
+ :rtype: List[int]
+ """
+ next_greater = defaultdict(lambda: -1)
+ stac... | |
c02d3e1b17549f1047fc374dafd9b9613c1e35fd | src/util/deleteLongLines.py | src/util/deleteLongLines.py | import os, sys
def errorExit(msg):
sys.stderr.write(msg)
sys.exit(1)
def main():
if len(sys.argv) != 3:
errorExit("Usage: {} MAXLEN FILE\n".format(os.path.basename(sys.argv[0])))
maxlen = int(sys.argv[1])
fileName = sys.argv[2]
if not os.path.isfile(fileName):
errorExit("{} do... | Add a Python script to delete long lines. We will use it for the Netflix data. | Add a Python script to delete long lines. We will use it for the Netflix data.
| Python | apache-2.0 | jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules | ---
+++
@@ -0,0 +1,27 @@
+import os, sys
+
+def errorExit(msg):
+ sys.stderr.write(msg)
+ sys.exit(1)
+
+def main():
+ if len(sys.argv) != 3:
+ errorExit("Usage: {} MAXLEN FILE\n".format(os.path.basename(sys.argv[0])))
+ maxlen = int(sys.argv[1])
+ fileName = sys.argv[2]
+ if not os.path.isf... | |
3275fe6bc958e2001ecbbb064d785199f9165814 | dataactcore/migrations/versions/d998c46bacd9_merge_job_err_with_add_fsrs.py | dataactcore/migrations/versions/d998c46bacd9_merge_job_err_with_add_fsrs.py | """merge job_err with add_fsrs
Revision ID: d998c46bacd9
Revises: 361fbffcf08b, caa6895e7450
Create Date: 2016-08-26 19:09:39.554574
"""
# revision identifiers, used by Alembic.
revision = 'd998c46bacd9'
down_revision = ('361fbffcf08b', 'caa6895e7450')
branch_labels = None
depends_on = None
from alembic import op
i... | Add merge migration to resolve alembic conflict | Add merge migration to resolve alembic conflict
| Python | cc0-1.0 | fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend | ---
+++
@@ -0,0 +1,36 @@
+"""merge job_err with add_fsrs
+
+Revision ID: d998c46bacd9
+Revises: 361fbffcf08b, caa6895e7450
+Create Date: 2016-08-26 19:09:39.554574
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = 'd998c46bacd9'
+down_revision = ('361fbffcf08b', 'caa6895e7450')
+branch_labels = None
+dep... | |
aea5a46a90fa01d429305e9abecb124fb2b22ae0 | src/iterations/exercise4.py | src/iterations/exercise4.py | # Print every single letter of a word with 'for' iteration and with 'while' iteration
# Also create a method for all single iteration required. Finally with main method
# require a word to be printed, until isn't typed 'done!'
#
def print_letters_with_for( word ):
for w in word:
print w
print '\n'
def print_lett... | Print every single letter of a word with 'for' iteration and with 'while' iteration | Print every single letter of a word with 'for' iteration and with 'while' iteration
# Print every single letter of a word with 'for' iteration and with 'while' iteration
# Also create a method for all single iteration required. Finally with main method
# require a word to be printed, until isn't typed 'done!'
| Python | mit | let42/python-course | ---
+++
@@ -0,0 +1,34 @@
+# Print every single letter of a word with 'for' iteration and with 'while' iteration
+# Also create a method for all single iteration required. Finally with main method
+# require a word to be printed, until isn't typed 'done!'
+#
+
+def print_letters_with_for( word ):
+
+ for w in word:
+ ... | |
110de31dd7e2d3727cc4b9c8bd606f3367e5eb13 | tests/subprocessdata/sigchild_ignore.py | tests/subprocessdata/sigchild_ignore.py | import os
import signal, sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
log = open('/var/tmp/subprocess', 'w')
log.write(os.path.join(os.path.dirname(__file__), '..', '..'))
log.close()
from kitchen.pycompat27.subprocess import _subprocess as subprocess
# On Linux this causes os.waitpid t... | Add the new subprocess test script | Add the new subprocess test script
| Python | lgpl-2.1 | fedora-infra/kitchen,fedora-infra/kitchen | ---
+++
@@ -0,0 +1,14 @@
+import os
+import signal, sys
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))
+
+log = open('/var/tmp/subprocess', 'w')
+log.write(os.path.join(os.path.dirname(__file__), '..', '..'))
+log.close()
+from kitchen.pycompat27.subprocess import _subprocess as subprocess
+... | |
3f758781c9c42b5c3bd14f70f70caa555d497d88 | rsplayer_logs.py | rsplayer_logs.py | """Helper to process RSPlayer logs for Programme Return.
Put RSPlayer logs into some folder, change to it, open a Python prompt and paste
in this code. Be sure that the logs contain only the data you want (ie trim the
start and end to get rid of data outside of the reporting period).
XXX To do:
"""
import ... | Convert RSPlayer 2 logs into CSV for programme return. | Convert RSPlayer 2 logs into CSV for programme return.
| Python | mit | radio-st-austell-bay/helpers | ---
+++
@@ -0,0 +1,73 @@
+"""Helper to process RSPlayer logs for Programme Return.
+
+Put RSPlayer logs into some folder, change to it, open a Python prompt and paste
+in this code. Be sure that the logs contain only the data you want (ie trim the
+start and end to get rid of data outside of the reporting period).
+... | |
7cd6515e7a06997bbdb24908accfd503b95824be | src/pythonic/test_primes.py | src/pythonic/test_primes.py | import pytest
import itertools
from main import Primes, Sieve
def test_sieve_limit():
limit = 10000
with Sieve(limit) as s:
assert s.upper_bound() >= limit
def test_upper_bound_exception():
limit = 10
with Sieve(limit) as s:
with pytest.raises(IndexError):
s.is_prime(101)... | Add basic Python tests for Primes and Sieve | Add basic Python tests for Primes and Sieve
* Make sure an exception is thrown if upper_bounds is exceeded
* 0 is not in primes list
* Number of prives asked for is given
* Sieve upper bounds >= limit
| Python | cc0-1.0 | Michael-F-Bryan/rust-ffi-guide,Michael-F-Bryan/rust-ffi-guide,Michael-F-Bryan/rust-ffi-guide | ---
+++
@@ -0,0 +1,28 @@
+import pytest
+import itertools
+from main import Primes, Sieve
+
+
+def test_sieve_limit():
+ limit = 10000
+ with Sieve(limit) as s:
+ assert s.upper_bound() >= limit
+
+
+def test_upper_bound_exception():
+ limit = 10
+ with Sieve(limit) as s:
+ with pytest.raise... | |
740e1c1171a3c9f50a0f69a6154acf840f52652f | Trie.py | Trie.py | #! /usr/bin/env python
# vim: set encoding=utf-8
from ctypes import *
libtrie = cdll.LoadLibrary("./libtrie.so")
libtrie.trie_lookup.restype = c_char_p
class TrieException(Exception):
pass
class Trie(object):
def __init__(self, filename):
self.ptr = libtrie.trie_load(filename)
if self.ptr ==... | Add a python binding via ctypes | Add a python binding via ctypes
| Python | bsd-3-clause | lubomir/libtrie,lubomir/libtrie,lubomir/libtrie | ---
+++
@@ -0,0 +1,28 @@
+#! /usr/bin/env python
+# vim: set encoding=utf-8
+
+from ctypes import *
+
+libtrie = cdll.LoadLibrary("./libtrie.so")
+libtrie.trie_lookup.restype = c_char_p
+
+class TrieException(Exception):
+ pass
+
+class Trie(object):
+ def __init__(self, filename):
+ self.ptr = libtrie.t... | |
61e542ab3fab4ef15cff8e1d5189652f8e10b5cf | scriptOffsets.py | scriptOffsets.py | from msc import *
from sys import argv
with open(argv[1], 'rb') as f:
mscFile = MscFile()
mscFile.readFromFile(f)
if len(argv) > 2:
nums = [int(i,0) for i in argv[2:]]
for num in nums:
for i,script in enumerate(mscFile):
if script.bounds[0] == num:
... | Add dev tool script to print off script names from offsets | Add dev tool script to print off script names from offsets
| Python | mit | jam1garner/pymsc | ---
+++
@@ -0,0 +1,15 @@
+from msc import *
+from sys import argv
+
+with open(argv[1], 'rb') as f:
+ mscFile = MscFile()
+ mscFile.readFromFile(f)
+ if len(argv) > 2:
+ nums = [int(i,0) for i in argv[2:]]
+ for num in nums:
+ for i,script in enumerate(mscFile):
+ if s... | |
ef32dccfe3df84b3619cf200463a6fa7d08e1bae | anydo/lib/tests/test_error.py | anydo/lib/tests/test_error.py | # -*- coding: utf-8 -*-
import unittest
from anydo import error
from anydo.lib import error as lib_error
class ErrorTests(unittest.TestCase):
def test_error_msg(self):
self.assertEqual(error.AnyDoAPIError('dummy', 'test').__str__(),
'(dummy): test')
def test_lib_error_msg(s... | Add unittest for anydo.error, anydo.lib.error. | Add unittest for anydo.error, anydo.lib.error.
Signed-off-by: Kouhei Maeda <c9f1823971fa1a4c79cdb50b3311094021cee31e@palmtb.net>
| Python | mit | gvkalra/python-anydo,gvkalra/python-anydo | ---
+++
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+from anydo import error
+from anydo.lib import error as lib_error
+
+
+class ErrorTests(unittest.TestCase):
+
+ def test_error_msg(self):
+ self.assertEqual(error.AnyDoAPIError('dummy', 'test').__str__(),
+ '(dummy... | |
a406e198127d22944340a0c364112684556177f2 | scripts/feature_selection.py | scripts/feature_selection.py | import pandas as pd
import numpy as np
from xgboost.sklearn import XGBClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import KFold
from sklearn.feature_selection import SelectFromModel
from utils.metrics import ndcg_scorer
pa... | Add structure to feature selection script | Add structure to feature selection script
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -0,0 +1,55 @@
+import pandas as pd
+import numpy as np
+from xgboost.sklearn import XGBClassifier
+from sklearn.preprocessing import LabelEncoder
+from sklearn.cross_validation import cross_val_score
+from sklearn.cross_validation import KFold
+from sklearn.feature_selection import SelectFromModel
+
+from ... | |
b5378ee0b1562401e5ee7274faa991ad59047d3a | whats_fresh/whats_fresh_api/migrations/0003_auto_20141120_2308.py | whats_fresh/whats_fresh_api/migrations/0003_auto_20141120_2308.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('whats_fresh_api', '0002_auto_20141120_2246'),
]
operations = [
migrations.AlterField(
model_name='image',
... | Add default values to name fields | Add default values to name fields
refs #17433
| Python | apache-2.0 | osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api,iCHAIT/whats-fresh-api,osu-cass/whats-fresh-api,iCHAIT/whats-fresh-api | ---
+++
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('whats_fresh_api', '0002_auto_20141120_2246'),
+ ]
+
+ operations = [
+ migrations.AlterFiel... | |
8332a9150e621306e94f3ac994f048451325e3db | scripts/scraper_converter.py | scripts/scraper_converter.py | '''
Usage:
python scraper_converter.py scraped.db formatted.db
Processes the cards scraped using the gatherer downloader and adds sane attributes fields for querying
(int pow/toughness, cmc) and saves the output to a new sqlite database.
Card attributes are saved according to finder.models.Card
'''
import sqlsoup
... | Add shell of "GathererDownloader" converter | Add shell of "GathererDownloader" converter
This script takes the raw values from GathererDownloader and adds
rich comparison values such as integer power, toughness, as well as
new fields such as tilde rules (for finding self-referential cards) or
ascii name for the whole series of Aether <Whatever>.
Currently this ... | Python | mit | numberoverzero/finder | ---
+++
@@ -0,0 +1,78 @@
+'''
+Usage:
+ python scraper_converter.py scraped.db formatted.db
+
+Processes the cards scraped using the gatherer downloader and adds sane attributes fields for querying
+(int pow/toughness, cmc) and saves the output to a new sqlite database.
+
+Card attributes are saved according to find... | |
df32bf731285be48a7f713657ef1b281229c3226 | get_module_api.py | get_module_api.py | #!/usr/bin/python3
import click
from pdc_client import PDCClient
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
def get_modulemd(module_name, stream):
"""
Check if module and stream are built successfully on PDC server
"""... | Add script to retrieve the RPM API of modules | Add script to retrieve the RPM API of modules
| Python | mit | sgallagher/baseruntime-package-lists,sgallagher/baseruntime-package-lists,fedora-modularity/baseruntime-package-lists,sgallagher/baseruntime-package-lists,fedora-modularity/baseruntime-package-lists,fedora-modularity/baseruntime-package-lists | ---
+++
@@ -0,0 +1,49 @@
+#!/usr/bin/python3
+
+import click
+from pdc_client import PDCClient
+import yaml
+try:
+ from yaml import CLoader as Loader, CDumper as Dumper
+except ImportError:
+ from yaml import Loader, Dumper
+
+def get_modulemd(module_name, stream):
+ """
+ Check if module and stream are ... | |
8840ac409cac7c187f2fd7941f8186397beb61fb | src/arlobot_apps/arlobot_navigation/scripts/laser_filter.py | src/arlobot_apps/arlobot_navigation/scripts/laser_filter.py | #!/usr/bin/env python
import rospy
from sensor_msgs.msg import LaserScan
import math
def callback(data):
#Option 1) Conform data to specified input/output ranges
#data.ranges = [data.range_max if range_val>data.range_max else (data.range_min if range_val<data.range_min else range_val) for range_val in data.ranges... | Add laster filter for adjusting laser scanner data on the fly. | Add laster filter for adjusting laser scanner data on the fly.
| Python | mit | remarvel/ArloBot,chrisl8/ArloBot,remarvel/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,chrisl8/ArloBot,DTU-R3/ArloBot,chrisl8/ArloBot,remarvel/ArloBot,DTU-R3/ArloBot,remarvel/ArloBot,chrisl8/ArloBot,remarvel/ArloBot,remarvel/ArloBot,DTU-R3/ArloBot,DTU-R3/ArloBot | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+import rospy
+from sensor_msgs.msg import LaserScan
+import math
+
+def callback(data):
+#Option 1) Conform data to specified input/output ranges
+ #data.ranges = [data.range_max if range_val>data.range_max else (data.range_min if range_val<data.range_min else rang... | |
2adb05bb518bbb18036c8c6ccc353e2381a79d86 | indra/tests/test_rest_api.py | indra/tests/test_rest_api.py | import requests
def test_rest_api_responsive():
stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ERK", "NCIT": "C26360", "BE": "E... | Add smoke test for REST API on Travis | Add smoke test for REST API on Travis
| Python | bsd-2-clause | johnbachman/belpy,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,johnbachman/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy | ---
+++
@@ -0,0 +1,8 @@
+import requests
+
+def test_rest_api_responsive():
+ stmt_str = '{"statements": [{"sbo": "http://identifiers.org/sbo/SBO:0000526", "type": "Complex", "id": "acc6d47c-f622-41a4-8ae9-d7b0f3d24a2f", "members": [{"db_refs": {"TEXT": "MEK", "BE": "MEK"}, "name": "MEK"}, {"db_refs": {"TEXT": "ER... | |
0c86a376e75d5ed2363bcd986558bb5f0841c8ec | Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Polyphony.py | Sketches/JT/Jam/library/trunk/Kamaelia/Apps/Jam/Audio/Polyphony.py | import Axon
class Polyphoniser(Axon.AdaptiveCommsComponent.AdaptiveCommsComponent):
polyphony = 8
def __init__(self, **argd):
super(Polyphoniser, self).__init__(**argd)
self.voices = []
for i in range(self.polyphony):
self.addOutbox("voice%i" % i)
self.voices.app... | Add polyphoniser component for routeing note on and off messages around a number of voices | Add polyphoniser component for routeing note on and off messages around a number of voices
| Python | apache-2.0 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | ---
+++
@@ -0,0 +1,36 @@
+import Axon
+
+class Polyphoniser(Axon.AdaptiveCommsComponent.AdaptiveCommsComponent):
+ polyphony = 8
+ def __init__(self, **argd):
+ super(Polyphoniser, self).__init__(**argd)
+ self.voices = []
+ for i in range(self.polyphony):
+ self.addOutbox("voice... | |
8bd1efce568b603159a5a083cc9f9ce3a550d2b8 | eva/util/kutil.py | eva/util/kutil.py | import keras.backend as K
def get_input(rows, cols, channels):
return (channels, rows, cols) if K.image_dim_ordering() == 'th' else (rows, cols, channels)
| Add keras util with get input func | Add keras util with get input func
| Python | apache-2.0 | israelg99/eva | ---
+++
@@ -0,0 +1,4 @@
+import keras.backend as K
+
+def get_input(rows, cols, channels):
+ return (channels, rows, cols) if K.image_dim_ordering() == 'th' else (rows, cols, channels) | |
f85d45a781eef0ab6d7362dad45da94be4bbf8df | zerver/management/commands/turn_off_digests.py | zerver/management/commands/turn_off_digests.py | from __future__ import absolute_import
from optparse import make_option
from django.core.management.base import BaseCommand
from zerver.lib.actions import do_change_enable_digest_emails
from zerver.models import Realm, UserProfile, get_user_profile_by_email
class Command(BaseCommand):
help = """Turn off digests... | Add a management command to bulk turn off digests. | Add a management command to bulk turn off digests.
(imported from commit 0ffb565ecc9be219807ae9a45abb7b0e3e940204)
| Python | apache-2.0 | qq1012803704/zulip,eastlhu/zulip,wweiradio/zulip,Gabriel0402/zulip,LeeRisk/zulip,JPJPJPOPOP/zulip,Jianchun1/zulip,Qgap/zulip,JanzTam/zulip,punchagan/zulip,Gabriel0402/zulip,gigawhitlocks/zulip,zorojean/zulip,suxinde2009/zulip,zacps/zulip,fw1121/zulip,JPJPJPOPOP/zulip,jeffcao/zulip,jimmy54/zulip,PhilSk/zulip,jainayush97... | ---
+++
@@ -0,0 +1,46 @@
+from __future__ import absolute_import
+
+from optparse import make_option
+
+from django.core.management.base import BaseCommand
+
+from zerver.lib.actions import do_change_enable_digest_emails
+from zerver.models import Realm, UserProfile, get_user_profile_by_email
+
+class Command(BaseCom... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.