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 |
|---|---|---|---|---|---|---|---|---|---|---|
31fff75ff499604453cd3cd07ad75496f5e0d222 | android_webview/tools/known_incompatible.py | android_webview/tools/known_incompatible.py | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""List of known-incompatibly-licensed directories for Android WebView.
This is not used by the webview_licenses tool itself; it is effectively a
"cache... | Add list of files with licenses not wanted in webview. | Android: Add list of files with licenses not wanted in webview.
The script which merges Chromium code into the Android tree needs to
know which directories to remove for licensing reasons; it's much easier
if this is just a static list in the tree which can subsequently be
validated with the webview_licences tool. The... | Python | bsd-3-clause | Jonekee/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,markYoungH/chromiu... | ---
+++
@@ -0,0 +1,37 @@
+# Copyright (c) 2012 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""List of known-incompatibly-licensed directories for Android WebView.
+
+This is not used by the webview_licenses tool ... | |
e58f75c0c0196d2c3cb9df3e24978142ac542933 | bot/action/extra/messages/stored_message.py | bot/action/extra/messages/stored_message.py | class StoredMessageMapper:
def from_api(self, message):
data = message.data.copy()
self.__replace_with_id_if_present(data, "from")
self.__replace_with_id_if_present(data, "forward_from")
self.__replace_with_id_if_present(data, "reply_to_message", "message_id")
self.__delete_i... | Create StoredMessageMapper from MessageStorageHandler code | Create StoredMessageMapper from MessageStorageHandler code
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -0,0 +1,37 @@
+class StoredMessageMapper:
+ def from_api(self, message):
+ data = message.data.copy()
+ self.__replace_with_id_if_present(data, "from")
+ self.__replace_with_id_if_present(data, "forward_from")
+ self.__replace_with_id_if_present(data, "reply_to_message", "mes... | |
7f9c94f99dcaed8c97d6288d9fbbc483a963c2d7 | stdnum/at/businessid.py | stdnum/at/businessid.py | # businessid.py - functions for handling Austrian company register numbers
#
# Copyright (C) 2015 Holvi Payment Services Oy
# Copyright (C) 2012, 2013 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by t... | Add company register number validation for Austria | Add company register number validation for Austria
| Python | lgpl-2.1 | arthurdejong/python-stdnum,t0mk/python-stdnum,dchoruzy/python-stdnum,arthurdejong/python-stdnum,holvi/python-stdnum,arthurdejong/python-stdnum,holvi/python-stdnum,holvi/python-stdnum | ---
+++
@@ -0,0 +1,70 @@
+# businessid.py - functions for handling Austrian company register numbers
+#
+# Copyright (C) 2015 Holvi Payment Services Oy
+# Copyright (C) 2012, 2013 Arthur de Jong
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General ... | |
2f308fbefad5f5cee8b6e160e9a89fda7f4e1ba9 | tests/test_renderers.py | tests/test_renderers.py | from flask import Flask
from flask_webapi import WebAPI, APIView, renderer, route
from flask_webapi.renderers import PickleRenderer
from unittest import TestCase
class TestRenderer(TestCase):
def setUp(self):
self.app = Flask(__name__)
self.api = WebAPI(self.app)
self.api.load_module('test... | Add unit tests for pickle renderer | Add unit tests for pickle renderer
| Python | mit | viniciuschiele/flask-webapi | ---
+++
@@ -0,0 +1,24 @@
+from flask import Flask
+from flask_webapi import WebAPI, APIView, renderer, route
+from flask_webapi.renderers import PickleRenderer
+from unittest import TestCase
+
+
+class TestRenderer(TestCase):
+ def setUp(self):
+ self.app = Flask(__name__)
+ self.api = WebAPI(self.ap... | |
8174893b7226f53f89d7f52cfcb5dd073557da07 | tools/letters_parser.py | tools/letters_parser.py | #coding=utf-8
import json
FILE_PATH = '/file-path'
FILE_NAME = 'file-name'
def main():
fp = open(FILE_PATH + FILE_NAME + '.txt', 'r')
out = {}
line = fp.readline()
out['law'] = line
out['letters'] = []
count = 0
while True:
line = fp.readline()
if not line:
... | Add the prototype of the parser of letters | Add the prototype of the parser of letters
| Python | mit | LWAlphaMonkey/ArchitectureLaw,LWAlphaMonkey/ArchitectureLaw | ---
+++
@@ -0,0 +1,40 @@
+#coding=utf-8
+import json
+FILE_PATH = '/file-path'
+FILE_NAME = 'file-name'
+
+def main():
+ fp = open(FILE_PATH + FILE_NAME + '.txt', 'r')
+ out = {}
+ line = fp.readline()
+ out['law'] = line
+ out['letters'] = []
+ count = 0
+
+ while True:
+ line = fp.re... | |
cd5678640e17cca0517c14f7d172b2ca1f10a560 | rarecommends.py | rarecommends.py | #!/usr/bin/python
# Gets stuff from Resident Advisor's awesome 'RA Recommends' section
# Note: this is just regexing the HTML... so may stop working if page structure changes
# This is not written by, or affiliated with Resident Advisor at all
# 2013 oldhill // MIT license
import urllib2
import re
def getResidentD... | #!/usr/bin/python
# Gets stuff from Resident Advisor's awesome 'RA Recommends' section
# Note: this is just regexing the HTML... so may stop working if page structure changes
# This is not written by, or affiliated with Resident Advisor at all
# 2013 oldhill // MIT license
import urllib2
import re
def getResidentD... | Fix Resident Advisor regex to match new page design | Fix Resident Advisor regex to match new page design
| Python | mit | oldhill/ra-recommends | ---
+++
@@ -11,13 +11,11 @@
def getResidentData():
- # grab all the data...
web_page = urllib2.urlopen('http://www.residentadvisor.net/reviews.aspx?format=recommend')
all_the_html = web_page.read()
- demarcator = 'pb2' # surrounds records of recommended stuff
- relevant_block = re.findall(demarcator+'(.... |
d9bdaf77e2b9834efd3539ec6ce599804a84b5dc | update_webhooks.py | update_webhooks.py | import requests
URL = "https://stripe.com/docs/api/curl/sections?all_sections=1&version=2019-02-19&cacheControlVersion=4"
response = requests.get(URL)
data = response.json()
event_types = data["event_types"]["data"]["event_types"]
class_template = """class {class_name}Webhook(Webhook):
name = "{name}"
desc... | Add script to generate webhooks | Add script to generate webhooks
| Python | mit | pinax/django-stripe-payments | ---
+++
@@ -0,0 +1,41 @@
+import requests
+
+
+URL = "https://stripe.com/docs/api/curl/sections?all_sections=1&version=2019-02-19&cacheControlVersion=4"
+response = requests.get(URL)
+
+data = response.json()
+
+event_types = data["event_types"]["data"]["event_types"]
+
+class_template = """class {class_name}Webhook(... | |
cebd5969fda658fd045c1228a8d28cc64fca103e | tests/test_ansi.py | tests/test_ansi.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test the cprint function."""
from colorise.nix.color_functions import to_ansi
import pytest
@pytest.mark.skip_on_windows
def test_ansi():
assert to_ansi(34, '95') == '\x1b[34;95m'
assert to_ansi(0) == '\x1b[0m'
assert to_ansi() == ''
| Test ansi escape sequence function | Test ansi escape sequence function
| Python | bsd-3-clause | MisanthropicBit/colorise | ---
+++
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""Test the cprint function."""
+
+from colorise.nix.color_functions import to_ansi
+import pytest
+
+
+@pytest.mark.skip_on_windows
+def test_ansi():
+ assert to_ansi(34, '95') == '\x1b[34;95m'
+ assert to_ansi(0) == '\x1b[0m'
+ ass... | |
61747aa05f183e7b0712df08c81d9a181cd5abc5 | tests/test_bbox.py | tests/test_bbox.py | import unittest
from coral import bbox
class TestBBox(unittest.TestCase):
def setUp(self):
self.a = bbox.BBox((20, 30), (50, 40))
self.b = self.a.scale(2)
self.c = self.b.translate(self.b.width() / 2, 0)
def test_width_height_area(self):
self.assertEqual(self.a.area(), self.a... | Add some tests for bbox. | Add some tests for bbox.
| Python | mit | lecram/coral | ---
+++
@@ -0,0 +1,47 @@
+import unittest
+
+from coral import bbox
+
+class TestBBox(unittest.TestCase):
+
+ def setUp(self):
+ self.a = bbox.BBox((20, 30), (50, 40))
+ self.b = self.a.scale(2)
+ self.c = self.b.translate(self.b.width() / 2, 0)
+
+ def test_width_height_area(self):
+ ... | |
5f69bf0adeee796ce2d66b605f1e65c67bc791bb | mininet/test/test_util.py | mininet/test/test_util.py | #!/usr/bin/env python
"""Package: mininet
Test functions defined in mininet.util."""
import unittest
from mininet.util import quietRun
class testQuietRun( unittest.TestCase ):
"""Test quietRun that runs a command and returns its merged output from
STDOUT and STDIN"""
@staticmethod
def getEchoCmd... | Add unit tests for util | Add unit tests for util
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+
+"""Package: mininet
+ Test functions defined in mininet.util."""
+
+import unittest
+
+from mininet.util import quietRun
+
+class testQuietRun( unittest.TestCase ):
+ """Test quietRun that runs a command and returns its merged output from
+ STDOUT and STDIN""... | |
a8ce7fbfecaf7a55d8f31a6e4489d5b8a3fc894b | src/gevent_sqlite3.py | src/gevent_sqlite3.py | #!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright 2017 - Luca Versari <veluca93@gmail.com>
"""This file can be imported instead of sq... | Add a sqlite3 gevent wrapper | Add a sqlite3 gevent wrapper
| Python | mpl-2.0 | algorithm-ninja/territoriali-backend | ---
+++
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+#
+# Copyright 2017 - Luca Versari <veluca93@gmail.com>
+
+"""This... | |
3d458090e3d1684e42b5dc9e9d30e268129dce58 | course_discovery/apps/course_metadata/migrations/0155_auto_20190207_1546.py | course_discovery/apps/course_metadata/migrations/0155_auto_20190207_1546.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-02-07 15:46
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('course_metadata', '0154_course_entitlement_default_currency'),
]
operations = [
mi... | Add migration file for removing unused curriculum models | Add migration file for removing unused curriculum models
| Python | agpl-3.0 | edx/course-discovery,edx/course-discovery,edx/course-discovery,edx/course-discovery | ---
+++
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.15 on 2019-02-07 15:46
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('course_metadata', '0154_course_entitlement_default_currency')... | |
e4166b3cf4f37f74f6c7e1be2641f556e5763a1a | evalQuadratic.py | evalQuadratic.py | def evalQuadratic( a, b, c, x ):
a = int ( a )
b = int ( b )
c = int ( c )
x = int ( x )
s = (a * (x ** 2)) + (b * x) + c
return s
a = input( "Enter a: " )
b = input( "Enter b: " )
c = input( "Enter c: " )
x = input( "Enter x: " )
print( "The answer of the quadratic equation is " + str( evalQuadratic( a, b, c... | Add the answer to the second question of Assignment 3 | Add the answer to the second question of Assignment 3
| Python | mit | SuyashD95/python-assignments | ---
+++
@@ -0,0 +1,16 @@
+def evalQuadratic( a, b, c, x ):
+
+ a = int ( a )
+ b = int ( b )
+ c = int ( c )
+ x = int ( x )
+
+ s = (a * (x ** 2)) + (b * x) + c
+ return s
+
+a = input( "Enter a: " )
+b = input( "Enter b: " )
+c = input( "Enter c: " )
+x = input( "Enter x: " )
+
+print( "The answer of the quadratic ... | |
92d35c82ce4843129668d5102fa185a02f6d5b7a | test/torch/tensors/test_parameter.py | test/torch/tensors/test_parameter.py | import random
import torch
import torch.nn.functional as F
from torch.nn import Parameter
import syft
from syft.frameworks.torch.tensors import LoggingTensor
class TestLogTensor(object):
def setUp(self):
hook = syft.TorchHook(torch, verbose=True)
self.me = hook.local_worker
self.me.is_c... | Add tests for send / get / remote op on parameters | Add tests for send / get / remote op on parameters
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -0,0 +1,63 @@
+import random
+
+import torch
+import torch.nn.functional as F
+from torch.nn import Parameter
+import syft
+
+from syft.frameworks.torch.tensors import LoggingTensor
+
+
+class TestLogTensor(object):
+ def setUp(self):
+ hook = syft.TorchHook(torch, verbose=True)
+
+ self.m... | |
4453d0158abec35a741f2fb5dcfcd6fa1fd3cd20 | django/website/contacts/tests/test_views_activation.py | django/website/contacts/tests/test_views_activation.py | from contacts.views.activation import ResetPassword
from django.conf import settings
def test_reset_password_subject_contains_site_name():
assert '{0}: password recovery'.format(settings.SITE_NAME) == ResetPassword().get_subject()
| Add test for ResetPassword email subject | Add test for ResetPassword email subject | Python | agpl-3.0 | daniell/kashana,aptivate/kashana,aptivate/alfie,daniell/kashana,aptivate/kashana,aptivate/kashana,aptivate/alfie,aptivate/alfie,aptivate/alfie,daniell/kashana,aptivate/kashana,daniell/kashana | ---
+++
@@ -0,0 +1,6 @@
+from contacts.views.activation import ResetPassword
+from django.conf import settings
+
+
+def test_reset_password_subject_contains_site_name():
+ assert '{0}: password recovery'.format(settings.SITE_NAME) == ResetPassword().get_subject() | |
25889cd86d8c6a58793660d52dbdef3562f12b70 | tests/test_stack_operations.py | tests/test_stack_operations.py | import pytest
from thinglang.execution.errors import UnknownVariable
from thinglang.runner import run
def test_stack_resolution_in_block():
assert run("""
thing Program
does start
number i = 0
Output.write("outside before, i =", i)
if true
Output.write("inside before, i =... | Add test for general scoping case in nested blocks | Add test for general scoping case in nested blocks
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | ---
+++
@@ -0,0 +1,27 @@
+import pytest
+
+from thinglang.execution.errors import UnknownVariable
+from thinglang.runner import run
+
+
+def test_stack_resolution_in_block():
+ assert run("""
+thing Program
+ does start
+
+ number i = 0
+ Output.write("outside before, i =", i)
+ if true
+ ... | |
cf7e8ec08410ce4567d7fc32f7c37c8a639e2039 | learn.py | learn.py | import RPi.GPIO as gpio
import time
class move:
def __init__(self, RF,RB,LF,LB,SLEEP):
self.RF = RF
self.RB = RB
self.LF = LF
self.LB = LB
self.SLEEP = SLEEP
def getRF(self):
return self.RF
def getRB(self):
return self.RB
def getLF(self):
retu... | Add new Class Based Movment | Add new Class Based Movment
| Python | apache-2.0 | aateichman/Vision | ---
+++
@@ -0,0 +1,52 @@
+import RPi.GPIO as gpio
+import time
+class move:
+
+ def __init__(self, RF,RB,LF,LB,SLEEP):
+ self.RF = RF
+ self.RB = RB
+ self.LF = LF
+ self.LB = LB
+ self.SLEEP = SLEEP
+
+ def getRF(self):
+ return self.RF
+ def getRB(self):
+ return... | |
b082b72fc0c6b297571131cbc23c78f62b1aa96b | tests/unit/asyncio/test_asyncio_repr.py | tests/unit/asyncio/test_asyncio_repr.py | from butter.asyncio.eventfd import Eventfd_async
from butter.asyncio.fanotify import Fanotify_async
from butter.asyncio.inotify import Inotify_async
from butter.asyncio.signalfd import Signalfd_async
from butter.asyncio.timerfd import Timerfd_async
from collections import namedtuple
import pytest
import sys
class Mock... | Test async objects for __repr__ as well | Test async objects for __repr__ as well
| Python | bsd-3-clause | arkaitzj/python-butter | ---
+++
@@ -0,0 +1,64 @@
+from butter.asyncio.eventfd import Eventfd_async
+from butter.asyncio.fanotify import Fanotify_async
+from butter.asyncio.inotify import Inotify_async
+from butter.asyncio.signalfd import Signalfd_async
+from butter.asyncio.timerfd import Timerfd_async
+from collections import namedtuple
+im... | |
926c095fbc1068658ed61195fe42b02d0211e013 | mzalendo/core/management/commands/core_fix_ward_names.py | mzalendo/core/management/commands/core_fix_ward_names.py | import re
from django.core.management.base import NoArgsCommand, CommandError
from django.template.defaultfilters import slugify
from optparse import make_option
from core.models import PlaceKind, Place
class Command(NoArgsCommand):
help = 'Standardize the form of ward names with regard to / and - separators'
... | Add a script to fix the Ward names + slugs in the database | Add a script to fix the Ward names + slugs in the database
The ward names imported from "Final Constituencies and Wards Description.pdf"
have strange formatting where the ward names are separated
by a '/' or a '-', where they have random whitespace after them
and none before. This creates problems for matching names ... | Python | agpl-3.0 | hzj123/56th,patricmutwiri/pombola,hzj123/56th,patricmutwiri/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,geoffkilpin/pombola,ken-muturi/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,patricmutwiri/pombola,ken-muturi/pombola,patricmutwiri/pombola... | ---
+++
@@ -0,0 +1,31 @@
+import re
+
+from django.core.management.base import NoArgsCommand, CommandError
+
+from django.template.defaultfilters import slugify
+
+from optparse import make_option
+
+from core.models import PlaceKind, Place
+
+class Command(NoArgsCommand):
+ help = 'Standardize the form of ward na... | |
e19d8b0deaf5c7d3d98d25ed42f932ee0281f728 | project_euler/test/tests.py | project_euler/test/tests.py | # Hack to allow import of ProjectEulerAnswers while it is still at top level.
from os import path
import sys
sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__ )))))
import unittest
import ProjectEulerAnswers as pea
class TestEuler(unittest.TestCase):
def test_prob1(self):
sel... | Add test cases for the first 4 problems | Add test cases for the first 4 problems
| Python | mit | tofu-rocketry/project-euler | ---
+++
@@ -0,0 +1,28 @@
+# Hack to allow import of ProjectEulerAnswers while it is still at top level.
+from os import path
+import sys
+sys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__ )))))
+
+import unittest
+
+import ProjectEulerAnswers as pea
+
+
+class TestEuler(unittest.TestCase):
... | |
5a0ec237878512c408dd392c20b440033aed402b | tests/mock_config.py | tests/mock_config.py | from scoring_engine.config_loader import ConfigLoader
class MockConfig(object):
def __init__(self, location):
self.file_location = location
@property
def config(self):
return ConfigLoader(self.file_location)
@property
def checks_location(self):
return 'scoring_engine/chec... | from scoring_engine.config_loader import ConfigLoader
class MockConfig(object):
def __init__(self, location):
self.file_location = location
@property
def config(self):
return ConfigLoader(self.file_location)
| Remove unnecessary config mock property | Remove unnecessary config mock property
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | ---
+++
@@ -8,7 +8,3 @@
@property
def config(self):
return ConfigLoader(self.file_location)
-
- @property
- def checks_location(self):
- return 'scoring_engine/checks' |
2ca3da2ffe97c1b77f8713d19819f44bf88728ed | corehq/apps/hqadmin/management/commands/report_code_metrics.py | corehq/apps/hqadmin/management/commands/report_code_metrics.py | from django.core.management.base import BaseCommand
from dimagi.ext.couchdbkit import Document
from corehq.util.metrics import metrics_gauge
class Command(BaseCommand):
help = "Display a variety of code-quality metrics, optionally sending them to datadog"
def add_arguments(self, parser):
parser.add... | Add management command to report computed stats | Add management command to report computed stats
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -0,0 +1,31 @@
+from django.core.management.base import BaseCommand
+
+from dimagi.ext.couchdbkit import Document
+
+from corehq.util.metrics import metrics_gauge
+
+
+class Command(BaseCommand):
+ help = "Display a variety of code-quality metrics, optionally sending them to datadog"
+
+ def add_argum... | |
cfa1a738da0d8bff2ab20f7070eab9e6ea967c49 | examples/cheapest_destinations.py | examples/cheapest_destinations.py | '''
Finds the cheapest fares filed to a given city
Example:
python cheapest-destinations.py YTO
Result:
FLL 165.62
MCO 165.62
JFK 172.36
LGA 191.12
'''
import datetime
import json
import sys
sys.path.append('..')
import sabre_dev_studio
import sabre_dev_studio.sabre_exceptions as sabre_exception... | Add first example: cheapest destinations | Add first example: cheapest destinations
| Python | mit | Jamil/sabre_dev_studio | ---
+++
@@ -0,0 +1,65 @@
+'''
+Finds the cheapest fares filed to a given city
+
+Example:
+ python cheapest-destinations.py YTO
+
+Result:
+ FLL 165.62
+ MCO 165.62
+ JFK 172.36
+ LGA 191.12
+'''
+
+import datetime
+import json
+import sys
+
+sys.path.append('..')
+import sabre_dev_studio
+import sabre... | |
7bafcf68f419a87f996960fb9be304468bc5154a | tests/test_synonym.py | tests/test_synonym.py | import sqlalchemy as sa
from sqlalchemy.ext.hybrid import hybrid_property
from wtforms_alchemy import ModelForm
from tests import ModelFormTestCase
class TestSynonym(ModelFormTestCase):
def test_synonym_returning_column_property(self):
class ModelTest(self.base):
__tablename__ = 'model_test'
... | Add tests for SA synonym | Add tests for SA synonym
| Python | bsd-3-clause | quantus/wtforms-alchemy,kelvinhammond/wtforms-alchemy,williamwu0220/wtforms-alchemy | ---
+++
@@ -0,0 +1,35 @@
+import sqlalchemy as sa
+from sqlalchemy.ext.hybrid import hybrid_property
+from wtforms_alchemy import ModelForm
+from tests import ModelFormTestCase
+
+
+class TestSynonym(ModelFormTestCase):
+ def test_synonym_returning_column_property(self):
+ class ModelTest(self.base):
+ ... | |
a846eadb0cdf02ace459e300ae4da7710754263f | IPython/__main__.py | IPython/__main__.py | # encoding: utf-8
"""Terminal-based IPython entry point.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with th... | Allow starting IPython as `python -m IPython`. | Allow starting IPython as `python -m IPython`.
Closes #2541.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -0,0 +1,14 @@
+# encoding: utf-8
+"""Terminal-based IPython entry point.
+"""
+#-----------------------------------------------------------------------------
+# Copyright (c) 2012, IPython Development Team.
+#
+# Distributed under the terms of the Modified BSD License.
+#
+# The full license is in the f... | |
3e9c3fb3ba1a05a751f2587a24d163f9c9fca7cb | twitterproj/fisher.py | twitterproj/fisher.py | """
Fisher information matrix of a Dirichlet distribution.
"""
from __future__ import division
import numpy as np
import scipy
from scipy.special import polygamma
import time
import twitterproj
import io
from operator import itemgetter
def fisher_information(counts):
"""
Calculates the Fisher information ... | Add functions to calculate Fisher information. | Add functions to calculate Fisher information.
| Python | unlicense | chebee7i/twitter,chebee7i/twitter,chebee7i/twitter | ---
+++
@@ -0,0 +1,79 @@
+"""
+Fisher information matrix of a Dirichlet distribution.
+
+"""
+from __future__ import division
+
+import numpy as np
+
+import scipy
+from scipy.special import polygamma
+
+import time
+
+import twitterproj
+import io
+from operator import itemgetter
+
+def fisher_information(counts):
+... | |
20f1dfd80dc6090c2b82ec0847315585d2ecf26b | udiskie/automount.py | udiskie/automount.py | """
Udiskie automounter daemon.
"""
__all__ = ['AutoMounter']
class AutoMounter(object):
"""
Automatically mount newly added media.
"""
def __init__(self, mounter):
self.mounter = mounter
def device_added(self, udevice):
self.mounter.add_device(udevice)
def media_added(self, u... | """
Udiskie automounter daemon.
"""
__all__ = ['AutoMounter']
class AutoMounter(object):
"""
Automatically mount newly added media.
"""
def __init__(self, mounter):
self.mounter = mounter
def device_added(self, udevice):
self.mounter.add_device(udevice)
def media_added(self, u... | Revert "Automount LUKS devices when they have been unlocked" | Revert "Automount LUKS devices when they have been unlocked"
This reverts commit d67f8c7284e8d3bff2e7c81711a9fece952aea46.
| Python | mit | khardix/udiskie,coldfix/udiskie,mathstuf/udiskie,coldfix/udiskie,pstray/udiskie,pstray/udiskie | ---
+++
@@ -16,8 +16,3 @@
def media_added(self, udevice):
self.mounter.add_device(udevice)
- # Automount LUKS cleartext holders after they have been unlocked.
- # Why doesn't this work in device_added?
- def device_unlocked(self, udevice):
- self.mounter.add_device(udevice.luks_clearte... |
e63f4e7b42b85e25fc89a31d0a622b19e01a1227 | tests/test_strings.py | tests/test_strings.py | """Tests for string searches"""
from nose.tools import eq_
from dxr.testing import SingleFileTestCase, MINIMAL_MAIN
class StringTests(SingleFileTestCase):
source = """
void main_idea() {
}
""" + MINIMAL_MAIN
def test_negated_phrase(self):
"""Make sure a negated phrase search... | Add a smoke test for negated phrase matches. | Add a smoke test for negated phrase matches. | Python | mit | gartung/dxr,jay-z007/dxr,kleintom/dxr,pelmers/dxr,gartung/dxr,KiemVM/Mozilla--dxr,jbradberry/dxr,srenatus/dxr,pelmers/dxr,erikrose/dxr,pelmers/dxr,gartung/dxr,erikrose/dxr,bozzmob/dxr,pombredanne/dxr,kleintom/dxr,kleintom/dxr,bozzmob/dxr,bozzmob/dxr,kleintom/dxr,jbradberry/dxr,jbradberry/dxr,gartung/dxr,srenatus/dxr,Ki... | ---
+++
@@ -0,0 +1,16 @@
+"""Tests for string searches"""
+
+from nose.tools import eq_
+
+from dxr.testing import SingleFileTestCase, MINIMAL_MAIN
+
+
+class StringTests(SingleFileTestCase):
+ source = """
+ void main_idea() {
+ }
+ """ + MINIMAL_MAIN
+
+ def test_negated_phrase(self):
+ ... | |
6676d3fdc7a50f7b694d557a1f3daff154fbd221 | setup.py | setup.py | #This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from setuptools import setup
setup(
name='Nereid',
version='2.8.0.2',
url='http://nereid.openlabs.co.in/docs/',
license='GPLv3',
author='Openlabs Te... | #This file is part of Tryton & Nereid. The COPYRIGHT file at the top level of
#this repository contains the full copyright notices and license terms.
from setuptools import setup
setup(
name='Nereid',
version='2.8.0.2',
url='http://nereid.openlabs.co.in/docs/',
license='GPLv3',
author='Openlabs Te... | Use a version of flask < 0.10 | Use a version of flask < 0.10
* Flask 0.10 has a bunch of changes which break nereid
| Python | bsd-3-clause | fulfilio/nereid,prakashpp/nereid,usudaysingh/nereid,prakashpp/nereid,riteshshrv/nereid,riteshshrv/nereid,usudaysingh/nereid,fulfilio/nereid | ---
+++
@@ -25,7 +25,7 @@
],
install_requires=[
'distribute',
- 'flask',
+ 'flask<0.10',
'wtforms',
'wtforms-recaptcha',
'babel', |
0e8dce6d960a8dc2b2521160fd543529a17efd2c | projects/relational_memory/pooling_test.py | projects/relational_memory/pooling_test.py | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... | Add ColumnPooler test for debugging | Add ColumnPooler test for debugging
| Python | agpl-3.0 | neuroidss/nupic.research,numenta/htmresearch,neuroidss/nupic.research,numenta/htmresearch,subutai/htmresearch,neuroidss/nupic.research,numenta/htmresearch,subutai/htmresearch,numenta/htmresearch,subutai/htmresearch,neuroidss/nupic.research,numenta/htmresearch,subutai/htmresearch,neuroidss/nupic.research,numenta/htmrese... | ---
+++
@@ -0,0 +1,74 @@
+# ----------------------------------------------------------------------
+# Numenta Platform for Intelligent Computing (NuPIC)
+# Copyright (C) 2018, Numenta, Inc. Unless you have an agreement
+# with Numenta, Inc., for a separate license for this software code, the
+# following terms and c... | |
eb09556cec13f2c80f57c7619d09d85d7fc29f32 | setup.py | setup.py | """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='2.1.1',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='dirg@its.umu.se',
license='Apache 2.0',
url='https://github.com/its-dirg/SATOSA',
packages=find_packages('src/'),
... | """
setup.py
"""
from setuptools import setup, find_packages
setup(
name='SATOSA',
version='2.1.1',
description='Protocol proxy (SAML/OIDC).',
author='DIRG',
author_email='dirg@its.umu.se',
license='Apache 2.0',
url='https://github.com/its-dirg/SATOSA',
packages=find_packages('src/'),
... | Update dependencies to make it installable. | Update dependencies to make it installable.
| Python | apache-2.0 | irtnog/SATOSA,irtnog/SATOSA,SUNET/SATOSA,its-dirg/SATOSA,SUNET/SATOSA | ---
+++
@@ -15,15 +15,15 @@
packages=find_packages('src/'),
package_dir={'': 'src'},
install_requires=[
- "oic==0.8.4.0",
+ "oic>=0.8.4.0",
"pyop==1.0.0",
"pyjwkest==1.1.5",
"pysaml2==4.0.3",
- "requests==2.9.1",
- "PyYAML==3.11",
- "gunicor... |
d4ad071a80bdbbc7e1ecc278800191bdf33f95c2 | problem_1.py | problem_1.py | sum = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
sum += i
#print("i:", i)
print("Result:", sum)
| Solve problem 1 in Python | Solve problem 1 in Python
| Python | mit | sirodoht/project-euler,sirodoht/project-euler,sirodoht/project-euler | ---
+++
@@ -0,0 +1,8 @@
+sum = 0
+
+for i in range(1, 1000):
+ if i % 3 == 0 or i % 5 == 0:
+ sum += i
+ #print("i:", i)
+
+print("Result:", sum) | |
0ebf0ecf1b4591960cd8b56a68eabf71fe85329d | tasks.py | tasks.py | from invocations.docs import docs, www, sites, watch_docs
from invocations.testing import test, coverage, integration, watch_tests
from invocations.packaging import vendorize, release
from invoke import Collection
from invoke.util import LOG_FORMAT
ns = Collection(
test, coverage, integration, vendorize, release... | from invocations.docs import docs, www, sites, watch_docs
from invocations.testing import test, coverage, integration, watch_tests
from invocations.packaging import vendorize, release
from invoke import Collection
from invoke.util import LOG_FORMAT
ns = Collection(
test, coverage, integration, vendorize, release... | Make sure test watcher picks up source code file changes | Make sure test watcher picks up source code file changes
| Python | bsd-2-clause | mkusz/invoke,mkusz/invoke,pyinvoke/invoke,pyinvoke/invoke | ---
+++
@@ -13,6 +13,7 @@
ns.configure({
'tests': {
'logformat': LOG_FORMAT,
+ 'package': 'invoke',
},
'packaging': {
'sign': True, |
319342a34feab6781986efb30aa69b2623460654 | ircstat/config.py | ircstat/config.py | # Copyright 2013 John Reese
# Licensed under the MIT license
import json
from os import path
def read_config(filepath, defaults=None):
"""Read configuration from a given file path, by executing the contents as
python code within a sandboxed set of globals. Default values may be
passed in as a dictionary... | Add module for reading sandboxed python from a file | Add module for reading sandboxed python from a file
| Python | mit | jreese/ircstat,jreese/ircstat | ---
+++
@@ -0,0 +1,32 @@
+# Copyright 2013 John Reese
+# Licensed under the MIT license
+
+import json
+
+from os import path
+
+def read_config(filepath, defaults=None):
+ """Read configuration from a given file path, by executing the contents as
+ python code within a sandboxed set of globals. Default values... | |
351ec5ef16a131d69054d05cef7666890a7d8888 | tests/test_cat2cohort.py | tests/test_cat2cohort.py | """Unit tests for cat2cohort."""
import unittest
from cat2cohort import api_url
class TestCat2Cohort(unittest.TestCase):
"""Test methods from Cat2Cohort."""
pass
| Add unittests module for cat2cohort | Add unittests module for cat2cohort
I want to have unit tests for the methods in cat2cohort.
Add empty module implementing unittest.
| Python | mit | danmichaelo/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,danmichaelo/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics,Commonists/wm_metrics | ---
+++
@@ -0,0 +1,11 @@
+"""Unit tests for cat2cohort."""
+
+import unittest
+from cat2cohort import api_url
+
+
+class TestCat2Cohort(unittest.TestCase):
+
+ """Test methods from Cat2Cohort."""
+
+ pass | |
edc0bf262e449d3b5ff2c9fb602f21536d7ba985 | tests/test_sample_seed.py | tests/test_sample_seed.py | import numpy as np
from SALib.sample import fast_sampler, finite_diff, latin, saltelli
from SALib.sample.morris import sample as morris_sampler
def problem_setup():
N=1
problem = {'num_vars': 3,
'names': ['x1','x2','x3'],
'bounds': [
[0,1],
[0,1],
[0,1]
... | Add tests to ensure seed values result in different samples | Add tests to ensure seed values result in different samples
| Python | mit | jdherman/SALib,jdherman/SALib,SALib/SALib | ---
+++
@@ -0,0 +1,68 @@
+import numpy as np
+
+from SALib.sample import fast_sampler, finite_diff, latin, saltelli
+from SALib.sample.morris import sample as morris_sampler
+
+
+def problem_setup():
+ N=1
+
+ problem = {'num_vars': 3,
+ 'names': ['x1','x2','x3'],
+ 'bounds': [
+ [0,1],... | |
9746e6f16dc0190dfd10c0499eec260a26d0c9f6 | alembic/versions/72a56f6f1148_fix_foreign_key_cascades.py | alembic/versions/72a56f6f1148_fix_foreign_key_cascades.py | revision = '72a56f6f1148'
down_revision = 'be28e555a2da'
branch_labels = None
depends_on = None
import alembic
import sqlalchemy
def upgrade():
# Remove cascading deletes from quote FKs
alembic.op.drop_constraint("quotes_game_id_fkey", "quotes", "foreignkey")
alembic.op.drop_constraint("quotes_show_id_fkey", "quot... | Remove cascading deletes from quote foreign keys | Remove cascading deletes from quote foreign keys
| Python | apache-2.0 | mrphlip/lrrbot,andreasots/lrrbot,andreasots/lrrbot,andreasots/lrrbot,mrphlip/lrrbot,mrphlip/lrrbot | ---
+++
@@ -0,0 +1,24 @@
+revision = '72a56f6f1148'
+down_revision = 'be28e555a2da'
+branch_labels = None
+depends_on = None
+
+import alembic
+import sqlalchemy
+
+def upgrade():
+ # Remove cascading deletes from quote FKs
+ alembic.op.drop_constraint("quotes_game_id_fkey", "quotes", "foreignkey")
+ alembic.op.drop_... | |
cb12e5da17a115ea751df604158992af7c0d6573 | rbtools/utils/console.py | rbtools/utils/console.py | import os
import subprocess
from distutils.util import strtobool
from rbtools.utils.filesystem import make_tempfile
def confirm(question):
"""Interactively prompt for a Yes/No answer.
Accepted values (case-insensitive) depend on distutils.util.strtobool():
'Yes' values: y, yes, t, true, on, 1
'No' v... | import os
import subprocess
from distutils.util import strtobool
from rbtools.utils.filesystem import make_tempfile
def confirm(question):
"""Interactively prompt for a Yes/No answer.
Accepted values (case-insensitive) depend on distutils.util.strtobool():
'Yes' values: y, yes, t, true, on, 1
'No' v... | Clean handling of lack of $EDITOR | Clean handling of lack of $EDITOR
Problem: If EDITOR is not set, and vim is not installed, rbt post exits with
just "CRITICAL: [Errno 2] No such file or directory" as an error message, which
does not indicate where the problem lies nor how to solve it.
vim is not installed by default on many distributions, or is inst... | Python | mit | davidt/rbtools,haosdent/rbtools,halvorlu/rbtools,davidt/rbtools,halvorlu/rbtools,reviewboard/rbtools,datjwu/rbtools,beol/rbtools,reviewboard/rbtools,haosdent/rbtools,datjwu/rbtools,reviewboard/rbtools,beol/rbtools,haosdent/rbtools,datjwu/rbtools,beol/rbtools,halvorlu/rbtools,davidt/rbtools | ---
+++
@@ -24,11 +24,16 @@
"""Allows a user to edit a block of text and returns the saved result.
The environment's default text editor is used if available, otherwise
- vim is used.
+ vi is used.
"""
tempfile = make_tempfile(content.encode('utf8'))
- editor = os.environ.get('EDITOR', ... |
ed8514a2d9f60bad6bea8174ef5263164f9f4857 | test/antTest.py | test/antTest.py | """
Code based on:
https://github.com/mvillalba/python-ant/blob/develop/demos/ant.core/03-basicchannel.py
in the python-ant repository and
https://github.com/tomwardill/developerhealth
by Tom Wardill
"""
import sys
import time
from ant.core import driver, node, event, message, log
from ant.c... | Test file that works 4 me. Adding some info on the doc in a second. | Test file that works 4 me. Adding some info on the doc in a second.
| Python | mit | jtoumey/powerBasedCC | ---
+++
@@ -0,0 +1,71 @@
+"""
+ Code based on:
+ https://github.com/mvillalba/python-ant/blob/develop/demos/ant.core/03-basicchannel.py
+ in the python-ant repository and
+ https://github.com/tomwardill/developerhealth
+ by Tom Wardill
+"""
+import sys
+import time
+from ant.core import driver,... | |
328eef0c145c1efbaedd9453d515955012d1a975 | backend/scripts/projsize.py | backend/scripts/projsize.py | #!/usr/bin/env python
import rethinkdb as r
from optparse import OptionParser
def compute_project_size(project_id, conn):
total = 0
for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table(
'datafiles')).zip().run(conn):
total = total + f... | Add script for computing total project size. | Add script for computing total project size.
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -0,0 +1,29 @@
+#!/usr/bin/env python
+
+import rethinkdb as r
+from optparse import OptionParser
+
+
+def compute_project_size(project_id, conn):
+ total = 0
+ for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table(
+ 'datafiles')).zip()... | |
d3aa2c658ae3ba624b209a1d583fa97137ab2e23 | chaco/tests/text_plot_1d_test_case.py | chaco/tests/text_plot_1d_test_case.py | import unittest
from numpy import alltrue, arange
from enable.compiled_path import CompiledPath
# Chaco imports
from chaco.api import (ArrayDataSource, DataRange1D, LinearMapper,
PlotGraphicsContext)
from chaco.text_plot_1d import TextPlot1D
class TextPlot1DTest(unittest.TestCase):
def s... | Add text plot 1d test case. | Add text plot 1d test case.
| Python | bsd-3-clause | tommy-u/chaco,tommy-u/chaco,tommy-u/chaco | ---
+++
@@ -0,0 +1,41 @@
+import unittest
+
+from numpy import alltrue, arange
+from enable.compiled_path import CompiledPath
+
+# Chaco imports
+from chaco.api import (ArrayDataSource, DataRange1D, LinearMapper,
+ PlotGraphicsContext)
+from chaco.text_plot_1d import TextPlot1D
+
+
+class TextPl... | |
2a579b7df30546e642d87b70417ecf8a1a9590e0 | axelrod/random_.py | axelrod/random_.py | import random
def random_choice(p=0.5):
"""
Return 'C' wit probability `p`, else return 'D'
Emulates Python's random.choice(['C', 'D']) since it is not consistent
across Python 2.7 to Python 3.4"""
r = random.random()
if r < p:
return 'C'
return 'D'
| Add missing file to git | Add missing file to git
| Python | mit | ranjinidas/Axelrod,marcharper/Axelrod,marcharper/Axelrod,ranjinidas/Axelrod | ---
+++
@@ -0,0 +1,13 @@
+import random
+
+def random_choice(p=0.5):
+ """
+ Return 'C' wit probability `p`, else return 'D'
+
+ Emulates Python's random.choice(['C', 'D']) since it is not consistent
+ across Python 2.7 to Python 3.4"""
+
+ r = random.random()
+ if r < p:
+ return 'C'
+ re... | |
ef3dc09af13bcb98667797a649cc9a2ff8af34ae | registrations/migrations/0005_subscriptionrequest_metadata.py | registrations/migrations/0005_subscriptionrequest_metadata.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-03-30 13:57
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('registrations', '0004_auto_20160323_1258'),
]
op... | Add metadata to subscription request for welcome message setting | Add metadata to subscription request for welcome message setting
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration | ---
+++
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.9.1 on 2016-03-30 13:57
+from __future__ import unicode_literals
+
+import django.contrib.postgres.fields.jsonb
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('registrations', '0... | |
c7136b117696b10664a7b6427f5293813bd1d3b0 | Time.py | Time.py | def _DoRough(time, big, bigname, little, littlename):
b = int(time / big / little)
l = int(((time + little / 2) / little) % big)
# print "b =", b, "l =", l, "time =", time, "/", b * big * little + l * little
t = str(b) + " " + bigname
if b > 1:
t += "s"
if l != 0:
t += " " + str(l... | Add rough time so when Felix adds time since last play, he can use this to show it. | Add rough time so when Felix adds time since last play, he can use
this to show it.
| Python | bsd-3-clause | erbridge/NQr,erbridge/NQr,erbridge/NQr | ---
+++
@@ -0,0 +1,35 @@
+def _DoRough(time, big, bigname, little, littlename):
+ b = int(time / big / little)
+ l = int(((time + little / 2) / little) % big)
+# print "b =", b, "l =", l, "time =", time, "/", b * big * little + l * little
+ t = str(b) + " " + bigname
+ if b > 1:
+ t += "s"
+ ... | |
0df2f253dd2f5059b76cfa5527b9705375c9c617 | utils.py | utils.py | import numpy as np
def param_correction(start, params, order):
pos = np.round(start.copy())
oldpos = np.round(start.copy())
pos_not_rounded = np.round(start.copy())
for i in range(len(params)):
param = np.reshape(params[i], [order, len(start)], order='F')
pos += np.sum(np.round(param),... | Create function for parameter correction. | Create function for parameter correction.
| Python | mit | petroolg/robo-spline | ---
+++
@@ -0,0 +1,18 @@
+import numpy as np
+
+
+def param_correction(start, params, order):
+ pos = np.round(start.copy())
+ oldpos = np.round(start.copy())
+ pos_not_rounded = np.round(start.copy())
+ for i in range(len(params)):
+ param = np.reshape(params[i], [order, len(start)], order='F')
+ ... | |
0c1a8445262920bda55f220bb82ab845f50d6585 | tests/providers/__init__.py | tests/providers/__init__.py | # Allow out-of-tree auth submodules.
from pkgutil import extend_path
from inbox.util.misc import register_backends
__path__ = extend_path(__path__, __name__)
module_registry = register_backends(__name__, __path__)
| Add stub for test auth providers | Add stub for test auth providers
| Python | agpl-3.0 | Eagles2F/sync-engine,PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,Eagles2F/sync-engine,nylas/sync-engine,closeio/nylas,EthanBlackburn/sync-engine,closeio/nylas,Eagles2F/sync-engine,EthanBlackburn/sync-engine,Eagles2F/sync-engine,PriviPK/privipk-sync-engine,EthanBla... | ---
+++
@@ -0,0 +1,5 @@
+# Allow out-of-tree auth submodules.
+from pkgutil import extend_path
+from inbox.util.misc import register_backends
+__path__ = extend_path(__path__, __name__)
+module_registry = register_backends(__name__, __path__) | |
125e2e67d71a70e29d36c6538d805bbb50008e46 | gravity_waves/mixedoperators.py | gravity_waves/mixedoperators.py | from __future__ import absolute_import, print_function, division
from firedrake import *
from function_spaces import generate_function_spaces
from vertical_normal import VerticalNormal
class MixedOperator(object):
"""A class describing the operator of the velocity-pressure sub-system
of the mixed (Velocity-... | Add draft of the mixed operator for the gravity wave problem | Add draft of the mixed operator for the gravity wave problem
| Python | mit | thomasgibson/firedrake-hybridization | ---
+++
@@ -0,0 +1,63 @@
+from __future__ import absolute_import, print_function, division
+
+from firedrake import *
+
+from function_spaces import generate_function_spaces
+from vertical_normal import VerticalNormal
+
+
+class MixedOperator(object):
+ """A class describing the operator of the velocity-pressure s... | |
d3da3bdd178de4cbda5b42db11bf17cab73056e5 | python/opencv/opencv_2/read_image.py | python/opencv/opencv_2/read_image.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
"""
OpenCV - Read image: read an image given in arguments
Required: opencv library (Debian: aptitude install python-opencv)
See: https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_ima... | Add a snippet (Python OpenCV). | Add a snippet (Python OpenCV).
| Python | mit | jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets | ---
+++
@@ -0,0 +1,43 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
+
+"""
+OpenCV - Read image: read an image given in arguments
+
+Required: opencv library (Debian: aptitude install python-opencv)
+
+See: https://opencv-python-tutroals.readthedocs.or... | |
fcbed0346d9f5abd1c4e2f6b98f28818a73d9ec5 | users/migrations/0010_add_fields_to_users_applications.py | users/migrations/0010_add_fields_to_users_applications.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-06-08 10:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('users', '0009_add_ad_groups'),
]
operations = [
... | Add missing migration to users | Add missing migration to users
| Python | mit | mikkokeskinen/tunnistamo,mikkokeskinen/tunnistamo | ---
+++
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.2 on 2017-06-08 10:36
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+import django.utils.timezone
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('users', '0009_add_ad_gro... | |
23be51d959763235df8ab44b7dc90047c33002c3 | tests/test_game_parser.py | tests/test_game_parser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import requests
from lxml import html
from parsers.game_parser import GameParser
def test_2013_centre_bell():
url = "http://www.nhl.com/scores/htmlreports/20132014/ES020001.HTM"
game_id = str(os.path.splitext(os.path.basename(url))[0][2:])
gp = ... | Add initial version of game parser test script | Add initial version of game parser test script
| Python | mit | leaffan/pynhldb | ---
+++
@@ -0,0 +1,26 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import os
+import requests
+from lxml import html
+
+from parsers.game_parser import GameParser
+
+
+def test_2013_centre_bell():
+
+ url = "http://www.nhl.com/scores/htmlreports/20132014/ES020001.HTM"
+
+ game_id = str(os.path.splitext... | |
0267f8a61e067c7b1a92cb307de36c477f79b455 | snippets/feature_generation.py | snippets/feature_generation.py | from sklearn.preprocessing import PolynomialFeatures
from sklearn.decomposition import PCA
import numpy as np
X = np.arange(9).reshape(3, 3)
print X
poly = PolynomialFeatures(2)
print poly.fit_transform(X)
poly = PolynomialFeatures(interaction_only=True)
print poly.fit_transform(X)
pca = PCA(n_components=1)
print ... | Add snippet with code to generate new features | Add snippet with code to generate new features
| Python | mit | davidgasquez/kaggle-airbnb | ---
+++
@@ -0,0 +1,16 @@
+from sklearn.preprocessing import PolynomialFeatures
+from sklearn.decomposition import PCA
+import numpy as np
+
+X = np.arange(9).reshape(3, 3)
+print X
+
+poly = PolynomialFeatures(2)
+print poly.fit_transform(X)
+
+poly = PolynomialFeatures(interaction_only=True)
+print poly.fit_transfor... | |
e308575d9723c90d3a15e5e8de45b0232c5d0b75 | parse_ast.py | parse_ast.py | """Parse python code into the abstract syntax tree and represent as JSON"""
from __future__ import print_function
import ast
from itertools import chain, count
import json
import sys
def dictify(obj):
if hasattr(obj, "__dict__"):
result = {k: dictify(v) for k, v in chain(obj.__dict__.items(), [("classname... | Add basic ast to json converter | Add basic ast to json converter
| Python | mit | RishiRamraj/wensleydale | ---
+++
@@ -0,0 +1,36 @@
+"""Parse python code into the abstract syntax tree and represent as JSON"""
+from __future__ import print_function
+import ast
+from itertools import chain, count
+import json
+import sys
+
+
+def dictify(obj):
+ if hasattr(obj, "__dict__"):
+ result = {k: dictify(v) for k, v in ch... | |
ef901f36d8eb8a3da1c747e64a79bd2fbad4878d | dev/clean_parse_tables.py | dev/clean_parse_tables.py | #!/usr/bin/env python
"""
A utility to fix PLY-generated lex and yacc tables to be Python 2 and
3 compatible.
"""
import os
for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), '..')):
for fname in files:
if not (fname.endswith('lextab.py') or fname.endswith('parsetab.py')):
... | Add tool to fix up parsing tables | Add tool to fix up parsing tables
| Python | bsd-3-clause | lpsinger/astropy,funbaker/astropy,tbabej/astropy,larrybradley/astropy,DougBurke/astropy,mhvk/astropy,DougBurke/astropy,larrybradley/astropy,MSeifert04/astropy,MSeifert04/astropy,AustereCuriosity/astropy,kelle/astropy,mhvk/astropy,mhvk/astropy,StuartLittlefair/astropy,AustereCuriosity/astropy,StuartLittlefair/astropy,ke... | ---
+++
@@ -0,0 +1,27 @@
+#!/usr/bin/env python
+
+"""
+A utility to fix PLY-generated lex and yacc tables to be Python 2 and
+3 compatible.
+"""
+
+import os
+
+for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__), '..')):
+ for fname in files:
+ if not (fname.endswith('lextab.py') or fn... | |
374278b45dd8be76ef897881f61144ae79318827 | utils/test_sims.py | utils/test_sims.py | import unittest
import random
import math
import sims
TRIALS = 1000 # number of trials to run per test case
MAX_DEGREE = 1.5 # max degree of freedom; refer to https://en.wikipedia.org/wiki/Pearson's_chi-squared_test
class TestCoinSim(unittest.TestCase):
def runTest(self):
# bad input
self.assertRaises(Exception... | Add test suite for coin simulation. | Add test suite for coin simulation.
| Python | mit | wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation,wei2912/bce-simulation | ---
+++
@@ -0,0 +1,61 @@
+import unittest
+import random
+import math
+
+import sims
+
+TRIALS = 1000 # number of trials to run per test case
+MAX_DEGREE = 1.5 # max degree of freedom; refer to https://en.wikipedia.org/wiki/Pearson's_chi-squared_test
+
+class TestCoinSim(unittest.TestCase):
+ def runTest(self):
+ # ... | |
4afb6229c89237079966ab91bb4d2372818a7f44 | greedy/fractional_knapsack/python/fractional_knapsack.py | greedy/fractional_knapsack/python/fractional_knapsack.py | def FractionalKnapsack(capacity, values, weights):
rel_value = [val / weight for val, weight in zip(values, weights)]
sorted_items = [i for _,i in sorted(zip(rel_value, range(len(rel_value))))]
carry_items = []
while capacity > 0 and len(sorted_items) > 0:
item = sorted_items.pop(0)
weig... | Add fractional knapsack greedy algorithm | Add fractional knapsack greedy algorithm
Implemented in Python
| Python | cc0-1.0 | ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovs... | ---
+++
@@ -0,0 +1,18 @@
+def FractionalKnapsack(capacity, values, weights):
+ rel_value = [val / weight for val, weight in zip(values, weights)]
+ sorted_items = [i for _,i in sorted(zip(rel_value, range(len(rel_value))))]
+ carry_items = []
+ while capacity > 0 and len(sorted_items) > 0:
+ item =... | |
7617826e2b9a01e9a377d6fa2c8f64768a184704 | nodeconductor/structure/tests/unittests/test_serializer.py | nodeconductor/structure/tests/unittests/test_serializer.py | from urlparse import urlparse
from django.contrib.auth import get_user_model
from django.core.urlresolvers import resolve
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from .. import factories as structure_factories
from ...serializers import BasicUserSerializer
User = get_user_m... | Add UUID serialization test case (NC-1214) | Add UUID serialization test case (NC-1214)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -0,0 +1,30 @@
+from urlparse import urlparse
+
+from django.contrib.auth import get_user_model
+from django.core.urlresolvers import resolve
+from django.test import TestCase
+
+from rest_framework.test import APIRequestFactory
+from .. import factories as structure_factories
+from ...serializers import Ba... | |
4afbd87d3d6d0c4953f4c41b3c37abf1fc3be0f1 | acapi/tests/test_database.py | acapi/tests/test_database.py | """ Tests the database class. """
import requests_mock
from . import BaseTest
from ..resources import Database, BackupList
@requests_mock.Mocker()
class TestDatabase(BaseTest):
"""Tests the Acquia Cloud API db class."""
def test_backups(self, mocker):
""" Test create call. """
json = [
... | Add test coverage for database resource | Add test coverage for database resource
| Python | mit | skwashd/python-acquia-cloud | ---
+++
@@ -0,0 +1,53 @@
+""" Tests the database class. """
+import requests_mock
+
+from . import BaseTest
+from ..resources import Database, BackupList
+
+@requests_mock.Mocker()
+class TestDatabase(BaseTest):
+ """Tests the Acquia Cloud API db class."""
+
+ def test_backups(self, mocker):
+ """ Test c... | |
3a0efca1a48563a50e634eeb3401b43b7e6b2da7 | ash/PRESUBMIT.py | ash/PRESUBMIT.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for ash.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into... | Enable presubmit warning for "git cl format" | Enable presubmit warning for "git cl format"
BUG=None
Review URL: https://codereview.chromium.org/835683004
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#311332}
| Python | bsd-3-clause | PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Fireble... | ---
+++
@@ -0,0 +1,14 @@
+# Copyright 2015 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Presubmit script for ash.
+
+See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
+for more details... | |
8fe69746a631054387019662d7aea37879909da7 | src/Mapping.py | src/Mapping.py | import enum
import logging
import json
import cv2
import os
from pynput import keyboard
from src import screen, helper
logger = logging.getLogger(__name__)
class Mapper():
def __init__(self):
self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin-emu', 'ScreenShots')
self.file_na... | Add rough state mapping class | Add rough state mapping class
| Python | mit | ENPH-479/dolphin-env-api,ENPH-479/dolphin-env-api,ENPH-479/dolphin-env-api,ENPH-479/dolphin-env-api | ---
+++
@@ -0,0 +1,66 @@
+import enum
+import logging
+import json
+import cv2
+import os
+from pynput import keyboard
+
+from src import screen, helper
+
+logger = logging.getLogger(__name__)
+
+
+class Mapper():
+ def __init__(self):
+ self.screenshot_dir = os.path.join(helper.get_home_folder(), '.dolphin... | |
e54785f1a7aa8aff1d652d3caef36f8aa04cd91f | tests/unit_tests/test_urr_capture.py | tests/unit_tests/test_urr_capture.py | import openmc
import pytest
@pytest.fixture
def th232_model():
# URR boundaries for Th232
e_min, e_max = 4000.0, 100000.0
model = openmc.model.Model()
th232 = openmc.Material()
th232.add_nuclide('Th232', 1.0)
surf = openmc.Sphere(r=100.0, boundary_type='reflective')
cell = openmc.Cell(fi... | Add (currently failing) test with URR (n,gamma) reaction rate check | Add (currently failing) test with URR (n,gamma) reaction rate check
| Python | mit | amandalund/openmc,amandalund/openmc,walshjon/openmc,amandalund/openmc,walshjon/openmc,walshjon/openmc,shikhar413/openmc,amandalund/openmc,shikhar413/openmc,shikhar413/openmc,shikhar413/openmc,walshjon/openmc | ---
+++
@@ -0,0 +1,42 @@
+import openmc
+import pytest
+
+
+@pytest.fixture
+def th232_model():
+ # URR boundaries for Th232
+ e_min, e_max = 4000.0, 100000.0
+
+ model = openmc.model.Model()
+ th232 = openmc.Material()
+ th232.add_nuclide('Th232', 1.0)
+
+ surf = openmc.Sphere(r=100.0, boundary_typ... | |
da4151a0e83e6738361b23edb2fda3ee0e386391 | localflavor/br/models.py | localflavor/br/models.py | from django.utils.translation import ugettext_lazy as _
from django.db.models.fields import CharField
from .br_states import STATE_CHOICES
class BRStateField(CharField):
"""
A model field for states of Brazil
"""
description = _("BR. state (two uppercase letters)")
def __init__(self, *args, **kw... | Add a model field for states of Brazil | Add a model field for states of Brazil
| Python | bsd-3-clause | zarelit/django-localflavor,rsalmaso/django-localflavor,maisim/django-localflavor,infoxchange/django-localflavor,M157q/django-localflavor,agustin380/django-localflavor,django/django-localflavor,thor/django-localflavor,jieter/django-localflavor | ---
+++
@@ -0,0 +1,16 @@
+from django.utils.translation import ugettext_lazy as _
+from django.db.models.fields import CharField
+
+from .br_states import STATE_CHOICES
+
+
+class BRStateField(CharField):
+ """
+ A model field for states of Brazil
+ """
+ description = _("BR. state (two uppercase letters)... | |
a4cd1c644d7b0636e0debc3a44df9d81a6fa7ce7 | app/main/views/register.py | app/main/views/register.py | from datetime import datetime
from flask import render_template, redirect, jsonify
from app.main import main
from app.main.dao import users_dao
from app.main.forms import RegisterUserForm
from app.models import User
@main.route("/register", methods=['GET'])
def render_register():
return render_template('registe... | from datetime import datetime
from flask import render_template, redirect, jsonify
from app.main import main
from app.main.dao import users_dao
from app.main.forms import RegisterUserForm
from app.models import User
@main.route("/register", methods=['GET'])
def render_register():
return render_template('registe... | Change to a generic message for database errors. | 108536374: Change to a generic message for database errors.
Need a story to handle db exceptions in the dao layer
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin | ---
+++
@@ -28,6 +28,6 @@
users_dao.insert_user(user)
return redirect('/two-factor')
except Exception as e:
- return jsonify(database_error=e.message), 400
+ return jsonify(database_error='encountered database error'), 400
else:
return jsonify(for... |
045e8b0dabd265e2f8cf0cbf26a5d912345a4533 | h2o-py/tests/testdir_parser/pyunit_PUBDEV_5705_drop_columns_parser_svmlight_large.py | h2o-py/tests/testdir_parser/pyunit_PUBDEV_5705_drop_columns_parser_svmlight_large.py | from __future__ import print_function
import sys
sys.path.insert(1, "../../")
import h2o
from tests import pyunit_utils
import os
def test_parser_svmlight_column_skip():
# generate a big frame
nrow = 10000
ncol = 10
seed = 12345
original_frame = h2o.create_frame(rows=nrow, cols=ncol, real_fractio... | Fix svm drop columns test - add test that missing skipped_columns or skipped_columns = [] should work correctly and give the same frame as original one | Fix svm drop columns test - add test that missing skipped_columns or skipped_columns = [] should work correctly and give the same frame as original one
| Python | apache-2.0 | h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3 | ---
+++
@@ -0,0 +1,48 @@
+from __future__ import print_function
+import sys
+
+sys.path.insert(1, "../../")
+import h2o
+from tests import pyunit_utils
+import os
+
+
+def test_parser_svmlight_column_skip():
+ # generate a big frame
+ nrow = 10000
+ ncol = 10
+ seed = 12345
+ original_frame = h2o.creat... | |
32f4c67cda624f1840b1ab92d1d1afc826f13dd5 | examples/plot_gmm_pdf.py | examples/plot_gmm_pdf.py | """
=================================
Gaussian Mixture Model Ellipsoids
=================================
Plot the confidence ellipsoids of a mixture of two gaussians.
"""
import numpy as np
from scikits.learn import gmm
import itertools
import pylab as pl
import matplotlib as mpl
import matplotlib.pyplot as plt
n... | Add an example with probability distribution estimates using GMM. | Add an example with probability distribution estimates using GMM.
This is a work in progress. Also, the .eval() function from GMM
might very likely change it's return type in the future.
| Python | bsd-3-clause | mayblue9/scikit-learn,qifeigit/scikit-learn,rrohan/scikit-learn,shusenl/scikit-learn,jseabold/scikit-learn,huobaowangxi/scikit-learn,frank-tancf/scikit-learn,shangwuhencc/scikit-learn,Srisai85/scikit-learn,RPGOne/scikit-learn,appapantula/scikit-learn,raghavrv/scikit-learn,hdmetor/scikit-learn,yask123/scikit-learn,xyguo... | ---
+++
@@ -0,0 +1,42 @@
+"""
+=================================
+Gaussian Mixture Model Ellipsoids
+=================================
+
+Plot the confidence ellipsoids of a mixture of two gaussians.
+"""
+
+import numpy as np
+from scikits.learn import gmm
+import itertools
+
+import pylab as pl
+import matplotlib a... | |
a3a8ba38c05741418c1a29e53a2079482b454453 | check_numbers.py | check_numbers.py | # -*- coding: utf-8 -*-
import feedparser
url = "https://edit.yournextmp.com/results/all.atom"
feed = feedparser.parse(url)
entries = {x['post_id']: x for x in feed.entries}.values()
results = {}
for x in entries:
if x['winner_party_name'] not in results:
results[x['winner_party_name']] = 0
results[x... | Add handy number checker script | Add handy number checker script
| Python | mit | andylolz/ge2015-results-bot | ---
+++
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+import feedparser
+
+url = "https://edit.yournextmp.com/results/all.atom"
+feed = feedparser.parse(url)
+
+entries = {x['post_id']: x for x in feed.entries}.values()
+
+results = {}
+for x in entries:
+ if x['winner_party_name'] not in results:
+ results[x[... | |
a8b92ad8318f86877986de8bfc9911e8363d2d2e | lib/FriendlyName.py | lib/FriendlyName.py | try:
import logging
except ImportError as err:
print("Error import module: " + str(err))
exit(128)
def FriendlyName(input_format):
# This function returns with friendly name of selected input format
if input_format == 'las':
return 'LAS PointCloud'
elif input_format == 'laz':
r... | Use function for input_format friendly names | Use function for input_format friendly names
Refactoring TransformerWorkflow to use newly created FriendlyName that returns a human readable names of specific input formats.
| Python | mpl-2.0 | KAMI911/lactransformer | ---
+++
@@ -0,0 +1,21 @@
+try:
+ import logging
+except ImportError as err:
+ print("Error import module: " + str(err))
+ exit(128)
+
+
+def FriendlyName(input_format):
+ # This function returns with friendly name of selected input format
+ if input_format == 'las':
+ return 'LAS PointCloud'
+ ... | |
b1bb4154a69a6ae4bb31cbf27f0871069291e1d6 | nist_beacon_constants.py | nist_beacon_constants.py | NIST_KEY_FREQUENCY = 'frequency'
NIST_KEY_OUTPUT_VALUE = 'outputValue'
NIST_KEY_PREVIOUS_OUTPUT_VALUE = 'previousOutputValue'
NIST_KEY_SEED_VALUE = 'seedValue'
NIST_KEY_SIGNATURE_VALUE = 'signatureValue'
NIST_KEY_STATUS_CODE = 'statusCode'
NIST_KEY_TIMESTAMP = 'timeStamp'
NIST_KEY_VERSION = 'version'
| Prepare constants into seperate location | Prepare constants into seperate location
| Python | apache-2.0 | urda/nistbeacon | ---
+++
@@ -0,0 +1,8 @@
+NIST_KEY_FREQUENCY = 'frequency'
+NIST_KEY_OUTPUT_VALUE = 'outputValue'
+NIST_KEY_PREVIOUS_OUTPUT_VALUE = 'previousOutputValue'
+NIST_KEY_SEED_VALUE = 'seedValue'
+NIST_KEY_SIGNATURE_VALUE = 'signatureValue'
+NIST_KEY_STATUS_CODE = 'statusCode'
+NIST_KEY_TIMESTAMP = 'timeStamp'
+NIST_KEY_VERS... | |
dc2def7ab47c93ed9c92c5535609ebbb375dff56 | src/draw_json_graph.py | src/draw_json_graph.py | import json
import networkx as nx
from networkx.readwrite import json_graph
with open("/query_results.json") as f:
json_data = f.read()
x = json.loads(json_data)
doc_graphs = list()
for corpus_name, data in x.iteritems():
for query, results in data["queries"].iteritems():
new_graph = nx.Graph()
... | Add skeleton script to draw similarites between objects | Add skeleton script to draw similarites between objects
| Python | mit | PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project | ---
+++
@@ -0,0 +1,31 @@
+import json
+import networkx as nx
+from networkx.readwrite import json_graph
+
+with open("/query_results.json") as f:
+ json_data = f.read()
+x = json.loads(json_data)
+doc_graphs = list()
+
+for corpus_name, data in x.iteritems():
+ for query, results in data["queries"].iteritems():... | |
4462b32aaa88628bc7c9f6746829c627bf79ddd2 | django_project/realtime/tasks/test/test_realtime_tasks.py | django_project/realtime/tasks/test/test_realtime_tasks.py | # coding=utf-8
"""Docstring here."""
import unittest
from django import test
from realtime.tasks.realtime.flood import process_flood
from realtime.tasks.flood import create_flood_report
from realtime.tasks.realtime.celery_app import app as realtime_app
@unittest.skipUnless(
realtime_app.control.ping(), 'Realtime... | Add unit test for process flood. | Add unit test for process flood.
| Python | bsd-2-clause | AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django | ---
+++
@@ -0,0 +1,24 @@
+# coding=utf-8
+"""Docstring here."""
+import unittest
+from django import test
+
+from realtime.tasks.realtime.flood import process_flood
+from realtime.tasks.flood import create_flood_report
+from realtime.tasks.realtime.celery_app import app as realtime_app
+
+
+@unittest.skipUnless(
+ ... | |
74ceceb6ccdb3b205a72aa6ca75b833c66eb659c | HearthStone2/copy_data.py | HearthStone2/copy_data.py | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Copy data from the given zip file to the project."""
import argparse
import fnmatch
import os
import time
import zipfile
__author__ = 'fyabc'
DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
DataFilePattern = '*/resources/*'
def main... | Add a script to copy data files conveniently. | Add a script to copy data files conveniently.
| Python | mit | fyabc/MiniGames | ---
+++
@@ -0,0 +1,38 @@
+#! /usr/bin/python
+# -*- coding: utf-8 -*-
+
+"""Copy data from the given zip file to the project."""
+
+import argparse
+import fnmatch
+import os
+import time
+import zipfile
+
+__author__ = 'fyabc'
+
+DataDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'MyHearthStone')
+Da... | |
7775d27af722031fc696693415d9f38d7f5409e2 | drivers/test_logger.py | drivers/test_logger.py | from __future__ import print_function
import time
from might_driver import MightyWattDriver
from buck_driver import FCCBuckDriver
discharger = FCCMPPTDriver()
discharger.open_serial('SNR=8543035353135160A201')
print(discharger.dev_id)
load = MightyWattDriver()
load.open_serial('SNR=854303535313513041E2')
print(load.... | Add a test Python script | Add a test Python script
| Python | bsd-2-clause | fnoorian/Free-buck-boost,fnoorian/Free-buck-boost,fnoorian/Free-buck-boost | ---
+++
@@ -0,0 +1,45 @@
+from __future__ import print_function
+import time
+
+from might_driver import MightyWattDriver
+from buck_driver import FCCBuckDriver
+
+discharger = FCCMPPTDriver()
+discharger.open_serial('SNR=8543035353135160A201')
+print(discharger.dev_id)
+
+load = MightyWattDriver()
+load.open_serial(... | |
da50bb53f05e487a00b3db2feb97ce37cf449afd | tests/squid.py | tests/squid.py | """
Squid Proxy Detector
********************
"""
import os
import httplib
import urllib2
from urlparse import urlparse
from plugoo import gen_headers
from plugoo.assets import Asset
from plugoo.tests import Test
__plugoo__ = "SquidProxy"
__desc__ = "This Test aims at detecting the squid transparent proxy"
... | Add some scaffolding for Squid Proxy detection test | Add some scaffolding for Squid Proxy detection test
| Python | bsd-2-clause | juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-probe,h... | ---
+++
@@ -0,0 +1,113 @@
+"""
+ Squid Proxy Detector
+ ********************
+
+"""
+import os
+import httplib
+import urllib2
+from urlparse import urlparse
+
+from plugoo import gen_headers
+from plugoo.assets import Asset
+from plugoo.tests import Test
+
+__plugoo__ = "SquidProxy"
+__desc__ = "This Test aims... | |
6e6f4b2ae0f085a649c1c4c3ebfe9c4aa6be37b1 | libnamebench/config_test.py | libnamebench/config_test.py | #!/usr/bin/env python
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | Add some tests for dns config parsing | Add some tests for dns config parsing
| Python | apache-2.0 | catap/namebench,jimmsta/namebench-1 | ---
+++
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+# Copyright 2009 Google 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/licen... | |
7284fac63bd5100700319ba655f5a2c335193a1b | ooni/tests/test_errors.py | ooni/tests/test_errors.py | from twisted.trial import unittest
import ooni.errors
class TestErrors(unittest.TestCase):
def test_catch_child_failures_before_parent_failures(self):
"""
Verify that more specific Failures are caught first by
handleAllFailures() and failureToString().
Fails if a subclass is list... | Test that specific Failures are caught before parent Failures | Test that specific Failures are caught before parent Failures
| Python | bsd-2-clause | 0xPoly/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe,0xPoly/ooni-probe | ---
+++
@@ -0,0 +1,20 @@
+from twisted.trial import unittest
+
+import ooni.errors
+
+class TestErrors(unittest.TestCase):
+
+ def test_catch_child_failures_before_parent_failures(self):
+ """
+ Verify that more specific Failures are caught first by
+ handleAllFailures() and failureToString().... | |
f0e4228d648617e374fb4848f980d72684e913c7 | openpnm/solvers/_scipy.py | openpnm/solvers/_scipy.py | import numpy as np
from scipy.integrate import solve_ivp
from scipy.interpolate import interp1d
from scipy.sparse import csr_matrix, csc_matrix
from scipy.sparse.linalg import spsolve
from openpnm.solvers import DirectSolver, Integrator
class ScipySpsolve(DirectSolver):
def solve(self, A, b, **kwargs):
i... | Add a basic integrator + solution class | Add a basic integrator + solution class
| Python | mit | PMEAL/OpenPNM | ---
+++
@@ -0,0 +1,56 @@
+import numpy as np
+from scipy.integrate import solve_ivp
+from scipy.interpolate import interp1d
+from scipy.sparse import csr_matrix, csc_matrix
+from scipy.sparse.linalg import spsolve
+from openpnm.solvers import DirectSolver, Integrator
+
+
+class ScipySpsolve(DirectSolver):
+
+ def ... | |
34080178f92de8e74138d2e8c361b877c55b6150 | redshirt/analyze.py | redshirt/analyze.py | import numpy as np
from scipy import ndimage as ndi
from skimage.filters import threshold_otsu
def _extract_roi(image, axis=-1):
max_frame = np.max(image, axis=axis)
initial_mask = max_frame > threshold_otsu(max_frame)
regions = ndi.label(initial_mask)[0]
region_sizes = np.bincount(np.ravel(regions))
... | Add early analysis script for traces | Add early analysis script for traces
| Python | mit | jni/python-redshirt | ---
+++
@@ -0,0 +1,34 @@
+import numpy as np
+from scipy import ndimage as ndi
+from skimage.filters import threshold_otsu
+
+
+def _extract_roi(image, axis=-1):
+ max_frame = np.max(image, axis=axis)
+ initial_mask = max_frame > threshold_otsu(max_frame)
+ regions = ndi.label(initial_mask)[0]
+ region_si... | |
0ed11ea6b92741a0ed232a93f1876204e14b0c53 | datapipe/classifiers/__init__.py | datapipe/classifiers/__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
# This script is provided under the terms and conditions of the MIT license:
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (th... | Add an empty package (classifiers). | Add an empty package (classifiers).
| Python | mit | jdhp-sap/data-pipeline-standalone-scripts,jdhp-sap/sap-cta-data-pipeline,jdhp-sap/sap-cta-data-pipeline,jdhp-sap/data-pipeline-standalone-scripts | ---
+++
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2016 Jérémie DECOCK (http://www.jdhp.org)
+
+# This script is provided under the terms and conditions of the MIT license:
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and... | |
4307ae93af2ee440570d2f642e62aa0a3baeecde | cumulusci/robotframework/locators_47.py | cumulusci/robotframework/locators_47.py | from cumulusci.robotframework import locators_46
lex_locators = locators_46.lex_locators.copy()
# At the moment, there are no changes to the locators.
| Add locator file for winter '20. Without this file, Salesforce.py will throw an error when it's imported while testing Winter '20. | Add locator file for winter '20.
Without this file, Salesforce.py will throw an error when it's imported
while testing Winter '20.
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI | ---
+++
@@ -0,0 +1,5 @@
+from cumulusci.robotframework import locators_46
+
+lex_locators = locators_46.lex_locators.copy()
+
+# At the moment, there are no changes to the locators. | |
a83048076db03923f0b3eff1e9d77f3b4b259c34 | tests/test_commands.py | tests/test_commands.py | """Tests for the management commands"""
from __future__ import absolute_import
from django.conf import settings
from django.core import management
from importlib import import_module
from django_cas_ng.models import SessionTicket, ProxyGrantingTicket
import pytest
SessionStore = import_module(settings.SESSION_ENGINE... | Add the management commands unit tests. | Add the management commands unit tests.
| Python | mit | mingchen/django-cas-ng,nitmir/django-cas-ng,pbaehr/django-cas-ng,bgroff/django-cas-ng | ---
+++
@@ -0,0 +1,52 @@
+"""Tests for the management commands"""
+from __future__ import absolute_import
+from django.conf import settings
+from django.core import management
+from importlib import import_module
+
+from django_cas_ng.models import SessionTicket, ProxyGrantingTicket
+
+import pytest
+
+SessionStore =... | |
9e900eb16e92027cfe990a07c5703a6adbb41a09 | drivers/python/wappalyzer.py | drivers/python/wappalyzer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import PyV8
import urllib
from urlparse import urlparse
try:
import json
except ImportError:
import simplejson as json
class Wappalyzer(object):
def __init__(self, url):
self.file_dir = os.path.dirname(__file__)
f = ope... | Add python driver (depend on PyV8) | Add python driver (depend on PyV8)
| Python | mit | WPO-Foundation/Wappalyzer,WPO-Foundation/Wappalyzer,WPO-Foundation/Wappalyzer,AliasIO/wappalyzer,AliasIO/wappalyzer | ---
+++
@@ -0,0 +1,53 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import os
+import sys
+import PyV8
+import urllib
+from urlparse import urlparse
+
+try:
+ import json
+except ImportError:
+ import simplejson as json
+
+
+class Wappalyzer(object):
+
+ def __init__(self, url):
+ self.file_di... | |
4a360a4d678d561bb74e37f857cfd09d35747db7 | core/migrations/0002_profile_image.py | core/migrations/0002_profile_image.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_profile'),
]
operations = [
migrations.AddField(
model_name='profile',
name='image',
... | Add the migration for the image field | Add the migration for the image field
| Python | mit | mauricioabreu/speakerfight,luanfonceca/speakerfight,luanfonceca/speakerfight,luanfonceca/speakerfight,mauricioabreu/speakerfight,mauricioabreu/speakerfight | ---
+++
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('core', '0001_profile'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_na... | |
2901763a10aa318112efecc2b5a56d83391f4de5 | pipelines/genome_scanner.py | pipelines/genome_scanner.py | """
Copyright [2009-2018] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | Add simple scanner pipeline to help with job submission | Add simple scanner pipeline to help with job submission
| Python | apache-2.0 | Rfam/rfam-production,Rfam/rfam-production,Rfam/rfam-production | ---
+++
@@ -0,0 +1,89 @@
+"""
+Copyright [2009-2018] EMBL-European Bioinformatics Institute
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+ http://www.apache.org/licenses/LICENSE-2.0
+Unle... | |
0a3431a597cb0ff000431dcc79ceeeec3048a3c1 | migrations/versions/953c5e0cebad_fix_the_type_of_the_updated_at_column_.py | migrations/versions/953c5e0cebad_fix_the_type_of_the_updated_at_column_.py | """fix the type of the updated_at column for shelters
Revision ID: 953c5e0cebad
Revises: 9bfedc780ac5
Create Date: 2016-06-17 09:00:35.875583
"""
# revision identifiers, used by Alembic.
revision = '953c5e0cebad'
down_revision = '9bfedc780ac5'
branch_labels = None
depends_on = None
from alembic import op
import sql... | Add alembic script to fix the type of the column updated_at of shelters | Add alembic script to fix the type of the column updated_at of shelters
| Python | mit | cedricbonhomme/shelter-database,cedricbonhomme/shelter-database,cedricbonhomme/shelter-database,cedricbonhomme/shelter-database | ---
+++
@@ -0,0 +1,28 @@
+"""fix the type of the updated_at column for shelters
+
+Revision ID: 953c5e0cebad
+Revises: 9bfedc780ac5
+Create Date: 2016-06-17 09:00:35.875583
+
+"""
+
+# revision identifiers, used by Alembic.
+revision = '953c5e0cebad'
+down_revision = '9bfedc780ac5'
+branch_labels = None
+depends_on =... | |
4a18d55f6d4785bc5e3f38b95ade854d5412b0df | fib-seq-recur.py | fib-seq-recur.py | # Implement fibonacci sequence function using recursion
def get_fib(position):
if position < 2: # base case
return position
else:
return get_fib(position-1) + get_fib(position-2) # add two previous numbers
| Add function for python implementation of fibonacci sequence | Add function for python implementation of fibonacci sequence
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep | ---
+++
@@ -0,0 +1,7 @@
+# Implement fibonacci sequence function using recursion
+
+def get_fib(position):
+ if position < 2: # base case
+ return position
+ else:
+ return get_fib(position-1) + get_fib(position-2) # add two previous numbers | |
94855b850f9ad71375ce0792a7b94f0d0662b9c0 | examples/with-descartes.py | examples/with-descartes.py |
import logging
import sys
from matplotlib import pyplot
from descartes import PolygonPatch
from fiona import collection
BLUE = '#6699cc'
fig = pyplot.figure(1, figsize=(6, 6), dpi=90)
ax = fig.add_subplot(111)
input = collection("docs/data/test_uk.shp", "r")
for f in input:
patch = PolygonPatch(f['geometry'],... | Add an example of interop with descartes and matplotlib | Add an example of interop with descartes and matplotlib
| Python | bsd-3-clause | Toblerity/Fiona,rbuffat/Fiona,sgillies/Fiona,Toblerity/Fiona,johanvdw/Fiona,perrygeo/Fiona,rbuffat/Fiona,perrygeo/Fiona | ---
+++
@@ -0,0 +1,25 @@
+
+import logging
+import sys
+
+from matplotlib import pyplot
+from descartes import PolygonPatch
+
+from fiona import collection
+
+
+BLUE = '#6699cc'
+fig = pyplot.figure(1, figsize=(6, 6), dpi=90)
+ax = fig.add_subplot(111)
+
+input = collection("docs/data/test_uk.shp", "r")
+for f in inp... | |
b670f82fa6cd9781b325a7906238e4beee0975ab | examples/cortesi-config.py | examples/cortesi-config.py | import libqtile
keys = [
libqtile.Key(
["mod1"], "k",
libqtile.command.Call("max_next").when(layout="max"),
libqtile.command.Call("stack_down").when(layout="stack"),
),
libqtile.Key(
["mod1"], "j",
libqtile.command.Call("max_previous").when(layout="max"),
lib... | Add my configuration file as an example. | Add my configuration file as an example.
| Python | mit | kseistrup/qtile,kynikos/qtile,nxnfufunezn/qtile,kseistrup/qtile,jdowner/qtile,kynikos/qtile,jdowner/qtile,himaaaatti/qtile,StephenBarnes/qtile,qtile/qtile,soulchainer/qtile,tych0/qtile,cortesi/qtile,bavardage/qtile,dequis/qtile,xplv/qtile,aniruddhkanojia/qtile,farebord/qtile,kopchik/qtile,kopchik/qtile,xplv/qtile,andre... | ---
+++
@@ -0,0 +1,78 @@
+import libqtile
+
+keys = [
+ libqtile.Key(
+ ["mod1"], "k",
+ libqtile.command.Call("max_next").when(layout="max"),
+ libqtile.command.Call("stack_down").when(layout="stack"),
+ ),
+ libqtile.Key(
+ ["mod1"], "j",
+ libqtile.command.Call("max_prev... | |
49fbd4c43465888d706d336c78f187c3849539e4 | hiora_cartpole/fourier_fa.py | hiora_cartpole/fourier_fa.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools
import numpy as np
def make_feature_vec(state_ranges, order):
"""
Arguments:
state_ranges – (2, n_dims) minima and maxima of possible state values
n_acts – int, number of actions that can happen
order –... | Add untested Fourier linear function approximator | Add untested Fourier linear function approximator
| Python | mit | rmoehn/cartpole | ---
+++
@@ -0,0 +1,54 @@
+# -*- coding: utf-8 -*-
+
+from __future__ import unicode_literals
+
+import itertools
+
+import numpy as np
+
+def make_feature_vec(state_ranges, order):
+ """
+
+ Arguments:
+ state_ranges – (2, n_dims) minima and maxima of possible state values
+ n_acts – int, number o... | |
5fc353fed4c839a050ef986a39fbc63d5464f492 | scripts/tmp/rewrite.py | scripts/tmp/rewrite.py | import json
import os
import re
def is_enum(pattern):
return pattern[0] == '^' and pattern[-1] == '$' and '[' not in pattern
def unpack_enum(pattern):
if '(' not in pattern:
return [pattern[1:-1]]
add_empty = False
if pattern[-2] == '?':
pattern = pattern[:-1]
add_empty = Tru... | Add script to convert regex to enum in schemas | Add script to convert regex to enum in schemas
This script is just to record how regular expression patterns describing
choices were converted into enums in the json schemas.
| Python | mit | RichardKnop/digitalmarketplace-api,mtekel/digitalmarketplace-api,mtekel/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,mtekel/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,alphagov/digitalmarketplace-api,RichardKnop/digitalmarketplac... | ---
+++
@@ -0,0 +1,67 @@
+import json
+import os
+import re
+
+
+def is_enum(pattern):
+ return pattern[0] == '^' and pattern[-1] == '$' and '[' not in pattern
+
+
+def unpack_enum(pattern):
+ if '(' not in pattern:
+ return [pattern[1:-1]]
+ add_empty = False
+ if pattern[-2] == '?':
+ patt... | |
1beb325fb2bf61689db6fc20ccb829285165227d | helper/git_clean_keep_ide_settings.py | helper/git_clean_keep_ide_settings.py | import subprocess
# Keep the following directories
# - .vscode (Visual Studio code project settings)
# - .vs (Visual Studio project files)
# - .idea (PyCharm project files)
subprocess.run(["git", "clean", "-dfx", "-e", ".vscode", "-e", ".idea", "-e", ".vs"], check=True)
| Add helper for git clean that keeps the IDE folders | Add helper for git clean that keeps the IDE folders
| Python | apache-2.0 | MSeifert04/iteration_utilities,MSeifert04/iteration_utilities,MSeifert04/iteration_utilities,MSeifert04/iteration_utilities | ---
+++
@@ -0,0 +1,7 @@
+import subprocess
+
+# Keep the following directories
+# - .vscode (Visual Studio code project settings)
+# - .vs (Visual Studio project files)
+# - .idea (PyCharm project files)
+subprocess.run(["git", "clean", "-dfx", "-e", ".vscode", "-e", ".idea", "-e", ".vs"], check=True) | |
73111cf0f1ab101ad0c75ab23de6e121a8eb656f | scripts/profile_generate.py | scripts/profile_generate.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from logya.generate import Generate
import cProfile, pstats, io
from pstats import SortKey
pr = cProfile.Profile()
pr.enable()
Generate(verbose=True)
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats(SortKey.CUMULATIVE)
ps.print_stats()
print(s.... | Add script for profiling the generate process. | Add script for profiling the generate process.
| Python | mit | elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya,elaOnMars/logya | ---
+++
@@ -0,0 +1,18 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+from logya.generate import Generate
+
+import cProfile, pstats, io
+from pstats import SortKey
+
+
+pr = cProfile.Profile()
+pr.enable()
+
+Generate(verbose=True)
+
+pr.disable()
+s = io.StringIO()
+ps = pstats.Stats(pr, stream=s).sort_stats(So... | |
5073d3da07cff017cc567ebc73f06d862c21c839 | tests/extmod/zlib_decompress.py | tests/extmod/zlib_decompress.py | try:
import zlib
except ImportError:
import zlibd as zlib
PATTERNS = [
# Packed results produced by CPy's zlib.compress()
(b'0', b'x\x9c3\x00\x00\x001\x001'),
(b'a', b'x\x9cK\x04\x00\x00b\x00b'),
(b'0' * 100, b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1'),
(bytes(range(64)), b'x\x9cc`dbfaec\xe7\xe0\... | Add test for zlibd module. | tests: Add test for zlibd module.
| Python | mit | turbinenreiter/micropython,cwyark/micropython,ryannathans/micropython,alex-robbins/micropython,pfalcon/micropython,dhylands/micropython,warner83/micropython,henriknelson/micropython,AriZuu/micropython,mhoffma/micropython,adafruit/micropython,noahchense/micropython,adafruit/micropython,AriZuu/micropython,tobbad/micropyt... | ---
+++
@@ -0,0 +1,16 @@
+try:
+ import zlib
+except ImportError:
+ import zlibd as zlib
+
+PATTERNS = [
+ # Packed results produced by CPy's zlib.compress()
+ (b'0', b'x\x9c3\x00\x00\x001\x001'),
+ (b'a', b'x\x9cK\x04\x00\x00b\x00b'),
+ (b'0' * 100, b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1'),
+ (byte... | |
1d2463d7aa476608b95dc1ca37ced23e7dcb13d4 | tests/handlers/test_analyses.py | tests/handlers/test_analyses.py | import pytest
@pytest.mark.parametrize("not_found", [False, True], ids=["200", "404"])
async def test_get(mocker, not_found, spawn_client):
client = await spawn_client(authorize=True)
document = {
"_id": "foobar",
"formatted": False
}
if not not_found:
await client.db.analyse... | Add some tests for analyses handlers | Add some tests for analyses handlers
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool | ---
+++
@@ -0,0 +1,96 @@
+import pytest
+
+
+@pytest.mark.parametrize("not_found", [False, True], ids=["200", "404"])
+async def test_get(mocker, not_found, spawn_client):
+ client = await spawn_client(authorize=True)
+
+ document = {
+ "_id": "foobar",
+ "formatted": False
+ }
+
+ if not no... | |
06906b820f312bbc0a59eea7518470856df478ac | pytoon/tests/test_brick_connection.py | pytoon/tests/test_brick_connection.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pytoon
----------------------------------
Tests for `pytoon` module.
"""
import unittest
from mock import patch, Mock
from pytoon.connection import BrickConnection
@patch('pytoon.connection.IPConnection')
class TestConnection(unittest.TestCase):
def test_m... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pytoon
----------------------------------
Tests for `pytoon` module.
"""
import unittest
from mock import patch, Mock
from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_hall_effect import HallEffect
from tinkerforge.bricklet_ambient_lig... | Add tests for connecting to three different sensors | Add tests for connecting to three different sensors
| Python | bsd-3-clause | marcofinalist/pytoon,marcoplaisier/pytoon,marcoplaisier/pytoon,marcofinalist/pytoon | ---
+++
@@ -10,15 +10,53 @@
import unittest
from mock import patch, Mock
+from tinkerforge.ip_connection import IPConnection
+from tinkerforge.bricklet_hall_effect import HallEffect
+from tinkerforge.bricklet_ambient_light import AmbientLight
+from tinkerforge.bricklet_line import Line
from pytoon.connection imp... |
0b9771c782394af2850161fab1e4947fc3c40cca | qregexeditor/api/match_highlighter.py | qregexeditor/api/match_highlighter.py | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def h... | import re
from pyqode.core.qt import QtGui
class MatchHighlighter(QtGui.QSyntaxHighlighter):
def __init__(self, document):
super().__init__(document)
self.prog = None
self._format = QtGui.QTextCharFormat()
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def h... | Fix infinite loop in highlighter | Fix infinite loop in highlighter
| Python | mit | ColinDuquesnoy/QRegexEditor | ---
+++
@@ -10,10 +10,13 @@
self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb')))
def highlightBlock(self, text):
- if self.prog:
+ if self.prog and text:
match = self.prog.search(text)
- while match:
+ if match:
start, end ... |
696be529ceaef9a9ab6fa43d599456d92336c083 | lglass/database/mongodb.py | lglass/database/mongodb.py | # coding: utf-8
import urllib.parse
import pymongo
import pymongo.database
import pymongo.uri_parser
import lglass.database.base
import lglass.rpsl
@lglass.database.base.register("mongodb")
class MongoDBDatabase(lglass.database.base.Database):
def __init__(self, mongo, database="lglass"):
if isinstance(mongo, st... | Implement database driver for MongoDB | Implement database driver for MongoDB
| Python | mit | fritz0705/lglass | ---
+++
@@ -0,0 +1,70 @@
+# coding: utf-8
+
+import urllib.parse
+
+import pymongo
+import pymongo.database
+import pymongo.uri_parser
+
+import lglass.database.base
+import lglass.rpsl
+
+@lglass.database.base.register("mongodb")
+class MongoDBDatabase(lglass.database.base.Database):
+ def __init__(self, mongo, data... | |
63bda7d2b33c2c238ef16d5dc5df782e709f0f99 | sqlobject/tests/test_md5.py | sqlobject/tests/test_md5.py | from md5 import md5
########################################
## md5.md5
########################################
def test_md5():
assert md5('').hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e'
assert md5('\n').hexdigest() == '68b329da9893e34099c7d8ad5cb9c940'
assert md5('123').hexdigest() == '202cb962ac5... | Add a few tests for md5.md5 | Add a few tests for md5.md5
git-svn-id: ace7fa9e7412674399eb986d17112e1377537c44@4673 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
| Python | lgpl-2.1 | drnlm/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject | ---
+++
@@ -0,0 +1,11 @@
+from md5 import md5
+
+########################################
+## md5.md5
+########################################
+
+def test_md5():
+ assert md5('').hexdigest() == 'd41d8cd98f00b204e9800998ecf8427e'
+ assert md5('\n').hexdigest() == '68b329da9893e34099c7d8ad5cb9c940'
+ assert m... | |
02512cb193372e02ac4e628631901f1ff7d0eab5 | scripts/setup-do-node.py | scripts/setup-do-node.py | #!/usr/bin/env python
import subprocess
import re
import os.path
subprocess.check_call(['fallocate', '-l', '2G', '/swapfile'])
subprocess.check_call(['mkswap', '/swapfile'])
subprocess.check_call(['swapon', '/swapfile'])
with open('/etc/fstab', 'rb') as f:
fstab = f.read()
print(fstab)
with open('/etc/fstab', 'w... | Add script for setting up DO nodes | Add script for setting up DO nodes
| Python | mit | muzhack/muzhack,muzhack/musitechhub,muzhack/musitechhub,muzhack/muzhack,muzhack/muzhack,muzhack/muzhack,muzhack/musitechhub,muzhack/musitechhub | ---
+++
@@ -0,0 +1,47 @@
+#!/usr/bin/env python
+import subprocess
+import re
+import os.path
+
+
+subprocess.check_call(['fallocate', '-l', '2G', '/swapfile'])
+subprocess.check_call(['mkswap', '/swapfile'])
+subprocess.check_call(['swapon', '/swapfile'])
+
+with open('/etc/fstab', 'rb') as f:
+ fstab = f.read()
... | |
1945a200cb8d517ce16eb039ecb4c3afc67acb9b | bin/checkpypi.py | bin/checkpypi.py | #!/usr/bin/env python
# Adapted from http://code.activestate.com/recipes/577708-check-for-package-updates-on-pypi-works-best-in-pi/
# Changelog:
# - patch to python 3.6
# - include hidden releases
import xmlrpc
import pip
pypi = xmlrpc.client.ServerProxy('https://pypi.python.org/pypi')
for dist in pip.get_installed_... | Check latest version of Python modules in Pypi | Check latest version of Python modules in Pypi | Python | apache-2.0 | verdimrc/linuxcfg,verdimrc/linuxcfg,verdimrc/linuxcfg | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+
+# Adapted from http://code.activestate.com/recipes/577708-check-for-package-updates-on-pypi-works-best-in-pi/
+# Changelog:
+# - patch to python 3.6
+# - include hidden releases
+
+import xmlrpc
+import pip
+
+pypi = xmlrpc.client.ServerProxy('https://pypi.python.org... | |
8a9f558387fbed5442f141a70aaffee265684755 | apps/network/tests/test_routes/test_roles.py | apps/network/tests/test_routes/test_roles.py | def test_create_role(client):
result = client.post("/roles/", data={"role": "admin"})
assert result.status_code == 200
assert result.get_json() == {"msg": "Role created succesfully!"}
def test_get_all_roles(client):
result = client.get("/roles/")
assert result.status_code == 200
assert result.... | ADD Network roles unit tests | ADD Network roles unit tests
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | ---
+++
@@ -0,0 +1,25 @@
+def test_create_role(client):
+ result = client.post("/roles/", data={"role": "admin"})
+ assert result.status_code == 200
+ assert result.get_json() == {"msg": "Role created succesfully!"}
+
+
+def test_get_all_roles(client):
+ result = client.get("/roles/")
+ assert result.s... | |
47bd7608cd67ab9657726ef024ac04a3c793aa82 | build/android/adb_reverse_forwarder.py | build/android/adb_reverse_forwarder.py | #!/usr/bin/env python
#
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Command line tool for forwarding ports from a device to the host.
Allows an Android device to connect to services running on ... | Add a command line tool for reverse port forwarding | [Android] Add a command line tool for reverse port forwarding
This patch adds a command line interface to
build/android/pylib/forwarder.py. It allows an Android device to access
services running on the host machine or elsewhere. This is essentially
the reverse of "adb forward".
Review URL: https://chromiumcodereview... | Python | bsd-3-clause | zcbenz/cefode-chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,M4sse/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,c... | ---
+++
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2013 The Chromium Authors. All rights reserved.
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
+
+"""Command line tool for forwarding ports from a device to the host.
+
+Allows an Android devic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.