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 |
|---|---|---|---|---|---|---|---|---|---|---|
41795bf65f6d834007c7f352fd079084f5ed940f | calc.py | calc.py | # -*- coding: utf-8 -*-
def add(x, y):
"""
引数xとyを加算した結果を返す
>>> add(2, 3)
5
"""
return x + y
| Implement sample module and doctest | Implement sample module and doctest
| Python | mit | raimon49/python-local-wheels-sample | ---
+++
@@ -0,0 +1,10 @@
+# -*- coding: utf-8 -*-
+
+
+def add(x, y):
+ """
+ 引数xとyを加算した結果を返す
+ >>> add(2, 3)
+ 5
+ """
+ return x + y | |
41ca7f51bc169dee1e371143615f2f0ae4880523 | examples/defining_new_state_relation.py | examples/defining_new_state_relation.py | import numpy as np
import matplotlib.pyplot as plt
from math import log
from rsfmodel import rsf
# This is really just the Ruina realtion, but let's pretend we invented it!
# We'll inherit attributes from rsf.StateRelation, but you wouldn't have to.
# It does provide velocity contribution calcualtion for us though!
... | Add example of how to define your own state relation | Add example of how to define your own state relation
| Python | mit | jrleeman/rsfmodel | ---
+++
@@ -0,0 +1,57 @@
+import numpy as np
+import matplotlib.pyplot as plt
+from math import log
+from rsfmodel import rsf
+
+# This is really just the Ruina realtion, but let's pretend we invented it!
+# We'll inherit attributes from rsf.StateRelation, but you wouldn't have to.
+# It does provide velocity contrib... | |
d8491825d38b6b9b393723467fd50c41be8e610f | bluebottle/events/migrations/0015_auto_20200226_0838.py | bluebottle/events/migrations/0015_auto_20200226_0838.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-02-26 07:38
from __future__ import unicode_literals
from datetime import datetime
from timezonefinder import TimezoneFinder
import pytz
from django.db import migrations
from django.utils import timezone
tf = TimezoneFinder()
def set_timezone(apps, schem... | Add migration to set start time to local timzeone | Add migration to set start time to local timzeone
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.15 on 2020-02-26 07:38
+from __future__ import unicode_literals
+from datetime import datetime
+from timezonefinder import TimezoneFinder
+import pytz
+
+from django.db import migrations
+from django.utils import timezone
+
+
+tf = Timezone... | |
50e50b3d3b98b9a3222194a8d3797ec9a9c91551 | python-omega-client/sample_usage.py | python-omega-client/sample_usage.py | # coding: utf-8
from omega_client import OmegaClient
clt = OmegaClient('http://offlineforward.dataman-inc.net', 'admin@shurenyun.com', 'Dataman1234')
print clt.get_clusters()
print clt.get_cluster(630)
print clt.get_node_identifier(630)
print clt.post_nodes(630, id='83ec44c13e2a482aa4645713d3857ff6', name='test_node'... | Add one sample usage file. | Add one sample usage file.
| Python | apache-2.0 | Dataman-Cloud/omega-client | ---
+++
@@ -0,0 +1,11 @@
+# coding: utf-8
+from omega_client import OmegaClient
+
+clt = OmegaClient('http://offlineforward.dataman-inc.net', 'admin@shurenyun.com', 'Dataman1234')
+
+print clt.get_clusters()
+print clt.get_cluster(630)
+print clt.get_node_identifier(630)
+print clt.post_nodes(630, id='83ec44c13e2a482... | |
9029ebbefa019c462d8bf7228517c7767d221e46 | tests/test_feeds.py | tests/test_feeds.py | import pytest
from django.core.urlresolvers import reverse
from name.models import Name, Location
pytestmark = pytest.mark.django_db
def test_feed_has_georss_namespace(client):
response = client.get(reverse('name_feed'))
assert 'xmlns:georss' in response.content
def test_feed_response_is_application_xml(... | Add tests for additional functionality provided by NameAtomFeedType. | Add tests for additional functionality provided by NameAtomFeedType.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name,damonkelley/django-name | ---
+++
@@ -0,0 +1,30 @@
+import pytest
+
+from django.core.urlresolvers import reverse
+
+from name.models import Name, Location
+
+pytestmark = pytest.mark.django_db
+
+
+def test_feed_has_georss_namespace(client):
+ response = client.get(reverse('name_feed'))
+ assert 'xmlns:georss' in response.content
+
+
+... | |
c78c4b4bd56453fe1f3a7db71222c12336c2dcf5 | future/tests/test_str_is_unicode.py | future/tests/test_str_is_unicode.py | from __future__ import absolute_import
from future import str_is_unicode
import unittest
class TestIterators(unittest.TestCase):
def test_str(self):
self.assertIsNot(str, bytes) # Py2: assertIsNot only in 2.7
self.assertEqual(str('blah'), u'blah') # Py3.3 and Py2 only
unittest.main()... | Add tests for str_is_unicode module | Add tests for str_is_unicode module
| Python | mit | michaelpacer/python-future,michaelpacer/python-future,krischer/python-future,QuLogic/python-future,QuLogic/python-future,PythonCharmers/python-future,PythonCharmers/python-future,krischer/python-future | ---
+++
@@ -0,0 +1,12 @@
+from __future__ import absolute_import
+
+from future import str_is_unicode
+
+import unittest
+
+class TestIterators(unittest.TestCase):
+ def test_str(self):
+ self.assertIsNot(str, bytes) # Py2: assertIsNot only in 2.7
+ self.assertEqual(str('blah'), u'blah') ... | |
8bf20ed375dba6caef2095f175863c2953daa67e | tests/utils_test.py | tests/utils_test.py | import datetime
import json
import unittest
from clippings.utils import DatetimeJSONEncoder
DATE = datetime.datetime(2016, 1, 2, 3, 4, 5)
DATE_STRING = "2016-01-02T03:04:05"
class DatetimeJSONEncoderTest(unittest.TestCase):
def test_datetime_encoder_format(self):
dictionary = {"now": DATE}
exp... | Add basic test for DatetimeJSONEncoder | Add basic test for DatetimeJSONEncoder
| Python | mit | samueldg/clippings | ---
+++
@@ -0,0 +1,24 @@
+import datetime
+import json
+import unittest
+
+from clippings.utils import DatetimeJSONEncoder
+
+
+DATE = datetime.datetime(2016, 1, 2, 3, 4, 5)
+DATE_STRING = "2016-01-02T03:04:05"
+
+
+class DatetimeJSONEncoderTest(unittest.TestCase):
+
+ def test_datetime_encoder_format(self):
+ ... | |
6e718a103c1a820125a50cd80a67fac6c810aa87 | CodeFights/isSumConsecutive2.py | CodeFights/isSumConsecutive2.py | #!/usr/local/bin/python
# Code Fights Is Sum Consecutive 2 Problem
def isSumConsecutive2(n):
count = 0
nums = list(range(1, n))
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
tmp = sum(nums[i:j])
if tmp == n:
count += 1
if tmp > n:
... | Solve Code Fights is sum consecutive 2 problem | Solve Code Fights is sum consecutive 2 problem
| Python | mit | HKuz/Test_Code | ---
+++
@@ -0,0 +1,37 @@
+#!/usr/local/bin/python
+# Code Fights Is Sum Consecutive 2 Problem
+
+
+def isSumConsecutive2(n):
+ count = 0
+ nums = list(range(1, n))
+ for i in range(len(nums)):
+ for j in range(i + 1, len(nums)):
+ tmp = sum(nums[i:j])
+ if tmp == n:
+ ... | |
178f3d84310c7c6caabb93260c962e0663713b87 | st2common/tests/unit/test_util_compact.py | st2common/tests/unit/test_util_compact.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | Add tests for to_ascii function. | Add tests for to_ascii function.
| Python | apache-2.0 | Plexxi/st2,StackStorm/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,StackStorm/st2 | ---
+++
@@ -0,0 +1,37 @@
+# -*- coding: utf-8 -*-
+# Licensed to the StackStorm, Inc ('StackStorm') under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache Li... | |
332c99e06505e084fb094c43ffd01ff58d53366b | utcdatetime/tests/test_time.py | utcdatetime/tests/test_time.py | import utcdatetime
from nose.tools import assert_equal
import datetime
TEST_CASES = [
(
utcdatetime.utcdatetime(2015, 5, 11, 16, 43, 10, 45),
datetime.time(16, 43, 10, 45)
),
]
def test_time_method():
for utc_dt, expected_time in TEST_CASES:
yield _assert_time_equals, utc_dt, e... | Add test for utcdatetime.time() method | Add test for utcdatetime.time() method
| Python | mit | paulfurley/python-utcdatetime,paulfurley/python-utcdatetime | ---
+++
@@ -0,0 +1,24 @@
+import utcdatetime
+
+from nose.tools import assert_equal
+
+import datetime
+
+
+TEST_CASES = [
+ (
+ utcdatetime.utcdatetime(2015, 5, 11, 16, 43, 10, 45),
+ datetime.time(16, 43, 10, 45)
+ ),
+]
+
+
+def test_time_method():
+ for utc_dt, expected_time in TEST_CASES:
... | |
4dd04ac5e74c1eaa341f4360a9d931ac6308288f | bin/cover_title.py | bin/cover_title.py | #!/usr/bin/env python
import sys
import os
import yaml
import re
file = sys.argv[1]
metafile = re.sub("-.*$", ".yml", file)
project = os.environ["PROJECT"]
metadata = open(metafile, 'r').read()
yamldata = yaml.load(metadata)
if "title" in yamldata:
title = yamldata["title"]
else:
title = "ERROR: No meta Data... | Add script for breaking titles into lines | Add script for breaking titles into lines
| Python | agpl-3.0 | alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile | ---
+++
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+
+import sys
+import os
+import yaml
+import re
+
+file = sys.argv[1]
+metafile = re.sub("-.*$", ".yml", file)
+project = os.environ["PROJECT"]
+metadata = open(metafile, 'r').read()
+yamldata = yaml.load(metadata)
+
+if "title" in yamldata:
+ title = yamldata["titl... | |
859a9aa684b793a31dbf0b1f8e559d5cd40a152e | tests/props_test.py | tests/props_test.py | from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
class PropsTest(GeneratorTest):
def testLotsaModelsGenerated(self):
for klass in self.klasses:
k = klass._get_kind()
assert ndb.Model._lookup_model(k) == klass, klass
| from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
import gaend.generator as generator
import re
class PropsTest(GeneratorTest):
def testEntityToPropsAndBack(self):
for klass in self.klasses:
# Create entity1 of this klass
kind = klass._get_kind()
... | Enumerate through choices of property values | Enumerate through choices of property values
| Python | mit | samedhi/gaend,talkiq/gaend,talkiq/gaend,samedhi/gaend | ---
+++
@@ -1,10 +1,23 @@
from fixture import GeneratorTest
from google.appengine.ext import testbed, ndb
+import gaend.generator as generator
+import re
class PropsTest(GeneratorTest):
- def testLotsaModelsGenerated(self):
+ def testEntityToPropsAndBack(self):
for klass in self.klasses:
- ... |
6ba3fe75f5939a58aee0f3835139b46f1ea8b46f | config/trace_pox_l2_multi.py | config/trace_pox_l2_multi.py | from config.experiment_config_lib import ControllerConfig
from sts.topology import StarTopology, BufferedPatchPanel, MeshTopology, GridTopology, BinaryLeafTreeTopology
from sts.controller_manager import UserSpaceControllerPatchPanel
from sts.control_flow.fuzzer import Fuzzer
from sts.control_flow.interactive import Int... | Add config for POX l2_multi traces | Add config for POX l2_multi traces
| Python | apache-2.0 | jmiserez/sts,jmiserez/sts | ---
+++
@@ -0,0 +1,59 @@
+from config.experiment_config_lib import ControllerConfig
+from sts.topology import StarTopology, BufferedPatchPanel, MeshTopology, GridTopology, BinaryLeafTreeTopology
+from sts.controller_manager import UserSpaceControllerPatchPanel
+from sts.control_flow.fuzzer import Fuzzer
+from sts.con... | |
8f41b0df8fa62b9bca031defe6eb91fae0219e56 | writeboards/urls.py | writeboards/urls.py | from django.conf.urls.defaults import *
from models import Writeboard
writeboard_list_dict = {
'queryset': Writeboard.objects.all(),
}
urlpatterns = patterns('',
(r'$','django.views.generic.list_detail.object_list',
writeboard_list_dict),
)
| Add writeboard list via generic views | Add writeboard list via generic views | Python | mit | rizumu/django-paste-organizer | ---
+++
@@ -0,0 +1,11 @@
+from django.conf.urls.defaults import *
+from models import Writeboard
+
+writeboard_list_dict = {
+ 'queryset': Writeboard.objects.all(),
+}
+
+urlpatterns = patterns('',
+ (r'$','django.views.generic.list_detail.object_list',
+ writeboard_list_dict),
+) | |
162d7f14cbc3f705b018669448eda369473a6b5a | tools/get_digest.py | tools/get_digest.py | import sys
import hashlib
FILE_BUFFER_SIZE = 4096
def get_digest(file_path, digest_func='md5'):
digester = getattr(hashlib, digest_func, None)
if digester is None:
raise ValueError('Unknow digest method: ' + digest_func)
h = digester()
with open(file_path, 'rb') as f:
while True:
... | Add utility script to get a file's digest, useful for debugging purpose | Add utility script to get a file's digest, useful for debugging purpose
| Python | lgpl-2.1 | DirkHoffmann/nuxeo-drive,arameshkumar/base-nuxeo-drive,arameshkumar/nuxeo-drive,arameshkumar/nuxeo-drive,DirkHoffmann/nuxeo-drive,loopingz/nuxeo-drive,DirkHoffmann/nuxeo-drive,arameshkumar/base-nuxeo-drive,loopingz/nuxeo-drive,loopingz/nuxeo-drive,DirkHoffmann/nuxeo-drive,IsaacYangSLA/nuxeo-drive,rsoumyassdi/nuxeo-driv... | ---
+++
@@ -0,0 +1,24 @@
+import sys
+import hashlib
+
+FILE_BUFFER_SIZE = 4096
+
+
+def get_digest(file_path, digest_func='md5'):
+ digester = getattr(hashlib, digest_func, None)
+ if digester is None:
+ raise ValueError('Unknow digest method: ' + digest_func)
+
+ h = digester()
+ with open(file_p... | |
b98c6deaa713504a06a01f3397b42b0d310a7fb4 | build/changelog.py | build/changelog.py | #!/usr/bin/env python
"""
changelog.py helps generate the CHANGELOG.md message for a particular release.
"""
import argparse
import subprocess
import shlex
import re
def run(cmd, *args, **kwargs):
return subprocess.check_output(shlex.split(cmd), *args, **kwargs)
def get_commit_ids(from_commit, to_commit):
... | Add script to help generate CHANGELOG.md | Add script to help generate CHANGELOG.md
| Python | apache-2.0 | timothyhinrichs/opa,tsandall/opa,open-policy-agent/opa,tsandall/opa,open-policy-agent/opa,Eva-xiaohui-luo/opa,open-policy-agent/opa,timothyhinrichs/opa,open-policy-agent/opa,Eva-xiaohui-luo/opa,tsandall/opa,open-policy-agent/opa,timothyhinrichs/opa,Eva-xiaohui-luo/opa,tsandall/opa,open-policy-agent/opa,timothyhinrichs/... | ---
+++
@@ -0,0 +1,86 @@
+#!/usr/bin/env python
+"""
+changelog.py helps generate the CHANGELOG.md message for a particular release.
+"""
+
+import argparse
+import subprocess
+import shlex
+import re
+
+
+def run(cmd, *args, **kwargs):
+ return subprocess.check_output(shlex.split(cmd), *args, **kwargs)
+
+
+def g... | |
cb149a64cf969edef79528f052f96bc4a847a11c | bin/run_benchmark.py | bin/run_benchmark.py | import datetime
import itertools
import os
import subprocess
# Modify parameters here
out_directory = datetime.datetime.now().strftime('benchmark_%Y-%m-%d_%H-%M-%S')
dimension = 3
size = 50
ppc = 1
temperature = 0.0
iterations = 1
representations = ["SoA", "AoS"]
storages = ["unordered", "ordered"]
# add... | Add a script to enumerate configurations for benchmarking. | Add a script to enumerate configurations for benchmarking.
| Python | mit | pictools/pica,pictools/pica,pictools/pica | ---
+++
@@ -0,0 +1,35 @@
+import datetime
+import itertools
+import os
+import subprocess
+
+# Modify parameters here
+out_directory = datetime.datetime.now().strftime('benchmark_%Y-%m-%d_%H-%M-%S')
+dimension = 3
+size = 50
+ppc = 1
+temperature = 0.0
+iterations = 1
+representations = ["SoA", "AoS"]
+storages = ["u... | |
5a97d88326e9d365afed7ed798720d97ba6fcc97 | tests/test_compat.py | tests/test_compat.py | import unittest
from mock import Mock, patch
from collectd_haproxy import compat
class CompatTests(unittest.TestCase):
@patch.object(compat, "PY3", False)
def test_iteritems_python2_uses_iteritems(self):
dictionary = Mock()
self.assertEqual(
compat.iteritems(dictionary),
... | Add tests for the compat module. | Add tests for the compat module.
| Python | mit | wglass/collectd-haproxy | ---
+++
@@ -0,0 +1,31 @@
+import unittest
+
+from mock import Mock, patch
+
+
+from collectd_haproxy import compat
+
+
+class CompatTests(unittest.TestCase):
+
+ @patch.object(compat, "PY3", False)
+ def test_iteritems_python2_uses_iteritems(self):
+ dictionary = Mock()
+
+ self.assertEqual(
+ ... | |
7f4e15c3bdc9e53f15670d88538d8a9723532ceb | incubation/parse_subtitles_py/print_subtitles.py | incubation/parse_subtitles_py/print_subtitles.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
# http://en.wikipedia.org/wiki/SubRip
# http://forum.doom9.org/showthread.php?p=470941#post470941
#
# srt format:
# Subtitle number
# Start time --> End time
# Text of subtitle (one or more lines)
# B... | Add a project in the 'incubator'. | Add a project in the 'incubator'.
| 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,72 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2013 Jérémie DECOCK (http://www.jdhp.org)
+
+# http://en.wikipedia.org/wiki/SubRip
+# http://forum.doom9.org/showthread.php?p=470941#post470941
+#
+# srt format:
+# Subtitle number
+# Start time --> End time
+# Text... | |
8404143e9335374979d028ffabbc9f7369a11e80 | admin/genkwh_remesa_cobrament_cron.py | admin/genkwh_remesa_cobrament_cron.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from erppeek import Client
import configdb
import datetime
'''
Script que agafa les inversions en esborrany i genera les factures de cobrament i les afegeix a la remesa.
python admin/genkwh_remesa_cobrament_cron.py
'''
def crear_remesa_generation(O):i
... | Add script to do investment generation payment order | Add script to do investment generation payment order
| Python | agpl-3.0 | Som-Energia/invoice-janitor | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+import sys
+from erppeek import Client
+import configdb
+import datetime
+
+'''
+ Script que agafa les inversions en esborrany i genera les factures de cobrament i les afegeix a la remesa.
+
+ python admin/genkwh_remesa_cobrament_cron.py
... | |
a53670aaf5440d1f4a0306cbbaacf8aae4baef26 | extract_exif.py | extract_exif.py | #!/usr/bin/env python
import sys,exifread
def main():
if len(sys.argv) != 2:
print("Usage: %s <JPG>" % sys.argv[0])
sys.exit(1)
JPG = sys.argv[1]
jpgfh = open(JPG, 'rb')
tags = exifread.process_file(jpgfh)
dttag = 'EXIF DateTimeOriginal'
dtsubtag = 'EXIF SubSecTimeOriginal'
if dttag in tags:
print(tags[d... | Add a EXIF extract utility. Later the EXIF "EXIF DateTimeOriginal" and "EXIF SubsecTimeOriginal" will be used to identify the same pic by taken time and subsec. | Add a EXIF extract utility. Later the EXIF "EXIF DateTimeOriginal" and
"EXIF SubsecTimeOriginal" will be used to identify the same pic by
taken time and subsec.
| Python | apache-2.0 | feifeijs/find_the_same_file | ---
+++
@@ -0,0 +1,21 @@
+#!/usr/bin/env python
+
+import sys,exifread
+
+def main():
+ if len(sys.argv) != 2:
+ print("Usage: %s <JPG>" % sys.argv[0])
+ sys.exit(1)
+ JPG = sys.argv[1]
+ jpgfh = open(JPG, 'rb')
+ tags = exifread.process_file(jpgfh)
+ dttag = 'EXIF DateTimeOriginal'
+ dtsubtag = 'EXIF SubSecTimeOri... | |
464abf7c047471ce31ef701d896e5be8077fd269 | call_by_object.py | call_by_object.py | #!/usr/bin/env python
# _*_ coding: utf-8 _*_
u""" From first entry of https://github.com/taizilongxu/interview_python.
Conditional call by object in python.
Add id() function to illustrate if we are refering to the same or different objects in action.
This is to show that Python is using pass by objec... | Add call by object illustration example with object ids. | Add call by object illustration example with object ids.
Signed-off-by: SJ Huang <55a36c562e010d4b156739b1c231e1aa17113c8e@gmail.com>
| Python | apache-2.0 | sjh/python | ---
+++
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+# _*_ coding: utf-8 _*_
+
+u""" From first entry of https://github.com/taizilongxu/interview_python.
+ Conditional call by object in python.
+ Add id() function to illustrate if we are refering to the same or different objects in action.
+
+ This is to show... | |
912322e083751ce13ec0a9b1469bc3c9eef8f39c | pombola/core/migrations/0002_add_related_name.py | pombola/core/migrations/0002_add_related_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='identifier',
name='conte... | Add corresponding migration for the Identifier related_name conflict | Add corresponding migration for the Identifier related_name conflict
| Python | agpl-3.0 | mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -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_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_... | |
ab639b991e9b44f533adf44eebbec20d62f560f6 | run_time/src/gae_server_test/test_web_handler.py | run_time/src/gae_server_test/test_web_handler.py | import webapp2
import unittest
import webtest
from gae_server.incremental_fonts import IncrementalFonts
class AppTest(unittest.TestCase):
def setUp(self):
# Create a WSGI application.
app = webapp2.WSGIApplication([('/', IncrementalFonts)])
# Wrap the app with WebTest’s TestApp.
se... | Test for server handler is added | Test for server handler is added
| Python | apache-2.0 | bstell/TachyFont,bstell/TachyFont,googlefonts/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlei18n/TachyFont,googlefonts/TachyFont,moyogo/tachyfont,googlefonts/TachyFont,bstell/TachyFont,googlefonts/TachyFont,bstell/TachyFont,googlei18n/TachyFont,moyogo/tachyfont,googlei18n/TachyFont,moyogo/tachyfont,bstell/Tachy... | ---
+++
@@ -0,0 +1,19 @@
+import webapp2
+import unittest
+import webtest
+from gae_server.incremental_fonts import IncrementalFonts
+
+
+class AppTest(unittest.TestCase):
+ def setUp(self):
+ # Create a WSGI application.
+ app = webapp2.WSGIApplication([('/', IncrementalFonts)])
+ # Wrap the ... | |
e40c295967e8d0b1a190c173dedebefe9eb89462 | Python/66_PlusOne.py | Python/66_PlusOne.py | class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[len(digits)-1] += 1
if digits[len(digits)-1] < 10:
return digits
for i in xrange(len(digits)-1,0,-1):
if digits[i] == 10:
di... | Add solution for 66 Plus One. | Add solution for 66 Plus One.
| Python | mit | comicxmz001/LeetCode,comicxmz001/LeetCode | ---
+++
@@ -0,0 +1,22 @@
+class Solution(object):
+ def plusOne(self, digits):
+ """
+ :type digits: List[int]
+ :rtype: List[int]
+ """
+ digits[len(digits)-1] += 1
+ if digits[len(digits)-1] < 10:
+ return digits
+ for i in xrange(len(digits)-1,0,-1):
+ ... | |
56e5eee44edfc1aae719a12eb5638316237fc55a | Python/twitterBot.py | Python/twitterBot.py | import tweepy
import markovify
import sys, random, time
ck = ''
cs = ''
ak = ''
ase = ''
auth = tweepy.OAuthHandler(ck, cs)
auth.set_access_token(ak, ase)
api = tweepy.API(auth)
# print(api.statuses_lookup(100))
# print(api.me())
with open('https://raw.githubusercontent.com/gastonstat/StarWars/master/Text_files/Episo... | Add a Twitter bot that creates dialog from Star Wars text using Markov models | Add a Twitter bot that creates dialog from Star Wars text using Markov models
| Python | mit | mckennapsean/code-examples,mckennapsean/code-examples,mckennapsean/code-examples,mckennapsean/code-examples,mckennapsean/code-examples,mckennapsean/code-examples,mckennapsean/code-examples | ---
+++
@@ -0,0 +1,35 @@
+import tweepy
+import markovify
+import sys, random, time
+
+ck = ''
+cs = ''
+ak = ''
+ase = ''
+auth = tweepy.OAuthHandler(ck, cs)
+auth.set_access_token(ak, ase)
+api = tweepy.API(auth)
+# print(api.statuses_lookup(100))
+# print(api.me())
+
+with open('https://raw.githubusercontent.com/g... | |
c0955ea64452808d97f4cd741ea6eb6fc1eaee20 | tests/test_character.py | tests/test_character.py | import npc
class TestCreation:
"""Test different instantiation behaviors"""
def test_dict(self):
char = npc.Character({"name": ["hello"]})
assert char["name"] == ["hello"]
def test_kwargs(self):
char = npc.Character(name=["hello"])
assert char["name"] == ["hello"]
def... | Add tests for Character class | Add tests for Character class
| Python | mit | aurule/npc,aurule/npc | ---
+++
@@ -0,0 +1,60 @@
+import npc
+
+class TestCreation:
+ """Test different instantiation behaviors"""
+
+ def test_dict(self):
+ char = npc.Character({"name": ["hello"]})
+ assert char["name"] == ["hello"]
+
+ def test_kwargs(self):
+ char = npc.Character(name=["hello"])
+ as... | |
9b2a2f7aeb0f24c6c5e7cbb474cf377a89dd48d6 | evaluation/collectStatistics.py | evaluation/collectStatistics.py | import packages.project as project
import packages.primitive as primitive
import packages.utils as utils
import packages.processing
import packages.io
import argparse
from matplotlib import pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
from scipy.stats import norm,kstest,skewtest,kurtosistest,normalte... | Add a new script processing different iterations of a run and computing statistics | Add a new script processing different iterations of a run and computing statistics
| Python | apache-2.0 | amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,NUAAXXY/globOpt,amonszpart/globOpt,amonszpart/globOpt,amonszpart/globOpt,NUAAXXY/globOpt | ---
+++
@@ -0,0 +1,83 @@
+import packages.project as project
+import packages.primitive as primitive
+import packages.utils as utils
+import packages.processing
+import packages.io
+import argparse
+from matplotlib import pyplot as plt
+import matplotlib.mlab as mlab
+import numpy as np
+from scipy.stats import norm,... | |
07eb99ca0fa82266dd183195ef5d03f4b0457d59 | tests/test_utilities.py | tests/test_utilities.py | """test_eniric.py"""
import pytest
import numpy as np
from eniric.utilities import get_spectrum_name, wav_selector
# Test using hypothesis
from hypothesis import given, example
import hypothesis.strategies as st
def test_get_spectrum_name():
""" """
test = ("PHOENIX-ACES_spectra/Z-0.0/lte02800-4.50"
... | Add some working utility tests | Add some working utility tests
Former-commit-id: 96e85547f79640d7c12fe0cbea9ed351396759f8 [formerly 7608385cbf13efc6342d0dcb295474eba71842d8] [formerly 91473ba3c3015cabd2c15fb4d679a355687adb10 [formerly 66526a15c595e72f014a13bf692996b624acede9]]
Former-commit-id: a01daec4a10620e2dad12e133c23bf1959d34e4d [formerly bd5... | Python | mit | jason-neal/eniric,jason-neal/eniric | ---
+++
@@ -0,0 +1,52 @@
+"""test_eniric.py"""
+
+import pytest
+import numpy as np
+from eniric.utilities import get_spectrum_name, wav_selector
+
+# Test using hypothesis
+from hypothesis import given, example
+import hypothesis.strategies as st
+
+
+def test_get_spectrum_name():
+ """ """
+ test = ("PHOENIX-... | |
835a4b21728e999ff2ef730f69afed34c7c3b98f | nb_train.py | nb_train.py | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.externals import joblib
print "Grabbing data..."
training_text_collection_f = open("training_text_collection.pkl", "rb")
training_text_collection = joblib.load(training_text_collection_f)
training_te... | Create Naive Bayes vectorizer and classifier pickles | Create Naive Bayes vectorizer and classifier pickles
| Python | mit | npentella/CuriousCorpus,npentella/CuriousCorpus,npentella/CuriousCorpus | ---
+++
@@ -0,0 +1,35 @@
+from sklearn.feature_extraction.text import TfidfVectorizer
+from sklearn.naive_bayes import MultinomialNB
+from sklearn.externals import joblib
+
+print "Grabbing data..."
+
+training_text_collection_f = open("training_text_collection.pkl", "rb")
+training_text_collection = joblib.load(trai... | |
950aa44a405b0ca6d057d2583d39f06409ca2c0c | contrib/performance/event_delete.py | contrib/performance/event_delete.py |
"""
Benchmark a server's handling of event deletion.
"""
from itertools import count
from urllib2 import HTTPDigestAuthHandler
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
from h... | Add a benchmark for event deletion | Add a benchmark for event deletion
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6238 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver | ---
+++
@@ -0,0 +1,58 @@
+
+"""
+Benchmark a server's handling of event deletion.
+"""
+
+from itertools import count
+from urllib2 import HTTPDigestAuthHandler
+
+from twisted.internet import reactor
+from twisted.internet.defer import inlineCallbacks, returnValue
+from twisted.web.client import Agent
+from twisted.... | |
6719988bc77b4e66fe438edd2d00fc619cc2adfb | proselint/checks/misc/symbols.py | proselint/checks/misc/symbols.py | # -*- coding: utf-8 -*-
"""MSC110: Symbols.
---
layout: post
error_code: MSC110
source: SublimeLinter-annotations
source_url: http://bit.ly/16Q7H41
title: symbols
date: 2014-06-10 12:31:19
categories: writing
---
Symbols.
"""
from proselint.tools import blacklist, memoize
@memoize
def check(text... | Add check for symbol usage | Add check for symbol usage
| Python | bsd-3-clause | amperser/proselint,jstewmon/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint | ---
+++
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+"""MSC110: Symbols.
+
+---
+layout: post
+error_code: MSC110
+source: SublimeLinter-annotations
+source_url: http://bit.ly/16Q7H41
+title: symbols
+date: 2014-06-10 12:31:19
+categories: writing
+---
+
+Symbols.
+
+"""
+from proselint.tools import ... | |
f947d72281c7909c1d51399b06c8ebb9671da68d | build/generate_standalone_timeline_view.py | build/generate_standalone_timeline_view.py | #!/usr/bin/env python
# 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.
import optparse
import parse_deps
import sys
import os
srcdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))
... | Add script to generate a standalone timeline view. | Add script to generate a standalone timeline view.
TBR=jgennis@google.com
Review URL: https://codereview.appspot.com/6497071
git-svn-id: 3a56fcae908c7e16d23cb53443ea4795ac387cf2@146 0e6d7f2b-9903-5b78-7403-59d27f066143
| Python | bsd-3-clause | bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer,bpsinc-native/src_third_party_trace-viewer | ---
+++
@@ -0,0 +1,85 @@
+#!/usr/bin/env python
+# 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.
+import optparse
+import parse_deps
+import sys
+import os
+
+srcdir = os.path.abspath(os.path.join(o... | |
9c77a1fd037e2a59cba57b5492671f32ffcb5409 | clodius/cli/utils.py | clodius/cli/utils.py | import math
def get_tile_box(zoom, x, y):
"""convert Google-style Mercator tile coordinate to
(minlat, maxlat, minlng, maxlng) bounding box"""
minlng, minlat = get_lng_lat_from_tile_pos(zoom, x, y)
maxlng, maxlat = get_lng_lat_from_tile_pos(zoom, x + 1, y + 1)
return (minlng, maxlng, minlat, max... | Add utility function for converting lng-lat to tile positions | Add utility function for converting lng-lat to tile positions
| Python | mit | hms-dbmi/clodius,hms-dbmi/clodius | ---
+++
@@ -0,0 +1,49 @@
+import math
+
+
+def get_tile_box(zoom, x, y):
+ """convert Google-style Mercator tile coordinate to
+ (minlat, maxlat, minlng, maxlng) bounding box"""
+
+ minlng, minlat = get_lng_lat_from_tile_pos(zoom, x, y)
+ maxlng, maxlat = get_lng_lat_from_tile_pos(zoom, x + 1, y + 1)
+
+ ... | |
64094025914de15107c450557b301b8a4dd9d9f9 | tests/test_volume.py | tests/test_volume.py | from farmfs.volume import *
from itertools import permutations
import re
def produce_mismatches():
""" Helper function to produce pairs of paths which have lexographical/path order mismatches"""
letters = list("abc/+")
paths = filter(lambda p: re.search("//", p) is None, map(lambda p: "/"+p, map(lambda s: reduce... | Add tests for lex order issue. | Add tests for lex order issue. | Python | mit | andrewguy9/farmfs,andrewguy9/farmfs | ---
+++
@@ -0,0 +1,35 @@
+from farmfs.volume import *
+from itertools import permutations
+import re
+
+def produce_mismatches():
+ """ Helper function to produce pairs of paths which have lexographical/path order mismatches"""
+ letters = list("abc/+")
+ paths = filter(lambda p: re.search("//", p) is None, map(la... | |
e65bc2b46eacca05720370d000564bc4a51de223 | seleniumbase/common/unobfuscate.py | seleniumbase/common/unobfuscate.py | """
Unobfuscates an encrypted string/password into a plaintext string/password.
Usage:
python unobfuscate.py
Then enter the encrypted string/password.
The result is a plaintext string/password.
Works the same as obfuscate.py, but doesn't mask the input.
"""
from seleniumbase.common import encryption
import time
def... | Add the user interface to reverse string obfuscation | Add the user interface to reverse string obfuscation
| Python | mit | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/seleniumspot,seleniumbase/SeleniumBase,mdmintz/seleniumspot | ---
+++
@@ -0,0 +1,34 @@
+"""
+Unobfuscates an encrypted string/password into a plaintext string/password.
+
+Usage:
+python unobfuscate.py
+Then enter the encrypted string/password.
+The result is a plaintext string/password.
+Works the same as obfuscate.py, but doesn't mask the input.
+"""
+
+from seleniumbase.comm... | |
0f30fb878ae0c493eb117e0b27a33937bb90e52c | examples/use_socket.py | examples/use_socket.py | """A basic example of using hug.use.Socket to return data from raw sockets"""
import hug
import socket
import struct
import time
http_socket = hug.use.Socket(connect_to=('www.google.com', 80), proto='tcp', pool=4, timeout=10.0)
ntp_service = hug.use.Socket(connect_to=('127.0.0.1', 123), proto='udp', pool=4, timeout=1... | Add example code for using hug.use.Socket with udp and tcp | Add example code for using hug.use.Socket with udp and tcp
| Python | mit | MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,timothycrosley/hug,MuhammadAlkarouri/hug,timothycrosley/hug,timothycrosley/hug | ---
+++
@@ -0,0 +1,33 @@
+"""A basic example of using hug.use.Socket to return data from raw sockets"""
+import hug
+import socket
+import struct
+import time
+
+
+http_socket = hug.use.Socket(connect_to=('www.google.com', 80), proto='tcp', pool=4, timeout=10.0)
+ntp_service = hug.use.Socket(connect_to=('127.0.0.1', ... | |
f297b67920f7406c6fbe4bbfabf99c7bcb5a8d05 | find_unimplemented_attacks.py | find_unimplemented_attacks.py | #!/usr/bin/env python3
"""
This script is meant to help discover attack types/damages that have not been
added to Pinobot unixmain.patch.
Example:
./find_unimplemented_attacks.py nethack/include/monattk.h pinobot/patch/unixmain.patch
"""
import re
import sys
AT_RE = re.compile('.*(AT|AD)_([0-9A-Za-z]+).*')
if __na... | Add the tool that lists all unimplemented AD_/AT_ flags. | Add the tool that lists all unimplemented AD_/AT_ flags.
| Python | mit | UnNetHack/pinobot,UnNetHack/pinobot | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/bin/env python3
+
+"""
+This script is meant to help discover attack types/damages that have not been
+added to Pinobot unixmain.patch.
+
+Example:
+./find_unimplemented_attacks.py nethack/include/monattk.h pinobot/patch/unixmain.patch
+"""
+
+import re
+import sys
+
+AT_RE = re.compi... | |
209774dfff05f0716cccca61bd8baa7eb456badf | apps/news/tests.py | apps/news/tests.py | from django import test
from django.http import QueryDict
from mock import patch
from news.models import Subscriber
from news.tasks import SET
class UserTest(test.TestCase):
@patch('news.views.update_user')
def test_user_set(self, update_user):
"""If the user view is sent a POST request, it should a... | Add test for user view. | Add test for user view. | Python | mpl-2.0 | glogiotatidis/basket,pmclanahan/basket,meandavejustice/basket,glogiotatidis/basket,pmclanahan/basket,meandavejustice/basket,glogiotatidis/basket | ---
+++
@@ -0,0 +1,21 @@
+from django import test
+from django.http import QueryDict
+
+from mock import patch
+
+from news.models import Subscriber
+from news.tasks import SET
+
+
+class UserTest(test.TestCase):
+ @patch('news.views.update_user')
+ def test_user_set(self, update_user):
+ """If the user ... | |
a8b6e3fd52796b17f5fd287e82364406f23461e0 | scripts/svmlight_sortcols.py | scripts/svmlight_sortcols.py | from sys import argv
from operator import itemgetter
if __name__ == "__main__":
if (len(argv) != 3):
print("Usage: " + argv[0] + " <input.svm> <output.svm>")
print("Example:")
print("input.svm:")
print("1 24:1 12:1 55:1")
print("0 84:1 82:1 15:1")
print("...")
... | Add helper script to sort svmlight files by column keys. | Add helper script to sort svmlight files by column keys.
| Python | apache-2.0 | YzPaul3/h2o-3,bospetersen/h2o-3,ChristosChristofidis/h2o-3,mrgloom/h2o-3,kyoren/https-github.com-h2oai-h2o-3,h2oai/h2o-3,michalkurka/h2o-3,junwucs/h2o-3,h2oai/h2o-3,nilbody/h2o-3,mathemage/h2o-3,kyoren/https-github.com-h2oai-h2o-3,mrgloom/h2o-3,tarasane/h2o-3,pchmieli/h2o-3,weaver-viii/h2o-3,ChristosChristofidis/h2o-3,... | ---
+++
@@ -0,0 +1,31 @@
+from sys import argv
+from operator import itemgetter
+
+if __name__ == "__main__":
+ if (len(argv) != 3):
+ print("Usage: " + argv[0] + " <input.svm> <output.svm>")
+ print("Example:")
+ print("input.svm:")
+ print("1 24:1 12:1 55:1")
+ print("0 84:1 82... | |
3316c68bdd61cc817f558e1fdd5862f64fd80bbb | spreadflow_core/test/test_config.py | spreadflow_core/test/test_config.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from tempfile import NamedTemporaryFile
from unittest import TestCase
from spreadflow_core.config import config_eval
from spreadflow_core.flow import Flowmap
class ConfigTestCase(TestCase):
... | Add test case for config_eval | Add test case for config_eval
| Python | mit | znerol/spreadflow-core,spreadflow/spreadflow-core | ---
+++
@@ -0,0 +1,22 @@
+from __future__ import absolute_import
+from __future__ import division
+from __future__ import unicode_literals
+
+import os
+
+from tempfile import NamedTemporaryFile
+from unittest import TestCase
+
+from spreadflow_core.config import config_eval
+from spreadflow_core.flow import Flowmap
... | |
03f4ab8b7ab39f39b3584a1a7ce68db0f8b92cd4 | tests/test_init.py | tests/test_init.py | # coding: utf-8
from __future__ import unicode_literals
import unittest
from textwrap import dedent
from conllu import parse, parse_tree
from conllu.compat import text
class TestParse(unittest.TestCase):
def test_multiple_sentences(self):
data = dedent("""\
1 The the DET DT Def... | Add test for parsing multiple sentences. | Add test for parsing multiple sentences.
| Python | mit | EmilStenstrom/conllu | ---
+++
@@ -0,0 +1,26 @@
+# coding: utf-8
+from __future__ import unicode_literals
+
+import unittest
+from textwrap import dedent
+
+from conllu import parse, parse_tree
+from conllu.compat import text
+
+
+class TestParse(unittest.TestCase):
+ def test_multiple_sentences(self):
+ data = dedent("""\
+ ... | |
3c5760c089e5222b968bb41925838db1ecaaba3b | python/bte_gen.py | python/bte_gen.py | #Parser of Baka-Tsuki ePUB generator page
#python3
import requests, re
from bs4 import BeautifulSoup
class bte_gen(BeautifulSoup):
def __init__(self, query):
self.query = query
self.result = dict()
self.bteUrl = "http://ln.m-chan.org/v3/"
self.bteGenHead = requests.get(self.bteUrl)
... | Add baka-tsuki epub generator parser | Add baka-tsuki epub generator parser
| Python | mit | DoumanAsh/collectionScripts,DoumanAsh/collectionScripts,DoumanAsh/collectionScripts | ---
+++
@@ -0,0 +1,41 @@
+#Parser of Baka-Tsuki ePUB generator page
+#python3
+import requests, re
+from bs4 import BeautifulSoup
+
+class bte_gen(BeautifulSoup):
+ def __init__(self, query):
+ self.query = query
+ self.result = dict()
+ self.bteUrl = "http://ln.m-chan.org/v3/"
+ self.b... | |
c9a97f15da4963884d13e654f901b331dae7886a | sqlobject/tests/test_class_hash.py | sqlobject/tests/test_class_hash.py | from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
# Test hashing a column instance
########################################
class ClassHashTest(SQLObject):
name = StringCol(length=50, alternateID=True, dbName='name_col')
def test_class_hash():
setupClass... | Add simple test case for hash implementation | Add simple test case for hash implementation
| Python | lgpl-2.1 | drnlm/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject | ---
+++
@@ -0,0 +1,23 @@
+from sqlobject import *
+from sqlobject.tests.dbtest import *
+
+
+########################################
+# Test hashing a column instance
+########################################
+
+
+class ClassHashTest(SQLObject):
+ name = StringCol(length=50, alternateID=True, dbName='name_col')
+... | |
93fa68985c211d43098b60a5b6409db8ae29c3de | aiozk/test/test_treecache.py | aiozk/test/test_treecache.py | import asyncio
import uuid
from .base import ZKBase
from ..exc import NoNode
class TestTreeCache(ZKBase):
async def setUp(self):
await super().setUp()
for attrname in ['basenode', 'node1', 'node2', 'subnode1', 'subnode2', 'subnode3']:
setattr(self, attrname, uuid.uuid4().hex)
f... | Test for the TreeCache recipe | Test for the TreeCache recipe
| Python | mit | tipsi/aiozk,tipsi/aiozk | ---
+++
@@ -0,0 +1,69 @@
+import asyncio
+import uuid
+
+from .base import ZKBase
+from ..exc import NoNode
+
+class TestTreeCache(ZKBase):
+ async def setUp(self):
+ await super().setUp()
+ for attrname in ['basenode', 'node1', 'node2', 'subnode1', 'subnode2', 'subnode3']:
+ setattr(self,... | |
7369f9374c11f28853cba4ecdd351c88d7e23d79 | nessusapi/utils.py | nessusapi/utils.py | import inspect
def multiton(cls):
"""
Class decorator to make a class a multiton.
That is, there will be only (at most) one object existing for a given set
of initialization parameters.
"""
instances = {}
def getinstance(*args, **kwargs):
key = _gen_key(cls, *args, **kwargs)
... | Add util class: the multiton | Add util class: the multiton
| Python | mit | sait-berkeley-infosec/pynessus-api | ---
+++
@@ -0,0 +1,72 @@
+import inspect
+
+def multiton(cls):
+ """
+ Class decorator to make a class a multiton.
+ That is, there will be only (at most) one object existing for a given set
+ of initialization parameters.
+ """
+ instances = {}
+ def getinstance(*args, **kwargs):
+ key = ... | |
5d182ac50d87c3d46d5419f449b7c9db7d9b2133 | kb/keyboard.py | kb/keyboard.py | import abc
from decimal import Decimal
from core import Key, Keyboard
class StandardKeyboard(Keyboard):
""" A StandardKeyboard is a keyboard with standard Cherry MX key sizes and spacings. (see: http://www.fentek-ind.com/images/CHERRY_MX_keyswitch.pdf)
"""
def __init__(self):
self.unit_height = ... | Implement parsing in StandardKeyboard class | Implement parsing in StandardKeyboard class
| Python | mit | Cyanogenoid/kb-project | ---
+++
@@ -0,0 +1,35 @@
+import abc
+from decimal import Decimal
+
+from core import Key, Keyboard
+
+
+class StandardKeyboard(Keyboard):
+ """ A StandardKeyboard is a keyboard with standard Cherry MX key sizes and spacings. (see: http://www.fentek-ind.com/images/CHERRY_MX_keyswitch.pdf)
+
+ """
+ def __ini... | |
99b27c037f8072f027ef025d6c4940093ad2c006 | tests/unit/modules/test_win_file.py | tests/unit/modules/test_win_file.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Shane Lee <slee@saltstack.com>`
'''
# Import Python Libs
from __future__ import absolute_import
import os
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
... | Add tests to avoid future regression | Add tests to avoid future regression
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -0,0 +1,58 @@
+# -*- coding: utf-8 -*-
+'''
+:codeauthor: :email:`Shane Lee <slee@saltstack.com>`
+'''
+# Import Python Libs
+from __future__ import absolute_import
+import os
+
+# Import Salt Testing Libs
+from tests.support.mixins import LoaderModuleMockMixin
+from tests.support.unit import TestCase, ski... | |
ed6628411e74f95b5228da0c14f890119d5a8a77 | ch7/profile_items.py | ch7/profile_items.py | '''
Listing 7.7: Profiling data partitioning
'''
import numpy as np
import pyopencl as cl
import pyopencl.array
import utility
NUM_INTS= 4096
NUM_ITEMS = 512
NUM_ITERATIONS = 2000
kernel_src = '''
__kernel void profile_items(__global int4 *x, int num_ints) {
int num_vectors = num_ints/(4 * get_global_size(0));
... | Add example from listing 7.7 | Add example from listing 7.7
| Python | mit | oysstu/pyopencl-in-action | ---
+++
@@ -0,0 +1,68 @@
+'''
+Listing 7.7: Profiling data partitioning
+'''
+
+import numpy as np
+import pyopencl as cl
+import pyopencl.array
+import utility
+
+NUM_INTS= 4096
+NUM_ITEMS = 512
+NUM_ITERATIONS = 2000
+
+kernel_src = '''
+__kernel void profile_items(__global int4 *x, int num_ints) {
+
+ int num_ve... | |
8d8cccf12e19283b57a61f34127f0536940ef34e | docs/examples/ccd.py | docs/examples/ccd.py | """Automatic derivation of CCD equations.
"""
import pickle
from pyspark import SparkConf, SparkContext
from sympy import IndexedBase, Rational
from drudge import PartHoleDrudge, CR, AN
conf = SparkConf().setAppName('CCSD-derivation')
ctx = SparkContext(conf=conf)
dr = PartHoleDrudge(ctx)
p = dr.names
c_ = dr.op[... | Add example script for CCD theory | Add example script for CCD theory
Currently this script may or may not work.
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge | ---
+++
@@ -0,0 +1,42 @@
+"""Automatic derivation of CCD equations.
+
+"""
+
+import pickle
+
+from pyspark import SparkConf, SparkContext
+from sympy import IndexedBase, Rational
+
+from drudge import PartHoleDrudge, CR, AN
+
+conf = SparkConf().setAppName('CCSD-derivation')
+ctx = SparkContext(conf=conf)
+dr = Part... | |
42a92130fc9d6f3358bb03a7ab56cdc5f20eb4d1 | tests/test_config.py | tests/test_config.py | import os
import pytest
from vrun import config
from vrun.compat import ConfigParser
@pytest.mark.parametrize('parts, result', [
(
['simple'],
['simple']
),
(
['multiple', 'simple'],
['multiple', 'simple']
),
(
['with', '"quotes"'],
['with', '"quot... | Add tests for ancillary functions | Add tests for ancillary functions
| Python | isc | bertjwregeer/vrun | ---
+++
@@ -0,0 +1,92 @@
+import os
+
+import pytest
+
+from vrun import config
+from vrun.compat import ConfigParser
+
+
+@pytest.mark.parametrize('parts, result', [
+ (
+ ['simple'],
+ ['simple']
+ ),
+ (
+ ['multiple', 'simple'],
+ ['multiple', 'simple']
+ ),
+ (
+ ... | |
5d990443a3157a1e8061e81d9bb21cfcde6a4d2b | server/rest/postgres_geojson.py | server/rest/postgres_geojson.py | import ast
from girder.api import access
from girder.api.describe import Description
from girder.api.rest import Resource
import psycopg2
# TODO: This will be changed with girder_db_items
def connect_to_gryphon(host="localhost",
port="5432",
user="username",
... | Add the logic to filter views | Add the logic to filter views
| Python | apache-2.0 | Kitware/minerva,Kitware/minerva,Kitware/minerva | ---
+++
@@ -0,0 +1,90 @@
+import ast
+
+from girder.api import access
+from girder.api.describe import Description
+from girder.api.rest import Resource
+
+import psycopg2
+
+# TODO: This will be changed with girder_db_items
+def connect_to_gryphon(host="localhost",
+ port="5432",
+ ... | |
4e132bbbcd8896885eb92b78c594dbd1dcfd9ee8 | zuul/needsrecheck.py | zuul/needsrecheck.py | #!/usr/bin/python
# Copyright 2014 Rackspace Australia
#
# 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... | Add a script to work out what to recheck after a TH failure | Add a script to work out what to recheck after a TH failure
| Python | apache-2.0 | rcbau/hacks,rcbau/hacks,rcbau/hacks | ---
+++
@@ -0,0 +1,56 @@
+#!/usr/bin/python
+
+# Copyright 2014 Rackspace Australia
+#
+# 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
+#
+... | |
6b0eaf125309d89bf9223d5a2da0a938b4e70da5 | feature_extractor.py | feature_extractor.py | import numpy as np
import re
def extract_train():
return extract('dataset/train.txt')
def extract_test():
return extract('dataset/test.txt')
def extract(file):
input_file = open(file)
traindata = input_file.readlines()
features = []
targets = []
for line in traindata:
formatted_l... | Implement feature extractor from data set files | Implement feature extractor from data set files
| Python | mit | trein/quora-classifier | ---
+++
@@ -0,0 +1,24 @@
+import numpy as np
+import re
+
+def extract_train():
+ return extract('dataset/train.txt')
+
+def extract_test():
+ return extract('dataset/test.txt')
+
+def extract(file):
+ input_file = open(file)
+ traindata = input_file.readlines()
+ features = []
+ targets = []
+
+ ... | |
8552542f6e23f886bae467f96e847b00327fa164 | scripts/ci/guideline_check.py | scripts/ci/guideline_check.py | #!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2021 Intel Corporation
import os
import sh
import argparse
import re
from unidiff import PatchSet
if "ZEPHYR_BASE" not in os.environ:
exit("$ZEPHYR_BASE environment variable undefined.")
repository_path = os.environ['ZEPHYR_BASE']
sh_s... | Apply coccinelle scripts in git diffs | ci: Apply coccinelle scripts in git diffs
This scripts receives the same parameter of what_changed.py. And run
coccinelle scripts for code guideline compliance in the given git
commits. e.g: ./guideline_check.py --commits origin/master..HEAD
Signed-off-by: Flavio Ceolin <979b9165500b0741b9d0500e2efd74fc1547bff7@intel... | Python | apache-2.0 | zephyrproject-rtos/zephyr,finikorg/zephyr,zephyrproject-rtos/zephyr,nashif/zephyr,nashif/zephyr,galak/zephyr,finikorg/zephyr,finikorg/zephyr,zephyrproject-rtos/zephyr,Vudentz/zephyr,zephyrproject-rtos/zephyr,galak/zephyr,nashif/zephyr,Vudentz/zephyr,zephyrproject-rtos/zephyr,galak/zephyr,nashif/zephyr,galak/zephyr,Vude... | ---
+++
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+# SPDX-License-Identifier: Apache-2.0
+# Copyright (c) 2021 Intel Corporation
+
+import os
+import sh
+import argparse
+import re
+from unidiff import PatchSet
+
+if "ZEPHYR_BASE" not in os.environ:
+ exit("$ZEPHYR_BASE environment variable undefined.")
+
+reposito... | |
67f13ee9a8cf04a863f867f6468b8b46da99b47a | rules/mpc.py | rules/mpc.py | import xyz
import os
import shutil
class Mpc(xyz.BuildProtocol):
pkg_name = 'mpc'
deps = ['gmp', 'mpfr']
def configure(self, builder, config):
builder.host_lib_configure(config=config)
rules = Mpc()
| Add support for MPC package | Add support for MPC package
| Python | mit | BreakawayConsulting/xyz | ---
+++
@@ -0,0 +1,12 @@
+import xyz
+import os
+import shutil
+
+class Mpc(xyz.BuildProtocol):
+ pkg_name = 'mpc'
+ deps = ['gmp', 'mpfr']
+
+ def configure(self, builder, config):
+ builder.host_lib_configure(config=config)
+
+rules = Mpc() | |
abe11541d94a185456a79286bb9e5800c44305c7 | vote.py | vote.py | #!/usr/bin/python
import commands
counter =0
while counter <=100 :
#alocate new Elastic IP, and get the allocation id
(stauts,output) = commands.getstatusoutput("aws ec2 allocate-address")
allocation_id = output.split('\t') [0]
#associate the allocated ip to indicated ec2 instance
(status,output) = commands.... | Add one script to use AWS CLI to allocate/associate/release EIP automatically. | Add one script to use AWS CLI to allocate/associate/release EIP automatically.
| Python | mit | yuecong/tools,yuecong/tools,yuecong/tools,yuecong/tools | ---
+++
@@ -0,0 +1,19 @@
+#!/usr/bin/python
+import commands
+counter =0
+while counter <=100 :
+ #alocate new Elastic IP, and get the allocation id
+ (stauts,output) = commands.getstatusoutput("aws ec2 allocate-address")
+ allocation_id = output.split('\t') [0]
+
+ #associate the allocated ip to indicated ec2 in... | |
8f322fd8dab9447721e6e1bfbb1d8776f66b8740 | stats_generator.py | stats_generator.py | #!/usr/bin/env python
from datetime import date, timedelta
import redis
def perdelta(start, end, delta):
curr = start
while curr < end:
yield curr
curr += delta
r = redis.Redis('localhost', 6334, db=1)
for result in perdelta(date(2015, 03, 01), date(2015, 12, 12), timedelta(days=1)):
va... | Add a script to generate stats | Add a script to generate stats
| Python | agpl-3.0 | CIRCL/url-abuse,CIRCL/url-abuse,CIRCL/url-abuse,CIRCL/url-abuse | ---
+++
@@ -0,0 +1,17 @@
+#!/usr/bin/env python
+
+from datetime import date, timedelta
+import redis
+
+
+def perdelta(start, end, delta):
+ curr = start
+ while curr < end:
+ yield curr
+ curr += delta
+
+r = redis.Redis('localhost', 6334, db=1)
+
+for result in perdelta(date(2015, 03, 01), date... | |
8baf08fd22a0e66734e927607aaab9b1a0bdd7f4 | time-complexity/time_complexity.py | time-complexity/time_complexity.py | #Comparison of different time complexities.
#####################
#constant time - O(1)
#####################
def constant(n):
result = n * n
return result
##############################
#Logarithmic time - O(log(n))
##############################
def logarithmic(n):
result = 0
while n > 1:
... | Add time-complexity: basic python examples | Add time-complexity: basic python examples
| 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,42 @@
+#Comparison of different time complexities.
+
+#####################
+#constant time - O(1)
+#####################
+def constant(n):
+ result = n * n
+ return result
+
+
+##############################
+#Logarithmic time - O(log(n))
+##############################
+
+def logarithmic(n)... | |
bc724fca4be4efa3cdcf78f9efb2da88e3dcac2c | tests/gengraphs.py | tests/gengraphs.py | import random
if __name__ == '__main__':
V, E = 10, 50
path = 'directed_{}_{}.yolo'.format(V, E)
title = 'YOLO_{}_{}'.format(V, E)
with open(path, 'w') as f:
f.write(title + '\n')
f.write(str(V) + '\n')
for _ in xrange(V):
rname = ''.join(map(chr, rando... | Add a random directed graphs generator | Add a random directed graphs generator
| Python | unlicense | Thooms/yolo-graphs,Thooms/yolo-graphs,Thooms/yolo-graphs | ---
+++
@@ -0,0 +1,25 @@
+import random
+
+if __name__ == '__main__':
+ V, E = 10, 50
+ path = 'directed_{}_{}.yolo'.format(V, E)
+ title = 'YOLO_{}_{}'.format(V, E)
+
+ with open(path, 'w') as f:
+ f.write(title + '\n')
+
+ f.write(str(V) + '\n')
+ for _ in xrange(V):
+ ... | |
5f910c64dcea524c1e5c887e1e03cf98dcb7d885 | scripts/migrate.py | scripts/migrate.py | import configparser
import os
import psycopg2.extras
SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), "../settings.ini")
config = configparser.ConfigParser()
config.read(SETTINGS_FILE_PATH)
username = config["DATABASE"]["Username"]
password = config["DATABASE"]["Password"]
name = config["DATABASE"]["Dat... | Add user-topic maps migration script | Add user-topic maps migration script
| Python | mit | brettkromkamp/topic_db | ---
+++
@@ -0,0 +1,29 @@
+import configparser
+import os
+
+import psycopg2.extras
+
+SETTINGS_FILE_PATH = os.path.join(os.path.dirname(__file__), "../settings.ini")
+
+config = configparser.ConfigParser()
+config.read(SETTINGS_FILE_PATH)
+
+username = config["DATABASE"]["Username"]
+password = config["DATABASE"]["Pa... | |
5a1446e6bccf6b0f89f4c616df7e41072f20b160 | scratchpad/map_test.py | scratchpad/map_test.py | #!/usr/bin/env python3
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
def show_value(value):
print(map_range(value, 650, 978, 12, 18))
show_value(650)
show_value(978)
show_value(0)
show_va... | Add sanity check for range map function | Add sanity check for range map function
| Python | mit | gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,thelonious/g2x | ---
+++
@@ -0,0 +1,15 @@
+#!/usr/bin/env python3
+
+def map_range(x, in_min, in_max, out_min, out_max):
+ out_delta = out_max - out_min
+ in_delta = in_max - in_min
+
+ return (x - in_min) * out_delta / in_delta + out_min
+
+def show_value(value):
+ print(map_range(value, 650, 978, 12, 18))
+
+show_value(650... | |
07801e9ae8c90f9832f5436a22b0485c2312b78b | daphne/server.py | daphne/server.py | import logging
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
logger = logging.getLogger(__name__)
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True, action_logger=None):
self.channel_layer = channel_layer
... | import logging
import time
from twisted.internet import reactor
from .http_protocol import HTTPFactory
logger = logging.getLogger(__name__)
class Server(object):
def __init__(self, channel_layer, host="127.0.0.1", port=8000, signal_handlers=True, action_logger=None):
self.channel_layer = channel_layer
... | Make daphne serving thread idle better | Make daphne serving thread idle better
| Python | bsd-3-clause | django/daphne,maikhoepfel/daphne | ---
+++
@@ -27,15 +27,18 @@
Run in a separate thread; reads messages from the backend.
"""
channels = self.factory.reply_channels()
+ delay = 0.3
# Quit if reactor is stopping
if not reactor.running:
logging.debug("Backend reader quitting due to reactor... |
2c025094ef9308ba2b1a5bfee224ddcaabbf8438 | dbbot.py | dbbot.py | #!/usr/bin/env python
import sys
import optparse
import sqlite3
from datetime import datetime
from os.path import abspath, exists, join
from xml.etree import ElementTree
def main():
parser = _get_option_parser()
options = _get_validated_options(parser)
xml_tree = _get_xml_tree(options, parser)
root_a... | Insert test run results to sqlite3 database | Insert test run results to sqlite3 database
| Python | apache-2.0 | robotframework/DbBot | ---
+++
@@ -0,0 +1,92 @@
+#!/usr/bin/env python
+
+import sys
+import optparse
+import sqlite3
+from datetime import datetime
+from os.path import abspath, exists, join
+from xml.etree import ElementTree
+
+
+def main():
+ parser = _get_option_parser()
+ options = _get_validated_options(parser)
+ xml_tree = ... | |
deb816d30c5accaa8496c6e8f6f491e0a25aefc7 | erpnext/patches/remove_duplicate_table_mapper_detail.py | erpnext/patches/remove_duplicate_table_mapper_detail.py | """
Removes duplicate entries created in
"""
import webnotes
def execute():
res = webnotes.conn.sql("""\
SELECT a.name
FROM
`tabTable Mapper Detail` a,
`tabTable Mapper Detail` b
WHERE
a.parent = b.parent AND
a.from_table = b.from_table AND
a.to_table = b.to_table AND
a.from_field = b.from_fi... | Patch to remove duplicate entries created due to change in validation_logic in Table Mapper Detail for the following doctypes: * Delivery Note-Receivable Voucher * Purchase Order-Purchase Voucher * Sales Order-Receivable Voucher | Patch to remove duplicate entries created due to change in
validation_logic in Table Mapper Detail for the following doctypes:
* Delivery Note-Receivable Voucher
* Purchase Order-Purchase Voucher
* Sales Order-Receivable Voucher
| Python | agpl-3.0 | gangadhar-kadam/verve_erp,anandpdoshi/erpnext,indictranstech/phrerp,MartinEnder/erpnext-de,gangadharkadam/sher,saurabh6790/omni-apps,indictranstech/vestasi-erpnext,hatwar/focal-erpnext,gangadhar-kadam/latestchurcherp,gmarke/erpnext,hatwar/Das_erpnext,hatwar/focal-erpnext,gangadharkadam/johnerp,gangadharkadam/saloon_erp... | ---
+++
@@ -0,0 +1,22 @@
+"""
+ Removes duplicate entries created in
+"""
+import webnotes
+def execute():
+ res = webnotes.conn.sql("""\
+ SELECT a.name
+ FROM
+ `tabTable Mapper Detail` a,
+ `tabTable Mapper Detail` b
+ WHERE
+ a.parent = b.parent AND
+ a.from_table = b.from_table AND
+ a.to_table = b... | |
8f246f28809025ad18f4910d75f703d37ec31b11 | examples/write_once.py | examples/write_once.py | """An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
import hug
import requests
@hug.local()
@hug.cli()
@hug.get()
def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
"""Returns the top post from the provided section"""
content = requests.g... | Add example of a write once API | Add example of a write once API
| Python | mit | MuhammadAlkarouri/hug,timothycrosley/hug,timothycrosley/hug,MuhammadAlkarouri/hug,MuhammadAlkarouri/hug,timothycrosley/hug | ---
+++
@@ -0,0 +1,13 @@
+"""An example of writing an API to scrapper hacker news once, and then enabling usage everywhere"""
+import hug
+import requests
+
+
+@hug.local()
+@hug.cli()
+@hug.get()
+def top_post(section:hug.types.one_of(('news', 'newest', 'show'))='news'):
+ """Returns the top post from the provide... | |
4a9cb81075a5b8821cbc81ebee635db1ebcc769d | experiments/someimp.py | experiments/someimp.py | #!/usr/bin/env python3
import threading
from time import sleep
def mymap(func, elements):
return [func(ele) for ele in elements]
assert mymap(lambda x: x*x, [1, 2, 3, 5]) == [1, 4, 9, 25]
def dbounce(func, wait):
timeout = None
def exec():
nonlocal timeout
if timeout:
timeou... | Implement JS functions in Python | Implement JS functions in Python
| Python | unlicense | fleith/coding,fleith/coding,fleith/coding | ---
+++
@@ -0,0 +1,31 @@
+#!/usr/bin/env python3
+
+import threading
+from time import sleep
+
+def mymap(func, elements):
+ return [func(ele) for ele in elements]
+
+assert mymap(lambda x: x*x, [1, 2, 3, 5]) == [1, 4, 9, 25]
+
+
+def dbounce(func, wait):
+ timeout = None
+ def exec():
+ nonlocal time... | |
c661d22facbc35b633213b1591bd3aef676ab634 | tests/test_spinsolve.py | tests/test_spinsolve.py | """ Tests for the fileio.spinsolve submodule """
import nmrglue as ng
from pathlib import Path
from setup import DATA_DIR
def test_acqu():
""" read nmr_fid.dx """
dic, data = ng.spinsolve.read(Path(DATA_DIR) / "spinsolve" / "ethanol", "nmr_fid.dx")
assert dic["acqu"]["Sample"] == "EtOH"
assert dic[... | Add test file for ng.fileio.spinsolve | Add test file for ng.fileio.spinsolve
| Python | bsd-3-clause | kaustubhmote/nmrglue,jjhelmus/nmrglue,kaustubhmote/nmrglue,jjhelmus/nmrglue | ---
+++
@@ -0,0 +1,57 @@
+""" Tests for the fileio.spinsolve submodule """
+
+
+import nmrglue as ng
+from pathlib import Path
+
+from setup import DATA_DIR
+
+
+def test_acqu():
+ """ read nmr_fid.dx """
+ dic, data = ng.spinsolve.read(Path(DATA_DIR) / "spinsolve" / "ethanol", "nmr_fid.dx")
+ assert dic["ac... | |
5356001d4244e67d6b70f0d4715b153b7d851293 | ci/run_all_spiders.py | ci/run_all_spiders.py | from scrapy.utils.project import get_project_settings
from scrapy.crawler import CrawlerProcess
if __name__ == '__main__':
settings = get_project_settings()
settings.set('LOG_FILE', 'all_spiders.log')
settings.set('LOG_LEVEL', 'WARN')
settings.set('TELNETCONSOLE_ENABLED', False)
settings.set('FEE... | Add script that runs all the spiders | Add script that runs all the spiders
| Python | mit | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | ---
+++
@@ -0,0 +1,20 @@
+from scrapy.utils.project import get_project_settings
+from scrapy.crawler import CrawlerProcess
+
+
+if __name__ == '__main__':
+ settings = get_project_settings()
+
+ settings.set('LOG_FILE', 'all_spiders.log')
+ settings.set('LOG_LEVEL', 'WARN')
+ settings.set('TELNETCONSOLE_E... | |
dbaf49af9553257c63f3374103ccdc1e6c40f20c | test/integration/ggrc_basic_permissions/test_undeleteable.py | test/integration/ggrc_basic_permissions/test_undeleteable.py | # Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: andraz@reciprocitylabs.com
# Maintained By: andraz@reciprocitylabs.com
"""
Test that some objects cannot be deleted by anyone.
"""
from integratio... | Add a test for objects that cannot be deleted | Add a test for objects that cannot be deleted
| Python | apache-2.0 | josthkko/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,j0gurt/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,andrei-karaliona... | ---
+++
@@ -0,0 +1,49 @@
+# Copyright (C) 2016 Google Inc., authors, and contributors <see AUTHORS file>
+# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
+# Created By: andraz@reciprocitylabs.com
+# Maintained By: andraz@reciprocitylabs.com
+
+"""
+Test that some objects cannot be delet... | |
8a394794c5c663ef11ef9e44df5448d00c859357 | interface/plugin/farmanager/01autoguid/__init__.py | interface/plugin/farmanager/01autoguid/__init__.py | """
Need to change all GUIDs for your every new plugin, is daunting, so let's
generate them from strings that are unique for plugins.
Low-level Far Manager API is here:
* https://api.farmanager.com/en/exported_functions/getglobalinfow.html
"""
# --- utility functions ---
import hashlib
def getuuid(data):
... | Add 01autoguid/ plugin with own GUIDs autogenerated | Add 01autoguid/ plugin with own GUIDs autogenerated
| Python | unlicense | techtonik/discovery,techtonik/discovery,techtonik/discovery | ---
+++
@@ -0,0 +1,40 @@
+"""
+Need to change all GUIDs for your every new plugin, is daunting, so let's
+generate them from strings that are unique for plugins.
+
+
+Low-level Far Manager API is here:
+
+ * https://api.farmanager.com/en/exported_functions/getglobalinfow.html
+
+"""
+
+# --- utility functions ---
+... | |
e0aeb2ebc1bb817ae59bc8b0550ae8b5fecbeba3 | chipy_org/apps/meetings/feeds.py | chipy_org/apps/meetings/feeds.py | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... | from django_ical.views import ICalFeed
from .models import Meeting
from datetime import timedelta
class MeetingFeed(ICalFeed):
"""
A iCal feed for meetings
"""
product_id = '-//chipy.org//Meeting//EN'
timezone = 'CST'
def items(self):
return Meeting.objects.order_by('-when').all()
... | Use unicode for ical description | Use unicode for ical description | Python | mit | bharathelangovan/chipy.org,tanyaschlusser/chipy.org,bharathelangovan/chipy.org,brianray/chipy.org,agfor/chipy.org,chicagopython/chipy.org,chicagopython/chipy.org,brianray/chipy.org,tanyaschlusser/chipy.org,brianray/chipy.org,agfor/chipy.org,agfor/chipy.org,tanyaschlusser/chipy.org,chicagopython/chipy.org,bharathelangov... | ---
+++
@@ -15,7 +15,7 @@
def item_description(self, item):
description = 'RSVP at http://chipy.org\n\n'
for topic in item.topics.all():
- description += '{title} by {speaker}\n{description}\n\n'.format(
+ description += u'{title} by {speaker}\n{description}\n\n'.format(
... |
bd23a87d28a1d0a1f82b0fd17abfababafba0dc7 | viaduct/api/page.py | viaduct/api/page.py | from flask.ext.login import current_user
from viaduct.models.page import Page, PagePermission, PageRevision
from viaduct import db
from flask import request, url_for, render_template
from viaduct.models.group import Group
class PageAPI:
@staticmethod
def remove_page(path):
page = Page.query.filter... | from flask.ext.login import current_user
from viaduct.models.page import Page, PageRevision
from viaduct import db
from flask import render_template
class PageAPI:
@staticmethod
def remove_page(path):
page = Page.query.filter(Page.path == path).first()
if not page:
return False
... | Remove footer print and make file PEP8 compliant | Remove footer print and make file PEP8 compliant
| Python | mit | viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct | ---
+++
@@ -1,16 +1,15 @@
from flask.ext.login import current_user
-from viaduct.models.page import Page, PagePermission, PageRevision
+from viaduct.models.page import Page, PageRevision
from viaduct import db
-from flask import request, url_for, render_template
+from flask import render_template
-from viad... |
86127511bfc0521969f0d78264f01b91695e1309 | data_api/migrations/0018_auto_20151114_2159.py | data_api/migrations/0018_auto_20151114_2159.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('auth', '0006_require_contenttypes_0002'),
('data_api', '0017_blob_mime_type'),
]
operations = [
migrations.RemoveFie... | Change local_computer group to foreign key from m2m | Change local_computer group to foreign key from m2m
| Python | mit | bwootton/Dator,bwootton/Dator,bwootton/Dator,bwootton/Dator | ---
+++
@@ -0,0 +1,24 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('auth', '0006_require_contenttypes_0002'),
+ ('data_api', '0017_blob_mime_type'),
+ ]
+
+ op... | |
f22f3953783052734c807639307cf13731323ee5 | rsk_mind/datasource/datasource_svmlight.py | rsk_mind/datasource/datasource_svmlight.py | from datasource import Datasource
from ..dataset import Dataset
import os
class SVMLightDatasource(Datasource):
def __init__(self, path):
super(SVMLightDatasource, self).__init__(path)
def read(self):
# NOTE: svmlight format does not include
# names for features, it only uses indexes... | Add support for svmlight format | Add support for svmlight format
This commit adds a Datasource that can read
a file in svmlight format and can write a
Dataset object in an svmlight format file.
| Python | mit | rsk-mind/rsk-mind-framework | ---
+++
@@ -0,0 +1,72 @@
+from datasource import Datasource
+from ..dataset import Dataset
+import os
+
+class SVMLightDatasource(Datasource):
+
+
+ def __init__(self, path):
+ super(SVMLightDatasource, self).__init__(path)
+
+ def read(self):
+ # NOTE: svmlight format does not include
+ # ... | |
f9140bf301c4ac3d159a8ff3383d8c0ab007de8c | search/management/commands/remove_index.py | search/management/commands/remove_index.py | from django.core.management import BaseCommand
from search.search_utils import ElasticAPI
class Command(BaseCommand):
def handle(self, *args, **kwargs):
api = ElasticAPI()
api.delete_index()
| Add remove index management command | Add remove index management command
| Python | mit | MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api | ---
+++
@@ -0,0 +1,8 @@
+from django.core.management import BaseCommand
+from search.search_utils import ElasticAPI
+
+
+class Command(BaseCommand):
+ def handle(self, *args, **kwargs):
+ api = ElasticAPI()
+ api.delete_index() | |
4b6756bd8305190a5d1dc1d2e8e9a0b94d5baa40 | tests/test_grid.py | tests/test_grid.py | import pytest
from aimaPy.grid import *
compare = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)])
def test_distance():
assert distance((1, 2), (5, 5)) == 5.0
def test_distance_squared():
assert distance_squared((1, 2), (5, 5)) == 25.0
def test_clip():
list_ = [clip(x, 0, 1) for x in [-... | import pytest
from aimaPy.grid import *
compare_list = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)])
def test_distance():
assert distance((1, 2), (5, 5)) == 5.0
def test_distance_squared():
assert distance_squared((1, 2), (5, 5)) == 25.0
def test_clip():
list_ = [clip(x, 0, 1) for x ... | Change name of compare function in test grid | Change name of compare function in test grid
| Python | mit | phaller0513/aima-python,AWPorter/aima-python,grantvk/aima-python,SeanCameronConklin/aima-python,SeanCameronConklin/aima-python,SnShine/aima-python,AWPorter/aima-python,chandlercr/aima-python,NolanBecker/aima-python,jottenlips/aima-python,WmHHooper/aima-python,grantvk/aima-python,AmberJBlue/aima-python,jottenlips/aima-p... | ---
+++
@@ -1,7 +1,7 @@
import pytest
from aimaPy.grid import *
-compare = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)])
+compare_list = lambda x, y: all([elm_x == y[i] for i, elm_x in enumerate(x)])
def test_distance():
@@ -16,7 +16,7 @@
list_ = [clip(x, 0, 1) for x in [-1, 0.5, 10]]
... |
13a92d18816de9aea90094422788532da05fc475 | tests/test_list.py | tests/test_list.py | """ Test list packing and unpacking. """
import xcffib
import struct
class TestList(object):
def test_struct_pack_uses_List(self):
# suppose we have a list of ints...
ints = struct.pack("=IIII", *range(4))
# Unpacker wants a cffi.cdata
cffi_ints = xcffib.bytes_to_cdata(ints)
... | Test that list packing is idempotent | Test that list packing is idempotent
| Python | apache-2.0 | tych0/xcffib | ---
+++
@@ -0,0 +1,19 @@
+""" Test list packing and unpacking. """
+
+import xcffib
+import struct
+
+class TestList(object):
+
+ def test_struct_pack_uses_List(self):
+ # suppose we have a list of ints...
+ ints = struct.pack("=IIII", *range(4))
+
+ # Unpacker wants a cffi.cdata
+ cffi... | |
642858629b118789ce6cd175bed0b19569cd0152 | linguist/managers.py | linguist/managers.py | # -*- coding: utf-8 -*-
import functools
from django.db import models
from django.db.query import QuerySet
from .models import Translation
from .mixins import LinguistMixin
from .utils.i18n import get_cache_key
def get_value_as_list(value):
"""
Ensure the given returned value is a list.
"""
if not i... | Add LinguistManager with with_translations() method. | Add LinguistManager with with_translations() method.
| Python | mit | ulule/django-linguist | ---
+++
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+import functools
+
+from django.db import models
+from django.db.query import QuerySet
+
+from .models import Translation
+from .mixins import LinguistMixin
+from .utils.i18n import get_cache_key
+
+
+def get_value_as_list(value):
+ """
+ Ensure the given retur... | |
5f7a694c72821110091d6aff5ee854681137bdcc | tests/testuser.py | tests/testuser.py | import unittest
from steam import user
class ProfileTestCase(unittest.TestCase):
VALID_ID64 = 76561198014028523
INVALID_ID64 = 123
# This is weird but there should be no reason that it's invalid
# So Valve, if you see this, be gewd guys and make 33 bit (condensed)
# IDs work properly. Or at least p... | Add initial steam.user test fixtures | Add initial steam.user test fixtures
| Python | isc | miedzinski/steamodd,Lagg/steamodd | ---
+++
@@ -0,0 +1,44 @@
+import unittest
+from steam import user
+
+class ProfileTestCase(unittest.TestCase):
+ VALID_ID64 = 76561198014028523
+ INVALID_ID64 = 123
+ # This is weird but there should be no reason that it's invalid
+ # So Valve, if you see this, be gewd guys and make 33 bit (condensed)
+ ... | |
3750cc97ac69c160f908b9e47b52ed831c8d9170 | ka_find_missing_descs.py | ka_find_missing_descs.py | #!/usr/bin/env python3
from kapi import *
import utils
import argparse, sys
import time
import json
def read_cmd():
"""Reading command line options."""
desc = "Program for finding KA content without descriptions."
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-s','--subject', dest... | Add script for finding missing descriptions in KA content | Add script for finding missing descriptions in KA content
| Python | mit | danielhollas/AmaraUpload,danielhollas/AmaraUpload | ---
+++
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+from kapi import *
+import utils
+import argparse, sys
+import time
+import json
+
+def read_cmd():
+ """Reading command line options."""
+ desc = "Program for finding KA content without descriptions."
+ parser = argparse.ArgumentParser(description=desc)
+ par... | |
8038040d1132de7648a3795a32605da1213bb741 | main.py | main.py | import pyb
LEDS = [pyb.LED(i) for i in range(1,5)]
while True:
for led in LEDS:
led.toggle()
pyb.delay(100)
| Add basic blinking LED script | Add basic blinking LED script
| Python | mit | Tyler314/led_matrix,Tyler314/led_matrix | ---
+++
@@ -0,0 +1,8 @@
+import pyb
+
+LEDS = [pyb.LED(i) for i in range(1,5)]
+
+while True:
+ for led in LEDS:
+ led.toggle()
+ pyb.delay(100) | |
364014ecc42150f8ad5959ebcdcc94ae07f38c01 | tests/test_commands.py | tests/test_commands.py | from pim.commands.init import _defaults, _make_package
from pim.commands.install import install
from pim.commands.uninstall import uninstall
from click.testing import CliRunner
def _create_test_package():
d = _defaults()
d['description'] = 'test package'
_make_package(d, True)
return d
def test_insta... | Create test package and round trip install/uninstall | TST: Create test package and round trip install/uninstall
| Python | mit | freeman-lab/pim | ---
+++
@@ -0,0 +1,27 @@
+from pim.commands.init import _defaults, _make_package
+from pim.commands.install import install
+from pim.commands.uninstall import uninstall
+
+from click.testing import CliRunner
+
+def _create_test_package():
+ d = _defaults()
+ d['description'] = 'test package'
+ _make_package(... | |
57051d3e59a4664a536588c19ae0581cb92f1350 | timed/redmine/admin.py | timed/redmine/admin.py | from django.contrib import admin
from timed.projects.admin import ProjectAdmin
from timed.projects.models import Project
from timed_adfinis.redmine.models import RedmineProject
admin.site.unregister(Project)
class RedmineProjectInline(admin.StackedInline):
model = RedmineProject
@admin.register(Project)
class... | Add RedmineProject as inline of ProjectAdmin | Add RedmineProject as inline of ProjectAdmin
| Python | agpl-3.0 | adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend,adfinis-sygroup/timed-backend | ---
+++
@@ -0,0 +1,18 @@
+from django.contrib import admin
+
+from timed.projects.admin import ProjectAdmin
+from timed.projects.models import Project
+from timed_adfinis.redmine.models import RedmineProject
+
+admin.site.unregister(Project)
+
+
+class RedmineProjectInline(admin.StackedInline):
+ model = RedminePr... | |
520dc3ecf931845beab6a4e0e9343633bbd22c73 | main.py | main.py | from numpy import array
from time import sleep
class GameOfLife(object):
def __init__(self, n, starting=[]):
self.game = array([[0]*n]*n)
self.size = n
for i, j in starting:
self.game[i, j] = 1
def get_square_pos(self, i, j):
im = i - 1
iM = i + 2
... | Create the Game class which has the rules implemented, can go a step forward and can draw itself. | Create the Game class which has the rules implemented, can
go a step forward and can draw itself. | Python | mit | nightmarebadger/conways-game-of-life-python | ---
+++
@@ -0,0 +1,85 @@
+from numpy import array
+from time import sleep
+
+
+class GameOfLife(object):
+ def __init__(self, n, starting=[]):
+ self.game = array([[0]*n]*n)
+ self.size = n
+ for i, j in starting:
+ self.game[i, j] = 1
+
+ def get_square_pos(self, i, j):
+ ... | |
b6c1e11682dea0acd6b78f5fc0dfb5220eb5db70 | tools/xmldir2tree.py | tools/xmldir2tree.py | #!/usr/bin/env python3
from collections import OrderedDict
try:
from lxml import etree
except:
from xml.etree import ElementTree as etree
class Node(object):
def __init__(self, name=None, depth=0):
self.name = name
self.depth = depth
self.sources = set()
self.children = Ord... | Add script calculating the tree structure of a set of XML files | Add script calculating the tree structure of a set of XML files
| Python | cc0-1.0 | Kungbib/datalab,Kungbib/datalab | ---
+++
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+from collections import OrderedDict
+try:
+ from lxml import etree
+except:
+ from xml.etree import ElementTree as etree
+
+
+class Node(object):
+ def __init__(self, name=None, depth=0):
+ self.name = name
+ self.depth = depth
+ self.sou... | |
40dd0738490a8fe27067b19e0539533a55c3b71c | physicalproperty/__init__.py | physicalproperty/__init__.py | # -*- coding: utf-8 -*-
"""
Base Library (:mod:`physicalproperty`)
======================================
.. currentmodule:: physicalproperty
"""
from physicalproperty import PhysicalProperty
__version__ = "0.0.1"
| Add init for multi-file module | Add init for multi-file module
| Python | mit | jrsmith3/physicalproperty,jrsmith3/tec,jrsmith3/ibei,jrsmith3/tec,jrsmith3/physicalproperty | ---
+++
@@ -0,0 +1,11 @@
+# -*- coding: utf-8 -*-
+"""
+Base Library (:mod:`physicalproperty`)
+======================================
+
+.. currentmodule:: physicalproperty
+"""
+
+from physicalproperty import PhysicalProperty
+
+__version__ = "0.0.1" | |
3cc9c4a72a863b12a298cc7b3d8927a22d9149d2 | agent.py | agent.py | import json
import logbook
from piper.db.core import LazyDatabaseMixin
from piper.utils import oneshot
class Agent(LazyDatabaseMixin):
"""
Listener endpoint that recieves requests and executes them
"""
_properties = None
FIELDS_TO_DB = (
# Main fields
'id',
'fqdn',
... | Add basic skeleton for Agent() | Add basic skeleton for Agent()
| Python | mit | thiderman/piper | ---
+++
@@ -0,0 +1,66 @@
+import json
+import logbook
+
+from piper.db.core import LazyDatabaseMixin
+from piper.utils import oneshot
+
+
+class Agent(LazyDatabaseMixin):
+ """
+ Listener endpoint that recieves requests and executes them
+
+ """
+
+ _properties = None
+
+ FIELDS_TO_DB = (
+ # Ma... | |
c3617a33e4829b65cca8f19a55caa4093e737405 | local.py | local.py | #!/usr/bin/python
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('archvyrt', 'console_scripts', 'archvyrt')()
)
| Add simple script to run archvyrt without being installed. | Add simple script to run archvyrt without being installed.
| Python | mit | andrekeller/archvyrt | ---
+++
@@ -0,0 +1,8 @@
+#!/usr/bin/python
+import sys
+from pkg_resources import load_entry_point
+
+if __name__ == '__main__':
+ sys.exit(
+ load_entry_point('archvyrt', 'console_scripts', 'archvyrt')()
+ ) | |
02903171a6aeec4089e028bd4dccfb2e6acd5fb1 | plumeria/plugins/rubygems.py | plumeria/plugins/rubygems.py | from plumeria import config
from plumeria.command import commands, CommandError
from plumeria.util import http
from plumeria.util.ratelimit import rate_limit
api_key = config.create("rubygems", "key",
fallback="",
comment="An API key from RubyGems.org (make an account, e... | Add RubyGems plugin to search packages. | Add RubyGems plugin to search packages.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria | ---
+++
@@ -0,0 +1,47 @@
+from plumeria import config
+from plumeria.command import commands, CommandError
+from plumeria.util import http
+from plumeria.util.ratelimit import rate_limit
+
+api_key = config.create("rubygems", "key",
+ fallback="",
+ comment="An API key fr... | |
e0a43a72af49e05156131684cadcba9889bc709f | graystruct/tests/test_handler.py | graystruct/tests/test_handler.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015 Simon Jagoe
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the 3-clause BSD license. See the LICENSE.txt file for details.
from __future__ import absolute_import
import json
import logging
import os
import unittest
import zlib... | Add tests for standard GELFHandler | Add tests for standard GELFHandler
| Python | bsd-3-clause | enthought/graystruct | ---
+++
@@ -0,0 +1,67 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2015 Simon Jagoe
+# All rights reserved.
+#
+# This software may be modified and distributed under the terms
+# of the 3-clause BSD license. See the LICENSE.txt file for details.
+from __future__ import absolute_import
+
+import json
+import logging
... | |
bd89051aa27bdd5dfb6667978f8245d0c76fa928 | s4v3.py | s4v3.py | from s4v2 import *
import openpyxl
from openpyxl import Workbook
from openpyxl.writer.excel import ExcelWriter
from openpyxl.cell import get_column_letter
def save_spreadsheet(filename, data_sample):
wb = Workbook() # shortcut for typing Workbook function
ws = wb.active # shortcut for typing active workbook function... | Create function to save data to Microsoft Excel file | Create function to save data to Microsoft Excel file
| Python | mit | alexmilesyounger/ds_basics | ---
+++
@@ -0,0 +1,21 @@
+from s4v2 import *
+import openpyxl
+from openpyxl import Workbook
+from openpyxl.writer.excel import ExcelWriter
+from openpyxl.cell import get_column_letter
+
+def save_spreadsheet(filename, data_sample):
+ wb = Workbook() # shortcut for typing Workbook function
+ ws = wb.active # shortcut... | |
a929cb4981cde475905b422d70f37e6647875c17 | is_json.py | is_json.py | #!/usr/bin/env python
"""A function and script for determining whether a file contains valid JSON."""
import json
def is_json(json_file):
"""Returns True if a file is valid JSON."""
try:
with open(json_file, 'r') as fp:
json.load(fp)
except ValueError:
return False
except I... | Add simple Python JSON validator | Add simple Python JSON validator
| Python | mit | mdpiper/wunderkammer,mdpiper/wunderkammer,mdpiper/wunderkammer,mdpiper/wunderkammer | ---
+++
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+"""A function and script for determining whether a file contains valid JSON."""
+import json
+
+
+def is_json(json_file):
+ """Returns True if a file is valid JSON."""
+ try:
+ with open(json_file, 'r') as fp:
+ json.load(fp)
+ except ValueEr... | |
c11eab6c1b9b707510b32ee54d684720f9f397ad | choosealicense/test/test_generate.py | choosealicense/test/test_generate.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for the `license generate` function
"""
from click.testing import CliRunner
from choosealicense.main import (generate, LICENSE_WITH_CONTEXT,
get_default_context)
def test_generate_license():
all_the_licenses = ('agpl-3... | Add test for `license generate` function | Add test for `license generate` function
| Python | mit | lord63/choosealicense-cli | ---
+++
@@ -0,0 +1,42 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+ Tests for the `license generate` function
+"""
+
+from click.testing import CliRunner
+
+from choosealicense.main import (generate, LICENSE_WITH_CONTEXT,
+ get_default_context)
+
+
+def test_generate_l... | |
8c972ebd2a93a9516230185118941995a921b1c6 | server/app/handlers.py | server/app/handlers.py | import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
b... | import os
import aiohttp
import json
from aiohttp import web
from .consts import KUDAGO_API_BASE_URL, CLIENT_DIR
async def serve_api(request):
url = '{}/{}/?{}'.format(
KUDAGO_API_BASE_URL,
request.match_info['path'],
request.query_string,
)
response = await aiohttp.get(url)
b... | Add content type to API responses | Add content type to API responses
It doesn’t make much of a difference, but it’s the nice thing to do
| Python | mit | despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics | ---
+++
@@ -21,7 +21,10 @@
if value:
body[field] = value.replace(KUDAGO_API_BASE_URL, '/api')
- return web.Response(body=json.dumps(body).encode('utf-8'))
+ return web.Response(
+ text=json.dumps(body),
+ content_type='application/json'
+ )
async def serve_c... |
48c227c263abc046f1b293ebc5864c229154cde4 | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '197fe67fee1e4d867c76264065b2eb80b9dbd3a0'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'bb664e4665851fe923ce904e620ba43d8d010ba5'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Upgrade libchromium for the accelerator fix. | Upgrade libchromium for the accelerator fix.
| Python | mit | trigrass2/electron,Rokt33r/electron,sky7sea/electron,Faiz7412/electron,pandoraui/electron,Ivshti/electron,vHanda/electron,bright-sparks/electron,baiwyc119/electron,fireball-x/atom-shell,mattotodd/electron,tincan24/electron,dkfiresky/electron,voidbridge/electron,bright-sparks/electron,brenca/electron,ianscrivener/electr... | ---
+++
@@ -5,7 +5,7 @@
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
-LIBCHROMIUMCONTENT_COMMIT = '197fe67fee1e4d867c76264065b2eb80b9dbd3a0'
+LIBCHROMIUMCONTENT_COMMIT = 'bb664e4665851fe923ce904e620ba43d8d010ba5'
ARCH = {
'cygwin': '32bit', |
3f4113fa5f58641af25077381e39ba3f4d74355a | weasyprint/stacking.py | weasyprint/stacking.py | # coding: utf8
"""
weasyprint.stacking
-------------------
:copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
from .formatting_structure import boxes
def establishes_stacking_conte... | Add a StackingContext in preparation for z-index drawing. | Add a StackingContext in preparation for z-index drawing.
| Python | bsd-3-clause | andrewleech/WeasyPrint,andrewleech/WeasyPrint,Kozea/WeasyPrint,marclaporte/WeasyPrint,jasco/WeasyPrint,jasco/WeasyPrint,prepare/TestWeasyPrint,prepare/TestWeasyPrint,Kozea/WeasyPrint,marclaporte/WeasyPrint | ---
+++
@@ -0,0 +1,68 @@
+# coding: utf8
+"""
+ weasyprint.stacking
+ -------------------
+
+ :copyright: Copyright 2011-2012 Simon Sapin and contributors, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+
+"""
+
+from __future__ import division, unicode_literals
+
+from .formatting_structure impor... | |
e092d456e157d1cb0340bdd6c0599ff9a65dacd0 | poradnia/cases/migrations/0033_auto_20170929_0815.py | poradnia/cases/migrations/0033_auto_20170929_0815.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-29 06:15
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cases', '0032_auto_20170923_1238'),
]
operations = [
migrations.AlterModelOptions(
... | Add missing migrations to cases | Add missing migrations to cases
| Python | mit | watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia | ---
+++
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10.7 on 2017-09-29 06:15
+from __future__ import unicode_literals
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('cases', '0032_auto_20170923_1238'),
+ ]
+
+ operations =... | |
77f77ba3e4ce035499c2dac15fedf451621b20c1 | pcols.py | pcols.py | import numpy as np
from functools import partial
name_func_dict = {
'backgate': {'label': 'Backgate voltage (V)'},
'MC': {'label': 'Mixing chamber temperature (K)'},
}
def parent_f(data, pdata, meta):
return data['MC'] * 10
name = 'MC*10'
func = partial(parent_f)
label = 'MC temperature in unhelpful uni... | Add sample file for pseudocolumns | Add sample file for pseudocolumns
| Python | mit | mchels/FolderBrowser | ---
+++
@@ -0,0 +1,16 @@
+import numpy as np
+from functools import partial
+
+
+name_func_dict = {
+ 'backgate': {'label': 'Backgate voltage (V)'},
+ 'MC': {'label': 'Mixing chamber temperature (K)'},
+}
+
+def parent_f(data, pdata, meta):
+ return data['MC'] * 10
+
+name = 'MC*10'
+func = partial(parent_f)... | |
463deac9f4f452f20c075fc1ff4591dce4191cad | csibe.py | csibe.py | #!/usr/bin/env python
import os
csibe_path = os.path.dirname(os.path.realpath(__file__))
build_directory = "build"
if not os.path.isdir(build_directory):
os.makedirs(build_directory)
os.chdir(build_directory)
os.system("cmake {0}".format(csibe_path))
| Add CSiBE build script with basic functionality | Add CSiBE build script with basic functionality
The build script csibe.py creates a build directory and executes
CMake there for native target.
| Python | bsd-3-clause | bgabor666/csibe,loki04/csibe,szeged/csibe,bgabor666/csibe,loki04/csibe,loki04/csibe,szeged/csibe,loki04/csibe,szeged/csibe,bgabor666/csibe,szeged/csibe,szeged/csibe,bgabor666/csibe,bgabor666/csibe,loki04/csibe,loki04/csibe,bgabor666/csibe,szeged/csibe,bgabor666/csibe,szeged/csibe,loki04/csibe | ---
+++
@@ -0,0 +1,14 @@
+#!/usr/bin/env python
+
+import os
+
+csibe_path = os.path.dirname(os.path.realpath(__file__))
+build_directory = "build"
+
+if not os.path.isdir(build_directory):
+ os.makedirs(build_directory)
+
+os.chdir(build_directory)
+
+os.system("cmake {0}".format(csibe_path))
+ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.