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 |
|---|---|---|---|---|---|---|---|---|---|---|
1af9b33c603a266b00274cb6b2e707a62d956242 | bin/debug/fix_usercache_processing.py | bin/debug/fix_usercache_processing.py | # Fixes usercache processing
# If there are any errors in the usercache processing, fix them and reload the data
# Basic flow
# - Copy data back to user cache
# - Attempt to moveToLongTerm
# - Find errors
# - Fix errors
# - Repeat until no errors are found
import sys
import logging
logging.basicConfig(level=logging.DEB... | Check in a script to debug usercache processing | Check in a script to debug usercache processing
Currently, if there are errors in processing the usercache, we store the
erroneous values into a separate usercache error database. But then, we want to
evaluate the errors and fix them if they reflect bugs. This is a script that
allows us to do that.
It basically copie... | Python | bsd-3-clause | yw374cornell/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,joshzarrabi/e-mission-server,sunil07t/e-mission-server,joshzarrabi/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-ser... | ---
+++
@@ -0,0 +1,48 @@
+# Fixes usercache processing
+# If there are any errors in the usercache processing, fix them and reload the data
+# Basic flow
+# - Copy data back to user cache
+# - Attempt to moveToLongTerm
+# - Find errors
+# - Fix errors
+# - Repeat until no errors are found
+import sys
+import logging
... | |
9d196fff2c1347361e3650363e2c4d718e84ce62 | CodeFights/avoidObstacles.py | CodeFights/avoidObstacles.py | #!//urs/local/bin/python
# Code Fights Avoid Obstacles Problem
def avoidObstacles(inputArray):
for jump in range(2, 40):
safe = True
for item in inputArray:
if item % jump == 0:
safe = False
break
if safe:
return jump
def main():
... | Solve Code Fights avoid obstacles problem | Solve Code Fights avoid obstacles problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,34 @@
+#!//urs/local/bin/python
+# Code Fights Avoid Obstacles Problem
+
+
+def avoidObstacles(inputArray):
+ for jump in range(2, 40):
+ safe = True
+ for item in inputArray:
+ if item % jump == 0:
+ safe = False
+ break
+ if safe:
+... | |
ce7a93bea9aeeaa49bec527b69f2b65efc7c450d | plotter.py | plotter.py | import plotly.graph_objs as go
import plotly.plotly as py
from plotly.tools import FigureFactory as FF
import matplotlib.pyplot as plt
def plot(x_data, y_data):
# x_data = iteration_numbers
# y_data = makespans
# colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', (1, 1, 0.2), (0.98,0.98,0.98)]
# ... | Move plotting out of main | Move plotting out of main
| Python | mit | Irvel/JSSP-Genetic-Algorithm | ---
+++
@@ -0,0 +1,35 @@
+import plotly.graph_objs as go
+import plotly.plotly as py
+from plotly.tools import FigureFactory as FF
+import matplotlib.pyplot as plt
+
+
+def plot(x_data, y_data):
+ # x_data = iteration_numbers
+ # y_data = makespans
+ # colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', ... | |
75f36085f81c763016517901084d3181f9f1f108 | pinax/eventlog/migrations/0003_auto_20160111_0208.py | pinax/eventlog/migrations/0003_auto_20160111_0208.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-11 02:08
from __future__ import unicode_literals
from django.db import migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('eventlog', '0002_auto_20150113_1450'),
]
operations = [
migr... | Add missing migration from the switch to jsonfield | Add missing migration from the switch to jsonfield
| Python | mit | pinax/pinax-eventlog | ---
+++
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.1 on 2016-01-11 02:08
+from __future__ import unicode_literals
+
+from django.db import migrations
+import jsonfield.fields
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('eventlog', '0002_auto_20150113_1450'),... | |
fd850084bd858be9fcc98fa8fbe29bdd481fc066 | qserver.py | qserver.py | #!/usr/bin/env python
"""
qserver
This module will use a queuing server to execute a number of tasks
across multiple threads.
Example
-------
tasks = (qserver.os_task("list files","ls -1"), \
qserver.task("my job",my_func,arg1,arg2,arg3))
qserver.start(tasks)
Written by Brian Powe... | Add queueing server to handle multiple processes | Add queueing server to handle multiple processes
| Python | mit | dalepartridge/seapy,ocefpaf/seapy,powellb/seapy | ---
+++
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+"""
+ qserver
+
+ This module will use a queuing server to execute a number of tasks
+ across multiple threads.
+
+ Example
+ -------
+
+ tasks = (qserver.os_task("list files","ls -1"), \
+ qserver.task("my job",my_func,arg1,arg2,arg3))
+ qserver... | |
0c3c3921897816f0c7c1c74ad0b52a25cef5b742 | tests/compat.py | tests/compat.py | import sys
if sys.version_info.major < 3:
import unittest2 as unittest
else:
import unittest
| from evelink.thirdparty.six import PY2
if PY2:
import unittest2 as unittest
else:
import unittest
| Use six for easy version info. | [PY3] Use six for easy version info.
| Python | mit | Morloth1274/EVE-Online-POCO-manager,FashtimeDotCom/evelink,ayust/evelink,zigdon/evelink,bastianh/evelink | ---
+++
@@ -1,5 +1,5 @@
-import sys
-if sys.version_info.major < 3:
+from evelink.thirdparty.six import PY2
+if PY2:
import unittest2 as unittest
else:
import unittest |
495a9617cd42b5d88f9391b47d355a93c960c988 | corehq/apps/data_interfaces/migrations/0007_logging_models.py | corehq/apps/data_interfaces/migrations/0007_logging_models.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-04 20:05
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('data_interfaces', '0006_case_rule_refactor'),
]
op... | Add migration for logging models | Add migration for logging models
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,49 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.6 on 2017-04-04 20:05
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('data_interfaces', '0... | |
f3bce5f47dc75e392a72846d98de467af6892f28 | dit/example_dists/tests/test_mdbsi.py | dit/example_dists/tests/test_mdbsi.py | """
Tests for the MDBSI distributions.
"""
import pytest
from dit.example_dists.mdbsi import dyadic, triadic
from dit.multivariate import (
entropy as H,
total_correlation as T,
dual_total_correlation as B,
coinformation as I,
residual_entropy as R,
caekl_mutual_information as J,
tse_compl... | Add tests regarding the dyadic and triadic distributions from MDBSI. | Add tests regarding the dyadic and triadic distributions from MDBSI.
| Python | bsd-3-clause | Autoplectic/dit,Autoplectic/dit,dit/dit,Autoplectic/dit,dit/dit,dit/dit,dit/dit,Autoplectic/dit,dit/dit,Autoplectic/dit | ---
+++
@@ -0,0 +1,51 @@
+"""
+Tests for the MDBSI distributions.
+"""
+
+import pytest
+
+from dit.example_dists.mdbsi import dyadic, triadic
+from dit.multivariate import (
+ entropy as H,
+ total_correlation as T,
+ dual_total_correlation as B,
+ coinformation as I,
+ residual_entropy as R,
+ cae... | |
ad705bd8993ba522326c64bd9b6232ef5374e65f | diffsettings-all.py | diffsettings-all.py | #!/usr/bin/env python
# Based on Django 1.5 diffsettings
# https://github.com/django/django/blob/1.5/django/core/management/commands/diffsettings.py
import sys
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"Converts a module namespace to a Python dictionary. Used by get_settings_diff."
re... | Add diffsettings --all for Django<=1.5 | scripts: Add diffsettings --all for Django<=1.5
| Python | bsd-3-clause | fmierlo/django-default-settings,fmierlo/django-default-settings | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+# Based on Django 1.5 diffsettings
+# https://github.com/django/django/blob/1.5/django/core/management/commands/diffsettings.py
+import sys
+
+
+def module_to_dict(module, omittable=lambda k: k.startswith('_')):
+ "Converts a module namespace to a Python dictionary.... | |
9f94ad31c1f94cccf4dbdaef6a7b8faa0199fa46 | test/integration/ggrc/converters/test_export_snapshots.py | test/integration/ggrc/converters/test_export_snapshots.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for snapshot export."""
from integration.ggrc import TestCase
class TestExportSnapshots(TestCase):
"""Tests basic snapshot export."""
def setUp(self):
super(TestExportSnapshots, self).se... | Add basic snapshot export test | Add basic snapshot export test
| Python | apache-2.0 | AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core | ---
+++
@@ -0,0 +1,34 @@
+# Copyright (C) 2017 Google Inc.
+# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
+
+"""Tests for snapshot export."""
+
+from integration.ggrc import TestCase
+
+
+class TestExportSnapshots(TestCase):
+ """Tests basic snapshot export."""
+
+ def setUp(self):
... | |
0129f699427300feaf61eb4dda122c98dab32328 | caffe2/python/operator_test/snapshot_test.py | caffe2/python/operator_test/snapshot_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core, workspace
import os
import shutil
import tempfile
import unittest
class SnapshotTest(unittest.TestCase):
"""A simple test case to ma... | Add a snapshot test for Simon Layton | Add a snapshot test for Simon Layton
Summary: This is mainly for the OSS side checking.
Reviewed By: dzhulgakov
Differential Revision: D4238349
fbshipit-source-id: 061da3f721341c4a1249e1cc6c8c842fc505860f
| Python | apache-2.0 | davinwang/caffe2,bwasti/caffe2,bwasti/caffe2,xzturn/caffe2,pietern/caffe2,davinwang/caffe2,Yangqing/caffe2,davinwang/caffe2,Yangqing/caffe2,xzturn/caffe2,xzturn/caffe2,Yangqing/caffe2,bwasti/caffe2,xzturn/caffe2,caffe2/caffe2,xzturn/caffe2,bwasti/caffe2,Yangqing/caffe2,sf-wind/caffe2,pietern/caffe2,sf-wind/caffe2,piete... | ---
+++
@@ -0,0 +1,44 @@
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import print_function
+from __future__ import unicode_literals
+
+from caffe2.python import core, workspace
+import os
+import shutil
+import tempfile
+import unittest
+
+
+class SnapshotTest(unittest.Te... | |
e16054a24c7e8d5325ad4b1fa31a65681febc43c | test/test_se.py | test/test_se.py | # vim: foldmethod=marker
from lobster.cmssw import dataset
from lobster import fs, se
import os
import shutil
import subprocess
import tempfile
import unittest
class TestSE(unittest.TestCase):
@classmethod
def setUpClass(cls):
path = os.path.expandvars('/hadoop/store/user/matze/')
cls.workdir =... | Add tests for non-DBS data discovery. | Add tests for non-DBS data discovery.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster | ---
+++
@@ -0,0 +1,69 @@
+# vim: foldmethod=marker
+from lobster.cmssw import dataset
+from lobster import fs, se
+import os
+import shutil
+import subprocess
+import tempfile
+import unittest
+
+class TestSE(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ path = os.path.expandvars('/hadoop/s... | |
cbd90060410108877d068913a4dfc681b81d6956 | galera_consistency.py | galera_consistency.py | import optparse
import subprocess
def table_checksum(user, password, host):
args = ['/usr/bin/pt-table-checksum', '-u', user, '-p', password]
if host:
args.extend(['-h', host])
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
(out, err) = proc.communicate()
return (proc.return_code, ... | Use pt-table-checksum to check for galera consistency | Use pt-table-checksum to check for galera consistency
| Python | apache-2.0 | jpmontez/rpc-openstack,cfarquhar/rpc-maas,miguelgrinberg/rpc-openstack,xeregin/rpc-openstack,mancdaz/rpc-openstack,nrb/rpc-openstack,stevelle/rpc-openstack,claco/rpc-openstack,BjoernT/rpc-openstack,npawelek/rpc-maas,shannonmitchell/rpc-openstack,rcbops/rpc-openstack,robb-romans/rpc-openstack,mattt416/rpc-openstack,andy... | ---
+++
@@ -0,0 +1,36 @@
+import optparse
+import subprocess
+
+
+def table_checksum(user, password, host):
+ args = ['/usr/bin/pt-table-checksum', '-u', user, '-p', password]
+ if host:
+ args.extend(['-h', host])
+
+ proc = subprocess.Popen(args, stderr=subprocess.PIPE)
+ (out, err) = proc.commun... | |
a948006eb02591d56f76b32b98d5bb8ace5c2600 | indra/sources/sofia/make_sofia_tsv.py | indra/sources/sofia/make_sofia_tsv.py | import sys
import json
def make_file(ont_json_file, fname):
with open(ont_json_file, 'r') as fh:
ont_json = json.load(fh)
rows = []
for top_key, entries in ont_json.items():
for entry_key, examples in entries.items():
entry_str = '%s/%s' % (top_key, entry_key)
examp... | Make SOFIA TSV for ontology mapping | Make SOFIA TSV for ontology mapping
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra | ---
+++
@@ -0,0 +1,23 @@
+import sys
+import json
+
+
+def make_file(ont_json_file, fname):
+ with open(ont_json_file, 'r') as fh:
+ ont_json = json.load(fh)
+ rows = []
+ for top_key, entries in ont_json.items():
+ for entry_key, examples in entries.items():
+ entry_str = '%s/%s' % ... | |
1ef08f6d940f47033df003dd641e61e718b2ca57 | src/tests/test_beeper.py | src/tests/test_beeper.py | from unittest import mock
from geometry_msgs.msg import PoseStamped
import rospy
from beeper import Beeper
class TestBeeper(object):
def setup(self):
rospy.init_node("beeper_test", anonymous=True)
self.beeper = Beeper()
self.pose = PoseStamped()
@mock.patch.object(Beeper, "beep", aut... | Add test file for beeper logic | Add test file for beeper logic
| Python | mit | masasin/spirit,masasin/spirit | ---
+++
@@ -0,0 +1,19 @@
+from unittest import mock
+
+from geometry_msgs.msg import PoseStamped
+import rospy
+from beeper import Beeper
+
+
+class TestBeeper(object):
+ def setup(self):
+ rospy.init_node("beeper_test", anonymous=True)
+ self.beeper = Beeper()
+ self.pose = PoseStamped()
+
+ ... | |
af5840c8f223d334997440878d0a7e7eaeb19be4 | test/alltests.py | test/alltests.py | #!/usr/bin/env python
"""Build the documentation, and run the JavaScript tests."""
import sphinx.cmdline
import os
import sys
# Build the documentation for vcwebedit.
source_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'doc')
build_dir = os.path.join(source_dir, '_build')
# Build html, warni... | Add script to run tests. | Add script to run tests.
| Python | apache-2.0 | thewtex/vcwebedit,thewtex/vcwebedit | ---
+++
@@ -0,0 +1,30 @@
+#!/usr/bin/env python
+
+"""Build the documentation, and run the JavaScript tests."""
+
+import sphinx.cmdline
+
+import os
+import sys
+
+# Build the documentation for vcwebedit.
+source_dir = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'doc')
+build_dir = os.path.join(so... | |
72169b77a1d5cf92aa906b616b93f702b3ce55a1 | spectra.py | spectra.py | import sys
import numpy as np
from realtime import *
class Spectra(object):
"""Return a spectra object that can plot the total absorption spectrum or
circular dichroism spectra for a given system. Can accept x,y,and z RT-TDDFT
log files"""
def __init__(self,x=None,y=None,z=None,s='abs',d=150):
... | Add Spectra class for plotting data from RealTime objects | Add Spectra class for plotting data from RealTime objects
| Python | mit | wavefunction91/gaussian_realtime_parse,jjgoings/gaussian_realtime_parse | ---
+++
@@ -0,0 +1,77 @@
+import sys
+import numpy as np
+from realtime import *
+
+class Spectra(object):
+ """Return a spectra object that can plot the total absorption spectrum or
+ circular dichroism spectra for a given system. Can accept x,y,and z RT-TDDFT
+ log files"""
+ def __init__(self,x=None,y=... | |
e08ac069b2bee1afaaf022a884dd098dc7daac07 | parseSubtitles.py | parseSubtitles.py | # the words "subtitles" and "captions" are used interchangeably
import re
def getVtt(fname):
with open(fname) as f:
content = f.readlines()
content = [x.strip() for x in content]
p = re.compile('\d{2}:\d{2}:\d{2}.\d{3} --> \d{2}:\d{2}:\d{2}.\d{3}')
pureText = ""
pay_attention = False
... | Store perfectly working parser for one of the subtitle formats. | Store perfectly working parser for one of the subtitle formats.
| Python | mit | aktivkohle/youtube-curation,aktivkohle/youtube-curation,aktivkohle/youtube-curation,aktivkohle/youtube-curation | ---
+++
@@ -0,0 +1,32 @@
+# the words "subtitles" and "captions" are used interchangeably
+
+import re
+
+def getVtt(fname):
+ with open(fname) as f:
+ content = f.readlines()
+ content = [x.strip() for x in content]
+
+ p = re.compile('\d{2}:\d{2}:\d{2}.\d{3} --> \d{2}:\d{2}:\d{2}.\d{3}')
+
+ pur... | |
7b4d626e9366ebe6e31d9835ce05f397056d5817 | tile_generator/tile_unittest.py | tile_generator/tile_unittest.py | # tile-generator
#
# Copyright (c) 2015-Present Pivotal Software, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#... | Add test for the "tile init" command. | Add test for the "tile init" command.
| Python | apache-2.0 | alex-slynko/tile-generator,cf-platform-eng/tile-generator,cf-platform-eng/tile-generator,alex-slynko/tile-generator,cf-platform-eng/tile-generator,alex-slynko/tile-generator,cf-platform-eng/tile-generator,alex-slynko/tile-generator | ---
+++
@@ -0,0 +1,35 @@
+# tile-generator
+#
+# Copyright (c) 2015-Present Pivotal Software, Inc. All Rights Reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://w... | |
6e8bade6225d3a7108cc679f1fcbe371f7241278 | councilmatic_core/migrations/0052_convert_last_action_date_to_datefield.py | councilmatic_core/migrations/0052_convert_last_action_date_to_datefield.py | # Generated by Django 2.2.16 on 2020-09-15 15:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('councilmatic_core', '0051_bill_last_action_date'),
]
operations = [
migrations.AlterField(
model_name='bill',
name=... | Add migration for last_action_date field change | Add migration for last_action_date field change
| Python | mit | datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic,datamade/django-councilmatic | ---
+++
@@ -0,0 +1,18 @@
+# Generated by Django 2.2.16 on 2020-09-15 15:27
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('councilmatic_core', '0051_bill_last_action_date'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ ... | |
a486899294faa18cf8d7c51dc12a2fe87b584804 | salt/_modules/minealiases.py | salt/_modules/minealiases.py | def psf_internal(cidr):
return __salt__["ip_picker.ip_addrs"](cidr=cidr)
def pypi_internal(cidr):
return __salt__["ip_picker.ip_addrs"](cidr=cidr)
| Add some mine alias functions | Add some mine alias functions
| Python | mit | dstufft/psf-salt,zooba/psf-salt,dstufft/psf-salt,zware/psf-salt,caktus/psf-salt,caktus/psf-salt,python/psf-salt,caktus/psf-salt,zooba/psf-salt,zooba/psf-salt,python/psf-salt,python/psf-salt,zware/psf-salt,zware/psf-salt,zware/psf-salt,dstufft/psf-salt,python/psf-salt | ---
+++
@@ -0,0 +1,6 @@
+def psf_internal(cidr):
+ return __salt__["ip_picker.ip_addrs"](cidr=cidr)
+
+
+def pypi_internal(cidr):
+ return __salt__["ip_picker.ip_addrs"](cidr=cidr) | |
3451b122a7b30c1aa43b56833051c6e1ae9c5874 | github_follow.py | github_follow.py | #!/usr/bin/env python
from __future__ import absolute_import, print_function
import getpass
import requests
from requests.auth import HTTPBasicAuth
from hs_oauth import get_access_token, get_batches, get_people_in_a_batch
def follow_user(username, auth):
url = 'https://api.github.com/user/following/%s' % usern... | Add script for batchwise GitHub follow. | Add script for batchwise GitHub follow.
| Python | unlicense | punchagan/hs-twitter-lists | ---
+++
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+from __future__ import absolute_import, print_function
+
+import getpass
+
+import requests
+from requests.auth import HTTPBasicAuth
+
+from hs_oauth import get_access_token, get_batches, get_people_in_a_batch
+
+
+def follow_user(username, auth):
+ url = 'https://a... | |
3dd24e35cbc79a07af49c86cc8dcdb2b20d91805 | final/problem3.py | final/problem3.py | # Problem 3
# 10.0 points possible (graded)
# Numbers in Mandarin follow 3 simple rules:
# There are words for each of the digits from 0 to 10.
# For numbers 11-19, the number is pronounced as "ten digit", so for example, 16 would be pronounced (using Mandarin) as "ten six".
# For numbers between 20 and 99, the number... | Write a procedure that converts an American number into the equivalent Mandarin. | Write a procedure that converts an American number into the equivalent Mandarin.
| Python | mit | Kunal57/MIT_6.00.1x | ---
+++
@@ -0,0 +1,42 @@
+# Problem 3
+# 10.0 points possible (graded)
+# Numbers in Mandarin follow 3 simple rules:
+
+# There are words for each of the digits from 0 to 10.
+# For numbers 11-19, the number is pronounced as "ten digit", so for example, 16 would be pronounced (using Mandarin) as "ten six".
+# For num... | |
8ac395498ed6efd8557bf0aac8d9fb75469019a6 | bin/religiousforums_scraper.py | bin/religiousforums_scraper.py | #!/usr/bin/env python
import argparse
import os
import os.path
from bs4 import BeautifulSoup
import requests
def post_filter(tag):
if tag.name != 'blockquote':
return False
if not tag.has_attr('class'):
return False
return isinstance(tag['class'], list) and 'messageText' in tag['class']
... | Write scraper script for Religiousforums forum | Write scraper script for Religiousforums forum
| Python | mit | kemskems/otdet | ---
+++
@@ -0,0 +1,45 @@
+#!/usr/bin/env python
+
+import argparse
+import os
+import os.path
+
+from bs4 import BeautifulSoup
+import requests
+
+
+def post_filter(tag):
+ if tag.name != 'blockquote':
+ return False
+ if not tag.has_attr('class'):
+ return False
+ return isinstance(tag['class'... | |
6388ac01b61266ca1cb9a5d0c3eb063c3dff0a6f | usingnamespace/forms/schemaform.py | usingnamespace/forms/schemaform.py | from deform import Form
class SchemaFormMixin(object):
@classmethod
def create_form(cls, *arg, **kw):
schema_vars = {}
form_vars = {}
for sn in ['validator', 'preparer', 'after_bind']:
if sn in kw:
schema_vars[sn] = kw[sn]
del kw[sn]
... | Add a MixIn that makes it simpler to instantiate a deform | Add a MixIn that makes it simpler to instantiate a deform
This adds a very simple MixIn that makes it easier to instantiate a form
along wth providing the right values to the various moving pieces, such
as the schema, the bindings and the form itself. Less boiler plate to
write elsewhere.
| Python | isc | usingnamespace/usingnamespace | ---
+++
@@ -0,0 +1,30 @@
+from deform import Form
+
+class SchemaFormMixin(object):
+ @classmethod
+ def create_form(cls, *arg, **kw):
+ schema_vars = {}
+ form_vars = {}
+
+ for sn in ['validator', 'preparer', 'after_bind']:
+ if sn in kw:
+ schema_vars[sn] = kw[s... | |
feb8db57d5a73593f066d63f10383e77576c226d | crawler/management/commands/recommendation_accuracy.py | crawler/management/commands/recommendation_accuracy.py | from django.core.management import BaseCommand
from crawler.models import *
class Command(BaseCommand):
help = 'Calculate recommendation accuracy per user'
def handle(self, *args, **options):
result_dict = dict()
users = User.objects.all()
for user in users:
count = 0
... | Create command to calculate recommendation's accuracy | Create command to calculate recommendation's accuracy
| Python | apache-2.0 | bkosawa/admin-recommendation | ---
+++
@@ -0,0 +1,33 @@
+from django.core.management import BaseCommand
+
+from crawler.models import *
+
+
+class Command(BaseCommand):
+ help = 'Calculate recommendation accuracy per user'
+
+ def handle(self, *args, **options):
+ result_dict = dict()
+ users = User.objects.all()
+
+ for... | |
c32a12ed83ec033462126dfacf3fcf144626cebf | euler021.py | euler021.py | #!/usr/bin/python
"""
First attempt to resolve was really brute force and slow,
this is a better solution, see problem page for explanation
"""
from math import floor, sqrt
LIMIT = 10000
result = 0
def d(n):
res = 0
r = floor(sqrt(n))
if r * r == n:
res = r + 1
r -= 1
else:
... | Add solution for problem 21 | Add solution for problem 21
| Python | mit | cifvts/PyEuler | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/bin/python
+
+"""
+First attempt to resolve was really brute force and slow,
+this is a better solution, see problem page for explanation
+"""
+
+from math import floor, sqrt
+
+LIMIT = 10000
+result = 0
+
+
+def d(n):
+ res = 0
+ r = floor(sqrt(n))
+ if r * r == n:
+ ... | |
c3b531f6c1dcd719adfa69f72ae95e4018debbac | euler035.py | euler035.py | #!/usr/bin/python
from math import sqrt, ceil, floor, log10, pow
LIMIT = 1000000
def decimalShift(x):
dec = x % 10;
power = floor(log10(x))
x //= 10;
x += dec * int(pow(10, power))
return x
sievebound = (LIMIT - 1) // 2
sieve = [0] * (sievebound)
crosslimit = (floor(sqrt(LIMIT)) - 1) // 2
for i ... | Add solution for problem 35 | Add solution for problem 35
| Python | mit | cifvts/PyEuler | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/python
+
+from math import sqrt, ceil, floor, log10, pow
+
+LIMIT = 1000000
+
+def decimalShift(x):
+ dec = x % 10;
+ power = floor(log10(x))
+ x //= 10;
+ x += dec * int(pow(10, power))
+ return x
+
+sievebound = (LIMIT - 1) // 2
+sieve = [0] * (sievebound)
+crossl... | |
b0c87f3959b747f5ea12c74434e6361296be0db9 | PVGeo/omf/__test__.py | PVGeo/omf/__test__.py | import unittest
import shutil
import tempfile
import os
import numpy as np
# VTK imports:
from vtk.util import numpy_support as nps
from .. import _helpers
# Functionality to test:
from .reader import *
RTOL = 0.000001
###############################################################################
class TestOMFRe... | Add complimation test for OMF | Add complimation test for OMF
| Python | bsd-3-clause | banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics,banesullivan/ParaViewGeophysics | ---
+++
@@ -0,0 +1,27 @@
+import unittest
+import shutil
+import tempfile
+import os
+import numpy as np
+
+# VTK imports:
+from vtk.util import numpy_support as nps
+
+from .. import _helpers
+# Functionality to test:
+from .reader import *
+
+
+RTOL = 0.000001
+
+####################################################... | |
43687a8c59c9ceb26073ba9517004426820ec45c | readthedocs/core/management/commands/whitelist_users.py | readthedocs/core/management/commands/whitelist_users.py | from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from core.models import UserProfile
from projects import tasks
from projects.models import Project
class Command(BaseCommand):
def handle(self, *args, **kwargs):
for user in User.objects.filter(profile__whitel... | Add ability to easily whitelist users. | Add ability to easily whitelist users.
| Python | mit | mrshoki/readthedocs.org,davidfischer/readthedocs.org,fujita-shintaro/readthedocs.org,attakei/readthedocs-oauth,VishvajitP/readthedocs.org,nikolas/readthedocs.org,fujita-shintaro/readthedocs.org,VishvajitP/readthedocs.org,wijerasa/readthedocs.org,kenshinthebattosai/readthedocs.org,agjohnson/readthedocs.org,royalwang/rea... | ---
+++
@@ -0,0 +1,13 @@
+from django.core.management.base import BaseCommand
+from django.contrib.auth.models import User
+
+from core.models import UserProfile
+from projects import tasks
+from projects.models import Project
+
+class Command(BaseCommand):
+
+ def handle(self, *args, **kwargs):
+ for user ... | |
0fa2f20e7c79ce2ebe88b01847d875e37ff21e62 | py/tests/scale.py | py/tests/scale.py | #!/usr/bin/python3
import pykms
import time
import random
card = pykms.Card()
res = pykms.ResourceManager(card)
conn = res.reserve_connector("hdmi")
crtc = res.reserve_crtc(conn)
plane = res.reserve_overlay_plane(crtc)
mode = conn.get_default_mode()
#mode = conn.get_mode(1920, 1080, 60, False)
# Blank framefuffer f... | Add a simple and hackish plane scaling test. | Add a simple and hackish plane scaling test.
Signed-off-by: Tomi Valkeinen <e1ca4dbb8be1acaf20734fecd2da10ed1d46a9bb@ti.com>
| Python | mpl-2.0 | tomba/kmsxx,tomba/kmsxx,tomba/kmsxx,tomba/kmsxx | ---
+++
@@ -0,0 +1,60 @@
+#!/usr/bin/python3
+
+import pykms
+import time
+import random
+
+card = pykms.Card()
+res = pykms.ResourceManager(card)
+conn = res.reserve_connector("hdmi")
+crtc = res.reserve_crtc(conn)
+plane = res.reserve_overlay_plane(crtc)
+
+mode = conn.get_default_mode()
+#mode = conn.get_mode(1920... | |
333f22e90994170b67ba1cb833d0020208c00efe | pombola/hansard/tests/test_sitting_view.py | pombola/hansard/tests/test_sitting_view.py | from django.contrib.auth.models import User
from django_webtest import WebTest
from pombola.core import models
from ..models import Entry, Sitting
class TestSittingView(WebTest):
fixtures = ['hansard_test_data']
def setUp(self):
self.staffuser = User.objects.create(
username='editor',
... | Add some tests for letting staff users see original speaker names | Add some tests for letting staff users see original speaker names
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -0,0 +1,56 @@
+from django.contrib.auth.models import User
+from django_webtest import WebTest
+
+from pombola.core import models
+from ..models import Entry, Sitting
+
+class TestSittingView(WebTest):
+
+ fixtures = ['hansard_test_data']
+
+ def setUp(self):
+ self.staffuser = User.objects.cr... | |
9771450342d65f4a87f502312f53058e91a1438e | eventkit/migrations/0003_auto_20150607_2314.py | eventkit/migrations/0003_auto_20150607_2314.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import polymorphic_tree.models
class Migration(migrations.Migration):
dependencies = [
('eventkit', '0002_auto_20150605_1418'),
]
operations = [
migrations.AlterField(
mo... | Add missing migration for MPTT update. | Add missing migration for MPTT update.
| Python | mit | ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit | ---
+++
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+import polymorphic_tree.models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('eventkit', '0002_auto_20150605_1418'),
+ ]
+
+ operations = [
+ ... | |
68769e2bc5bc7a633ef2bcbd2efdc6f69952858d | scripts/find_duplicate_identifiers.py | scripts/find_duplicate_identifiers.py | #!/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
This scripts looks for duplicate identifiers in the "Identifiers" table.
The caller passes the name of one of the source ID indexes (e.g. MiroID),
and the script looks at every instance of that source ID. If a source ID
has multiple canonical IDs, it prints informa... | Add a script for spotting doubly-minted identifiers | Add a script for spotting doubly-minted identifiers
| Python | mit | wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api | ---
+++
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+# -*- encoding: utf-8 -*-
+"""
+This scripts looks for duplicate identifiers in the "Identifiers" table.
+
+The caller passes the name of one of the source ID indexes (e.g. MiroID),
+and the script looks at every instance of that source ID. If a source ID
+has multip... | |
d154a2dbdb45d28e12a1b3d67790653bbf4d17dc | src/teammails/__init__.py | src/teammails/__init__.py | from contextlib import contextmanager
import os
import smtplib
import database as db
from email.mime.text import MIMEText
from jinja2 import Template
from database.model import Team
from webapp.cfg import config
@contextmanager
def smtp_session():
session = smtplib.SMTP(config.MAIL_SERVER, config.MAIL_PORT)
... | Add code to send informal emails to the teams. | Add code to send informal emails to the teams.
| Python | bsd-3-clause | eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system | ---
+++
@@ -0,0 +1,62 @@
+from contextlib import contextmanager
+import os
+import smtplib
+import database as db
+
+from email.mime.text import MIMEText
+
+from jinja2 import Template
+from database.model import Team
+
+from webapp.cfg import config
+
+
+@contextmanager
+def smtp_session():
+ session = smtplib.SM... | |
f8eaf2bb9046d5d6a9dd6a1ad91e7ae3b4a88688 | tests/api/views/airports_test.py | tests/api/views/airports_test.py | # coding=utf-8
from tests.data import airports
def test_read_missing(db_session, client):
res = client.get('/airports/1')
assert res.status_code == 404
assert res.json == {
'message': 'Sorry, there is no such record (1) in our database.'
}
def test_read(db_session, client):
airport = air... | Add tests for "GET /airport/:id" | tests/api: Add tests for "GET /airport/:id"
| Python | agpl-3.0 | shadowoneau/skylines,Turbo87/skylines,shadowoneau/skylines,Turbo87/skylines,RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Harry-R/skylines,Harry-R/skylines,skylines-project/skylines,RBE-Avionik/skylines,shadowoneau/skylines,skylines-project/skylines,Harry-R/skylines,Turbo87/skylines,RBE-Avionik/skylines,sk... | ---
+++
@@ -0,0 +1,29 @@
+# coding=utf-8
+from tests.data import airports
+
+
+def test_read_missing(db_session, client):
+ res = client.get('/airports/1')
+ assert res.status_code == 404
+ assert res.json == {
+ 'message': 'Sorry, there is no such record (1) in our database.'
+ }
+
+
+def test_rea... | |
84f17a5443e1268c62f94f104b0a7d4d6a631f22 | symcalc.py | symcalc.py | from sympy.abc import *
from flask import Flask, request
app = Flask(__name__)
@app.route('/code', methods=['GET', 'POST'])
def code():
return str(eval(request.json['code']))
if __name__ == "__main__":
app.run(debug=True, port=80)
| Add flask server for evaluating expressions | Add flask server for evaluating expressions
| Python | mit | boppreh/symcalc | ---
+++
@@ -0,0 +1,11 @@
+from sympy.abc import *
+
+from flask import Flask, request
+app = Flask(__name__)
+
+@app.route('/code', methods=['GET', 'POST'])
+def code():
+ return str(eval(request.json['code']))
+
+if __name__ == "__main__":
+ app.run(debug=True, port=80) | |
1b19af261261d16c37885bda634f02f9a3abc027 | zerver/tests/test_subdomains.py | zerver/tests/test_subdomains.py |
import mock
from typing import Any, List
from django.test import TestCase, override_settings
from zerver.lib.subdomains import get_subdomain
from zerver.models import Realm
class SubdomainsTest(TestCase):
def test_get_subdomain(self):
# type: () -> None
def request_mock(host):
# typ... | Write some tests for get_subdomain. | subdomains: Write some tests for get_subdomain.
This logic is a bit subtle, and we're about to make changes to it.
So let's have some tests.
| Python | apache-2.0 | mahim97/zulip,kou/zulip,shubhamdhama/zulip,showell/zulip,punchagan/zulip,dhcrzf/zulip,brainwane/zulip,rht/zulip,tommyip/zulip,brockwhittaker/zulip,kou/zulip,eeshangarg/zulip,rishig/zulip,rishig/zulip,dhcrzf/zulip,eeshangarg/zulip,eeshangarg/zulip,timabbott/zulip,rishig/zulip,rishig/zulip,brockwhittaker/zulip,zulip/zuli... | ---
+++
@@ -0,0 +1,31 @@
+
+import mock
+from typing import Any, List
+
+from django.test import TestCase, override_settings
+
+from zerver.lib.subdomains import get_subdomain
+from zerver.models import Realm
+
+class SubdomainsTest(TestCase):
+ def test_get_subdomain(self):
+ # type: () -> None
+
+ ... | |
4fb5d4895ba955e30cb7908921ef7036c904d646 | wrapper.py | wrapper.py | from subprocess import check_output
import sys
def list_accounts():
stdout = check_output(['aqhbci-tool4', 'listaccounts'])
account_list = []
for account_row in stdout.decode(sys.stdout.encoding).split('\n'):
account_row = account_row.split()
if len(account_row):
account_list.... | Add first attempt to pull information out of aqhbci | Add first attempt to pull information out of aqhbci
| Python | apache-2.0 | hedderich/aqbanking-cli-wrapper | ---
+++
@@ -0,0 +1,15 @@
+from subprocess import check_output
+import sys
+
+
+def list_accounts():
+ stdout = check_output(['aqhbci-tool4', 'listaccounts'])
+
+ account_list = []
+ for account_row in stdout.decode(sys.stdout.encoding).split('\n'):
+ account_row = account_row.split()
+ if len(a... | |
ff85bc7013eeae9c092a855787d454cf39bdcf98 | mysite/fix_duplicate_citations.py | mysite/fix_duplicate_citations.py | for citation in Citation.objects.all().order_by('pk'):
citation.ignored_due_to_duplicate = False
citation.save()
citation.save_and_check_for_duplicates()
| Add script for fixing duplicate citations. | Add script for fixing duplicate citations.
| Python | agpl-3.0 | waseem18/oh-mainline,mzdaniel/oh-mainline,nirmeshk/oh-mainline,sudheesh001/oh-mainline,willingc/oh-mainline,onceuponatimeforever/oh-mainline,heeraj123/oh-mainline,mzdaniel/oh-mainline,heeraj123/oh-mainline,heeraj123/oh-mainline,ehashman/oh-mainline,mzdaniel/oh-mainline,eeshangarg/oh-mainline,campbe13/openhatch,SnappleC... | ---
+++
@@ -0,0 +1,4 @@
+for citation in Citation.objects.all().order_by('pk'):
+ citation.ignored_due_to_duplicate = False
+ citation.save()
+ citation.save_and_check_for_duplicates() | |
e6a90e5926d589e405b3a575de442e2f399e81cf | 03_task/sample_test.py | 03_task/sample_test.py | import datetime
import unittest
import solution
class TestSocialGraph(unittest.TestCase):
def setUp(self):
self.terry = solution.User("Terry Gilliam")
self.eric = solution.User("Eric Idle")
self.graham = solution.User("Graham Chapman")
self.john = solution.User("John Cleese")
... | Add 03-task sample test file. | Add 03-task sample test file.
| Python | mit | pepincho/Python-Course-FMI | ---
+++
@@ -0,0 +1,59 @@
+import datetime
+import unittest
+
+import solution
+
+
+class TestSocialGraph(unittest.TestCase):
+ def setUp(self):
+ self.terry = solution.User("Terry Gilliam")
+ self.eric = solution.User("Eric Idle")
+ self.graham = solution.User("Graham Chapman")
+ self.j... | |
47961252b369d1fd946020816f46a54b6ee00f84 | antxetamedia/news/migrations/0011_auto_20150915_0327.py | antxetamedia/news/migrations/0011_auto_20150915_0327.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('news', '0010_auto_20150807_0733'),
]
operations = [
migrations.AlterModelOptions(
name='newspodcast',
... | Change verbose name for some news models fields | Change verbose name for some news models fields
| Python | agpl-3.0 | GISAElkartea/amv2,GISAElkartea/amv2,GISAElkartea/amv2 | ---
+++
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('news', '0010_auto_20150807_0733'),
+ ]
+
+ operations = [
+ migrations.AlterModelOptions(
+... | |
02832aee17b4cae8dc49a035bc8c6d11a69dd7ac | ws-tests/test_valid_study_put_override_author.py | ws-tests/test_valid_study_put_override_author.py | #!/usr/bin/env python
from opentreetesting import test_http_json_method, config
import datetime
import codecs
import json
import sys
import os
DOMAIN = config('host', 'apihost')
SUBMIT_URI = DOMAIN + '/v1/study/1003'
inpf = codecs.open('../nexson-validator/tests/single/input/1003.json', 'rU', encoding='utf-8')
n = jso... | Add a test for over-riding author info | Add a test for over-riding author info
| Python | bsd-2-clause | leto/new_opentree_api,leto/new_opentree_api | ---
+++
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+from opentreetesting import test_http_json_method, config
+import datetime
+import codecs
+import json
+import sys
+import os
+
+DOMAIN = config('host', 'apihost')
+SUBMIT_URI = DOMAIN + '/v1/study/1003'
+inpf = codecs.open('../nexson-validator/tests/single/input/1003.... | |
0faf570db96db22ddbbd8dc81053bcbd36a1aa74 | tests/unit/config_test.py | tests/unit/config_test.py | # -*- coding: utf-8 -*-\
'''
unit.config_test
~~~~~~~~~~~~~~~~
Configuration related unit testing
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
:copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
'''
# Import p... | Add a test case to test loading config from an environment variable. | Add a test case to test loading config from an environment variable.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,83 @@
+# -*- coding: utf-8 -*-\
+'''
+ unit.config_test
+ ~~~~~~~~~~~~~~~~
+
+ Configuration related unit testing
+
+ :codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
+ :copyright: © 2013 by the SaltStack Team, see AUTHORS for more details.
+ :license: Apache 2.0, see LICE... | |
25fba421673c1e86d71b42af208fc47996f1c326 | site_analytics.py | site_analytics.py | #!/usr/local/bin/python3.6
# read nginx access log
# parse and get the ip addresses and times
# match ip addresses to geoip
# possibly ignore bots
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re... | Read and regex match the log lines | Read and regex match the log lines
| Python | mit | mouhtasi/basic_site_analytics | ---
+++
@@ -0,0 +1,37 @@
+#!/usr/local/bin/python3.6
+
+# read nginx access log
+# parse and get the ip addresses and times
+# match ip addresses to geoip
+# possibly ignore bots
+
+import re
+
+
+def get_log_lines(path):
+ """Return a list of regex matched log lines from the passed nginx access log path"""
+ lines... | |
18f84f266d172e0390eef61250909dc9c0401f4b | utils/swift_build_support/swift_build_support/compiler_stage.py | utils/swift_build_support/swift_build_support/compiler_stage.py | # ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt... | Introduce infrastructure for auto-prefixing stage2 options. | [build-script] Introduce infrastructure for auto-prefixing stage2 options.
This will let me introduce a stage generic swift implementation that adds a
postfix '_stage2' to certain stage specific options. This ensures we can have a
single swift build-script product implementation for both stage1 and stage2
compilers.
| Python | apache-2.0 | benlangmuir/swift,xwu/swift,xwu/swift,JGiola/swift,gregomni/swift,atrick/swift,apple/swift,roambotics/swift,apple/swift,atrick/swift,gregomni/swift,xwu/swift,xwu/swift,hooman/swift,hooman/swift,benlangmuir/swift,ahoppen/swift,glessard/swift,benlangmuir/swift,roambotics/swift,apple/swift,rudkx/swift,roambotics/swift,atr... | ---
+++
@@ -0,0 +1,32 @@
+# ===--- compiler_stage.py -----------------------------------------------===#
+#
+# This source file is part of the Swift.org open source project
+#
+# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
+# Licensed under Apache License v2.0 with Runtime Library Exception
+#
... | |
539b680a6c9bc416d28ba02087db2e46b4037f06 | salt/modules/openbsdservice.py | salt/modules/openbsdservice.py | '''
The service module for OpenBSD
'''
import os
# XXX enable/disable support would be nice
def __virtual__():
'''
Only work on OpenBSD
'''
if __grains__['os'] == 'OpenBSD' and os.path.exists('/etc/rc.d/rc.subr'):
return 'service'
return False
def start(name):
'''
Start the sp... | Add an openbsd service module. | Add an openbsd service module.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,66 @@
+'''
+The service module for OpenBSD
+'''
+
+import os
+
+
+# XXX enable/disable support would be nice
+
+
+def __virtual__():
+ '''
+ Only work on OpenBSD
+ '''
+ if __grains__['os'] == 'OpenBSD' and os.path.exists('/etc/rc.d/rc.subr'):
+ return 'service'
+ return False... | |
b9f2a5816c55334013a8447da705066f783dfda2 | paperwork_parser/base.py | paperwork_parser/base.py | import inspect
from enum import IntEnum
from pdfquery import PDFQuery
class DocFieldType(IntEnum):
NUMBER = 1
TEXT = 2
CUSTOM = 3 # TODO: Forget this and have 'type' take a callable instead?
class DocField(object):
def __init__(self, bbox, type=DocFieldType.TEXT, required=False,
d... | Add primitives for pdf parsing | Add primitives for pdf parsing
| Python | mit | loanzen/zen_document_parser | ---
+++
@@ -0,0 +1,91 @@
+import inspect
+
+from enum import IntEnum
+from pdfquery import PDFQuery
+
+
+class DocFieldType(IntEnum):
+ NUMBER = 1
+ TEXT = 2
+ CUSTOM = 3 # TODO: Forget this and have 'type' take a callable instead?
+
+
+class DocField(object):
+ def __init__(self, bbox, type=DocFieldType... | |
a4ffbfa5204a2eeaba7291881064d0c6ba5ebc3e | test/filter_test.py | test/filter_test.py | import unittest
import vapoursynth as vs
class FilterTestSequence(unittest.TestCase):
def setUp(self):
self.core = vs.get_core()
self.Transpose = self.core.std.Transpose
self.BlankClip = self.core.std.BlankClip
def test_transpose8_test(self):
clip = self.BlankClip(format=vs.... | Add general filter test file | Add general filter test file
| Python | lgpl-2.1 | vapoursynth/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth,Kamekameha/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,vapoursynth/vapoursynth,Kamekameha/vapoursynth | ---
+++
@@ -0,0 +1,28 @@
+import unittest
+import vapoursynth as vs
+
+class FilterTestSequence(unittest.TestCase):
+
+ def setUp(self):
+ self.core = vs.get_core()
+ self.Transpose = self.core.std.Transpose
+ self.BlankClip = self.core.std.BlankClip
+
+ def test_transpose8_test(self):
+ ... | |
bfbf598cb80ad5df0f6032197f173da794311a33 | test/test_logger.py | test/test_logger.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function
from __future__ import unicode_literals
import logbook
import pytest
from simplesqlite import (
set_logger,
set_log_level,
)
class Test_set_logger(object):
@pytest.mark.param... | Add test cases for the logger | Add test cases for the logger
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite | ---
+++
@@ -0,0 +1,49 @@
+# encoding: utf-8
+
+"""
+.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
+"""
+
+from __future__ import print_function
+from __future__ import unicode_literals
+
+import logbook
+import pytest
+from simplesqlite import (
+ set_logger,
+ set_log_level,
+)
+
+
+class Tes... | |
ee1e6587044aa5dc9b47776c648c7da55220306a | scratchpad/push-compass-values.py | scratchpad/push-compass-values.py | #!/usr/bin/env python3
from sense_hat import SenseHat
from pymongo import MongoClient
sense = SenseHat()
client = MongoClient("mongodb://192.168.0.128:27017")
db = client.g2x
for _ in range(0, 1000):
reading = sense.get_compass()
db.compass.insert_one({"angle": reading})
# db.compass.insert_one({"angle":... | Create script to time compass reads and db writes | Create script to time compass reads and db writes
| Python | bsd-3-clause | gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2 | ---
+++
@@ -0,0 +1,13 @@
+#!/usr/bin/env python3
+
+from sense_hat import SenseHat
+from pymongo import MongoClient
+
+sense = SenseHat()
+client = MongoClient("mongodb://192.168.0.128:27017")
+db = client.g2x
+
+for _ in range(0, 1000):
+ reading = sense.get_compass()
+ db.compass.insert_one({"angle": reading}... | |
efafb94f6512a00baa13ecc2ab18e80441f41922 | tests/decorators.py | tests/decorators.py | from selenium.common.exceptions import TimeoutException, StaleElementReferenceException
def retry_on_stale_element_exception(func):
def wrapped(*args, **kwargs):
try:
result = func(*args, **kwargs)
except StaleElementReferenceException:
result = func(*args, **kwargs)
... | Add decorator that will catch and retry on StaleElementReferenceException | Add decorator that will catch and retry on StaleElementReferenceException
| Python | mit | alphagov/notifications-functional-tests,alphagov/notifications-functional-tests | ---
+++
@@ -0,0 +1,12 @@
+from selenium.common.exceptions import TimeoutException, StaleElementReferenceException
+
+
+def retry_on_stale_element_exception(func):
+ def wrapped(*args, **kwargs):
+ try:
+ result = func(*args, **kwargs)
+ except StaleElementReferenceException:
+ r... | |
88a74b351c29c4c6e337c76b105f9bc25591f755 | tests/test_resources.py | tests/test_resources.py | from conference_scheduler.resources import Event
def test_can_construct_event():
e = Event(
name='example',
duration=60,
demand=100,
tags=['beginner', 'python'],
unavailability=[]
)
assert isinstance(e, Event)
assert e.name == 'example'
assert e.tags == ['be... | Add tests for optional arguments on Event | Add tests for optional arguments on Event
| Python | mit | PyconUK/ConferenceScheduler | ---
+++
@@ -0,0 +1,35 @@
+from conference_scheduler.resources import Event
+
+
+def test_can_construct_event():
+ e = Event(
+ name='example',
+ duration=60,
+ demand=100,
+ tags=['beginner', 'python'],
+ unavailability=[]
+ )
+ assert isinstance(e, Event)
+ assert e.nam... | |
763775b1295b920a2440dec0275349af4b9e7cb4 | candidates/management/commands/candidates_record_new_versions.py | candidates/management/commands/candidates_record_new_versions.py | from datetime import datetime
from random import randint
import sys
from django.core.management.base import BaseCommand
from django.db import transaction
from candidates.models import PersonExtra
class Command(BaseCommand):
help = "Record the current version for all people"
def add_arguments(self, parser)... | Add a command to record the current version of every person | Add a command to record the current version of every person
| Python | agpl-3.0 | datamade/yournextmp-popit,mysociety/yournextmp-popit,neavouli/yournextrepresentative,neavouli/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,datamade/yournextmp-popit,neavouli/yournextrepresentative,mysociety/yournextrepresentat... | ---
+++
@@ -0,0 +1,44 @@
+from datetime import datetime
+from random import randint
+import sys
+
+from django.core.management.base import BaseCommand
+from django.db import transaction
+
+from candidates.models import PersonExtra
+
+
+class Command(BaseCommand):
+
+ help = "Record the current version for all peop... | |
f0d3cf2bfcaa569f47eb888d5553659c5c57f07d | ajaximage/urls.py | ajaximage/urls.py | from django.conf.urls.defaults import url, patterns
from ajaximage.views import ajaximage
from ajaximage.forms import FileForm
urlpatterns = patterns('',
url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<crop>\d+)', ajaximage, {
'form_class': FileForm,
'response': lambda n... | try:# pre 1.6
from django.conf.urls.defaults import url, patterns
except ImportError:
from django.conf.urls import url, patterns
from ajaximage.views import ajaximage
from ajaximage.forms import FileForm
urlpatterns = patterns('',
url('^upload/(?P<upload_to>.*)/(?P<max_width>\d+)/(?P<max_height>\d+)/(?P<... | Fix import for 1.6 version. | Fix import for 1.6 version.
| Python | mit | bradleyg/django-ajaximage,bradleyg/django-ajaximage,subhaoi/kioskuser,subhaoi/kioskuser,subhaoi/kioskuser,bradleyg/django-ajaximage | ---
+++
@@ -1,4 +1,7 @@
-from django.conf.urls.defaults import url, patterns
+try:# pre 1.6
+ from django.conf.urls.defaults import url, patterns
+except ImportError:
+ from django.conf.urls import url, patterns
from ajaximage.views import ajaximage
from ajaximage.forms import FileForm |
c3a6347357e2ee604db0271cde829e6795794cf9 | cheat/printer.py | cheat/printer.py | #!/usr/bin/env/python3
class Printer:
"""
Base class for the cheatsheet printers. Takes care of the actuall printing.
Args:
Takes a configparser objects to print.
"""
def __init__(self, configparser):
self.configparser = configparser
def printsheet(self, template):
for d... | Refactor - Moved Printer classes to seperate file | Refactor - Moved Printer classes to seperate file
| Python | mit | martialblog/cheatsheet | ---
+++
@@ -0,0 +1,61 @@
+#!/usr/bin/env/python3
+
+
+class Printer:
+ """
+ Base class for the cheatsheet printers. Takes care of the actuall printing.
+
+ Args:
+ Takes a configparser objects to print.
+ """
+
+ def __init__(self, configparser):
+ self.configparser = configparser
+
+ def... | |
ac7b572b8bf7d690ac70b479814deed2c0a772e4 | webapp/tests/test_finders.py | webapp/tests/test_finders.py | import random
import time
from django.test import TestCase
from graphite.intervals import Interval, IntervalSet
from graphite.node import LeafNode, BranchNode
from graphite.storage import Store, get_finder
class FinderTest(TestCase):
def test_custom_finder(self):
store = Store(finders=[get_finder('tests... | Add simple test for a custom finder | Add simple test for a custom finder
| Python | apache-2.0 | Squarespace/graphite-web,disqus/graphite-web,dbn/graphite-web,brutasse/graphite-web,AICIDNN/graphite-web,brutasse/graphite-web,esnet/graphite-web,disqus/graphite-web,pu239ppy/graphite-web,nkhuyu/graphite-web,graphite-server/graphite-web,phreakocious/graphite-web,goir/graphite-web,JeanFred/graphite-web,zBMNForks/graphit... | ---
+++
@@ -0,0 +1,52 @@
+import random
+import time
+
+from django.test import TestCase
+
+from graphite.intervals import Interval, IntervalSet
+from graphite.node import LeafNode, BranchNode
+from graphite.storage import Store, get_finder
+
+
+class FinderTest(TestCase):
+ def test_custom_finder(self):
+ ... | |
21f02e452546cdbe4209bfbb8ec6addecf083ebf | spam/common/collections.py | spam/common/collections.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import namedtuple
Data = namedtuple('Data', ['X', 'Y', 'y', ])
Dataset = namedtuple('Dataset', ['unlabel', 'train', 'test', ])
| Add data and dataset collection. | Add data and dataset collection.
| Python | mit | benigls/spam,benigls/spam | ---
+++
@@ -0,0 +1,9 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from collections import namedtuple
+
+
+Data = namedtuple('Data', ['X', 'Y', 'y', ])
+
+Dataset = namedtuple('Dataset', ['unlabel', 'train', 'test', ]) | |
dcc0d0373b6cb72a62c3279ae753f7cf0663f63b | heroku.py | heroku.py | #!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ShipURLMixin
import evesrp.auth.testauth
from os import environ as env
from binascii import unhexlify
skel_url = 'https://wiki.eveonline.com/en/wiki/{name}'
class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): pass
app = cr... | #!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ShipURLMixin
from evesrp.auth.testauth import TestAuth
from os import environ as env
from binascii import unhexlify
skel_url = 'https://wiki.eveonline.com/en/wiki/{name}'
class EOWikiCREST(CRESTMail, ShipURLMixin(skel_url)): p... | Use new AuthMethod configuration for Heroku | Use new AuthMethod configuration for Heroku | Python | bsd-2-clause | eskwire/evesrp,paxswill/evesrp,eskwire/evesrp,eskwire/evesrp,paxswill/evesrp,eskwire/evesrp,paxswill/evesrp | ---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
from evesrp import create_app
from evesrp.killmail import CRESTMail, ShipURLMixin
-import evesrp.auth.testauth
+from evesrp.auth.testauth import TestAuth
from os import environ as env
from binascii import unhexlify
@@ -15,7 +15,7 @@
app.config['SQLALCHEMY_DATABASE... |
efbf92af38a6bcaa87327b9c5fc44680888a6793 | src/diamond/handler/Handler.py | src/diamond/handler/Handler.py | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.l... | # coding=utf-8
import logging
import threading
import traceback
class Handler(object):
"""
Handlers process metrics that are collected by Collectors.
"""
def __init__(self, config=None):
"""
Create a new instance of the Handler class
"""
# Initialize Log
self.l... | Move away from using the with statement for 2.4 support | Move away from using the with statement for 2.4 support
| Python | mit | Netuitive/Diamond,codepython/Diamond,Netuitive/netuitive-diamond,Ensighten/Diamond,Nihn/Diamond-1,Clever/Diamond,hamelg/Diamond,Ensighten/Diamond,szibis/Diamond,Precis/Diamond,Slach/Diamond,anandbhoraskar/Diamond,TAKEALOT/Diamond,eMerzh/Diamond-1,CYBERBUGJR/Diamond,jriguera/Diamond,Netuitive/Diamond,sebbrandt87/Diamond... | ---
+++
@@ -26,11 +26,13 @@
"""
try:
self.log.debug("Running Handler %s locked" % (self))
- with self.lock:
- self.process(metric)
+ self.lock.acquire()
+ self.process(metric)
+ self.lock.release()
except Exception:
... |
9c1ae3592c5a376433b4048442837cb40a7af552 | Detect_Face_Sides.py | Detect_Face_Sides.py | #scan through each row
#when you hit a high intensity pixel store x
#when you hit a low intensity pixel for more than like 10 pixels set xfinal
#scan each row and store all of the size values in a matrix
#scan through the matrix, when the values remain smooth for a while
#then designate a point for the top right and t... | Add detection of left side of face | Add detection of left side of face
| Python | mit | anassinator/codejam,anassinator/codejam-2014 | ---
+++
@@ -0,0 +1,20 @@
+#scan through each row
+#when you hit a high intensity pixel store x
+#when you hit a low intensity pixel for more than like 10 pixels set xfinal
+#scan each row and store all of the size values in a matrix
+#scan through the matrix, when the values remain smooth for a while
+#then designat... | |
b07b12b2645e394c5a85a3585512acf7bdfb05b7 | euler023.py | euler023.py | #!/usr/bin/python
from math import floor, sqrt
LIMIT = 28134
def isAbundant(n):
max_t = floor(sqrt(n)) + 1
sum_d = 1
for i in range(2, max_t):
if n % i == 0:
sum_d += i + n // i
if i == n / i:
sum_d -= i
return sum_d > n
""" Main """
abd_l = [0] * LIMIT
for i... | Add solution for problem 23, it's quite fast | Add solution for problem 23, it's quite fast
| Python | mit | cifvts/PyEuler | ---
+++
@@ -0,0 +1,34 @@
+#!/usr/bin/python
+
+from math import floor, sqrt
+
+LIMIT = 28134
+
+
+def isAbundant(n):
+ max_t = floor(sqrt(n)) + 1
+ sum_d = 1
+ for i in range(2, max_t):
+ if n % i == 0:
+ sum_d += i + n // i
+ if i == n / i:
+ sum_d -= i
+ return sum_d ... | |
5b3a001af9ff992d061f880d6350292250fd8687 | apps/explorer/tests/test_views.py | apps/explorer/tests/test_views.py | from django.core.urlresolvers import reverse
from apps.core.factories import PIXELER_PASSWORD, PixelerFactory
from apps.core.tests import CoreFixturesTestCase
from apps.core.management.commands.make_development_fixtures import (
make_development_fixtures
)
class PixelSetListViewTestCase(CoreFixturesTestCase):
... | Add tests for the pixelset list view | Add tests for the pixelset list view
| Python | bsd-3-clause | Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel,Candihub/pixel | ---
+++
@@ -0,0 +1,52 @@
+from django.core.urlresolvers import reverse
+
+from apps.core.factories import PIXELER_PASSWORD, PixelerFactory
+from apps.core.tests import CoreFixturesTestCase
+from apps.core.management.commands.make_development_fixtures import (
+ make_development_fixtures
+)
+
+
+class PixelSetListV... | |
14c953533b135e014164277a0c33d8115866de6a | mochi/utils/path_helper.py | mochi/utils/path_helper.py | """Helpers for working with paths an similar.
"""
import os
class TempDir(object):
"""Switch to a temporary directory and back.
This is a context manager.
usage:
# in orig_dir
with TempDir('/path/to/temp_dir'):
# in temp_dir
do_something_in_temp_dir()
# ... | Add context manager for temp dir. | Add context manager for temp dir.
| Python | mit | slideclick/mochi,pya/mochi,i2y/mochi,slideclick/mochi,pya/mochi,i2y/mochi | ---
+++
@@ -0,0 +1,33 @@
+"""Helpers for working with paths an similar.
+"""
+
+import os
+
+
+class TempDir(object):
+ """Switch to a temporary directory and back.
+
+ This is a context manager.
+
+ usage:
+
+ # in orig_dir
+ with TempDir('/path/to/temp_dir'):
+ # in temp_dir
+ ... | |
1a86f43428e9f05ade880b047a0b194ca776bfad | lib/util.py | lib/util.py | def op_cmp(op1, op2):
"""
Compare an operation by active and then opid.
"""
if op1['active'] != op2['active']:
return -1 if op1['active'] else 1
return cmp(op1['opid'], op2['opid'])
| Add the classic missing file. | Add the classic missing file.
| Python | apache-2.0 | beaufour/mtop | ---
+++
@@ -0,0 +1,8 @@
+def op_cmp(op1, op2):
+ """
+ Compare an operation by active and then opid.
+ """
+ if op1['active'] != op2['active']:
+ return -1 if op1['active'] else 1
+
+ return cmp(op1['opid'], op2['opid']) | |
ab0492c1c71bf9e77a0327efa2c8eca5be9ae728 | tests/formatter/test_yamler.py | tests/formatter/test_yamler.py | import unittest, argparse
from echolalia.formatter.yamler import Formatter
class YamlerTestCase(unittest.TestCase):
def setUp(self):
self.parser = argparse.ArgumentParser()
self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
self.formatter = Formatter()
def test_add_args(self):
... | Add tests for formatter yaml | Add tests for formatter yaml
| Python | mit | eiri/echolalia-prototype | ---
+++
@@ -0,0 +1,20 @@
+import unittest, argparse
+from echolalia.formatter.yamler import Formatter
+
+class YamlerTestCase(unittest.TestCase):
+
+ def setUp(self):
+ self.parser = argparse.ArgumentParser()
+ self.data = [{'char': chr(i), 'order': i - 96} for i in xrange(97, 100)]
+ self.formatter = Forma... | |
e271d355e057f72c85efe3f1a407c55e54faca74 | migrations/008_convert_ga_buckets_to_utc.py | migrations/008_convert_ga_buckets_to_utc.py | """
Convert Google Analytics buckets from Europe/London to UTC
"""
import logging
import copy
from itertools import imap, ifilter
from datetime import timedelta
from backdrop.core.records import Record
from backdrop.core.timeutils import utc
log = logging.getLogger(__name__)
GA_BUCKETS_TO_MIGRATE = [
"carers_al... | Add migration to convert GA timezone to UTC | Add migration to convert GA timezone to UTC
We are ignoring the timezone from GA requests so previous data needs to
be converted to account for this.
See https://www.pivotaltracker.com/story/show/62779118 for details.
| Python | mit | alphagov/backdrop,alphagov/backdrop,alphagov/backdrop | ---
+++
@@ -0,0 +1,91 @@
+"""
+Convert Google Analytics buckets from Europe/London to UTC
+"""
+import logging
+import copy
+from itertools import imap, ifilter
+from datetime import timedelta
+
+from backdrop.core.records import Record
+from backdrop.core.timeutils import utc
+
+
+log = logging.getLogger(__name__)
+... | |
94e906d938cb860ff8744326ade4d65297805cc2 | deleteAllJobs.py | deleteAllJobs.py | #!/usr/bin/env python
############################################################################
# #
# Copyright 2014 Prelert Ltd #
# ... | Add delete all jobs script | Add delete all jobs script
| Python | apache-2.0 | prelert/engine-python,pemontto/engine-python | ---
+++
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+############################################################################
+# #
+# Copyright 2014 Prelert Ltd #
+# ... | |
4d50bb1140d8108c642ed89534bad1cb568123bb | examples/subprocess_evaluator.py | examples/subprocess_evaluator.py | import argparse
import os
from subprocess import PIPE, Popen
# insert your client_token into sigopt_creds.py
# otherwise you'll see "This endpoint requires an authenticated user" errors
from sigopt_creds import client_token
from sigopt.interface import Connection
class SubProcessEvaluator(object):
def __init__(sel... | Create an example script that opens executable in subprocess and evaluates | Create an example script that opens executable in subprocess and evaluates
| Python | mit | sigopt/sigopt-python,sigopt/sigopt-python | ---
+++
@@ -0,0 +1,57 @@
+import argparse
+import os
+from subprocess import PIPE, Popen
+
+# insert your client_token into sigopt_creds.py
+# otherwise you'll see "This endpoint requires an authenticated user" errors
+from sigopt_creds import client_token
+
+from sigopt.interface import Connection
+
+class SubProces... | |
5246ec4a98bca8c087d820b3ad10525ca9d6e1f2 | wagtailnews/blocks.py | wagtailnews/blocks.py | from __future__ import absolute_import, unicode_literals
from django.utils.functional import cached_property
from wagtail.wagtailcore.blocks import ChooserBlock
class NewsChooserBlock(ChooserBlock):
def __init__(self, target_model, **kwargs):
super(NewsChooserBlock, self).__init__(**kwargs)
self.... | Add NewsChooserBlock for choosing news items in StreamFields | Add NewsChooserBlock for choosing news items in StreamFields
| Python | bsd-2-clause | takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews,takeflight/wagtailnews | ---
+++
@@ -0,0 +1,18 @@
+from __future__ import absolute_import, unicode_literals
+
+from django.utils.functional import cached_property
+from wagtail.wagtailcore.blocks import ChooserBlock
+
+
+class NewsChooserBlock(ChooserBlock):
+ def __init__(self, target_model, **kwargs):
+ super(NewsChooserBlock, se... | |
4fbcf7b251253062465a286829b97c910b124c06 | gem/migrations/0027_set_site_settings_correctly.py | gem/migrations/0027_set_site_settings_correctly.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
from molo.profiles.models import UserProfilesSettings
from wagtail.wagtailcore.models import Site
def set_site_settings(apps, schema_editor):
for site in Site.objects.all():
settings = UserProfilesSettings.... | Add migration to set UserProfilesSettings correctly | Add migration to set UserProfilesSettings correctly
| Python | bsd-2-clause | praekelt/molo-gem,praekelt/molo-gem,praekelt/molo-gem | ---
+++
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+from molo.profiles.models import UserProfilesSettings
+
+from wagtail.wagtailcore.models import Site
+
+
+def set_site_settings(apps, schema_editor):
+ for site in Site.objects.all():
+... | |
161973b337c9574d95b1b4c71c802f6d9a2d6d62 | core/migrations/0005_merge_20191122_0450.py | core/migrations/0005_merge_20191122_0450.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.20 on 2019-11-22 04:50
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20190715_0912'),
('core', '0004_auto_20190222_1451'),
]
operatio... | Merge migrations file to resolve conflicts | Fix: Merge migrations file to resolve conflicts
| Python | bsd-2-clause | lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry | ---
+++
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.20 on 2019-11-22 04:50
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0004_auto_20190715_0912'),
+ ('core', '0004_au... | |
84fc02af75bec18b1c436741453762c793700ea3 | tests/test_middleware_key_auth.py | tests/test_middleware_key_auth.py | import json
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from api_bouncer.models import Api, Consumer
User = get_user_model()
class KeyAuthMiddlewareTests(APITestCase):
def setUp(self):
self.superuser = User.objects.create_... | Add test cases for KeyAuthMiddleware, Test apikey authentication | Add test cases for KeyAuthMiddleware, Test apikey authentication
| Python | apache-2.0 | menecio/django-api-bouncer | ---
+++
@@ -0,0 +1,62 @@
+import json
+
+from rest_framework import status
+from rest_framework.test import APITestCase
+from django.contrib.auth import get_user_model
+
+from api_bouncer.models import Api, Consumer
+
+User = get_user_model()
+
+
+class KeyAuthMiddlewareTests(APITestCase):
+ def setUp(self):
+ ... | |
0e86d708c2a1a266f1ba5b5f6a28e2105d291d66 | generate_stats.py | generate_stats.py | import argparse
import datetime
import time
from os import linesep
import psutil
def system_stats(duration):
for _ in range(duration):
now = datetime.datetime.isoformat(datetime.datetime.utcnow())
cpu = psutil.cpu_percent()
mem = psutil.virtual_memory().percent
net = psutil.net_io... | Add script to collect data from the system | Add script to collect data from the system
| Python | cc0-1.0 | timClicks/make-for-data | ---
+++
@@ -0,0 +1,41 @@
+import argparse
+import datetime
+import time
+from os import linesep
+
+import psutil
+
+
+def system_stats(duration):
+ for _ in range(duration):
+ now = datetime.datetime.isoformat(datetime.datetime.utcnow())
+ cpu = psutil.cpu_percent()
+ mem = psutil.virtual_memo... | |
7cd265eede78f5c9a50086776aca2eee593e28bc | common/djangoapps/student/migrations/0008_default_enrollment_honor.py | common/djangoapps/student/migrations/0008_default_enrollment_honor.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0008_auto_20161117_1209'),
]
operations = [
migrations.AlterField(
model_name='courseenrollment',
... | Add missing migration, student course enrollment | Add missing migration, student course enrollment
This was fixed by running `makemigrations`, which we presumably should
have done when we made the original change [1].
This has probably been broken all this time, potentially as far back as
December 2016.
Despite earlier suspicion, it's no longer clear that this will ... | Python | agpl-3.0 | Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform | ---
+++
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ('student', '0008_auto_20161117_1209'),
+ ]
+ operations = [
+ migrations.AlterField(
+ ... | |
4138baea40ad25635967f7382f082256099da4d2 | examples/head.py | examples/head.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Add example script for HEAD requests | Add example script for HEAD requests
Change-Id: I3d2421f1fb6e0db02e01789edc78ca432e34975f
| Python | apache-2.0 | stackforge/python-openstacksdk,dudymas/python-openstacksdk,dudymas/python-openstacksdk,briancurtin/python-openstacksdk,briancurtin/python-openstacksdk,mtougeron/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openstacksdk,openstack/python-openstacksdk,openstack/python-openst... | ---
+++
@@ -0,0 +1,31 @@
+# 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 writi... | |
2ef2ebf54e16ba1426dd370c6e3d656e8e2f97dd | pyUpdate.py | pyUpdate.py | #!/usr/bin/python3
# Import modules
from os import system as do
from time import sleep
# Set Variables
upCache = " "
upSys = " "
remAuto = " "
# define how to get config
def getConfig(filename):
import imp
f = open(filename)
global data
data = imp.load_source('data', '', f)
f.close()
# path to "... | Create in 63 glorious lines | Create in 63 glorious lines | Python | mit | hyperdriveguy/pyUpdate,hyperdriveguy/pyUpdate | ---
+++
@@ -0,0 +1,63 @@
+#!/usr/bin/python3
+
+# Import modules
+from os import system as do
+from time import sleep
+
+# Set Variables
+upCache = " "
+upSys = " "
+remAuto = " "
+
+# define how to get config
+def getConfig(filename):
+ import imp
+ f = open(filename)
+ global data
+ data = imp.load_sour... | |
733a9ef22a1c9479ee4d2debcfc92fe2d09a7aa5 | pytask/helpers/__init__.py | pytask/helpers/__init__.py | """Package containing the helper functions that may be used through out
the site.
"""
__authors__ = [
'"Madhusudan.C.S" <madhusudancs@fossee.in>',
]
| Create a separate package to hold all the PyTask sitewide helpers. | Create a separate package to hold all the PyTask sitewide helpers.
| Python | agpl-3.0 | madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask | ---
+++
@@ -0,0 +1,7 @@
+"""Package containing the helper functions that may be used through out
+the site.
+"""
+
+__authors__ = [
+ '"Madhusudan.C.S" <madhusudancs@fossee.in>',
+ ] | |
6f7d8055613c8b0542dca5185cdc46e37a96942a | tests/test_status_page.py | tests/test_status_page.py | import subprocess
import unittest
from aws_status.status_page import StatusPage
class TestStatusPage(unittest.TestCase):
def test_number_of_detected_feeds(self):
command = "curl -s http://status.aws.amazon.com/|grep rss|sort -u|wc -l"
p = subprocess.Popen(command, stdout=subprocess.PIPE,
... | Add integration test for number of detected RSS feeds | Add integration test for number of detected RSS feeds
| Python | mit | jbbarth/aws-status,jbbarth/aws-status | ---
+++
@@ -0,0 +1,15 @@
+import subprocess
+import unittest
+
+from aws_status.status_page import StatusPage
+
+class TestStatusPage(unittest.TestCase):
+ def test_number_of_detected_feeds(self):
+ command = "curl -s http://status.aws.amazon.com/|grep rss|sort -u|wc -l"
+ p = subprocess.Popen(comman... | |
81c2b0abcb5cec457e30c0b0d071212304f3da1d | scikits/learn/externals/setup.py | scikits/learn/externals/setup.py | # -*- coding: utf-8 -*-
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('externals',parent_package,top_path)
config.add_subpackage('joblib')
config.add_subpackage('joblib/test')
return config
| Make sure that joblib does get installed. | BUG: Make sure that joblib does get installed.
| Python | bsd-3-clause | mayblue9/scikit-learn,terkkila/scikit-learn,fabianp/scikit-learn,ningchi/scikit-learn,amueller/scikit-learn,glemaitre/scikit-learn,aflaxman/scikit-learn,larsmans/scikit-learn,ishanic/scikit-learn,Fireblend/scikit-learn,moutai/scikit-learn,nikitasingh981/scikit-learn,cybernet14/scikit-learn,xwolf12/scikit-learn,tdhopper... | ---
+++
@@ -0,0 +1,10 @@
+# -*- coding: utf-8 -*-
+
+def configuration(parent_package='', top_path=None):
+ from numpy.distutils.misc_util import Configuration
+ config = Configuration('externals',parent_package,top_path)
+ config.add_subpackage('joblib')
+ config.add_subpackage('joblib/test')
+
+ retu... | |
ab242c4d4fe2aa3bc7ce5a44eb7bd1ffcc5a922e | bin/2000/crosswalk_msa_block.py | bin/2000/crosswalk_msa_block.py | """crosswalk_msa_block.py
Extract the crosswalk between 2000 msa and blocks
"""
import os
import csv
#
# Import data
#
## MSA to counties crosswalk
# county_to_msa = {county: {msa: [cousub ids]}
county_to_msa = {}
with open('data/2000/crosswalks/msa_county.csv', 'r') as source:
reader = csv.reader(source, delimi... | Add script to extract the crosswalk between msas and blocks | Add script to extract the crosswalk between msas and blocks
| Python | bsd-2-clause | scities/2000-us-metro-atlas | ---
+++
@@ -0,0 +1,66 @@
+"""crosswalk_msa_block.py
+
+Extract the crosswalk between 2000 msa and blocks
+"""
+import os
+import csv
+
+#
+# Import data
+#
+
+## MSA to counties crosswalk
+# county_to_msa = {county: {msa: [cousub ids]}
+county_to_msa = {}
+with open('data/2000/crosswalks/msa_county.csv', 'r') as sour... | |
4b531ec853036b18f3014d310803f81e4fa511b8 | openedx/tests/xblock_integration/test_external_xblocks.py | openedx/tests/xblock_integration/test_external_xblocks.py | """
This will run tests on all XBlocks in the `xblock.test.v0`
entrypoint. Did you notice something about that entry point? It ends
with a v0. That means this is not finished. At some point, we might
stop running v0 tests, replacing them with test case failures, and
run v1 tests only.
That be the dragon here.
"""
impo... | Allow us to run tests from external XBlock repositories | Allow us to run tests from external XBlock repositories
| Python | agpl-3.0 | zhenzhai/edx-platform,zhenzhai/edx-platform,zhenzhai/edx-platform,zhenzhai/edx-platform,zhenzhai/edx-platform | ---
+++
@@ -0,0 +1,53 @@
+"""
+This will run tests on all XBlocks in the `xblock.test.v0`
+entrypoint. Did you notice something about that entry point? It ends
+with a v0. That means this is not finished. At some point, we might
+stop running v0 tests, replacing them with test case failures, and
+run v1 tests only.
+... | |
77e71d20d67af9965ca42c8e187614be1a9c7ffc | KineticToolkit/__init__.py | KineticToolkit/__init__.py | """
Simple and extensible toolkit for theoretic chemical kinetics
=============================================================
In theoretic study of chemical kinetics, it is quite often that a large
amount of quantum chemical computation needs to be performed and recorded,
which could make the post-processing of the ... | Add the main package module file | Add the main package module file
A basic introduction to the utility and philosophy of the package is
added to the package docstring.
| Python | mit | tschijnmo/KineticsToolkit | ---
+++
@@ -0,0 +1,39 @@
+"""
+Simple and extensible toolkit for theoretic chemical kinetics
+=============================================================
+
+In theoretic study of chemical kinetics, it is quite often that a large
+amount of quantum chemical computation needs to be performed and recorded,
+which coul... | |
18275a566f23d4387ffbd1d19e5cd8d6d449dad9 | corehq/apps/app_manager/management/commands/applications_with_add_ons.py | corehq/apps/app_manager/management/commands/applications_with_add_ons.py | from __future__ import absolute_import
import csv
from django.core.management.base import BaseCommand
from corehq import toggles
from corehq.apps.app_manager.models import Domain
class Command(BaseCommand):
help = """
Checks if an add on is enabled or was ever enabled for applications under all domains
o... | Add command to find applications enabled for an add on | Add command to find applications enabled for an add on [skip ci]
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,54 @@
+from __future__ import absolute_import
+import csv
+
+from django.core.management.base import BaseCommand
+from corehq import toggles
+from corehq.apps.app_manager.models import Domain
+
+
+class Command(BaseCommand):
+ help = """
+ Checks if an add on is enabled or was ever enabled fo... | |
8b7f48d9b077377ebaeed8c57ab02b705e0ba556 | test_game_parser.py | test_game_parser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from lxml import html
from parsers.team_parser import TeamParser
from parsers.game_parser import GameParser
def test_2016():
url = "http://www.nhl.com/scores/htmlreports/20162017/ES020776.HTM"
tp = TeamParser(get_data(url))
tp.load_data()
... | Add tests for game parser item | Add tests for game parser item
| Python | mit | leaffan/pynhldb | ---
+++
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import requests
+from lxml import html
+
+from parsers.team_parser import TeamParser
+from parsers.game_parser import GameParser
+
+
+def test_2016():
+
+ url = "http://www.nhl.com/scores/htmlreports/20162017/ES020776.HTM"
+
+ tp = Team... | |
57b4d39749021305a2d5850e642537224d30611f | requests/hooks.py | requests/hooks.py | # -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request``:
The Request object, directly after being created.
``pre_send``:
The Request ... | # -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``args``:
A dictionary of the arguments being sent to Request().
``pre_request``:
The Request object, directly after being created.
``pre_send``:
The Request ... | Remove exception eating from dispatch_hook. | Remove exception eating from dispatch_hook. | Python | isc | Bluehorn/requests,revolunet/requests,revolunet/requests,psf/requests | ---
+++
@@ -25,8 +25,6 @@
"""
-import traceback
-
HOOKS = ('args', 'pre_request', 'pre_send', 'post_request', 'response')
@@ -42,12 +40,9 @@
hooks = [hooks]
for hook in hooks:
- try:
- _hook_data = hook(hook_data)
- if _hook_data is not None:
... |
48b1479a84fcb6d16d8aea8ca256d01e9898eeea | tools/fake_robot.py | tools/fake_robot.py | import json
from time import time
from threading import Timer
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import WebSocketHandler
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interva... | Add fake robot utility tool. | Add fake robot utility tool.
| Python | mit | pollen/pyrobus | ---
+++
@@ -0,0 +1,115 @@
+import json
+
+from time import time
+from threading import Timer
+
+from tornado.ioloop import IOLoop
+from tornado.web import Application
+from tornado.websocket import WebSocketHandler
+
+
+class RepeatedTimer(object):
+ def __init__(self, interval, function, *args, **kwargs):
+ ... | |
46600be25ea95a0c823730694a7f79be453477b1 | list_projects.py | list_projects.py | from yastlib import *
yast_id = 'id'
yast_password = 'password'
yast = Yast()
yast_hash = yast.login(yast_id, yast_password)
if yast_hash != False:
print 'Connected to yast.com'
projects = yast.getProjects()
nodes = projects.items()
for k, n in nodes:
print 'project ' + str(k) + ': ' + 'name: "' + n.name + '" pa... | Add script to list projects | Add script to list projects
| Python | mit | jfitz/hours-reporter | ---
+++
@@ -0,0 +1,18 @@
+from yastlib import *
+
+yast_id = 'id'
+yast_password = 'password'
+yast = Yast()
+yast_hash = yast.login(yast_id, yast_password)
+if yast_hash != False:
+ print 'Connected to yast.com'
+ projects = yast.getProjects()
+ nodes = projects.items()
+ for k, n in nodes:
+ print 'project ' + str... | |
7a4368bd4e3477300dd07408f622af4e55a106d2 | src/test.py | src/test.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from mst_tree_builder import *
from framenetreader import *
if __name__ == '__main__':
unittest.main()
| Test all modules in one fell swoop | Test all modules in one fell swoop
git-svn-id: a2d0af3c19596d99b5c1e07a0b4fed4eaca14ddf@18173 7fff26f0-e11d-0410-b8d0-f4b6ff9b0dc5
| Python | agpl-3.0 | aymara/knowledgesrl,aymara/knowledgesrl | ---
+++
@@ -0,0 +1,10 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+import unittest
+
+from mst_tree_builder import *
+from framenetreader import *
+
+if __name__ == '__main__':
+ unittest.main() | |
df298d5bb8925ce54a9cd400494831c975ca8578 | experimental/directshow.py | experimental/directshow.py | #!/usr/bin/python
# $Id:$
# Play an audio file with DirectShow. Tested ok with MP3, WMA, MID, WAV, AU.
# Caveats:
# - Requires a filename (not from memory or stream yet). Looks like we need
# to manually implement a filter which provides an output IPin. Lot of
# work.
# - Theoretically can traverse the ... | Move win32 audio experiment to trunk. | Move win32 audio experiment to trunk.
git-svn-id: d4fdfcd4de20a449196f78acc655f735742cd30d@736 14d46d22-621c-0410-bb3d-6f67920f7d95
| Python | bsd-3-clause | regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations | ---
+++
@@ -0,0 +1,47 @@
+#!/usr/bin/python
+# $Id:$
+
+# Play an audio file with DirectShow. Tested ok with MP3, WMA, MID, WAV, AU.
+# Caveats:
+# - Requires a filename (not from memory or stream yet). Looks like we need
+# to manually implement a filter which provides an output IPin. Lot of
+# work.
+# - The... | |
a9af0878b349238f72dda384d3084bc31518b0ab | set-nmea.py | set-nmea.py | #!/usr/bin/python
# Enable or disable the use of NMEA.
import ubx
import struct
import calendar
import os
import gobject
import logging
import sys
import socket
import time
loop = gobject.MainLoop()
def callback(ty, packet):
print("callback %s" % repr([ty, packet]))
if ty == "CFG-PRT":
if sys.argv[1... | #!/usr/bin/python
# Enable or disable the use of NMEA.
import ubx
import struct
import calendar
import os
import gobject
import logging
import sys
import socket
import time
loop = gobject.MainLoop()
def callback(ty, packet):
print("callback %s" % repr([ty, packet]))
if ty == "CFG-PRT":
if sys.argv[1... | Fix the script. It did not work at all before. | Fix the script. It did not work at all before.
| Python | mit | berkeleyapplied/ubx,aanjhan/ubx,aanjhan/ubx,berkeleyapplied/ubx | ---
+++
@@ -19,12 +19,12 @@
if ty == "CFG-PRT":
if sys.argv[1] == "on":
# NMEA and UBX
- packet[0]["In_proto_mask"] = 1 + 2
- packet[0]["Out_proto_mask"] = 1 + 2
+ packet[1]["In_proto_mask"] = 1 + 2
+ packet[1]["Out_proto_mask"] = 1 + 2
e... |
a3084c3672a2dcfdadf22535540e9f843feb3561 | busstops/management/commands/enhance_ni_stops.py | busstops/management/commands/enhance_ni_stops.py | """Usage:
./manage.py enhance_ni_stops
"""
import requests
from time import sleep
from django.core.management.base import BaseCommand
from ...models import StopPoint
SESSION = requests.Session()
class Command(BaseCommand):
def handle(self, *args, **options):
for stop in StopPoint.objects.filter(at... | Add reverse geocode command for NI | Add reverse geocode command for NI
| Python | mpl-2.0 | stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk | ---
+++
@@ -0,0 +1,29 @@
+"""Usage:
+
+ ./manage.py enhance_ni_stops
+"""
+
+import requests
+from time import sleep
+from django.core.management.base import BaseCommand
+from ...models import StopPoint
+
+
+SESSION = requests.Session()
+
+
+class Command(BaseCommand):
+ def handle(self, *args, **options):
+ ... | |
88b2011e0f337f1d91192dc62cb051590914ab8e | globOpt/scripts/normal_distr.py | globOpt/scripts/normal_distr.py |
import healpy as hp
import numpy as np
import matplotlib.pyplot as plt
def load_ply(path):
lines = []
verts = []
norms = []
f = open(path, "r")
for line in f:
lines.append(line)
if (lines[0] != "ply\n"):
return 0
i = 1
#get number of ve... | Add script to display normal distribution | Add script to display normal distribution
| Python | apache-2.0 | amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,NUAAXXY/globOpt | ---
+++
@@ -0,0 +1,78 @@
+
+import healpy as hp
+import numpy as np
+
+import matplotlib.pyplot as plt
+
+def load_ply(path):
+
+ lines = []
+ verts = []
+ norms = []
+
+
+ f = open(path, "r")
+ for line in f:
+ lines.append(line)
+
+ if (lines[0] != "ply\n"):
+ ... | |
c786ae11e5dfb6166e3d94a64ac5efed5be2de78 | DataWrangling/stream_csv.py | DataWrangling/stream_csv.py | """Use a generator with numpy loadtxt"""
import numpy as np
def file_stream(file_name):
for line in open(file_name):
yield line
def demo_use():
file_name = 'census_abs2011_summary.csv'
# Skip the header, return 3 columns: the age, weekly rental and total family income
data = np.loadtxt(file... | Use a generator with numpy.loadtxt | Use a generator with numpy.loadtxt
| Python | apache-2.0 | chengsoonong/didbits | ---
+++
@@ -0,0 +1,21 @@
+"""Use a generator with numpy loadtxt"""
+
+import numpy as np
+
+
+def file_stream(file_name):
+ for line in open(file_name):
+ yield line
+
+
+def demo_use():
+ file_name = 'census_abs2011_summary.csv'
+ # Skip the header, return 3 columns: the age, weekly rental and total ... | |
73b6f640d74f274ad00bfcdedbe9483d67db9936 | larger_embedding.py | larger_embedding.py | """
Embed motif in larger network
"""
import copy
import numpy as np
import networkx as nx
import scipy.stats as scis
import matplotlib.pyplot as plt
from tqdm import trange
from system import SDESystem
from solver import solve_system
from filters import filter_steady_state
def get_system(N, v_in=5, D=1):
ass... | Add unstable embedding in larger network | Add unstable embedding in larger network
| Python | mit | kpj/SDEMotif,kpj/SDEMotif | ---
+++
@@ -0,0 +1,80 @@
+"""
+Embed motif in larger network
+"""
+
+import copy
+
+import numpy as np
+import networkx as nx
+import scipy.stats as scis
+import matplotlib.pyplot as plt
+
+from tqdm import trange
+
+from system import SDESystem
+from solver import solve_system
+from filters import filter_steady_stat... | |
a0a8e481eaaff042ad43ae3f40110f215b144c26 | auth0/v2/test/test_jobs.py | auth0/v2/test/test_jobs.py | import unittest
import mock
from ..jobs import Jobs
class TestJobs(unittest.TestCase):
@mock.patch('auth0.v2.jobs.RestClient')
def test_get(self, mock_rc):
mock_instance = mock_rc.return_value
j = Jobs(domain='domain', jwt_token='jwttoken')
j.get('an-id')
mock_instance.get.a... | Add unit tests for Jobs() | Add unit tests for Jobs()
| Python | mit | auth0/auth0-python,auth0/auth0-python | ---
+++
@@ -0,0 +1,42 @@
+import unittest
+import mock
+from ..jobs import Jobs
+
+
+class TestJobs(unittest.TestCase):
+
+ @mock.patch('auth0.v2.jobs.RestClient')
+ def test_get(self, mock_rc):
+ mock_instance = mock_rc.return_value
+
+ j = Jobs(domain='domain', jwt_token='jwttoken')
+ j.g... | |
1e867909e241777ab75abf19a160b83de50160d2 | migrations/versions/34c2049aaee2_add_indexes_on_ads_for_numero_and_insee.py | migrations/versions/34c2049aaee2_add_indexes_on_ads_for_numero_and_insee.py | """Add indexes on ADS for numero and insee
Revision ID: 34c2049aaee2
Revises: e187aca7c77a
Create Date: 2019-10-21 16:35:48.431148
"""
# revision identifiers, used by Alembic.
revision = '34c2049aaee2'
down_revision = 'e187aca7c77a'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import post... | Add migrations for indexes on ADS | Add migrations for indexes on ADS
| Python | agpl-3.0 | openmaraude/APITaxi,openmaraude/APITaxi | ---
+++
@@ -0,0 +1,24 @@
+"""Add indexes on ADS for numero and insee
+
+Revision ID: 34c2049aaee2
+Revises: e187aca7c77a
+Create Date: 2019-10-21 16:35:48.431148
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '34c2049aaee2'
+down_revision = 'e187aca7c77a'
+
+from alembic import op
+import sqlalchemy a... | |
8e0c00254997e0223141bf02f599bce3eacca747 | proc-mem.py | proc-mem.py | #!/usr/bin/env python
import os
import sys
def show_usage():
sys.stderr.write('''memio - Simple I/O for /proc/<pid>/mem
Dump /proc/<pid>/maps:
memio.py <pid>
Read from or write to (when some input is present on stdin) memory:
memio.py <pid> <start> (<end> | +<size>)
memio.py <pid> <hexrange>
<hexra... | Add process memory usage script | Add process memory usage script | Python | mit | voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts,voidabhi/python-scripts | ---
+++
@@ -0,0 +1,66 @@
+#!/usr/bin/env python
+import os
+import sys
+
+def show_usage():
+ sys.stderr.write('''memio - Simple I/O for /proc/<pid>/mem
+Dump /proc/<pid>/maps:
+ memio.py <pid>
+Read from or write to (when some input is present on stdin) memory:
+ memio.py <pid> <start> (<end> | +<size>)
+ ... | |
95ab6c0c23f756372a3e34e4386c15b4beaf0aa7 | tests/UnreachableSymbolsRemove/SimpleTest.py | tests/UnreachableSymbolsRemove/SimpleTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy-transforms
"""
from unittest import main, TestCase
from grammpy import *
from grammpy_transforms import *
class SimpleTest(TestCase):
pass
if __name__ == '__main__':
main()
| Add file for simple test of unreachable symbols remove | Add file for simple test of unreachable symbols remove
| Python | mit | PatrikValkovic/grammpy | ---
+++
@@ -0,0 +1,20 @@
+#!/usr/bin/env python
+"""
+:Author Patrik Valkovic
+:Created 23.06.2017 16:39
+:Licence GNUv3
+Part of grammpy-transforms
+
+"""
+
+from unittest import main, TestCase
+from grammpy import *
+from grammpy_transforms import *
+
+
+class SimpleTest(TestCase):
+ pass
+
+
+if __name__ == '__... | |
1bd5e8897991cec7d1c7f5c6a8320415841887e5 | migrations/versions/0104_more_letter_orgs.py | migrations/versions/0104_more_letter_orgs.py | """empty message
Revision ID: 0104_more_letter_orgs
Revises: 0103_add_historical_redact
Create Date: 2017-06-29 12:44:16.815039
"""
# revision identifiers, used by Alembic.
revision = '0104_more_letter_orgs'
down_revision = '0103_add_historical_redact'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.... | Add more organisations for letter branding | Add more organisations for letter branding
> The logos are now ready to go on DVLA side- so far we've got:
> 001 = HM Government
> 002 = OPG
> 003 = DWP
> 004 = GEO
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | ---
+++
@@ -0,0 +1,28 @@
+"""empty message
+
+Revision ID: 0104_more_letter_orgs
+Revises: 0103_add_historical_redact
+Create Date: 2017-06-29 12:44:16.815039
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '0104_more_letter_orgs'
+down_revision = '0103_add_historical_redact'
+
+from alembic import op
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.