commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
6adc4b650ef0de41110b6038634139c2d0bb33c3 | pymanopt/manifolds/__init__.py | pymanopt/manifolds/__init__.py | from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean
from .product import Product
__all__ = ["Grassmann", "Sphere", "Stiefel", "PSDFixedRank"... | from .grassmann import Grassmann
from .sphere import Sphere
from .stiefel import Stiefel
from .psd import PSDFixedRank, PSDFixedRankComplex, Elliptope, PositiveDefinite
from .oblique import Oblique
from .euclidean import Euclidean
from .product import Product
__all__ = ["Grassmann", "Sphere", "Stiefel", "PSDFixedRank"... | Add Positive definite to manifolds init __all__ | Add Positive definite to manifolds init __all__
Signed-off-by: Jamie Townsend <712d3bf917252432b8abdc41edb77e32fa2cc414@gmail.com>
| Python | bsd-3-clause | nkoep/pymanopt,tingelst/pymanopt,j-towns/pymanopt,nkoep/pymanopt,pymanopt/pymanopt,nkoep/pymanopt,pymanopt/pymanopt |
d2f02fa4171cb490df87a4426c78ffc37560c5d6 | equadratures/distributions/__init__.py | equadratures/distributions/__init__.py | import equadratures.distributions.template
import equadratures.distributions.gaussian
import equadratures.distributions.truncated_gaussian
import equadratures.distributions.chebyshev
import equadratures.distributions.cauchy
import equadratures.distributions.chisquared
import equadratures.distributions.beta
import equad... | import equadratures.distributions.template
import equadratures.distributions.gaussian
import equadratures.distributions.truncated_gaussian
import equadratures.distributions.chebyshev
import equadratures.distributions.cauchy
import equadratures.distributions.chisquared
import equadratures.distributions.beta
import equad... | Add tri distribution import to init. | Add tri distribution import to init.
| Python | lgpl-2.1 | Effective-Quadratures/Effective-Quadratures |
7ec92591324717cfdefc8531549654f146e8b15c | test/unit/test_id_iterators.py | test/unit/test_id_iterators.py | from unittest import TestCase, main
import re
from uuid import UUID
from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \
random_iterator
class TestHexIterator(TestCase):
def test(self):
i = hex_iterator()
self.assertEqual('1', next(i))
i = hex_iterator(9)
self... | from unittest import TestCase, main
import re
from uuid import UUID
from jsonrpcclient.id_iterators import hex_iterator, uuid_iterator, \
random_iterator
class TestHexIterator(TestCase):
def test(self):
i = hex_iterator()
self.assertEqual('1', next(i))
i = hex_iterator(9)
self... | Add statements to run id_iterators tests | Add statements to run id_iterators tests
Closes #8
| Python | mit | bcb/jsonrpcclient |
094c3e428644631c78837def24ac65ba4c84b1c7 | pythainlp/tokenize/__init__.py | pythainlp/tokenize/__init__.py | # -*- coding: utf-8 -*-
"""
Thai tokenizers
"""
from pythainlp.corpus import thai_syllables, thai_words
from pythainlp.util.trie import Trie
DEFAULT_WORD_TOKENIZE_ENGINE = "newmm"
DEFAULT_SENT_TOKENIZE_ENGINE = "crfcut"
DEFAULT_SUBWORD_TOKENIZE_ENGINE = "tcc"
DEFAULT_SYLLABLE_TOKENIZE_ENGINE = "dict"
DEFAULT_WORD_DIC... | # -*- coding: utf-8 -*-
"""
Thai tokenizers
"""
from pythainlp.corpus import thai_syllables, thai_words
from pythainlp.util.trie import Trie
DEFAULT_WORD_TOKENIZE_ENGINE = "newmm"
DEFAULT_SENT_TOKENIZE_ENGINE = "crfcut"
DEFAULT_SUBWORD_TOKENIZE_ENGINE = "tcc"
DEFAULT_SYLLABLE_TOKENIZE_ENGINE = "dict"
DEFAULT_WORD_DIC... | Make pythainlp.util.Trie still accessibl through pythainlp.tokenize.Trie (will deprecate later) | Make pythainlp.util.Trie still accessibl through pythainlp.tokenize.Trie (will deprecate later)
| Python | apache-2.0 | PyThaiNLP/pythainlp |
d72eb62bc0afe1b37c675babed8373bd536de73c | python/challenges/plusMinus.py | python/challenges/plusMinus.py | """
Problem Statement:
Given an array of integers, calculate which fraction of the elements are positive, negative, and zeroes, respectively. Print the decimal value of each fraction.
Input Format:
The first line, N, is the size of the array.
The second line contains N space-separated integers describing the array of ... | import unittest
"""
Problem Statement:
Given an array of integers, calculate which fraction of the elements are positive, negative, and zeroes, respectively. Print the decimal value of each fraction.
Input Format:
The first line, N, is the size of the array.
The second line contains N space-separated integers describ... | Create way to compute ratios of each number type | Create way to compute ratios of each number type
| Python | mit | markthethomas/algorithms,markthethomas/algorithms,markthethomas/algorithms,markthethomas/algorithms |
31632158c7882e20122a91643aebfbba7ae602e7 | tests/test_modules/git_test.py | tests/test_modules/git_test.py | from subprocess import call, check_output
class TestGit:
""" Test that the user has a modern version of git installed """ | from subprocess import call, check_output
class TestGit:
""" Test that the user has a modern version of git installed """
def git_version(self):
""" returns a tuple with execution of git --version """
exit_code = call(["git", "--version"])
output = check_output(["git", "--version"]... | Add tests for git installation | Add tests for git installation
| Python | bsd-3-clause | DevBlend/zenias,DevBlend/zenias,DevBlend/DevBlend,DevBlend/zenias,DevBlend/DevBlend,DevBlend/DevBlend,DevBlend/DevBlend,byteknacker/fcc-python-vagrant,DevBlend/zenias,DevBlend/DevBlend,byteknacker/fcc-python-vagrant,DevBlend/zenias,DevBlend/DevBlend,DevBlend/zenias |
25b35032828593af3220b4310e6a5bd65f90d197 | db/editdbfile.py | db/editdbfile.py | #!/usr/bin/python
# Edit an AES encrypted json/pickle file.
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, passwo... | #!/usr/bin/python
# Edit an AES encrypted json/pickle file.
import os
import sys
import json
import getpass
import tempfile
import subprocess
import aespckfile
import aesjsonfile
def editfile(fn, password):
filetype = aespckfile
if ".json" in fn:
filetype = aesjsonfile
db = filetype.load(fn, passwo... | Check mtime to see if we need to write out new db file. | Check mtime to see if we need to write out new db file.
| Python | agpl-3.0 | vincebusam/pyWebCash,vincebusam/pyWebCash,vincebusam/pyWebCash |
10588fc5caa881a82d78449e29216a68e8b12074 | setup.py | setup.py | from distutils.core import setup
import os
setup(name='django-flashpolicies',
version='1.3',
description='Flash cross-domain policies for Django sites',
long_description=open(os.path.join(os.path.dirname(__file__), 'README')).read(),
author='James Bennett',
author_email='james@b-list.org... | from distutils.core import setup
import os
setup(name='django-flashpolicies',
version='1.3.1',
description='Flash cross-domain policies for Django sites',
long_description=open(os.path.join(os.path.dirname(__file__), 'README')).read(),
author='James Bennett',
author_email='james@b-list.o... | Make the packaging process include the tests. | Make the packaging process include the tests.
| Python | bsd-3-clause | ubernostrum/django-flashpolicies |
412d84fd08f55e20a23314cb09a8e49751df38c2 | setup.py | setup.py | from distutils.core import Extension, setup
try:
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = [
Extension('mathix.vector', ['mathix/vector.pyx']),
]
cmdclass = {
'build_ext': build_ext
}
... | from distutils.core import Extension, setup
try:
from Cython.Build import cythonize
from Cython.Distutils import build_ext
except ImportError:
use_cython = False
else:
use_cython = True
if use_cython:
extensions = cythonize([
Extension('mathix.vector', ['mathix/vector.pyx']),
])
... | Use "cythonize" if Cython is installed. | Use "cythonize" if Cython is installed.
| Python | mit | PeithVergil/cython-example |
6b65eb6767390ac01bb74306cabdb76e97f96054 | setup.py | setup.py | from distutils.core import setup
setup(
name='wagtail-commons',
version='0.0.1',
author=u'Brett Grace',
author_email='brett@codigious.com',
packages=['wagtail_commons'],
url='http://github.com/bgrace/wagtail-commons',
license='BSD licence, see LICENCE file',
description='Utility command... | from distutils.core import setup
setup(
name='wagtail-commons',
version='0.0.1',
author=u'Brett Grace',
author_email='brett@codigious.com',
packages=['wagtail_commons', 'wagtail_commons.core'],
url='http://github.com/bgrace/wagtail-commons',
license='BSD licence, see LICENCE file',
desc... | Add subpaackage to allow use with -e | Add subpaackage to allow use with -e
Rookie mistake
| Python | bsd-3-clause | bgrace/wagtail-commons |
52fd4086b0ef1ac290b393b8cd534a042826b145 | scripts/addStitleToBlastTab.py | scripts/addStitleToBlastTab.py | import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--db2Name', help='tab-separated database lookup: full name file for reference (eg nr or swissprot)')
parser.add_argument('-b','--blast', help='blast input file')
args = parser.parse_args()
blastOrder = []
blastD = {}
with open(args.blast, ... | import sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--db2Name', help='tab-separated database lookup: full name file for reference (eg nr or swissprot)')
parser.add_argument('-b','--blast', help='blast input file')
args = parser.parse_args()
blastOrder = []
blastD = {}
with open(args.blast, ... | Fix mixed indents. replaced tabs with spaces | Fix mixed indents. replaced tabs with spaces
| Python | bsd-3-clause | bluegenes/MakeMyTranscriptome,bluegenes/MakeMyTranscriptome,bluegenes/MakeMyTranscriptome |
cacc51595ec59c90b7f6ea60469bc804593916f3 | queue.py | queue.py | #!/usr/bin/env python
'''Implementation of a simple queue data structure.
The queue has `enqueue`, `dequeue`, and `peek` methods.
Items in the queue have `value` and `behind` attributes.
The queue has a `front` attribute.
'''
class Item(object):
def __init__(self, value, behind=None):
self.value = value
... | #!/usr/bin/env python
'''Implementation of a simple queue data structure.
The queue has `enqueue`, `dequeue`, and `peek` methods.
Items in the queue have `value` and `behind` attributes.
The queue has a `front` attribute.
'''
class Item(object):
def __init__(self, value, behind=None):
self.value = value
... | Add init function for Queue class | Add init function for Queue class
| Python | mit | jwarren116/data-structures-deux |
0595cc06357a572ef604d6c3e0b560974720524c | spacy/tests/regression/test_issue595.py | spacy/tests/regression/test_issue595.py | import pytest
import spacy
@pytest.mark.models
def test_not_lemmatize_base_forms():
nlp = spacy.load('en', parser=False)
doc = nlp(u"Don't feed the dog")
feed = doc[2]
feed.tag_ = u'VB'
assert feed.text == u'feed'
assert feed.lemma_ == u'feed'
| from __future__ import unicode_literals
import pytest
from ...symbols import POS, VERB, VerbForm_inf
from ...tokens import Doc
from ...vocab import Vocab
from ...lemmatizer import Lemmatizer
@pytest.fixture
def index():
return {'verb': {}}
@pytest.fixture
def exceptions():
return {'verb': {}}
@pytest.fixtu... | Change test595 to mock data, instead of requiring model. | Change test595 to mock data, instead of requiring model.
| Python | mit | honnibal/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,raphael0202/spaCy,recognai/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,honnibal/spaCy,Gregory-Howard/spaCy,spacy-io/spaCy,recognai/spaCy,raphael0202/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,oroszgy/spaCy.hu,aikr... |
2607d142a32ad31fd4c432c0830c3173daee79fb | src/util/results.py | src/util/results.py | import datetime
from context_manager.db_context_manager import DBContextManager
from util.constants import QUERIES
def export_results(data, controller_name, trajectory_name, database_path):
creation_datetime = datetime.datetime.now()
with DBContextManager(database_path) as cursor:
table_name = ('_'.... | import datetime
from context_manager.db_context_manager import DBContextManager
from util.constants import QUERIES
def export_results(data, controller_name, trajectory_name, database_path):
def get_table_name(controller, trajectory, date_time):
return '_'.join([controller,
trajec... | Create inner function and rename variables | refactor: Create inner function and rename variables
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking |
5d8a09ebff9cc8a8e8bdf4bff3963cee7a1aae6a | tools/skp/page_sets/skia_ebay_desktop.py | tools/skp/page_sets/skia_ebay_desktop.py | # Copyright 2019 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.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | # Copyright 2019 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.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... | Add wait time to ebay pageset | Add wait time to ebay pageset
Bug: skia:11898
Change-Id: I0bb58f1d8e9c6ad48148d50b840f152fc158f071
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/400538
Reviewed-by: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.com>
Commit-Queue: Ravi Mistry <9fa2e7438b8cb730f96b74865492597170561628@google.... | Python | bsd-3-clause | aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia,google/skia,go... |
acf2729f368ad4eabc0219d1a191089e8d5f740f | dmz/geolocate.py | dmz/geolocate.py | #Using MaxMind, so import pygeoip
import pygeoip
def geolocate(ip_addresses):
#Read in files, storing in memory for speed
ip4_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIP.dat", flags = 1)
ip6_geo = pygeoip.GeoIP(filename = "/usr/share/GeoIP/GeoIPv6.dat", flags = 1)
#Check type
if not(isinstan... | """
Provides simple functions that geo-locate an IP address (IPv4 or IPv4) using the
MaxMind Geo Database.
"""
import pygeoip
class GeoLocator(object):
"""Geo locate IP addresses using the MaxMind database"""
def __init__(self, ipv4_geo_path='/usr/share/GeoIP/GeoIP.dat',
ipv6_geo_path='/usr/sh... | Move the Geo Location stuff into a class | Move the Geo Location stuff into a class
| Python | mit | yuvipanda/edit-stats |
35b45fd793ac695f6ec6a792534fdde77a3023aa | napalm_yang/supported_models.py | napalm_yang/supported_models.py | SUPPORTED_MODELS = (
# module_name, models
("openconfig-interfaces", ["interfaces"]),
("openconfig-network-instance", ["network_instances"]),
("openconfig-platform", ["components"]),
("openconfig-vlan", ["vlans"]),
)
| SUPPORTED_MODELS = (
# module_name, models
("openconfig-interfaces", ["interfaces"]),
("openconfig-network-instance", ["network_instances"]),
("openconfig-platform", ["components"]),
("openconfig-vlan", ["vlans"]),
('openconfig-system', ['system'])
)
| Add system as supported models | Add system as supported models
| Python | apache-2.0 | napalm-automation/napalm-yang,napalm-automation/napalm-yang |
5f1fa23dd8e0850a9f0e6a054ec6738e5a174ff7 | database/tables.py | database/tables.py | #!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
tables.py
Table definitions for pearbot database submodule.
Tables are not assigned to variables, they can be accessed using the global
metadata object though.
Copyright (c) 2015 Twisted Pear <pear at twistedpear dot at>
See the file LICENS... | #!/usr/bin/env python3
# vim:fileencoding=utf-8:ts=8:et:sw=4:sts=4:tw=79
"""
tables.py
Table definitions for pearbot database submodule.
Tables are not assigned to variables, they can be accessed using the global
metadata object though.
Copyright (c) 2015 Twisted Pear <pear at twistedpear dot at>
See the file LICENS... | Add a table for caching moderators | Add a table for caching moderators
| Python | mit | pyrige/pump19 |
77dc80e60b252833940dc6b2a1c512684ed8decd | doc/conf.py | doc/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build dire... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Use sphinx-quickstart to create your own conf.py file!
# After that, you have to edit a few things. See below.
# Select nbsphinx and, if needed, add a math extension (mathjax or pngmath):
extensions = [
'nbsphinx',
'sphinx.ext.mathjax',
]
# Exclude build dire... | Set default syntax highlighting language to 'none' | DOC: Set default syntax highlighting language to 'none'
| Python | mit | spatialaudio/nbsphinx,spatialaudio/nbsphinx,spatialaudio/nbsphinx |
e36c4a3f2fa54be390f8b0ae00f9151f95c49ed4 | sqlobject/tests/test_schema.py | sqlobject/tests/test_schema.py | from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getCon... | from sqlobject import *
from sqlobject.tests.dbtest import *
########################################
## Schema per connection
########################################
class Test(SQLObject):
foo = UnicodeCol(length=200)
def test_connection_schema():
if not supports('schema'):
return
conn = getCon... | Allow the test to be run without 'schema=' parameter in the DB URI. | Allow the test to be run without 'schema=' parameter in the DB URI.
git-svn-id: 07e5abd2c6e244bc465bf007dc23a4c6bc1bee58@3524 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
| Python | lgpl-2.1 | drnlm/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,sqlobject/sqlobject |
5709acf3c2effcdeef10323bbc956860c15f7ece | tasks.py | tasks.py | from arctasks import lint # noqa
from arctasks.release import * # noqa
| from arctasks import lint # noqa
from arctasks.python import show_upgraded_packages # noqa
from arctasks.release import * # noqa
| Include show_upgraded_packages task from ARCTasks | Include show_upgraded_packages task from ARCTasks
| Python | mit | wylee/django-arcutils,PSU-OIT-ARC/django-arcutils,wylee/django-arcutils,PSU-OIT-ARC/django-arcutils |
0c20b2194cd608551b1792f036de347bf7a36ddf | packages/QtInventor/__init__.py | packages/QtInventor/__init__.py | """
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
gra... | """
Helper classes for creating 3D applications with PySide.
PySide is a binding to the Qt cross-platform application framework. This
package contains helper classes that integrate Open Inventor / Coin3D
into PySide based applications, namely:
- QIVWidget: Viewport widget for rendering and interacting with scene
gra... | Load extensions given in IV_LIBS variable. | Load extensions given in IV_LIBS variable.
| Python | bsd-3-clause | TheHubbit/PyInventor,TheHubbit/PyInventor |
e1b2b35e36566e92bf789c4d5ab7c668d520f492 | taca/illumina/NextSeq_Runs.py | taca/illumina/NextSeq_Runs.py | import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
from flowce... | import os
import re
import csv
import glob
import shutil
import gzip
import operator
import subprocess
from datetime import datetime
from taca.utils.filesystem import chdir, control_fastq_filename
from taca.illumina.Runs import Run
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.utils import misc
import log... | Clear samplesheet parser from header | Clear samplesheet parser from header
| Python | mit | SciLifeLab/TACA,SciLifeLab/TACA,SciLifeLab/TACA |
e17fab647a7840bbe56f5c37fbe32c73557d98b2 | workers/subscriptions.py | workers/subscriptions.py | import os
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
i = 0
while True:
if i % 10 == 0:
bot.collect_plugins()
for name, check, send in bot.... | import os
import time
import telegram
from leonard import Leonard
if __name__ == '__main__':
os.chdir('../')
telegram_client = telegram.Bot(os.environ['BOT_TOKEN'])
bot = Leonard(telegram_client)
bot.collect_plugins()
while True:
for name, check, send in bot.subscriptions:
sen... | Remove collecting plugins every second | Remove collecting plugins every second
| Python | mit | sevazhidkov/leonard |
657f88cb6e65731ca1d39067094cbe0f5d18e2fc | sample-functions/SentimentAnalysis/handler.py | sample-functions/SentimentAnalysis/handler.py | import sys
import json
from textblob import TextBlob
# set default encoding to UTF-8 to eliminate decoding errors
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob =... | import sys
import json
from textblob import TextBlob
# Set encoding to UTF-8 (vs ASCII to eliminate potential errors).
reload(sys)
sys.setdefaultencoding('utf8')
def get_stdin():
buf = ""
for line in sys.stdin:
buf = buf + line
return buf
if(__name__ == "__main__"):
st = get_stdin()
blob ... | Correct identation error in sample. | Correct identation error in sample.
| Python | mit | openfaas/faas,rgee0/faas,alexellis/faas,rgee0/faas,alexellis/faas,alexellis/faas,haru01/faas,openfaas/faas,haru01/faas,rgee0/faas,alexellis/faas,haru01/faas,rgee0/faas,rgee0/faas,haru01/faas,haru01/faas,alexellis/faas,rgee0/faas,rgee0/faas,rgee0/faas,openfaas/faas,alexellis/faas,alexellis/faas,haru01/faas,rgee0/faas,ha... |
b60f9f22703d97cfaeaa69e36fe283d1ef5d2f5d | download_data.py | download_data.py | import bz2
import urllib.request
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = urllib.request.urlopen(url)
decompressor ... | import bz2
import urllib.request
import os
import os.path
DATA_DIR = 'data'
OPEN_CORPORA_URL = 'http://opencorpora.org/files/export/annot/annot.opcorpora.no_ambig.xml.bz2'
OPEN_CORPORA_DEST_FILE = 'data/annot.opcorpora.no_ambig.xml'
CHUNK = 16 * 1024
def download_and_unbzip(url, dest_file):
source = ... | Create dir before data downloading | Create dir before data downloading
| Python | mit | Nizametdinov/cnn-pos-tagger |
19a9ccb0b896c87ba04b47081c6b796cb37bd022 | test/test_cypher.py | test/test_cypher.py | from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_start_cypher():
jim = User2(email='jim@test.com').save()
email = jim.start_cypher("RETURN a.email")[0][0][0]
assert email == 'jim@test.com'
def test_cypher():
jim... | from neomodel import StructuredNode, StringProperty, CypherException
class User2(StructuredNode):
email = StringProperty()
def test_cypher():
jim = User2(email='jim1@test.com').save()
email = jim.cypher("START a=node({self}) RETURN a.email")[0][0][0]
assert email == 'jim1@test.com'
def test_cypher... | Remove test of deprecated method | Remove test of deprecated method
| Python | mit | bleib1dj/neomodel,robinedwards/neomodel,cristigociu/neomodel_dh,fpieper/neomodel,andrefsp/neomodel,wcooley/neomodel,robinedwards/neomodel,bleib1dj/neomodel,pombredanne/neomodel |
7dc239db20a5a0cb507644f1650e2d0fb752608a | migrations/versions/88d46e8e73ef_industry_index_remove_date.py | migrations/versions/88d46e8e73ef_industry_index_remove_date.py | """industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgra... | """industry index remove date
Revision ID: 88d46e8e73ef
Revises: 6543398f0773
Create Date: 2016-03-08 19:51:18.026000
"""
# revision identifiers, used by Alembic.
revision = '88d46e8e73ef'
down_revision = '6543398f0773'
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
def upgr... | Fix migration file that didn't work correctly | Fix migration file that didn't work correctly
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith |
62ca16d355716c3baaf7a661269e54a517fef25d | tests/test_hooks.py | tests/test_hooks.py | from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mo... | from io import BytesIO
from unittest.mock import MagicMock, patch
from isort import hooks
def test_git_hook():
"""Simple smoke level testing of git hooks"""
# Ensure correct subprocess command is called
with patch("subprocess.run", MagicMock()) as run_mock:
hooks.git_hook()
assert run_mo... | Fix mock statement for new API | Fix mock statement for new API
| Python | mit | PyCQA/isort,PyCQA/isort |
c70b6717ec69fbf235b89d34c668686ecf9b8c26 | tests/test_utils.py | tests/test_utils.py | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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... | #!/usr/bin/python2.5
#
# Copyright 2008 the Melange authors.
#
# 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... | Add a start and end method to MockRequest | Add a start and end method to MockRequest
| Python | apache-2.0 | rhyolight/nupic.son,rhyolight/nupic.son,rhyolight/nupic.son |
55f787d653f1ee7b923a460f892a27a4143ec408 | providers/moviedata/provider.py | providers/moviedata/provider.py | from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under... | from __future__ import print_function
from providers.provider import BaseProvider
# Subclasses implement a way to get movie data for from a search string
#
# To implement a MoviedataProvider:
# - Create a new file in moviedata/ and call it provider_[your name].py
# - Add the path to your file in settings.py, under... | Add docs for add transform_data helper method. | Add docs for add transform_data helper method.
| Python | mit | EmilStenstrom/nephele |
458fb9b764cae3419b6513dcc1fedf2ea8949829 | networkx/generators/tests/test_stochastic.py | networkx/generators/tests/test_stochastic.py | from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5... | from nose.tools import assert_true, assert_equal,assert_raises
import networkx as nx
def test_stochastic():
G=nx.DiGraph()
G.add_edge(0,1)
G.add_edge(0,2)
S=nx.stochastic_graph(G)
assert_true(nx.is_isomorphic(G,S))
assert_equal(sorted(S.edges(data=True)),
[(0, 1, {'weight': 0.5... | Test stochstic graph with ints | Test stochstic graph with ints
| Python | bsd-3-clause | blublud/networkx,dhimmel/networkx,nathania/networkx,goulu/networkx,ltiao/networkx,ionanrozenfeld/networkx,bzero/networkx,dmoliveira/networkx,aureooms/networkx,yashu-seth/networkx,ghdk/networkx,ionanrozenfeld/networkx,nathania/networkx,harlowja/networkx,michaelpacer/networkx,ionanrozenfeld/networkx,aureooms/networkx,har... |
69d856b5b6ec9f87b55174ebbd414d9960bb626d | tests/offline/test_pricing.py | tests/offline/test_pricing.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 <>
#
# Distributed under terms of the MIT license.
# Python modules
from __future__ import unicode_literals
# Third-party modules
import pytest
# Project modules
from fnapy.exceptions import FnapyPricingError
from tests import make... | Update the tests for query_pricing | Update the tests for query_pricing
| Python | mit | alexandriagroup/fnapy,alexandriagroup/fnapy |
7d0f1c9cea6e71d5cc515ae3790226ae6badda79 | Logger.py | Logger.py | import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.... | import time
class Logger():
def __init__(self, name = "defaultLogFile"):
timestamp = time.strftime('%Y_%m_%d-%H_%M_%S')
self.name = "Logs/" + timestamp + "_" + name + ".txt"
try:
self.logfile = open(self.name, 'w')
self.opened = True
except:
self.... | Correct and simplify calculation of miliseconds | Correct and simplify calculation of miliseconds
Signed-off-by: TeaPackCZ <a78d8486eff6e2cb08b2d9907449b92187b8e215@gmail.com>
| Python | mit | TeaPackCZ/RobotZed,TeaPackCZ/RobotZed |
fc636b5ae0db4190e0499c6bec58d40ad0d0afe4 | cms/management/commands/subcommands/moderator.py | cms/management/commands/subcommands/moderator.py | # -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2... | # -*- coding: utf-8 -*-
from cms.management.commands.subcommands.base import SubcommandsCommand
from cms.models import CMSPlugin
from cms.models.pagemodel import Page
from django.core.management.base import NoArgsCommand
class ModeratorOnCommand(NoArgsCommand):
help = 'Turn moderation on, run AFTER upgrading to 2... | Apply revert to the draft page. | Apply revert to the draft page.
| Python | bsd-3-clause | keimlink/django-cms,mkoistinen/django-cms,foobacca/django-cms,FinalAngel/django-cms,nimbis/django-cms,Jaccorot/django-cms,memnonila/django-cms,nostalgiaz/django-cms,jproffitt/django-cms,adaptivelogic/django-cms,Livefyre/django-cms,sznekol/django-cms,MagicSolutions/django-cms,benzkji/django-cms,iddqd1/django-cms,SinnerS... |
0fdaff5b0715722de7590aa2b57266291bafd000 | umibukela/models.py | umibukela/models.py | import os
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make S3 image filenames
"""
return 'ima... | import os
import uuid
from django.db import models
# ------------------------------------------------------------------------------
# General utilities
# ------------------------------------------------------------------------------
def image_filename(instance, filename):
""" Make image filenames
"""
re... | Remove image name dependency on object ID | Remove image name dependency on object ID
| Python | mit | Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela,Code4SA/umibukela |
8897defe3b11a6518d3ad1148a5ee9321bfa176c | froniusLogger.py | froniusLogger.py | """
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples
def main():
print("started")
... | """
Logs key data from a Fronius inverter to a CSV file for later analysis.
peter.marks@pobox.com
"""
import requests
import json
import datetime
import time
# Set this to the IP address of your inverter
host = "192.168.0.112"
sample_seconds = 60 # how many seconds between samples, set to zero to run once and exit
... | Make the timestamp more sane. Add the ability to run once and exit for use with cron. | Make the timestamp more sane.
Add the ability to run once and exit for use with cron.
| Python | apache-2.0 | peterbmarks/froniusLogger,peterbmarks/froniusLogger |
ce644b55ee72790d111435b81fb76a2ea15913c5 | gabbi/fixture.py | gabbi/fixture.py | """Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Create the fixture class and stop it."""
fixture = fixture_class()
fixture.stop... | """Manage fixtures for gabbi at the test file level."""
def start_fixture(fixture_class):
"""Create the fixture class and start it."""
fixture = fixture_class()
fixture.start()
def stop_fixture(fixture_class):
"""Re-Create the fixture class and stop it."""
fixture = fixture_class()
fixture.s... | Add some docs to GabbiFixture | Add some docs to GabbiFixture
| Python | apache-2.0 | FND/gabbi,jasonamyers/gabbi,jasonamyers/gabbi,FND/gabbi |
186eaeb5b5e8d7c7f06305566729bf36424c6e77 | grab/__init__.py | grab/__init__.py | from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabReque... | from base import (GrabError, DataNotFound, GrabNetworkError,
GrabMisuseError, UploadContent, UploadFile,
GrabTimeoutError)
from transport.curl import GrabCurl
#from transport.urllib import GrabUrllib
from transport.selenium import GrabSelenium
from transport.requests import GrabReque... | Add default_logging function to package namespace | Add default_logging function to package namespace
| Python | mit | DDShadoww/grab,maurobaraldi/grab,DDShadoww/grab,liorvh/grab,SpaceAppsXploration/grab,huiyi1990/grab,subeax/grab,lorien/grab,pombredanne/grab-1,giserh/grab,alihalabyah/grab,kevinlondon/grab,shaunstanislaus/grab,subeax/grab,maurobaraldi/grab,kevinlondon/grab,SpaceAppsXploration/grab,shaunstanislaus/grab,pombredanne/grab-... |
b3ef68f209e014b624b8de26e53af5933e20aa9c | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **field... | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **field... | Use 'fields' instead of 'kwargs' to document intent. | Use 'fields' instead of 'kwargs' to document intent.
| Python | bsd-2-clause | swayf/grako,swayf/grako |
2277e8412fbd92c26cd822f389ecb7e099519da4 | .conda/merge_dups.py | .conda/merge_dups.py | #!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml'))
res = yaml.load(open('data_osx-.yml'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key = '|'.join([package[x] for x in ('url', 'version... | #!/usr/bin/env python
import yaml
linux = yaml.load(open('data_linux-64.yml', 'r'))
res = yaml.load(open('data_osx-.yml', 'r'))
res.extend(linux)
# Remove duplicates
unique_packages = {}
for package in res:
# This information is the unique portion, so we key on that
key_data = [
package['version'],
... | Handle lists of URLs like in r-ada | Handle lists of URLs like in r-ada
| Python | mit | galaxyproject/cargo-port,galaxyproject/cargo-port,erasche/community-package-cache,erasche/community-package-cache,erasche/community-package-cache |
8cc88e1f6e09e91f2ffc5bbf43b58b2d129a12c9 | bnc.py | bnc.py | import nltk.corpus.reader.bnc
| import nltk.corpus.reader.bnc
import time
start_time = time.perf_counter()
BNC_data = nltk.corpus.reader.bnc.BNCCorpusReader(root='/home/ubuntu/ug-d/bncbaby/',
fileids=r'aca/\w*\.xml', # r'aca/\w*\.xml', # r'[a-z]{3}/\w*\.xml')
la... | Load BNC into memory and time process. | Load BNC into memory and time process.
| Python | mit | albertomh/ug-dissertation |
396c9128aa4d3bc7b31f5fb00363a7f52dba7476 | indra/java_vm.py | indra/java_vm.py | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | Fix java VM starting when there is not classpath set | Fix java VM starting when there is not classpath set
| Python | bsd-2-clause | johnbachman/belpy,sorgerlab/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,johnbachman/indra,jmuhlich/indra,sorgerlab/indra,bgyori/indra,jmuhlich/indra,sorgerlab/indra,jmuhlich/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,... |
da2e17366f83ebb1b95b80296e5d6376bc21b4eb | pyinapp/googleplay.py | pyinapp/googleplay.py | from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
... | from pyinapp.errors import InAppValidationError
from pyinapp.purchase import Purchase
import base64
import json
import rsa
purchase_state_ok = 0
def make_pem(public_key):
return '\n'.join((
'-----BEGIN PUBLIC KEY-----',
'\n'.join(public_key[i:i+64] for i in range(0, len(public_key), 64)),
... | Add extra validation for Google Play signature | Add extra validation for Google Play signature
| Python | mit | keeprocking/pyinapp |
cdfdfd7418f33cc38aa7db3e42e0050d4189ab77 | webserver/utility/templatetags/active_tags.py | webserver/utility/templatetags/active_tags.py | import re
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
print pattern
request = context['request']
if re.search(pattern, request.path):
return 'active'
return ''
| import re
from django import template
from django.conf import settings
from django.template import Context, Template
register = template.Library()
@register.simple_tag(takes_context=True)
def active(context, pattern):
request = context['request']
template = Template(pattern)
context = Context(context)
... | Update active templatetag to accept more complex strings | Update active templatetag to accept more complex strings
| Python | bsd-3-clause | siggame/webserver,siggame/webserver,siggame/webserver |
fc6db503809e3e350081637ccb7b0f7e8eb67619 | account_verification_flask/config/local.py | account_verification_flask/config/local.py | SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite:////Work/account_verification.db'
SQLALCHEMY_EC... | SECRET_KEY = '%^!@@*!&$8xdfdirunb52438#(&^874@#^&*($@*(@&^@)(&*)Y_)((+'
AUTHY_KEY = 'your_authy_key'
TWILIO_ACCOUNT_SID = 'your_twilio_account_sid'
TWILIO_AUTH_TOKEN = 'your_twilio_auth_token'
TWILIO_NUMBER = 'your_twilio_phone_number'
SQLALCHEMY_DATABASE_URI = 'sqlite://'
SQLALCHEMY_ECHO = True | Switch the default config to use in memory sqlite | Switch the default config to use in memory sqlite
| Python | mit | TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask,TwilioDevEd/account-verification-flask |
4ee8cef54d21316c9490f49ee2b3f2f16ffdcfbb | python_scripts/solr_query_fetch_all.py | python_scripts/solr_query_fetch_all.py | #!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
while ( le... | #!/usr/bin/python
import requests
import ipdb
import time
import csv
import sys
import pysolr
def fetch_all( solr, query ) :
documents = []
num_matching_documents = solr.search( query ).hits
start = 0
rows = num_matching_documents
sys.stderr.write( ' starting fetch for ' + query )
sys.stderr... | Save word counts to file. | Save word counts to file.
| Python | agpl-3.0 | AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT... |
bc02af25e3bbcb97de838eff1fc130f52258db2d | grammar/automator.py | grammar/automator.py | import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xd... | import os
class Automator:
def __init__(self, real = True):
self.xdo_list = []
self.real = real
def xdo(self, xdo):
self.xdo_list.append(xdo)
def flush(self):
if len(self.xdo_list) == 0: return
command = '/usr/bin/xdotool' + ' '
command += ' '.join(self.xd... | Support apostrophe and period in dictation (and minus, just in case). | Support apostrophe and period in dictation (and minus, just in case).
Example: "phrase don't like x. rays".
| Python | bsd-2-clause | dwks/silvius,dwks/silvius |
5f935bb952a616c3fe9ca24fa862621dfc1bda24 | guv/hubs/watchers.py | guv/hubs/watchers.py | from guv.hubs.abc import AbstractListener
class FdListener(AbstractListener):
"""Default implementation of :cls:`AbstractListener`
"""
pass
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to b... | from guv.hubs.abc import AbstractListener
class PollFdListener(AbstractListener):
def __init__(self, evtype, fd, cb):
"""
:param cb: Callable
:param args: tuple of arguments to be passed to cb
"""
super().__init__(evtype, fd)
self.cb = cb
class UvFdListener(Abstra... | Remove unneeded default Listener implementation | Remove unneeded default Listener implementation
| Python | mit | veegee/guv,veegee/guv |
93cebc0f0a99677f33005502217d83964de48478 | notifications/templatetags/notifications_tags.py | notifications/templatetags/notifications_tags.py | # -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from notifications.models import Notification
from django.template import Node
register = Library()
# TODO: Simplify this: it's a really simple tag!
class InboxCountNode(Node):
"For use in the notific... | # -*- coding: utf-8 -*-
from django.template import Library
from django.template.base import TemplateSyntaxError
from django.template import Node
register = Library()
@register.simple_tag(takes_context=True)
def notifications_unread(context):
if 'user' not in context:
return ''
user = context['us... | Simplify the notification tag. No longer can store the value in a variable. | Simplify the notification tag.
No longer can store the value in a variable.
| Python | bsd-3-clause | iberben/django-notifications,django-notifications/django-notifications,iberben/django-notifications,Evidlo/django-notifications,iberben/django-notifications,brandonberney/basic-django-notifications,alazaro/django-notifications,Natgeoed/django-notifications,brandonberney/basic-django-notifications,philroche/django-notif... |
4d8b0fefa420efd60da0c6a29968f2fd441b9e09 | openbox/configuration_builder/transformations.py | openbox/configuration_builder/transformations.py | def to_int(value):
return int(value)
def identity(value):
return value | def to_int(value, num=None):
return int(value)
def to_float(value, num=None):
return float(value)
def identity(value, num=None):
return value | Add to_float function and add num keyword | Transformations: Add to_float function and add num keyword
| Python | apache-2.0 | DeepnessLab/obsi,OpenBoxProject/obsi,DeepnessLab/obsi,pavel-lazar/obsi,pavel-lazar/obsi,OpenBoxProject/obsi,DeepnessLab/obsi,pavel-lazar/obsi,DeepnessLab/obsi,pavel-lazar/obsi,OpenBoxProject/obsi,OpenBoxProject/obsi |
aaf8ebb7b1b12b15ab96c2cd1d7cb053154e8d64 | tests/lib/query_models/test_query_string_match.py | tests/lib/query_models/test_query_string_match.py | from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
class TestQueryStringMatchPositiveTestSuite(PositiveTestSuite):
def query_tests(... | from positive_test_suite import PositiveTestSuite
from negative_test_suite import NegativeTestSuite
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../lib"))
from query_models import QueryStringMatch
hostname_test_regex = 'hostname: /(.*\.)*(sub|bus)+(\..*)*\.abc(\..*)*\.company\.com... | Add extra tests to query string query model | Add extra tests to query string query model
| Python | mpl-2.0 | ameihm0912/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,gdestuynder/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,Phrozyn/MozDef,mpurzynski/MozDef,Phrozyn/MozDef,gdestuynder/MozDef,ameihm0912/MozDef,Phrozyn/MozDef,mozilla/MozDef,jeffbryner/MozDef,ameihm0912/MozDef,jeffbryner/MozDef,gdestuynd... |
ff2bf51f003fc5af1f62fc1aa181ca11a766c8f6 | fs/archive/__init__.py | fs/archive/__init__.py | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_en... | # coding: utf-8
from __future__ import absolute_import
from __future__ import unicode_literals
import contextlib
@contextlib.contextmanager
def open_archive(fs_url, archive):
from pkg_resources import iter_entry_points
from ..opener import open_fs
from ..opener._errors import Unsupported
it = iter_en... | Make sure files and FS are properly closed in open_archive | Make sure files and FS are properly closed in open_archive
| Python | mit | althonos/fs.archive |
12c1ee81843e3e163756a39b68671cf5c1842df2 | scrapi/harvesters/mason_archival.py | scrapi/harvesters/mason_archival.py | """
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http:... | """
Harvester for Mason Archival Repository Service for the SHARE NS
"""
from __future__ import unicode_literals
from scrapi.base import OAIHarvester
class MasonArchival(OAIHarvester):
short_name = 'mason'
long_name = 'Mason Archival Repository Service'
url = 'http://mars.gmu.edu/'
base_url = 'http:... | Add approved set to gmu | Add approved set to gmu
| Python | apache-2.0 | CenterForOpenScience/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,erinspace/scrapi,erinspace/scrapi |
82bca5898d753638536abdd965c799bd947163e5 | scipy/ndimage/tests/test_regression.py | scipy/ndimage/tests/test_regression.py | import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4... | import numpy as np
from numpy.testing import *
import scipy.ndimage as ndimage
def test_byte_order_median():
"""Regression test for #413: median_filter does not handle bytes orders."""
a = np.arange(9, dtype='<f4').reshape(3, 3)
ref = ndimage.filters.median_filter(a,(3, 3))
b = np.arange(9, dtype='>f4... | Use run_module_suite instead of deprecated NumpyTest. | Use run_module_suite instead of deprecated NumpyTest.
| Python | bsd-3-clause | teoliphant/scipy,gef756/scipy,ChanderG/scipy,raoulbq/scipy,petebachant/scipy,dch312/scipy,zaxliu/scipy,gertingold/scipy,ndchorley/scipy,zxsted/scipy,sonnyhu/scipy,ortylp/scipy,jsilter/scipy,rgommers/scipy,jseabold/scipy,surhudm/scipy,vhaasteren/scipy,jamestwebber/scipy,piyush0609/scipy,ales-erjavec/scipy,WillieMaddox/s... |
596b435e57275714b3d37529cc342cacc15a86bf | moto/s3/utils.py | moto/s3/utils.py | import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.lstrip("www.")
if 'amazonaws.com' in domain:
bucket_result = bucket_name_rege... | import re
import urllib2
import urlparse
bucket_name_regex = re.compile("(.+).s3.amazonaws.com")
def bucket_name_from_url(url):
domain = urlparse.urlparse(url).netloc
# If 'www' prefixed, strip it.
domain = domain.replace("www.", "")
if 'amazonaws.com' in domain:
bucket_result = bucket_name... | Fix the 'www.' strip changing the lstrip method by the replace | Fix the 'www.' strip changing the lstrip method by the replace
| Python | apache-2.0 | okomestudio/moto,william-richard/moto,araines/moto,william-richard/moto,whummer/moto,Affirm/moto,Brett55/moto,EarthmanT/moto,rocky4570/moto,andresriancho/moto,jszwedko/moto,riccardomc/moto,braintreeps/moto,ImmobilienScout24/moto,heddle317/moto,william-richard/moto,whummer/moto,heddle317/moto,heddle317/moto,ZuluPro/moto... |
316dac037b8cef3086f5bdf6b9fd2afa0b2bfbd3 | mama_cas/urls.py | mama_cas/urls.py | """
URLconf for CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.v... | """
(2) CAS server URIs as described in the CAS protocol.
"""
from django.conf.urls import patterns
from django.conf.urls import url
from mama_cas.views import LoginView
from mama_cas.views import LogoutView
from mama_cas.views import ValidateView
from mama_cas.views import ServiceValidateView
from mama_cas.views imp... | Add CAS 3.0 specific endpoints | Add CAS 3.0 specific endpoints
| Python | bsd-3-clause | jbittel/django-mama-cas,jbittel/django-mama-cas,orbitvu/django-mama-cas,orbitvu/django-mama-cas |
308f9d8e1d4083bb7cc6bca0cf021118502d141b | marble/common.py | marble/common.py | # -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared thoughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_class... | # -*- coding: utf-8 -*-
"""common.py
Contains basic functions that are shared throughout the module
"""
def compute_totals(distribution, classes):
"Compute the number of individuals per class, per unit and in total"
N_unit = {au:sum([distribution[au][cl] for cl in classes]) for au in distribution}
N_clas... | Raise exception if faulty definition of classes inserted | Raise exception if faulty definition of classes inserted
| Python | bsd-3-clause | scities/marble,walkerke/marble |
5bf441e34b672a5a369ad7e42cdc2fc7f7699476 | publishers/base_publisher.py | publishers/base_publisher.py | from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform... | from shared.base_component import BaseComponent
class BasePublisher(BaseComponent):
def __init__(self, conf):
BaseComponent.__init__(self, conf)
def publish(self, message):
pass
def __call__(self, message):
if self.query.match(message):
message = self.project.transform... | Discard None values in projections in publishers | Discard None values in projections in publishers
| Python | mit | weapp/miner |
14447e99f550d4b41ccee474fa89382bb0744eb3 | bookmarks/forms.py | bookmarks/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
ma... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import (DataRequired, Length, EqualTo, Email, Regexp,
URL)
class BookmarkForm(FlaskForm):
b_id = StringField('Bookmark ID', [
Length(min=6,
ma... | Add regex password validation to register form | Add regex password validation to register form
Checks for password complexity on registartion
| Python | apache-2.0 | byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks |
c41115875ce46be3eacc1ec7c539010b430b0374 | kegg_adapter/kegg.py | kegg_adapter/kegg.py | import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
... | import urllib2
import json
#response = urllib2.urlopen('http://rest.kegg.jp/list/pathway/ath')
#html = response.read()
#lines = html.split('\n');
#data = {};
#for line in lines:
# parts = line.split('\t');
# if len(parts) >= 2:
# data[parts[0]] = parts[1]
#json_data = json.dumps(data)
#print json_data
... | Remove debugging print statements changed exit status from 1 to 0 | Remove debugging print statements
changed exit status from 1 to 0
| Python | artistic-2.0 | Arabidopsis-Information-Portal/Intern-Hello-World,Arabidopsis-Information-Portal/KEGG-Pathway-API |
b1c8ce6ac2658264a97983b185ebef31c0952b33 | depot/tests.py | depot/tests.py | from django.test import TestCase
from .models import Depot
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
| from django.test import TestCase
from .models import Depot, Item
class DepotTestCase(TestCase):
def test_str(self):
depot = Depot(1, "My depot")
self.assertEqual(depot.__str__(), "Depot My depot")
class ItemTestCase(TestCase):
def test_str(self):
depot = Depot(2, "My depot")
... | Add test case for Item __str__ function | Add test case for Item __str__ function
| Python | agpl-3.0 | verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool |
c6e23473520a3b055896524663779fa582189763 | datacats/tests/test_cli_pull.py | datacats/tests/test_cli_pull.py | from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter =... | from datacats.cli.pull import _retry_func
from datacats.error import DatacatsError
from unittest import TestCase
def raise_an_error(_):
raise DatacatsError('Hi')
class TestPullCli(TestCase):
def test_cli_pull_retry(self):
def count(*dummy, **_):
count.counter += 1
count.counter =... | Move around assertions as Ian talked about | Move around assertions as Ian talked about
| Python | agpl-3.0 | datawagovau/datacats,JJediny/datacats,JackMc/datacats,reneenoble/datacats,wardi/datacats,deniszgonjanin/datacats,poguez/datacats,datawagovau/datacats,wardi/datacats,datacats/datacats,reneenoble/datacats,JackMc/datacats,poguez/datacats,deniszgonjanin/datacats,JJediny/datacats,datacats/datacats |
2a550df5d9200deb6700fca4270526633811d592 | osfclient/cli.py | osfclient/cli.py | """Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = os.getenv("OSF_PA... | """Command line interface to the OSF"""
import os
from .api import OSF
CHUNK_SIZE = int(5e6)
def _setup_osf(args):
# command line argument overrides environment variable
username = os.getenv("OSF_USERNAME")
if args.username is not None:
username = args.username
password = None
if usern... | Stop grabbing password when there is no username | Stop grabbing password when there is no username
| Python | bsd-3-clause | betatim/osf-cli,betatim/osf-cli |
11906213015f03cfdb3f247a6dbcab0619be61e3 | comrade/core/decorators.py | comrade/core/decorators.py | from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
from django.http import HttpResponse
from django.template import loader, RequestContext
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
... | from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from comrade.views.simple import direct_to_template
from functools import wraps
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
... | Use our own code, when possible. | Use our own code, when possible.
| Python | mit | bueda/django-comrade |
6eee384ef75d119f5fbb3c6ff91fd2c49f9a5630 | lib/authenticator.py | lib/authenticator.py | #
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class H... | #
# HamperAuthenticator is the class to handle the authentication part of the provisioning portal.
# Instantiate with the email and password you want, it'll pass back the cookie jar if successful,
# or an error message on failure
#
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class H... | Use parameter to pass Webdriver object to share execution | Use parameter to pass Webdriver object to share execution
| Python | mit | MobileXLabs/hamper |
48b38ea71a79eaed81a4f83a46bf8bf3db8cfa18 | txircd/modules/extra/listmodules.py | txircd/modules/extra/listmodules.py | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesCommand(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesCommand"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def lis... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from zope.interface import implements
class ModulesList(ModuleData):
implements(IPlugin, IModuleData)
name = "ModulesList"
def actions(self):
return [ ("statsruntype-modules", 1, self.listModules) ]
def listModul... | Rename ModulesCommand to be more appropriate | Rename ModulesCommand to be more appropriate
| Python | bsd-3-clause | Heufneutje/txircd |
d7fa7d2bacd45a50f14e4e1aeae57cfc56a315db | __init__.py | __init__.py | from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name_... | from openedoo_project import db
from openedoo.core.libs import Blueprint
from .controllers.employee import EmployeeLogin, EmployeeLogout, AddEmployee, \
AssignEmployeeAsTeacher, EmployeeDashboard, EditEmployee, DeleteEmployee, \
SearchEmployee, AddSubject
module_employee = Blueprint('module_employee', __name_... | Make dashboard route become admin's default | Make dashboard route become admin's default
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee |
64d75740c485b8e3ac3108b916cdf72ad41b0611 | nacl/__init__.py | nacl/__init__.py | from . import hash # pylint: disable=W0622
| from . import __about__
from . import hash # pylint: disable=W0622
__all__ = ["hash"] + __about__.__all__
# - Meta Information -
# This is pretty ugly
for attr in __about__.__all__:
if hasattr(__about__, attr):
globals()[attr] = getattr(__about__, attr)
# - End Meta Information -
| Add meta information to the nacl package | Add meta information to the nacl package
| Python | mit | dstufft/pynacl,ucoin-bot/cutecoin,hoffmabc/pynacl,Insoleet/cutecoin,xueyumusic/pynacl,scholarly/pynacl,ucoin-io/cutecoin,dstufft/pynacl,lmctv/pynacl,JackWink/pynacl,JackWink/pynacl,xueyumusic/pynacl,pyca/pynacl,reaperhulk/pynacl,scholarly/pynacl,lmctv/pynacl,ucoin-io/cutecoin,alex/pynacl,pyca/pynacl,xueyumusic/pynacl,a... |
69ff671582bb343bd2ac9515964a3913e29f3d72 | oabutton/wsgi.py | oabutton/wsgi.py | """
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | """
WSGI config for oabutton project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION``... | Enable Django secure mode in WSGI module | Enable Django secure mode in WSGI module
| Python | mit | OAButton/OAButton_old,OAButton/OAButton_old,OAButton/OAButton_old |
65ef07040e8b0e34ce6dae42850789bdd8f4806a | cmsplugin_filer_file/models.py | cmsplugin_filer_file/models.py | from posixpath import exists
from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of ... | from cms.models import CMSPlugin
from django.db import models
from django.utils.translation import ugettext_lazy as _
from filer.fields.file import FilerFileField
from cmsplugin_filer_utils import FilerPluginManager
class FilerFile(CMSPlugin):
"""
Plugin for storing any type of file.
Default template di... | Use the file's storage to determine whether the file exists or not. The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage | Use the file's storage to determine whether the file exists or not.
The existing implementation that uses posixpath.exists only works if the storage backend is the default FileSystemStorage
| Python | bsd-3-clause | nephila/cmsplugin-filer,stefanfoulis/cmsplugin-filer,centralniak/cmsplugin-filer,creimers/cmsplugin-filer,stefanfoulis/cmsplugin-filer,yvess/cmsplugin-filer,alsoicode/cmsplugin-filer,yvess/cmsplugin-filer,jrutila/cmsplugin-filer,brightinteractive/cmsplugin-filer,wlanslovenija/cmsplugin-filer,sephii/cmsplugin-filer,elia... |
7b3f1edc1e9ba120a2718d0001135aa45c7a6753 | personnel/views.py | personnel/views.py | '''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory person... | '''This app contains the views for the personnel app.
'''
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from personnel.models import Person, JobPosting
class LaboratoryPersonnelList(ListView):
'''This class generates the view for current laboratory person... | Reset personnel page back to ordering by creation date. | Reset personnel page back to ordering by creation date.
| Python | mit | davebridges/Lab-Website,davebridges/Lab-Website,davebridges/Lab-Website |
39d67ed57d5c944afb06da1db4a18320e9ebd758 | bids/ext/__init__.py | bids/ext/__init__.py | __path__ = __import__('pkgutil').extend_path(__path__, __name__)
| """
The PyBIDS extension namespace package
``bids.ext`` is reserved as a namespace for extensions to install into.
To write such an extension, the following things are needed:
1) Create a new package with the following structure (assuming setuptools)::
package/
bids/
ext/
__init__.py
... | Add an explanation of how to set up a namespace package | DOC: Add an explanation of how to set up a namespace package
| Python | mit | INCF/pybids |
5d15ae493663b23d1554f4f285cf3d2044134878 | pybossa_analyst/zip_builder.py | pybossa_analyst/zip_builder.py | # -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.Zi... | # -*- coding: utf8 -*-
"""Zip builder module for pybossa-analyst."""
import requests
import zipstream
def _download(url):
"""Download data from a URL."""
yield requests.get(url).content
def _generate_zip(tasks, fn_key, url_key):
"""Generate a zip containing downloaded task data."""
z = zipstream.Zi... | Add jpg link for flickr downloads | Add jpg link for flickr downloads
| Python | unknown | alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,alexandermendes/pybossa-analyst,LibCrowds/libcrowds-analyst |
662f245ca6c3dbe50d92a73549715af7ec46015e | chainerrl/explorers/additive_gaussian.py | chainerrl/explorers/additive_gaussian.py | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class A... | from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import numpy as np
from chainerrl import explorer
class A... | Add low and high options to AdditiveGaussian | Add low and high options to AdditiveGaussian
| Python | mit | toslunar/chainerrl,toslunar/chainerrl |
bc6a7ddca30093fa469800c32690d77c4f443018 | tests/unit/test_notes.py | tests/unit/test_notes.py | import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"status": "ok"
}
"""
@requests_mock.mock()
def test_add_note(self, m... | import unittest
import requests_mock
from alertaclient.api import Client
class NotesTestCase(unittest.TestCase):
def setUp(self):
self.client = Client()
self.note = """
{
"id": "62b62c6c-fca3-4329-b517-fc47c2371e63",
"note": {
"at... | Fix unit tests for notes | Fix unit tests for notes
| Python | apache-2.0 | alerta/python-alerta,alerta/python-alerta-client,alerta/python-alerta-client |
4520360a0bbf223805cc963d58409626be2bd728 | capstone/mdp/fixed_game_mdp.py | capstone/mdp/fixed_game_mdp.py | from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
self._game = game
... | from .mdp import MDP
from .game_mdp import GameMDP
from ..utils import utility
class FixedGameMDP(GameMDP):
def __init__(self, game, opp_player, opp_idx):
'''
opp_player: the opponent player
opp_idx: the idx of the opponent player in the game
'''
super(FixedGameMDP, self).... | Call super __init__ in GameMDP | Call super __init__ in GameMDP
| Python | mit | davidrobles/mlnd-capstone-code |
cf1aa4c0e07e4049f6f41b43898047fb5a0893b2 | towel/templatetags/modelview_detail.py | towel/templatetags/modelview_detail.py | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
{% for ... | from django import template
from django.db import models
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def model_details(instance, fields=None):
"""
Returns a stream of ``verbose_name``, ``value`` pairs for the specified
model instance::
<table>
... | Allow specifying fields for model_details | Allow specifying fields for model_details
| Python | bsd-3-clause | matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel |
d150299c4e3165dbaf83867ac9944f03611cd63b | tornado_json/__init__.py | tornado_json/__init__.py | __version__='0.01'
| # As setup.py imports this module to get the version, try not to do anything
# with dependencies for the project here. If that happens, setup.py
# should not import tornado_json and instead use this find_version
# thing: https://github.com/jezdez/envdir/blob/a062497e4339d5eb11e8a95dc6186dea6231aeb1/setup.py#L24
#... | Add warning about setup.py import | Add warning about setup.py import
| Python | mit | ktalik/tornado-json,hfaran/Tornado-JSON,Tarsbot/Tornado-JSON |
ca214643b2a93bd9362182134624a8641b44aba2 | tree_stars/tree_stars.py | tree_stars/tree_stars.py | """Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
spaces = (levels... | """Output a tree of stars like so:
*
***
*
***
*****
*
***
*****
*******
Input argument is the number of levels to the tree (3 in this example)
"""
from sys import argv
def main(levels):
for level in xrange(levels):
for sub_level in xrange(level+2):
stars = ((2 * su... | Add solution using format method for centering. | Add solution using format method for centering.
| Python | mit | bm5w/codeeval |
9068a532bfc7ff2b6d6fb276efda669a5cd60b36 | example.py | example.py | import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUIn... | import os
import mmstats
import libgettid
class MyStats(mmstats.BaseMmStats):
pid = mmstats.StaticUIntField(label="sys.pid", value=os.getpid)
tid = mmstats.StaticInt64Field(label="sys.tid", value=libgettid.gettid)
uid = mmstats.StaticUInt64Field(label="sys.uid", value=os.getuid)
gid = mmstats.StaticUIn... | Make it more obvious that values initialize at 0 | Make it more obvious that values initialize at 0
| Python | bsd-3-clause | schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats |
906a5ee2b6e20b09b12d36d61271cd63cac49418 | py2pack/utils.py | py2pack/utils.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | Raise a ValueError from _get_archive_filelist instead of Exception | Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
| Python | apache-2.0 | saschpe/py2pack |
e26e3572a81e7ea3fd9ac4b3fd7f7739aa6c5779 | pymt/__init__.py | pymt/__init__.py | from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
| from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
# See https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode
import numpy as np
np.set_printoptions(legacy='1.13')
| Use legacy docstrings with numpy 1.14 | Use legacy docstrings with numpy 1.14
For an explanation, see https://github.com/numpy/numpy/blob/master/doc/release/1.14.0-notes.rst#many-changes-to-array-printing-disableable-with-the-new-legacy-printing-mode.
| Python | mit | csdms/pymt,csdms/coupling,csdms/coupling |
53aa7104616944f6206f8e2cd3684b0084158a11 | fabfile.py | fabfile.py | from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
... | from fabric.api import env, cd, run, shell_env, sudo
env.hosts = ['134.213.147.235']
env.user = 'root'
env.key_filename = '~/.ssh/id_di'
env.forward_agent = True
def deploy():
with cd('/srv/venv/mysite'):
run('git pull')
with cd('mysite'), shell_env(DJANGO_CONFIGURATION='Production'):
... | Add fab task to rebuild production database | Add fab task to rebuild production database
| Python | bsd-3-clause | Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto,Kvoti/ditto |
8dcf5b2c85430a09502649bb3bb95c7b56312c03 | pysearch/urls.py | pysearch/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'pysearch.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', inclu... | Connect search route to app | Connect search route to app
| Python | mit | nh0815/PySearch,nh0815/PySearch |
8025b6cad403ace01eb71af05d284d5fa0fa4ff7 | pandoc-figref.py | pandoc-figref.py | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#(... | #! /usr/bin/env python3
"""Pandoc filter that replaces labels of format {#?:???}, where ? is a
single lower case character defining the type and ??? is an alphanumeric
label, with numbers. Different types are counted separately.
"""
from pandocfilters import toJSONFilter, Str
import re
REF_PAT = re.compile('(.*)\{#(... | Fix issue with missing space after replacement | Fix issue with missing space after replacement
| Python | mit | scotthartley/pandoc-figref |
43612c86a3040de857e73bcc8ba7d24bde5a6a43 | pgcli/pgstyle.py | pgcli/pgstyle.py | from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style ... | from pygments.token import Token
from pygments.style import Style
from pygments.util import ClassNotFound
from prompt_toolkit.styles import default_style_extensions
import pygments.styles
def style_factory(name):
try:
style = pygments.styles.get_style_by_name(name)
except ClassNotFound:
style ... | Set completions meta-text styling to match | Set completions meta-text styling to match
| Python | bsd-3-clause | nosun/pgcli,TamasNo1/pgcli,zhiyuanshi/pgcli,dbcli/pgcli,nosun/pgcli,lk1ngaa7/pgcli,d33tah/pgcli,joewalnes/pgcli,joewalnes/pgcli,dbcli/vcli,janusnic/pgcli,suzukaze/pgcli,n-someya/pgcli,zhiyuanshi/pgcli,w4ngyi/pgcli,darikg/pgcli,d33tah/pgcli,janusnic/pgcli,w4ngyi/pgcli,koljonen/pgcli,koljonen/pgcli,suzukaze/pgcli,n-somey... |
8b33e63ab84e2da2168259d8ce17c8afac964500 | cacheops/management/commands/cleanfilecache.py | cacheops/management/commands/cleanfilecache.py | import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def handle(self, **options):
os.system('find %s -type f \! -iname "\." -mmin +0 -delete' % settings.FILE_CACHE_DIR)
| import os
from django.core.management.base import BaseCommand
from cacheops.conf import settings
class Command(BaseCommand):
help = 'Clean filebased cache'
def add_arguments(self, parser):
parser.add_argument('path', nargs='*', default=['default'])
def handle(self, **options):
for path... | Allow cleaning file cache in non default place | Allow cleaning file cache in non default place
| Python | bsd-3-clause | LPgenerator/django-cacheops,Suor/django-cacheops |
c4dae009a376f5ce4f707595c860e6d92f9953ea | web/webViews/dockletrequest.py | web/webViews/dockletrequest.py | import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request:... | import requests
from flask import abort, session
from webViews.log import logger
endpoint = "http://0.0.0.0:9000"
class dockletRequest():
@classmethod
def post(self, url = '/', data = {}):
#try:
data = dict(data)
data['token'] = session['token']
logger.info ("Docklet Request:... | Fix a bug that will lead to error when external_login() is called | Fix a bug that will lead to error when external_login() is called
| Python | bsd-3-clause | FirmlyReality/docklet,scorpionis/docklet,caodg/docklet,caodg/docklet,scorpionis/docklet,caodg/docklet,FirmlyReality/docklet,caodg/docklet,FirmlyReality/docklet,FirmlyReality/docklet |
aa07f5afe1b976e6b7f503056387e184ec0b64c3 | phileo/models.py | phileo/models.py | import datetime
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Like(models.Model):
sender = models.ForeignKey(User, related_name="liking")
receiver_content_typ... | from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Like(models.Model):
sender = models.ForeignKey(User, related_name="liking")
rec... | Update the use of now() | Update the use of now() | Python | mit | rizumu/pinax-likes,pinax/pinax-likes,jacobwegner/phileo,pinax/phileo,rizumu/pinax-likes,pinax/phileo,jacobwegner/phileo |
6dab43543e1b6a1e1e8119db9b38cc685dd81f82 | ckanext/qa/controllers/base.py | ckanext/qa/controllers/base.py | from ckan.lib.base import BaseController
from pylons import config
class QAController(BaseController):
def __init__(self, *args, **kwargs):
super(QAController, self).__init(*args, **kwargs) | from ckan.lib.base import BaseController
from pylons import config
class QAController(BaseController):
pass
| Fix typo in constructor. Seems unnecessary anyway. | Fix typo in constructor. Seems unnecessary anyway.
| Python | mit | ckan/ckanext-qa,ckan/ckanext-qa,ckan/ckanext-qa |
461f23a52569067a26c18dbf70a830c0494c0342 | deepchem/models/torch_models/__init__.py | deepchem/models/torch_models/__init__.py | # flake8:noqa
from deepchem.models.torch_models.torch_model import TorchModel
from deepchem.models.torch_models.attentivefp import AttentiveFP, AttentiveFPModel
from deepchem.models.torch_models.cgcnn import CGCNN, CGCNNModel
from deepchem.models.torch_models.gat import GAT, GATModel
from deepchem.models.torch_models.g... | # flake8:noqa
from deepchem.models.torch_models.torch_model import TorchModel
from deepchem.models.torch_models.attentivefp import AttentiveFP, AttentiveFPModel
from deepchem.models.torch_models.cgcnn import CGCNN, CGCNNModel
from deepchem.models.torch_models.gat import GAT, GATModel
from deepchem.models.torch_models.g... | Add layer to module imports | Add layer to module imports
| Python | mit | deepchem/deepchem,deepchem/deepchem |
93bf6cafa078978890df74a75355a48345f40534 | django_bootstrap_calendar/serializers.py | django_bootstrap_calendar/serializers.py | # -*- coding: utf-8 -*-
__author__ = 'sandlbn'
from django.utils import simplejson
from django.db.models.query import QuerySet
def event_serializer(events):
"""
serialize event model
"""
objects_body = []
if isinstance(events, QuerySet):
for event in events:
field = {
... | # -*- coding: utf-8 -*-
__author__ = 'sandlbn'
import json
from django.db.models.query import QuerySet
def event_serializer(events):
"""
serialize event model
"""
objects_body = []
if isinstance(events, QuerySet):
for event in events:
field = {
"id": event.pk,... | Use json (from stdlib) instead of simplejson from django utils | Use json (from stdlib) instead of simplejson from django utils
| Python | bsd-3-clause | sandlbn/django-bootstrap-calendar,mfmarlonferrari/django-bootstrap-calendar,arbitrahj/django-bootstrap-calendar,arbitrahj/django-bootstrap-calendar,dannybrowne86/django-bootstrap-calendar,tiagovaz/django-bootstrap-calendar,mfmarlonferrari/django-bootstrap-calendar,sandlbn/django-bootstrap-calendar,mfmarlonferrari/djang... |
c9ffe4fb86ccd39d199c953c860a9076cb309e0c | labonneboite/importer/jobs/check_etablissements.py | labonneboite/importer/jobs/check_etablissements.py | import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
if __name__ == "__main__":
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETAB... | import sys
from labonneboite.importer import util as import_util
from labonneboite.importer import settings
def run():
filename = import_util.detect_runnable_file("etablissements")
if filename:
with open(settings.JENKINS_ETAB_PROPERTIES_FILENAME, "w") as f:
f.write("LBB_ETABLISSEMENT_INPUT_... | Add a run method for the entry point | Add a run method for the entry point
| Python | agpl-3.0 | StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite,StartupsPoleEmploi/labonneboite |
25da28f685b9cffa86b9400957089bdd7b5513de | kaptan/handlers/yaml_handler.py | kaptan/handlers/yaml_handler.py | # -*- coding: utf8 -*-
"""
kaptan.handlers.yaml_handler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by the authors and contributors (See AUTHORS file).
:license: BSD, see LICENSE for more details.
"""
from __future__ import print_function, unicode_literals
import yaml
from . import BaseHandler... | # -*- coding: utf8 -*-
"""
kaptan.handlers.yaml_handler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2013 by the authors and contributors (See AUTHORS file).
:license: BSD, see LICENSE for more details.
"""
from __future__ import print_function, unicode_literals
import yaml
from . import BaseHandler... | Make YAML handler safe by default | Make YAML handler safe by default
Fixes #43 | Python | bsd-3-clause | emre/kaptan |
15d87fb06b3882334f48fd71b258e915dbefa6e1 | koans/about_list_assignments.py | koans/about_list_assignments.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(__, names)
def test_parallel_assignments(self):
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrayAssignments in the Ruby Koans
#
from runner.koan import *
class AboutListAssignments(Koan):
def test_non_parallel_assignment(self):
names = ["John", "Smith"]
self.assertEqual(["John", "Smith"], names)
def test_parallel_assi... | Add completed list assignments koan. | Add completed list assignments koan.
| Python | mit | javierjulio/python-koans-completed,javierjulio/python-koans-completed |
75edc4ff2dfc244f79504eea9770e072fceb5df9 | ppci/__main__.py | ppci/__main__.py | """ Main entry point """
# from ppci.cli import main
import sys
import importlib
valid_programs = [
"archive",
"asm",
"build",
"c3c",
"cc",
"disasm",
"hexdump",
"hexutil",
"java",
"link",
"llc",
"mkuimage",
"objcopy",
"objdump",
"ocaml",
"opt",
"p... | """ Main entry point """
# from ppci.cli import main
import sys
import importlib
valid_programs = [
"archive",
"asm",
"build",
"c3c",
"cc",
"disasm",
"hexdump",
"hexutil",
"java",
"ld",
"link",
"llc",
"mkuimage",
"objcopy",
"objdump",
"ocaml",
"op... | Add ld alias for the link subcommand. | Add ld alias for the link subcommand.
| Python | bsd-2-clause | windelbouwman/ppci-mirror,windelbouwman/ppci-mirror,windelbouwman/ppci-mirror,windelbouwman/ppci-mirror,windelbouwman/ppci-mirror,windelbouwman/ppci-mirror |
0463d8937f9efd571f3ad6846f6d1f351fcfe8e1 | px/px_cpuinfo.py | px/px_cpuinfo.py | def get_core_count():
"""
Count the number of cores in the system.
Returns a tuple (physical, logical) with counts of physical and logical
cores.
"""
pass
def get_core_count_from_proc_cpuinfo(proc_cpuinfo="/proc/cpuinfo"):
pass
def get_core_count_from_sysctl():
pass
| import os
import errno
import subprocess
def get_core_count():
"""
Count the number of cores in the system.
Returns a tuple (physical, logical) with counts of physical and logical
cores.
"""
pass
def get_core_count_from_proc_cpuinfo(proc_cpuinfo="/proc/cpuinfo"):
pass
def get_core_cou... | Implement core counting of OS X | Implement core counting of OS X
| Python | mit | walles/px,walles/px |
1f2a30c4316c6da714b7cbda1d6052e6e5040312 | rasterio/tool.py | rasterio/tool.py |
import code
import collections
import logging
import sys
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source, cmap='gray'):
"""Show a raster using matplotlib.
The raste... |
import code
import collections
import logging
import sys
import matplotlib.pyplot as plt
import numpy
import rasterio
logger = logging.getLogger('rasterio')
Stats = collections.namedtuple('Stats', ['min', 'max', 'mean'])
def main(banner, dataset):
def show(source, cmap='gray'):
"""Show a raster usin... | Add plt to rio_insp locals. | Add plt to rio_insp locals.
| Python | bsd-3-clause | johanvdw/rasterio,perrygeo/rasterio,youngpm/rasterio,youngpm/rasterio,clembou/rasterio,sgillies/rasterio,youngpm/rasterio,kapadia/rasterio,clembou/rasterio,kapadia/rasterio,kapadia/rasterio,brendan-ward/rasterio,brendan-ward/rasterio,perrygeo/rasterio,johanvdw/rasterio,njwilson23/rasterio,snorfalorpagus/rasterio,njwils... |
8d544103d08b17a48dc9d424db4498184e10d8a3 | tweepy/asynchronous/__init__.py | tweepy/asynchronous/__init__.py | # Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy.asynchronoous
Asynchronous interfaces with the Twitter API
"""
try:
import aiohttp
import oauthlib
except ModuleNotFoundError:
from tweepy.errors import TweepyException
raise TweepyException(
"tweepy.asynchr... | # Tweepy
# Copyright 2009-2022 Joshua Roesslein
# See LICENSE for details.
"""
Tweepy.asynchronoous
Asynchronous interfaces with the Twitter API
"""
try:
import aiohttp
import async_lru
import oauthlib
except ModuleNotFoundError:
from tweepy.errors import TweepyException
raise TweepyException(
... | Check for async_lru when importing asynchronous subpackage | Check for async_lru when importing asynchronous subpackage
| Python | mit | svven/tweepy,tweepy/tweepy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.