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 |
|---|---|---|---|---|---|---|---|---|---|
f38eb25fe13320297baad173c8e6d6ac7cfb9542 | spacy/tests/tokens/test_vec.py | spacy/tests/tokens/test_vec.py | from __future__ import unicode_literals
from spacy.en import English
import pytest
@pytest.mark.models
def test_vec(EN):
hype = EN.vocab['hype']
assert hype.orth_ == 'hype'
assert 0.08 >= hype.vector[0] > 0.07
@pytest.mark.models
def test_capitalized(EN):
hype = EN.vocab['Hype']
assert hype.ort... | from __future__ import unicode_literals
from spacy.en import English
import pytest
@pytest.mark.models
def test_vec(EN):
hype = EN.vocab['hype']
assert hype.orth_ == 'hype'
assert -0.7 >= hype.vector[0] > -0.8
@pytest.mark.models
def test_capitalized(EN):
hype = EN.vocab['Hype']
assert hype.ort... | Fix test for word vector | Fix test for word vector
| Python | mit | oroszgy/spaCy.hu,recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,banglakit/spaCy,explosion/spaCy,explosion/spaCy,raphael0202/spaCy,banglakit/spaCy,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,recognai/spaCy,Gregory-Howard/spaCy,aikramer2/spaCy,honnibal/spaCy,recognai/spaCy,banglakit/spaCy,explosion/spaCy,a... |
e81c56e1f3b682e0cfffa40851aed817be3b1812 | etcd3/__init__.py | etcd3/__init__.py | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.2.2'
__all__ = (
'Etcd3Cli... | from __future__ import absolute_import
import etcd3.etcdrpc as etcdrpc
from etcd3.client import Etcd3Client
from etcd3.client import Transactions
from etcd3.client import client
from etcd3.leases import Lease
from etcd3.members import Member
__author__ = 'Louis Taylor'
__email__ = 'louis@kragniz.eu'
__version__ = '0.... | Add Lease to public api | Add Lease to public api
| Python | apache-2.0 | kragniz/python-etcd3 |
00a7f13ac2dbbd7449fd0ce260a21448c67b73e9 | birdwatch/api.py | birdwatch/api.py | __author__ = 'jloeffler'
def list_projects():
return {}
def list_contributors():
return {}
| __author__ = 'jloeffler'
from github3 import GitHub
from github3.models import GitHubError
from github3.repos.repo import Repository
from birdwatch.configuration import configuration
from birdwatch.collector import Project
def list_projects():
# just for testing
github = GitHub(token=configuration.github_tok... | Return one project for testing | Return one project for testing
| Python | apache-2.0 | marky-mark/catwatch,AlexanderYastrebov/catwatch,AlexanderYastrebov/catwatch,marky-mark/catwatch,AlexanderYastrebov/catwatch,marky-mark/catwatch,AlexanderYastrebov/catwatch,marky-mark/catwatch |
692f13b9dbe994baf44bf42384e956608b94fede | aldryn_apphooks_config/utils.py | aldryn_apphooks_config/utils.py | # -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request obj... | # -*- coding: utf-8 -*-
from app_data import AppDataContainer, app_registry
from cms.apphook_pool import apphook_pool
from django.core.urlresolvers import resolve
def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request obj... | Add better check for being in a CMS-page request | Add better check for being in a CMS-page request
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config |
829ad434f42b457294d44108b26c6880cd0e4c36 | pymatgen/__init__.py | pymatgen/__init__.py | __author__ = ", ".join(["Shyue Ping Ong", "Anubhav Jain", "Geoffroy Hautier",
"William Davidson Richard", "Stephen Dacek",
"Sai Jayaraman", "Michael Kocher", "Dan Gunter",
"Shreyas Cholia", "Vincent L Chevrier",
"Rickard Arm... | __author__ = ", ".join(["Shyue Ping Ong", "Anubhav Jain", "Geoffroy Hautier",
"William Davidson Richard", "Stephen Dacek",
"Sai Jayaraman", "Michael Kocher", "Dan Gunter",
"Shreyas Cholia", "Vincent L Chevrier",
"Rickard Arm... | Remove zopen in pymatgen root. | Remove zopen in pymatgen root.
Former-commit-id: 375be0147716d3b4d2dee95680eae4ee3804716b [formerly 05648421c1fa77f6f339f68be2c43bb7952e918a]
Former-commit-id: e5cfaf0277815951ddb09d9d6b30876e400870d7 | Python | mit | dongsenfo/pymatgen,Bismarrck/pymatgen,czhengsci/pymatgen,fraricci/pymatgen,blondegeek/pymatgen,johnson1228/pymatgen,montoyjh/pymatgen,richardtran415/pymatgen,vorwerkc/pymatgen,fraricci/pymatgen,tallakahath/pymatgen,mbkumar/pymatgen,davidwaroquiers/pymatgen,ndardenne/pymatgen,montoyjh/pymatgen,xhqu1981/pymatgen,vorwerkc... |
0563882d0d1bfdf4e64a65bcd91e8d6d4ab6ed8f | core/polyaxon/polypod/compiler/lineage/artifacts_collector.py | core/polyaxon/polypod/compiler/lineage/artifacts_collector.py | #!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | #!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Fix artifacts name sanitization for root folders | Fix artifacts name sanitization for root folders
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
365da65390a0c2093fbbc5681c72cbfbd73ae78f | rctk/widgets/text.py | rctk/widgets/text.py | from rctk.widgets.control import Control, remote_attribute
from rctk.task import Task
from rctk.event import Changable, Submittable
class Text(Control, Changable, Submittable):
name = "text"
value = remote_attribute('value', "")
def __init__(self, tk, value="", rows=1, columns=20):
self._value =... | from rctk.widgets.control import Control, remote_attribute
from rctk.task import Task
from rctk.event import Changable, Submittable
class Text(Control, Changable, Submittable):
name = "text"
value = remote_attribute('value', "")
def __init__(self, tk, value="", rows=1, columns=20, **properties):
... | Allow additional properties on Text | Allow additional properties on Text
git-svn-id: ec97508af0aa29a1d296967d6f0ba22a468c79d6@350 286bb87c-ec97-11de-a004-2f18c49ebcc3
| Python | bsd-2-clause | rctk/rctk,rctk/rctk |
5d1fe61d152d2c5544982322a9f156809ea267f0 | main.py | main.py | from __future__ import print_function
import time
from slackclient import SlackClient
import mh_python as mh
import argparse
import random
def main():
parser = argparse.ArgumentParser(
description="Slack chatbot using MegaHAL")
parser.add_argument(
"-t", "--token", type=str, help="Slack token"... | from __future__ import print_function
import time
from slackclient import SlackClient
import mh_python as mh
import argparse
import random
def main():
parser = argparse.ArgumentParser(
description="Slack chatbot using MegaHAL")
parser.add_argument(
"-t", "--token", type=str, help="Slack token"... | Fix crashes from misc. events | Fix crashes from misc. events
| Python | mit | Spferical/slack-megahal,Spferical/matrix-chatbot,Spferical/matrix-chatbot,Spferical/matrix-megahal |
152dfbb9fc5ca5fe5c859fea5ba4a25a31f3ff13 | gn/compile_processors.py | gn/compile_processors.py | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
skslc = sys.argv[1]
clangFormat = sys.argv[2]
fetchClangFormat = sys.argv[3]
processors = sys.argv[4:]
exeSuffix = '.exe'... | #!/usr/bin/env python
#
# Copyright 2017 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import subprocess
import sys
skslc = sys.argv[1]
clangFormat = sys.argv[2]
fetchClangFormat = sys.argv[3]
processors = sys.argv[4:]
exeSuffix = '.exe'... | Remove "Recompiling..." output when building .fp files | Remove "Recompiling..." output when building .fp files
Change-Id: I41402dc04d4388217d7f7cd8de9aff8fbb4a3765
Reviewed-on: https://skia-review.googlesource.com/c/skia/+/317391
Reviewed-by: John Stiles <f4fcf42d3bb5924557f1eeb3be66747535e585da@google.com>
Commit-Queue: Brian Osman <794c0b5534edf5601d88e1d41975d0262da1289... | Python | bsd-3-clause | google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/pla... |
c1508d51a90db1ebf3c0278c777ff3169e0d13f9 | tests/unit/test_wrapper.py | tests/unit/test_wrapper.py | import numpy as np
from functools import partial
from elfi.wrapper import Wrapper
class Test_wrapper():
def test_echo_exec_arg(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper("1")
assert ret == 1
def test_echo_default_arg(self):
command ... | import numpy as np
from functools import partial
from elfi.wrapper import Wrapper
class Test_wrapper():
def test_echo_exec_arg(self):
command = "echo {0}"
wrapper = Wrapper(command, post=int)
ret = wrapper("1")
assert ret == 1
def test_echo_default_arg(self):
command ... | Add test for 1d array arguments for Wrapper | Add test for 1d array arguments for Wrapper
| Python | bsd-3-clause | lintusj1/elfi,elfi-dev/elfi,lintusj1/elfi,HIIT/elfi,elfi-dev/elfi |
90655c89fcf56af06a69f8110a9f7154294ca11c | ritter/analytics/sentiment_analyzer.py | ritter/analytics/sentiment_analyzer.py | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calculate_friend_scores... | import re, math
from collections import Counter
import itertools
from sentimental import sentimental
class SentimentAnalyzer():
_sentimental = sentimental.Sentimental(max_ngrams=2, undersample=True)
path = sentimental.Sentimental.get_datafolder()
_sentimental.train([path + '/sv/ruhburg'])
def calcu... | Update to Sentimental 2.2.x with undersampling | feat: Update to Sentimental 2.2.x with undersampling
| Python | mit | ErikGartner/ghostdoc-ritter |
93be15b7f74673247eeabc208fd56cc6cb735e43 | tests/matchers/test_contain.py | tests/matchers/test_contain.py | import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestAbove(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain({1, 2, 3}, 1).matches()) == True
expect(Contain([1, 2, 3], 2).matches()... | import unittest
from robber import expect
from robber.matchers.contain import Contain
class TestAbove(unittest.TestCase):
def test_matches(self):
expect(Contain({'key': 'value'}, 'key').matches()) == True
expect(Contain([1, 2, 3], 2).matches()) == True
expect(Contain((1, 2, 3), 3).matches()... | Remove sets from tests Since python 2.6 does not have literal set syntax | Remove sets from tests
Since python 2.6 does not have literal set syntax | Python | mit | vesln/robber.py,taoenator/robber.py |
6ee083f5b5a190f30f4916698c57c7ee1c2225fe | create_sample.py | create_sample.py | # importing modules/ libraries
import pandas as pd
import random
# create sample of order products train data
n = 1384617
s = round(0.1 * n)
skip = sorted(random.sample(range(1,n), n-s))
order_products__train_sample_df = pd.read_csv('Data/order_products__train.csv',
skiprows = s... | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create sample of order products train data
n = 1384617
s = round(0.1 * n)
skip = sorted(random.sample(range(1,n), n-s))
order_products__train_sample_df = pd.read_csv('Data/order_products__train.csv',
... | Change create sample code to ensure matching order ids data | fix: Change create sample code to ensure matching order ids data
| Python | mit | rjegankumar/instacart_prediction_model |
acc3888ef55d7df22df08b16cc746186fc1a75c7 | main.py | main.py | #!/usr/bin/env python3
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(loop... | #!/usr/bin/env python3.6
import argparse
import asyncio
import logging
import sys
from pathlib import Path
from MoMMI.logsetup import setup_logs
# Do this BEFORE we import master, because it does a lot of event loop stuff.
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop()
asyncio.set_event_loop(lo... | Use uvloop because apparently it's fast. | Use uvloop because apparently it's fast.
| Python | mit | PJB3005/MoMMI,PJB3005/MoMMI,PJB3005/MoMMI |
3fb56e434182e5b28dcad0c547b0326ebe5be352 | main.py | main.py | from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(descripti... | from createCollection import createCollectionFile
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path, argparse
CONST_COLLECTIONS_NAME = 'collections'
def generateArgumentsFromParser():
parser = parser = argparse.ArgumentParser(descripti... | Refactor create action into function | Refactor create action into function
| Python | apache-2.0 | AmosGarner/PyInventory |
f34f67247d97d75039c65f71da8489fbffa17575 | snowpenguin/django/recaptcha2/tests.py | snowpenguin/django/recaptcha2/tests.py | import os
from django.forms import Form
from django.test import TestCase
from snowpenguin.django.recaptcha2.fields import ReCaptchaField
from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget
class RecaptchaTestForm(Form):
recaptcha = ReCaptchaField(widget=ReCaptchaWidget())
class TestRecaptchaForm... | import os
from django.forms import Form
from django.test import TestCase
from snowpenguin.django.recaptcha2.fields import ReCaptchaField
from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget
class RecaptchaTestForm(Form):
recaptcha = ReCaptchaField(widget=ReCaptchaWidget())
class TestRecaptchaForm... | Check possible exception with wrong key data | Check possible exception with wrong key data
| Python | lgpl-2.1 | kbytesys/django-recaptcha2,kbytesys/django-recaptcha2 |
969aed7046e4965962e8ed5daa9c557baffc48bc | glue_h5part/io.py | glue_h5part/io.py | import os
import h5py
from glue.core import Data
def read_step_to_data(filename, step_id=0):
"""
Given a filename and a step ID, read in the data into a new Data object.
"""
f = h5py.File(filename, 'r')
try:
group = f['Step#{0}'.format(step_id)]
except KeyError:
raise ValueEr... | import os
import h5py
from glue.core import Data
def read_step_to_data(filename, step_id=0):
"""
Given a filename and a step ID, read in the data into a new Data object.
"""
f = h5py.File(filename, 'r')
try:
group = f['Step#{0}'.format(step_id)]
except KeyError:
raise ValueEr... | Fix issue with HDF5 objects that don't have a value | Fix issue with HDF5 objects that don't have a value | Python | bsd-2-clause | glue-viz/glue-h5part |
adee7a2530d22d1242f89cddc84795efd1d02653 | imagesift/cms_plugins.py | imagesift/cms_plugins.py | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesif... | import datetime
from django.utils.translation import ugettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from .models import GalleryPlugin
class ImagesiftPlugin(CMSPluginBase):
model = GalleryPlugin
name = _('Imagesift Plugin')
render_template = "imagesif... | Sort returned images by date, taking into account overrides | Sort returned images by date, taking into account overrides
| Python | bsd-3-clause | topiaruss/cmsplugin-imagesift,topiaruss/cmsplugin-imagesift,topiaruss/cmsplugin-imagesift |
8f14126e36e7f5c15431cd7541762e485c3f8169 | main.py | main.py | from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime
import json
def main():
#createCollection('agarner','books')
now = datetime.datetime.now()
items = []
for i in range(0,10):
... | from createCollection import createCollection
from ObjectFactories.ItemFactory import ItemFactory
from DataObjects.Collection import Collection
import datetime, json, os.path
CONST_COLLECTIONS_NAME = 'collections'
CONST_USERNAME = 'agarner'
CONST_COLLECTION = 'Items'
def generateItemsCollection():
items = []
... | Implement ability to save json data to collection file | Implement ability to save json data to collection file
| Python | apache-2.0 | AmosGarner/PyInventory |
d63509e0d68a1dceabbbcf58432a92f7a4cbfd77 | robot/robot/src/autonomous/main.py | robot/robot/src/autonomous/main.py |
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self):
super().__init__()
print("Team 1418 robot code for 2014")
... |
try:
import wpilib
except ImportError:
from pyfrc import wpilib
# import components here
from components import drive, intake, catapult
class MyRobot(wpilib.SimpleRobot):
def __init__ (self, drive, intake, catapult):
super().__init__()
print("Team 1418 autonomous... | Bring the autonomous mode back | Bring the autonomous mode back
| Python | bsd-3-clause | frc1418/2014 |
ba4ea2169a13d61d30c94e89db512a34bc0fe3b5 | bluesky/tests/test_documents.py | bluesky/tests/test_documents.py | from bluesky.run_engine import RunEngine
from bluesky.tests.utils import setup_test_run_engine
from bluesky.examples import simple_scan, motor
RE = setup_test_run_engine()
def test_custom_metadata():
def assert_lion(name, doc):
assert 'animal' in doc
assert doc['animal'] == 'lion'
RE(simple... | import pytest
import jsonschema
from bluesky.run_engine import RunEngine
from event_model import DocumentNames, schemas
from bluesky.tests.utils import setup_test_run_engine
from bluesky.utils import new_uid
from bluesky.examples import simple_scan, motor
RE = setup_test_run_engine()
def test_custom_metadata():
... | Test that event_model forbids dots in key names. | TST: Test that event_model forbids dots in key names.
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky |
aca1b138350434c9afb08f31164269cd58de1d2d | YouKnowShit/CheckFile.py | YouKnowShit/CheckFile.py | import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updir)
for file in filenames... | import os
import sys
(dir, filename) = os.path.split(os.path.abspath(sys.argv[0]))
print(dir)
filenames = os.listdir(dir)
for file in filenames:
print(file)
print()
print()
print()
print('*****************************************************')
updir = os.path.abspath('..')
print(updir)
filenames = os.listdir(updi... | Add a level of uper directory | Add a level of uper directory
| Python | mit | jiangtianyu2009/PiSoftCake |
1f527bd99a35cf6396e6300369719b3f5f5490ff | app/main/forms.py | app/main/forms.py | from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
class EmailAddressForm(Form):
email_address = StripWhitespaceStringField('Email address', validators=[
validators.DataRequired(message="Email can not be empty"),
validators.Email(mes... | from flask.ext.wtf import Form
from wtforms import validators
from dmutils.forms import StripWhitespaceStringField
from .. import data_api_client
class AdminEmailAddressValidator(object):
def __init__(self, message=None):
self.message = message
def __call__(self, form, field):
if not data_... | Add new validator that applies data_api_client.email_is_valid_for_admin_user to field | Add new validator that applies data_api_client.email_is_valid_for_admin_user to field
| Python | mit | alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend |
62b7b01fe9a1d87692e97a6a75b52d542f8a43be | scrapi/processing/elastic_search.py | scrapi/processing/elastic_search.py | import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('elasticsearch.... | import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('elasticsearch.... | Add some versioning for dateUpdated so that updated documents aren't bumped to the top of the stream | Add some versioning for dateUpdated so that updated documents aren't bumped to the top of the stream
| Python | apache-2.0 | fabianvf/scrapi,felliott/scrapi,fabianvf/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,mehanig/scrapi,felliott/scrapi,ostwald/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,jeffreyliu3230/scrapi,alexgarciac/scrapi |
0460404bb7f3e9a9f6ece1c4a141b16fced6f741 | tests/test_chunked_http.py | tests/test_chunked_http.py | from disco.test import TestCase, TestJob
from disco.core import Job
import disco
import threading
import BaseHTTPServer
def map(line, params):
for word in line.split():
yield word, 1
def reduce(iter, params):
from disco.util import kvgroup
for word, counts in kvgroup(sorted(iter)):
yield ... | from disco.test import TestCase, TestJob
from disco.core import Job
from disco.compat import http_server
import disco
import threading
def map(line, params):
for word in line.split():
yield word, 1
def reduce(iter, params):
from disco.util import kvgroup
for word, counts in kvgroup(sorted(iter)):... | Use the disco.compat.http_server to work with python3. | Use the disco.compat.http_server to work with python3.
| Python | bsd-3-clause | pombredanne/disco,simudream/disco,ErikDubbelboer/disco,beni55/disco,discoproject/disco,ErikDubbelboer/disco,oldmantaiter/disco,simudream/disco,oldmantaiter/disco,seabirdzh/disco,seabirdzh/disco,seabirdzh/disco,discoproject/disco,ktkt2009/disco,discoproject/disco,ktkt2009/disco,beni55/disco,ErikDubbelboer/disco,pombreda... |
dd5b8c55e601709f1f04cb0ec7dbde63b84801d8 | snippet_parser/fr.py | snippet_parser/fr.py | #-*- encoding: utf-8 -*-
import base
class SnippetParser(base.SnippetParserBase):
def strip_template(self, template, normalize, collapse):
if template.name.matches('unité'):
return ' '.join(map(unicode, template.params[:2]))
elif self.is_citation_needed(template):
repl = [b... | #-*- encoding: utf-8 -*-
import base
def handle_date(template):
year = None
if len(template.params) >= 3:
try:
year = int(unicode(template.params[2]))
except ValueError:
pass
if isinstance(year, int):
# assume {{date|d|m|y|...}}
return ' '.join(map(u... | Implement a couple of other French templates. | Implement a couple of other French templates.
Still need to add tests for these.
Former-commit-id: 4021d27a7bd15a396b637beb57c10fc95936cb3f | Python | mit | eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,eggpi/citationhunt |
878c14e04327f2f9d2d4acd22de21ed23b0cfb9a | skan/test/test_vendored_correlate.py | skan/test/test_vendored_correlate.py | from time import time
import numpy as np
from skan.vendored import thresholding as th
class Timer:
def __init__(self):
self.interval = 0
def __enter__(self):
self.t0 = time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.interval = time() - self.t0
def... | from time import time
from functools import reduce
import numpy as np
from skan.vendored import thresholding as th
from skimage.transform import integral_image
from scipy import ndimage as ndi
class Timer:
def __init__(self):
self.interval = 0
def __enter__(self):
self.t0 = time()
ret... | Add test for new fast correlation | Add test for new fast correlation
| Python | bsd-3-clause | jni/skan |
98ba687e67c8d5a17560bed59f42dbe8e3fb0cf6 | amaascore/books/enums.py | amaascore/books/enums.py | from __future__ import absolute_import, division, print_function, unicode_literals
BOOK_TYPES = {'Counterparty', 'Individual', 'Management', 'Trading', 'Wash'}
| from __future__ import absolute_import, division, print_function, unicode_literals
BOOK_TYPES = {'Counterparty', 'Management', 'Trading', 'Wash'}
| Remove Individual as a book_type - it doesn’t really add anything. AMAAS-639. | Remove Individual as a book_type - it doesn’t really add anything. AMAAS-639.
| Python | apache-2.0 | amaas-fintech/amaas-core-sdk-python,nedlowe/amaas-core-sdk-python,paul-rs/amaas-core-sdk-python,amaas-fintech/amaas-core-sdk-python,nedlowe/amaas-core-sdk-python,paul-rs/amaas-core-sdk-python |
4650b6730d925c4a5fde34ec4c2f9058763ab58b | cupcake/smush.py | cupcake/smush.py | """
User-facing interface to all dimensionality reduction algorithms
"""
def smushplot(data, smusher):
if isinstance(smusher, str):
# Need to get appropriate smusher from sklearn given the string
pass
else:
# Assume this is already an initialized sklearn object with the
# ``fit_... | """
User-facing interface for plotting all dimensionality reduction algorithms
"""
def smushplot(data, smusher, n_components=2, marker='o', marker_order=None,
text=False, text_order=None, linewidth=1, linewidth_order=None,
edgecolor='k', edgecolor_order=None, smusher_kws=None,
... | Add a bunch of plotting and keyword arguments | Add a bunch of plotting and keyword arguments
| Python | bsd-3-clause | olgabot/cupcake |
fc7c08aecf9d247e54db70ae14c999902d6f6bfa | workflow/migrations/0024_auto_20180620_0537.py | workflow/migrations/0024_auto_20180620_0537.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-06-20 12:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workflow', '0023_auto_20180425_0136'),
]
operations = [
migrations.AddField... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2018-06-20 12:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workflow', '0023_auto_20180425_0136'),
]
operations = [
migrations.AddField... | Fix the dashboard migration for UUID | Fix the dashboard migration for UUID
| Python | apache-2.0 | toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity,toladata/TolaActivity |
9c6ad90f20354ca47a2fc56cc0d7ff6ebfc613d3 | weather/weather-display.py | weather/weather-display.py | #!/usr/bin/env python
from subprocess import call
URL = 'http://microdash.herokuapp.com/FOG/'
OUTPUT_FILE = '/mnt/us/weather/weather-script-output.png'
def clear_screen():
call('/usr/sbin/eips -c', shell=True)
def get_image():
call('wget -O "%s" "%s"' % (OUTPUT_FILE, URL), shell=True)
def main():
cle... | #!/usr/bin/env python
from subprocess import call
from datetime import datetime
URL = 'http://microdash.herokuapp.com/FOG/'
OUTPUT_FILE = '/mnt/us/weather/weather-script-output.png'
def clear_screen():
call('/usr/sbin/eips -c', shell=True)
def get_dashboard(url, output_file):
call('rm %s' % output_file, sh... | Update weather display to be run during specified intervals. | Update weather display to be run during specified intervals.
| Python | bsd-3-clause | alfredo/microdash,alfredo/microdash |
c1189bf7c24068fda9871436a705b70fd016dfd5 | examples/json_editor.py | examples/json_editor.py | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSO... | """
This is a very basic usage example of the JSONCodeEdit.
The interface is minimalist, it will open a test file. You can open other
documents by pressing Ctrl+O
"""
import logging
import os
import random
import sys
from pyqode.qt import QtWidgets
from pyqode.core import api, modes
from pyqode.json.widgets import JSO... | Add missing open action to the example so that you can open other files | Add missing open action to the example so that you can open other files
(usefull for testing and evaluating)
| Python | mit | pyQode/pyqode.json,pyQode/pyqode.json |
446738f7615711766952205558fee7ce85ca3a3b | MS1/ddp-erlang-style/dna_lib.py | MS1/ddp-erlang-style/dna_lib.py | __author__ = 'mcsquaredjr'
import os
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
def my_lines(ip):
with open(cad_file, "r") as cad:
lines = []
for line in cad:
ip, port = line.split(":")
if ip == str(ip):
... | __author__ = 'mcsquaredjr'
import os
import socket
node_file = os.environ["NODES"]
cad_file = os.environ["CAD"]
procs_per_nod = os.environ["PROCS_PER_NODE"]
itemcount = os.environ["ITEMCOUNT"]
ddp = os.environment["DDP"]
def my_lines(i):
ip = socket.gethostbyname(socket.gethostname())
with open(cad_file, "... | Add more variables and bug fixes | Add more variables and bug fixes
| Python | apache-2.0 | SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC,SKA-ScienceDataProcessor/RC |
f6013aa29fddf9883f8f0bea4b7733718b9d8846 | core/admin/migrations/versions/3f6994568962_.py | core/admin/migrations/versions/3f6994568962_.py | """ Add keep as an option in fetches
Revision ID: 3f6994568962
Revises: 2335c80a6bc3
Create Date: 2017-02-02 22:31:00.719703
"""
# revision identifiers, used by Alembic.
revision = '3f6994568962'
down_revision = '2335c80a6bc3'
from alembic import op
import sqlalchemy as sa
from mailu import app
fetch_table = sa.... | """ Add keep as an option in fetches
Revision ID: 3f6994568962
Revises: 2335c80a6bc3
Create Date: 2017-02-02 22:31:00.719703
"""
# revision identifiers, used by Alembic.
revision = '3f6994568962'
down_revision = '2335c80a6bc3'
from alembic import op
import sqlalchemy as sa
fetch_table = sa.Table(
'fetch',
... | Fix an old migration that was reading configuration before migrating | Fix an old migration that was reading configuration before migrating
| Python | mit | kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io,kaiyou/freeposte.io |
9e785ef701e4c9d04924eff0ffc9c8d50fa267f6 | ingestors/email/outlookpst.py | ingestors/email/outlookpst.py | from ingestors.base import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
class OutlookPSTIngestor(Ingestor, TempFileSupport, ShellSupport, OLESupport):
MIME... | from ingestors.base import Ingestor
from ingestors.support.temp import TempFileSupport
from ingestors.support.shell import ShellSupport
from ingestors.support.ole import OLESupport
from ingestors.directory import DirectoryIngestor
class OutlookPSTIngestor(Ingestor, TempFileSupport, ShellSupport, OLESupport):
MIME... | Make readpst partial output ingest. | Make readpst partial output ingest.
| Python | mit | alephdata/ingestors |
b4c292374175b8623a232bed47e8fa0bef60680b | astatsscraper/parsing.py | astatsscraper/parsing.py | def parse_app_page(response):
# Should always be able to grab a title
title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip()
# Parse times into floats
time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[s... | def parse_app_page(response):
# Should always be able to grab a title
title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip()
# Parse times into floats
time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[s... | Fix up parse search func | Fix up parse search func
| Python | mit | SingingTree/AStatsScraper,SingingTree/AStatsScraper |
43d283cb4cb01ec919f9129571a51594e699fcf5 | src/gogoutils/formats.py | src/gogoutils/formats.py | """Determine the generator format"""
from collections import ChainMap
DEFAULT_FORMAT = {
'domain': 'example.com',
'app': '{repo}{project}',
'dns_elb': '{repo}.{project}.{env}.{domain}',
'dns_instance': '{repo}{project}-xx.{env}.{domain}',
'iam_base': '{project}_{repo}',
'iam_user': '{project}_{... | """Determine the generator format"""
try:
from collections import ChainMap
except ImportError:
from ConfigParser import _Chainmap as ChainMap
DEFAULT_FORMAT = {
'domain': 'example.com',
'app': '{repo}{project}',
'dns_elb': '{repo}.{project}.{env}.{domain}',
'dns_instance': '{repo}{project}-xx.{... | Add Chainmap support for python2 | Add Chainmap support for python2
| Python | apache-2.0 | gogoair/gogo-utils |
a75ff3a9d9b86ea71fbc582641ea943c282bfe2d | analyser/api.py | analyser/api.py | from flask.ext.classy import FlaskView
class AnalyserView(FlaskView):
def get(self):
return "awesome"
| from flask.ext.classy import FlaskView
from utils.decorators import validate, require
from utils.validators import validate_url
class AnalyserView(FlaskView):
@require('url')
@validate({
'url': validate_url
})
def post(self, url):
return url
| Add more joy using decorators | Add more joy using decorators
| Python | apache-2.0 | vtemian/kruncher |
402c010b6ab4673ae3b5c684b8e0c155ec98b172 | gentle/gt/operations.py | gentle/gt/operations.py | #coding=utf-8
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green
from .utils import repl_root
from .project import... | #coding=utf-8
from __future__ import absolute_import
from fabric.api import local, run, sudo, task
from fabric.contrib.console import confirm
from fabric.state import env
from fabric.context_managers import cd, lcd, hide, settings
from fabric.colors import red, green, yellow
from .utils import repl_root
from .projec... | Add yellow color for services | Add yellow color for services
| Python | apache-2.0 | dongweiming/gentle |
7a804eac3f354a778eda3daa8cd5f88b09259f74 | south/signals.py | south/signals.py | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... | Remove the auth contenttypes thing for now, needs improvement | Remove the auth contenttypes thing for now, needs improvement
| Python | apache-2.0 | smartfile/django-south,smartfile/django-south |
8b1d878aff4168d74437d3ba0cfaf8307e7c377d | consts/model_type.py | consts/model_type.py | class ModelType(object):
"""
Enums for the differnet model types
DO NOT CHANGE EXISTING ONES
"""
EVENT = 0
TEAM = 1
MATCH = 2
EVENT_TEAM = 3
DISTRICT = 4
AWARD = 5
MEDIA = 6
| class ModelType(object):
"""
Enums for the differnet model types
DO NOT CHANGE EXISTING ONES
"""
EVENT = 0
TEAM = 1
MATCH = 2
EVENT_TEAM = 3
DISTRICT = 4
DISTRICT_TEAM = 5
AWARD = 6
MEDIA = 7
| Update model enums to match app | Update model enums to match app
| Python | mit | josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,1fish2/the-blue-alliance,synth3tk/the-blue-alliance,bvisness/the-blue-alli... |
4fb3a127706d7ff7ead0d2d8b698183905d85d4e | dependency_injector/__init__.py | dependency_injector/__init__.py | """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Ob... | """Dependency injector."""
from .catalog import AbstractCatalog
from .catalog import override
from .providers import Provider
from .providers import Delegate
from .providers import Factory
from .providers import Singleton
from .providers import ExternalDependency
from .providers import Class
from .providers import Ob... | Add additional shortcuts for top level package | Add additional shortcuts for top level package
| Python | bsd-3-clause | ets-labs/python-dependency-injector,ets-labs/dependency_injector,rmk135/dependency_injector,rmk135/objects |
b61bf7dbdb26b6ff3e76f10173ffb94a76cd4f4e | lego.py | lego.py | import cv2
WINDOW_NAME = 'hello'
def global_on_mouse(event, x, y, unknown, lego_player):
lego_player.on_mouse(event, x, y)
class LegoPlayer(object):
def __init__(self):
self.rect = []
cv2.namedWindow(WINDOW_NAME)
cv2.setMouseCallback(WINDOW_NAME, global_on_mouse, self)
self.c... | import numpy as np
import cv2
WINDOW_NAME = 'hello'
def global_on_mouse(event, x, y, unknown, lego_player):
lego_player.on_mouse(event, x, y)
class LegoPlayer(object):
def __init__(self):
self.rect = np.empty((4, 2))
self.rect_index = -1
cv2.namedWindow(WINDOW_NAME)
cv2.setMo... | Use numpy array for ROI | Use numpy array for ROI
| Python | mit | superquadratic/beat-bricks |
da75222fa286588394da7f689d47bd53716ffaa1 | coverage/execfile.py | coverage/execfile.py | """Execute files of Python code."""
import imp, os, sys
def run_python_file(filename, args):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, includin... | """Execute files of Python code."""
import imp, os, sys
def run_python_file(filename, args):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, includin... | Simplify the construction of the __main__ module in run_python_file. | Simplify the construction of the __main__ module in run_python_file.
| Python | apache-2.0 | blueyed/coveragepy,nedbat/coveragepy,larsbutler/coveragepy,blueyed/coveragepy,7WebPages/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,blueyed/coveragepy,7... |
64d7fb0b9ae9e14447a236a51e27b033aee20219 | urls.py | urls.py | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^registration/', include('registration.urls')),
(r'^$', direct_to_... | from django.conf.urls.defaults import *
from django.contrib import admin
from django.views.generic.simple import direct_to_template
import settings
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^accounts/', include('registration.urls')),
(r'^$', direct_to_temp... | Move pages from registration to accounts/ | Move pages from registration to accounts/
| Python | agpl-3.0 | pu239ppy/authentic2,BryceLohr/authentic,pu239ppy/authentic2,incuna/authentic,adieu/authentic2,pu239ppy/authentic2,pu239ppy/authentic2,incuna/authentic,adieu/authentic2,adieu/authentic2,BryceLohr/authentic,BryceLohr/authentic,incuna/authentic,incuna/authentic,adieu/authentic2,incuna/authentic,BryceLohr/authentic |
96884e4c35b89cb1f63a6249c9c24e27894a3752 | tacker/db/api.py | tacker/db/api.py | # Copyright 2011 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Copyright 2011 VMware, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | Remove unused LOG to keep code clean | Remove unused LOG to keep code clean
TrivialFix
Change-Id: I21fa9ebda98005c377d395f498cb44cf6599f0e5
| Python | apache-2.0 | stackforge/tacker,zeinsteinz/tacker,stackforge/tacker,openstack/tacker,openstack/tacker,openstack/tacker,zeinsteinz/tacker |
50bdb59f7629b60d6aa6c9f3f21b447f00476b19 | webmanager/views_oauth2.py | webmanager/views_oauth2.py | from djangoautoconf.django_utils import retrieve_param
from django.utils import timezone
from provider.oauth2.backends import AccessTokenBackend
from provider.oauth2.models import AccessToken
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import login
def login_from_oauth2(request... | from djangoautoconf.django_utils import retrieve_param
from django.utils import timezone
from provider.oauth2.backends import AccessTokenBackend
from provider.oauth2.models import AccessToken
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import login
from djangoautoconf.req_with_a... | Move user login code to djangoautoconf. | Move user login code to djangoautoconf.
| Python | bsd-3-clause | weijia/webmanager,weijia/webmanager,weijia/webmanager |
e4a3d3c273a1b7e26e9fdcf7f8da060bf127f27e | examples/django_project/django_project/tests.py | examples/django_project/django_project/tests.py | import unittest
from datetime import datetime
from snapshottest.django import TestCase
def api_client_get(url):
return {
'url': url,
}
class TestDemo(TestCase):
def test_api_me(self):
now = datetime.now().isoformat()
my_api_response = api_client_get('/' + now)
self.asse... | import unittest
from datetime import datetime
from snapshottest.django import TestCase
def api_client_get(url):
return {
'url': url,
}
class TestDemo(TestCase):
def test_api_me(self):
# Note this tests should fail unless the snapshot-update command line
# option is specified. R... | Add note for test_api_me django-project test | Add note for test_api_me django-project test
| Python | mit | syrusakbary/snapshottest |
18a133cc3b56fdc1a5185bf3da3bed001e1b5c64 | dictionary.py | dictionary.py | # Import non-standard modules
import json
def definition(word):
'''This function returns the available definitions(s) of the input'''
return data[word]
# Load dictionary data from data.json to python dictionary
data = json.load(open('data.json', 'r'))
while True:
ip = input("Enter word:")
if ip in... | # Import non-standard modules
import json
from difflib import get_close_matches
def definition(word):
'''This function returns the available definitions(s) of the input'''
return data[word]
# Load dictionary data from data.json to python dictionary
data = json.load(open('data.json', 'r'))
# Infinite loop f... | Add feature to process user input and provide automatic suggestions | Add feature to process user input and provide automatic suggestions
| Python | mit | jojenreed/Python-CLI-Dictionary |
cc838a311e891294da10ca7465782d71e622b5ef | dodge.py | dodge.py | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
pass
def select_applications(self... | import platform
class OSXDodger(object):
allowed_version = "10.12.1"
def __init__(self, applications_dir):
self.app_dir = applications_dir
def load_applications(self):
"""
Read all applications in the `/Applications/` dir
"""
self.pc_is_macintosh()
def select... | Add class method to check if PC is a Mac | Add class method to check if PC is a Mac
| Python | mit | yoda-yoda/osx-dock-dodger,denisKaranja/osx-dock-dodger |
967f9363872ff64847e4b93a7c1ea75869eaabd9 | benchmarks/benchmarks.py | benchmarks/benchmarks.py | # Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.
import os.path as osp
import numpy as np
from tempfile import TemporaryDirectory
import h5py
class TimeSuite:
"""
An example benchmark that times the performance of various kinds
of iterating over dict... | # Write the benchmarking functions here.
# See "Writing benchmarks" in the asv docs for more information.
import os.path as osp
import numpy as np
from tempfile import TemporaryDirectory
import h5py
class TimeSuite:
"""
An example benchmark that times the performance of various kinds
of iterating over dict... | Add benchmark for writing with index of last dimension | Add benchmark for writing with index of last dimension
| Python | bsd-3-clause | h5py/h5py,h5py/h5py,h5py/h5py |
7613fc5c3ef1cc552d39e5fde533e8f9af7cc931 | form_designer/tests/test_cms_plugin.py | form_designer/tests/test_cms_plugin.py | import django
from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models imp... | from django.contrib.auth.models import AnonymousUser
from django.utils.crypto import get_random_string
import pytest
from cms import api
from cms.page_rendering import render_page
from form_designer.contrib.cms_plugins.form_designer_form.cms_plugins import FormDesignerPlugin
from form_designer.models import FormDefini... | Revert "Disable Django-CMS test on Django 1.10+" | Revert "Disable Django-CMS test on Django 1.10+"
Django CMS tests should work now with Django 1.10 and 1.11 too, since
the Django CMS version 3.4.5 supports them.
This reverts commit fcfe2513fc8532dc2212a254da42d75048e76de7.
| Python | bsd-3-clause | kcsry/django-form-designer,andersinno/django-form-designer-ai,kcsry/django-form-designer,andersinno/django-form-designer,andersinno/django-form-designer-ai,andersinno/django-form-designer |
39a1212508c27a5c21f8b027fef3fb409a28657f | app/commands.py | app/commands.py | from flask import current_app
def list_routes():
"""List URLs of all application routes."""
for rule in sorted(current_app.url_map.iter_rules(), key=lambda r: r.rule):
print("{:10} {}".format(", ".join(rule.methods - set(['OPTIONS', 'HEAD'])), rule.rule)) # noqa
def setup_commands(application):
... | import click
from flask import current_app
from flask.cli import with_appcontext
@click.command('list-routes')
@with_appcontext
def list_routes():
"""List URLs of all application routes."""
for rule in sorted(current_app.url_map.iter_rules(), key=lambda r: r.rule):
print("{:10} {}".format(", ".join(ru... | Switch existing command to standard approach | Switch existing command to standard approach
This is the suggested approach in the documentation [1] and using
it makes it clearer what's going on and to add other commands with
arguments, which we'll do in the next commit.
[1]: https://flask.palletsprojects.com/en/2.0.x/cli/#custom-commands
| Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
79a2f5ddc1d6d05dca0d44ee6586b2d8809ee1c0 | deep_q_rl/ale_run.py | deep_q_rl/ale_run.py | """This script launches all of the processes necessary to train a
deep Q-network on an ALE game.
Usage:
ale_run.py [--glue_port GLUE_PORT]
All unrecognized command line arguments will be passed on to
rl_glue_ale_agent.py
"""
import subprocess
import sys
import os
import argparse
ROM_PATH = "/home/spragunr/neural_rl... | """This script launches all of the processes necessary to train a
deep Q-network on an ALE game.
Usage:
ale_run.py [--glue_port GLUE_PORT]
All unrecognized command line arguments will be passed on to
rl_glue_ale_agent.py
"""
import subprocess
import sys
import os
import argparse
# Put your binaries under the direct... | Make the position of the roms work for everybody. | Make the position of the roms work for everybody.
Here you previously used a directory that mentions your particular setting. Substitute it by a relative directory so it works for everybody. Also, suggest at the read file to create a 'rome' directory with 'breakout.bin' in it. | Python | bsd-3-clause | r0k3/deep_q_rl,aaannndddyyy/deep_q_rl,davidsj/deep_q_rl,spragunr/deep_q_rl,gogobebe2/deep_q_rl,aaannndddyyy/deep_q_rl,omnivert/deep_q_rl,npow/deep_q_rl,vvw/deep_q_rl,codeaudit/deep_q_rl,alito/deep_q_rl,jleni/deep_q_rl,peterzcc/deep_q_rl,davidsj/deep_q_rl,spragunr/deep_q_rl,codeaudit/deep_q_rl,udibr/deep_q_rl,udibr/deep... |
8b16084a4fe72a369ada80969f6b728abf611d8f | marathon_itests/environment.py | marathon_itests/environment.py | import time
from itest_utils import wait_for_marathon
from itest_utils import print_container_logs
def before_all(context):
wait_for_marathon()
def after_scenario(context, scenario):
"""If a marathon client object exists in our context, delete any apps in Marathon and wait until they die."""
print_cont... | import time
from itest_utils import wait_for_marathon
from itest_utils import print_container_logs
def before_all(context):
wait_for_marathon()
def after_scenario(context, scenario):
"""If a marathon client object exists in our context, delete any apps in Marathon and wait until they die."""
if scenari... | Print container logs only in case of failed scenario | Print container logs only in case of failed scenario
| Python | apache-2.0 | somic/paasta,gstarnberger/paasta,Yelp/paasta,gstarnberger/paasta,somic/paasta,Yelp/paasta |
a8af7cd7918322615a342c2fd662f394866da55f | tests/sentry/metrics/test_datadog.py | tests/sentry/metrics/test_datadog.py | from __future__ import absolute_import
import socket
from mock import patch
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(prefix='sentrytest.')
@patch('... | from __future__ import absolute_import
from mock import patch
from datadog.util.hostname import get_hostname
from sentry.metrics.datadog import DatadogMetricsBackend
from sentry.testutils import TestCase
class DatadogMetricsBackendTest(TestCase):
def setUp(self):
self.backend = DatadogMetricsBackend(pr... | Test DatadogMetricsBackend against datadog's get_hostname | Test DatadogMetricsBackend against datadog's get_hostname
This fixes tests in Travis since the hostname returned is different
| Python | bsd-3-clause | pauloschilling/sentry,pauloschilling/sentry,pauloschilling/sentry |
7c117c4555fdf30b3d98a453c7e28245dca0c9b9 | tests/test_stack/test_stack.py | tests/test_stack/test_stack.py | import unittest
from aids.stack.stack import Stack
class StackTestCase(unittest.TestCase):
'''
Unit tests for the Stack data structure
'''
def setUp(self):
pass
def test_stack_initialization(self):
test_stack = Stack()
self.assertTrue(isinstance(test_stack, Stack))
def test_stack_is_em... | import unittest
from aids.stack.stack import Stack
class StackTestCase(unittest.TestCase):
'''
Unit tests for the Stack data structure
'''
def setUp(self):
self.test_stack = Stack()
def test_stack_initialization(self):
self.assertTrue(isinstance(self.test_stack, Stack))
def test_stack... | Add unit tests for push, peek, pop and size | Add unit tests for push, peek, pop and size | Python | mit | ueg1990/aids |
1ef1851e508295f6d4bf01289591f42c21656df7 | test/on_yubikey/test_interfaces.py | test/on_yubikey/test_interfaces.py | import unittest
from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present
from yubikit.core.otp import OtpConnection
from yubikit.core.fido import FidoConnection
from yubikit.core.smartcard import SmartCardConnection
from ykman.device import connect_to_device
from time import sleep
@unittest.ski... | import unittest
from .framework import DestructiveYubikeyTestCase, exactly_one_yubikey_present
from yubikit.core.otp import OtpConnection
from yubikit.core.fido import FidoConnection
from yubikit.core.smartcard import SmartCardConnection
from ykman.base import YUBIKEY
from ykman.device import connect_to_device
from ti... | Test handling of reclaim timeout. | Test handling of reclaim timeout.
| Python | bsd-2-clause | Yubico/yubikey-manager,Yubico/yubikey-manager |
300cbd3ff4d0e5021892f7c9940635695cb017a3 | integration-test/197-clip-buildings.py | integration-test/197-clip-buildings.py | from shapely.geometry import shape
# this is mid way along the High Line in NYC, which is a huge long
# "building". we should be clipping it to a buffer of 3x the tile
# dimensions.
# http://www.openstreetmap.org/way/37054313
with features_in_tile_layer(16, 19295, 24631, 'buildings') as buildings:
# max width and ... | from shapely.geometry import shape
# this is mid way along the High Line in NYC, which is a huge long
# "building". we should be clipping it to a buffer of 3x the tile
# dimensions.
# http://www.openstreetmap.org/relation/7141751
with features_in_tile_layer(16, 19295, 24631, 'buildings') as buildings:
# max width ... | Update data for the High Line, NYC | Update data for the High Line, NYC
Looks like it was turned into a multipolygon relation in [this changeset](http://www.openstreetmap.org/changeset/47542769).
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
86446c6d1b0b8583562e0fccf1745e95ce7003c2 | util/__init__.py | util/__init__.py | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | #!/usr/bin/env python
#
# dials.util.__init__.py
#
# Copyright (C) 2013 Diamond Light Source
#
# Author: James Parkhurst
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
from __future__ import division
class HalError(RuntimeError):
def _... | Print out errors to log. | Print out errors to log. | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials |
aa3134912af3e57362310eb486d0f4e1d8660d0c | grains/grains.py | grains/grains.py | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
import itertools
square = [x for x in r... | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
square = [x for x in range(1, 65)]
grai... | Reformat total_after function + Remove itertools | Reformat total_after function + Remove itertools
| Python | mit | amalshehu/exercism-python |
5188861fb873ea301eb5ec386f1df65c0707e146 | openstack/tests/functional/object/v1/test_container.py | openstack/tests/functional/object/v1/test_container.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Add functional tests for container metadata and delete | Add functional tests for container metadata and delete
Change-Id: Id13073b37d19482ca6ff6e53e315aaa424c3f1b9
| Python | apache-2.0 | openstack/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openstacksdk,briancurtin/python-openstacksdk,dudymas/python-openstacksdk,briancurtin/python-openstacksdk,dudymas/python-openstacksdk,openstack/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,mtougeron/python-openst... |
6b84688c1b5a7f2e8c9e5007455b88cbaa845e9f | tests/test_track_output/results.py | tests/test_track_output/results.py | #!/usr/bin/env python
import os
import sys
import glob
import shutil
from subprocess import call
# If vtk python module is not available, we can't run track.py so skip this
# test
cwd = os.getcwd()
try:
import vtk
except ImportError:
print('----------------Skipping test-------------')
shutil.copy('results... | #!/usr/bin/env python
import os
import sys
import glob
import shutil
from subprocess import call
# If vtk python module is not available, we can't run track.py so skip this
# test
cwd = os.getcwd()
try:
import vtk
except ImportError:
print('----------------Skipping test-------------')
shutil.copy('results... | Fix path to script in test_track_output | Fix path to script in test_track_output
| Python | mit | mjlong/openmc,wbinventor/openmc,bhermanmit/openmc,wbinventor/openmc,johnnyliu27/openmc,paulromano/openmc,mjlong/openmc,smharper/openmc,lilulu/openmc,johnnyliu27/openmc,amandalund/openmc,samuelshaner/openmc,mit-crpg/openmc,shikhar413/openmc,johnnyliu27/openmc,mit-crpg/openmc,liangjg/openmc,kellyrowland/openmc,amandalund... |
85cb348dab356386362fe7657dee3e31aa1f92bf | rep.py | rep.py | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds a dummy evaluate routine.
"""
import sys
# ------------------------------
def evaluate(expression):
"""
Evaluate an APL expression - dummy version
"""
return (expression)
def read_evaluate... | """
The top level of the APL Read-Evaluate-Print loop
UNDER DEVELOPMENT
This version adds simple APL exception handling
"""
import sys
from apl_exception import APL_Exception as apl_exception
# ------------------------------
def evaluate(expression):
"""
Evaluate an APL expression - dummy ... | Add exception handling to the read-evaluate-loop | Add exception handling to the read-evaluate-loop
| Python | apache-2.0 | NewForester/apl-py,NewForester/apl-py |
574fba0650e4c68b7a31533207c26d8d57ed49c2 | run.py | run.py | from sys import argv
from examples.connect4.connect4 import Connect4Network
if __name__ == '__main__':
if argv[1] == 'connect4':
Connect4Network().play()
| from sys import argv
from examples.connect4.connect4 import Connect4Network
if __name__ == '__main__':
if len(argv) > 1:
if argv[1] == 'connect4':
Connect4Network().play()
| Check length of argv before accessing it | Check length of argv before accessing it
| Python | mit | tysonzero/py-ann |
a7867806a6bd3abfd6bf2bcac6c490965be000e2 | tests/test_completeness.py | tests/test_completeness.py | import unittest as unittest
from syntax import Syntax
from jscodegen import CodeGenerator
def add_cases(generator):
def class_decorator(cls):
"""Add tests to `cls` generated by `generator()`."""
for f, token in generator():
test = lambda self, i=token, f=f: f(self, i)
test.... | import unittest as unittest
from jscodegen.syntax import Syntax
from jscodegen import CodeGenerator
def add_cases(generator):
def class_decorator(cls):
"""Add tests to `cls` generated by `generator()`."""
for f, token in generator():
test = lambda self, i=token, f=f: f(self, i)
... | Fix an issue in the tests | Fix an issue in the tests
| Python | mit | ksons/jscodegen.py |
eb0a5e5768c2f699cbc1f6395d3c14320d8e730d | template/__init__.py | template/__init__.py | #!/usr/bin/env python
# pylint: disable=import-error
"""Generate files from Jinja2 templates and environment variables."""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
) # pylint: disable=duplicate-code
from os import environ
from sys import stdin, stdout
impor... | #!/usr/bin/env python
# pylint: disable=import-error
"""A CLI tool for generating files from Jinja2 templates and environment
variables."""
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
) # pylint: disable=duplicate-code
from os import environ
from sys import st... | Use the docstring as the CLI description. | Use the docstring as the CLI description.
| Python | agpl-3.0 | adarnimrod/template,adarnimrod/template |
ae593fd5de74a123b5064ef2e018b4955dc9e6c9 | runserver.py | runserver.py | #!/usr/local/bin/python2.7
import sys
from datetime import date
from main import app
from upload_s3 import set_metadata
from flask_frozen import Freezer
# cron is called with 3 arguments, should only run in the first week of month
cron_condition = len(sys.argv) == 3 and date.today().day > 8
force_update = len(sys.ar... | #!/usr/local/bin/python2.7
import sys
from datetime import date
from main import app
from upload_s3 import set_metadata
from flask_frozen import Freezer
# cron is called with 3 arguments, should only run in the first week of month
cron_condition = len(sys.argv) == 3 and date.today().day < 8
force_update = len(sys.ar... | Complete testing, change back to production code | Complete testing, change back to production code
| Python | apache-2.0 | vprnet/dorothys-list,vprnet/dorothys-list,vprnet/dorothys-list |
3cef3e4774923b81e622f03aee44a933293c6a8d | modelview/migrations/0036_auto_20170322_1622.py | modelview/migrations/0036_auto_20170322_1622.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-22 15:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('modelview', '0035_auto_20160426_1721'),
]
operations = [
migrations.AlterFi... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2017-03-22 15:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
#('modelview', '0035_auto_20160426_1721'),
('modelview', '0035_auto_20170724_1801'),
... | Change reference from modelview/0035_auto_20160426 to 0035_auto_20170724 | Change reference from modelview/0035_auto_20160426 to 0035_auto_20170724
| Python | agpl-3.0 | openego/oeplatform,tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,openego/oeplatform |
c50d9efe011417162ab6e99e19973dcde6b3ddfa | utils/get_collection_object_count.py | utils/get_collection_object_count.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(
description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to coll... | #!/usr/bin/env python
# -*- coding: utf8 -*-
import sys
import argparse
from deepharvest.deepharvest_nuxeo import DeepHarvestNuxeo
def main(argv=None):
parser = argparse.ArgumentParser(
description='Print count of objects for a given collection.')
parser.add_argument('path', help="Nuxeo path to coll... | Change default arg value for pynuxrc | Change default arg value for pynuxrc
| Python | bsd-3-clause | barbarahui/nuxeo-calisphere,barbarahui/nuxeo-calisphere |
dad05c2eff78383e3179fd1f4a4502fe553afecd | tests/lib/docker_compose_tools.py | tests/lib/docker_compose_tools.py | # pylint: disable=line-too-long
""" Handles docker compose """
from lib.docker_tools import docker_compose
from lib.tools import show_status
def set_up(pg_version, es_version):
""" Start containers """
compose = docker_compose(pg_version, es_version)
show_status(
"Starting testing environment f... | # pylint: disable=line-too-long
""" Handles docker compose """
import sys
from sh import ErrorReturnCode
from lib.docker_tools import docker_compose
from lib.tools import show_status
def set_up(pg_version, es_version):
""" Start containers """
compose = docker_compose(pg_version, es_version)
show_sta... | Print full stdout / stderr when image build fails | Print full stdout / stderr when image build fails
| Python | mit | matthewfranglen/postgres-elasticsearch-fdw |
482bcbaeddf3d18c445b780a083d723a85a6dd88 | wok/renderers.py | wok/renderers.py | from markdown import markdown
import docutils.core
from docutils.writers.html4css1 import Writer as rst_html_writer
class Renderer(object):
extensions = []
@classmethod
def render(cls, plain):
return plain
class Markdown(Renderer):
extensions = ['markdown', 'mkd']
@classmethod
def re... | from markdown import markdown
import docutils.core
from docutils.writers.html4css1 import Writer as rst_html_writer
class Renderer(object):
extensions = []
@classmethod
def render(cls, plain):
return plain
class Markdown(Renderer):
extensions = ['markdown', 'mkd']
@classmethod
def re... | Enable syntax highlighting with Markdown. | Enable syntax highlighting with Markdown.
| Python | mit | wummel/wok,mythmon/wok,ngokevin/wok,matt-garman/wok,Avaren/wok,algor512/wok,edunham/wok,ngokevin/wok,chrplace/wok,moreati/wok,mythmon/wok,algor512/wok,vaygr/wok,vaygr/wok,edunham/wok,algor512/wok,moreati/wok,abbgrade/wok,edunham/wok,gchriz/wok,abbgrade/wok,matt-garman/wok,chrplace/wok,chrplace/wok,matt-garman/wok,jneve... |
eef8498388c672b25344a3f6fd8c05166e4ed4f6 | xea_core/urls.py | xea_core/urls.py | """xea_core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | """xea_core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-ba... | Add namespace to jwt_knox URLs | Add namespace to jwt_knox URLs
| Python | agpl-3.0 | gpul-org/xea-core |
6cce924d849f209fb8251acd4c21d65ad0daa24c | plugins/basic_info_plugin.py | plugins/basic_info_plugin.py | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
short_description = 'List some basic info about the string in a table'
header = 'Basic info:'
default = True
description = textwrap.deden... | import string
import textwrap
from veryprettytable import VeryPrettyTable
from plugins import BasePlugin
from plugins.util import green, red
__author__ = 'peter'
class BasicInfoPlugin(BasePlugin):
short_description = 'List some basic info about the string in a table'
header = 'Basic info:'
default = T... | Add hex check to basic info | Add hex check to basic info
| Python | mit | Sakartu/stringinfo |
1e82bf0e23775dfc2541dc8c2dec4447c20f2cda | tests/submitsaved.py | tests/submitsaved.py | #!/usr/bin/env python2
import pickle, sys
sys.path.append('../')
from lewas.parsers import UnitParser, AttrParser, field_rangler
import lewas.datastores
import lewas.models
config = "../config"
config = lewas.readConfig(config)
lewas.datastores.submitRequest(pickle.load(open(sys.argv[1])), config, False)
| #!/usr/bin/env python2
import pickle, sys
sys.path.append('../')
from lewas.parsers import UnitParser, AttrParser, field_rangler
import lewas.datastores
import lewas.models
config = "../config"
config = lewas.readConfig(config)
for fn in sys.argv[1:]:
lewas.datastores.submitRequest(pickle.load(open(fn)), config, ... | Add capability to resubmit multiple files | Add capability to resubmit multiple files
| Python | mit | LEWASatVT/lewas |
904644ba540fbf6dcd47fb5a006d03a64d299fb2 | src/yoi/pages.py | src/yoi/pages.py | from flask import request
from flaskext.genshi import render_response
from yoi.app import app
@app.route('/')
def get_index():
return render_response('index.html')
@app.route('/home')
def get_home():
return render_response('home.html')
@app.route('/journal')
def get_journal():
return render_response('jo... | from flask import request
from flaskext.genshi import render_response
from yoi.app import app
@app.route('/')
def index():
return render_response('index.html')
@app.route('/home')
def home():
return render_response('home.html')
@app.route('/journal')
def journal():
return render_response('journal.html')... | Remove `get_` prefix on page functions. | Remove `get_` prefix on page functions.
| Python | mit | doptio/you-owe-it,doptio/you-owe-it,doptio/you-owe-it,doptio/you-owe-it |
8365945ef62b8f9cd37022302e8ee6299716720d | masterfirefoxos/base/helpers.py | masterfirefoxos/base/helpers.py | from feincms.templatetags.feincms_tags import feincms_render_region
from jingo import register
from jinja2 import Markup
@register.function
def render_region(feincms_page, region, request):
return Markup(feincms_render_region(None, feincms_page, region, request))
| from django.contrib.staticfiles.templatetags.staticfiles import static as static_helper
from feincms.templatetags.feincms_tags import feincms_render_region
from jingo import register
from jinja2 import Markup
static = register.function(static_helper)
@register.function
def render_region(feincms_page, region, reques... | Add static helper for jinja2 | Add static helper for jinja2
| Python | mpl-2.0 | craigcook/masterfirefoxos,glogiotatidis/masterfirefoxos,mozilla/masterfirefoxos,craigcook/masterfirefoxos,enng0227/masterfirefoxos,glogiotatidis/masterfirefoxos,mozilla/masterfirefoxos,liu21st/masterfirefoxos,enng0227/masterfirefoxos,enng0227/masterfirefoxos,mozilla/masterfirefoxos,glogiotatidis/masterfirefoxos,glogiot... |
538a48b0ec6589d4d8fcf1c4253898a0fd3367e3 | hello.py | hello.py | # Based on "Flask is Fun" demo from Flask documentation.
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.config.update(
SERVER_NAME='127.0.0.1:%d' % int(os.environ.get('PORT', 5000)),
)
app.run()
| # Based on "Flask is Fun" demo from Flask documentation.
import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.config.update(
SERVER_NAME='127.0.0.1:%d' % int(os.environ.get('PORT', 5000)),
)
app.run(host='0.... | Add external access for demo process | Add external access for demo process
Avoid using Lynx web browser on a Raspberry pi for reaching localhost on console :-) | Python | mit | smartmob-project/strawboss-demo,smartmob-project/strawboss-demo |
1598c699dc6bdf5d6edd700b70e11df207412dcd | hackernews.py | hackernews.py | import requests
class HackerNews():
def __init__(self):
self.url = 'https://hacker-news.firebaseio.com/v0/{uri}'
def request(self, method, uri):
url = self.url.format(uri=uri)
return requests.request(method, url)
def item(self, item_id):
r = self.request('GET', 'item/{it... | from datetime import datetime
import requests
class HackerNews():
def __init__(self, timeout=5):
self.url = 'https://hacker-news.firebaseio.com/v0/{uri}'
self.timeout = timeout
def request(self, method, uri):
url = self.url.format(uri=uri)
return requests.request(method, url... | Convert timestamps to native datetime objects (breaking change) | Convert timestamps to native datetime objects (breaking change)
| Python | mit | abrinsmead/hackernews-python |
8b7a7e09a53d23b37266c67995756cf1dadf520d | conanfile.py | conanfile.py | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.1.2"
class CMakeIncludeGuardConan(ConanFile):
name = "cmake-include-guard"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
requires = ("cmake-module-common/master@smspillaz/cmake-module-common", )
... | from conans import ConanFile
from conans.tools import download, unzip
import os
VERSION = "0.1.2"
class CMakeIncludeGuardConan(ConanFile):
name = "cmake-include-guard"
version = os.environ.get("CONAN_VERSION_OVERRIDE", VERSION)
generators = "cmake"
url = "http://github.com/polysquare/cmake-include-gu... | Make cmake-module-common a dev-only requirement | conan: Make cmake-module-common a dev-only requirement
| Python | mit | polysquare/cmake-include-guard |
70686bc62b85d36894b6e7909ceaa25d122ffe95 | users/serializers.py | users/serializers.py | from rest_framework import serializers
from django.contrib.auth.models import User, Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('name',)
class UserSerializer(serializers.ModelSerializer):
groups_complete = GroupSerializer(source='groups', rea... | from rest_framework import serializers
from django.contrib.auth.models import User, Group
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ('name',)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id... | Remove nested serializer for groups, make password optional in serializer for user edition | Remove nested serializer for groups, make password optional in serializer for user edition
| Python | mit | fernandolobato/balarco,fernandolobato/balarco,fernandolobato/balarco |
c86ccf75fdf49115697548bb046bc83f348a1aba | tests/test_exceptions.py | tests/test_exceptions.py | from framewirc import exceptions
class MissingAttributesTest:
def test_message(self):
attrs = ['some', 'attrs']
expected = 'Required attribute(s) missing: {}'.format(attrs)
exception = exceptions.MissingAttributes(attrs)
assert str(exception) == expected
| from framewirc import exceptions
def test_message():
attrs = ['some', 'attrs']
expected = 'Required attribute(s) missing: {}'.format(attrs)
exception = exceptions.MissingAttributes(attrs)
assert str(exception) == expected
| Fix test that wasn't running | Fix test that wasn't running
| Python | bsd-2-clause | meshy/framewirc |
4b926ab5de00bc4885021fff0b2ac3679703707a | nova/db/sqlalchemy/migrate_repo/versions/034_change_instance_id_in_migrations.py | nova/db/sqlalchemy/migrate_repo/versions/034_change_instance_id_in_migrations.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/... | Drop FK before dropping instance_id column. | Drop FK before dropping instance_id column. | Python | apache-2.0 | klmitch/nova,hanlind/nova,aristanetworks/arista-ovs-nova,fajoy/nova,dawnpower/nova,gooddata/openstack-nova,joker946/nova,shail2810/nova,orbitfp7/nova,jeffrey4l/nova,zaina/nova,tianweizhang/nova,ruslanloman/nova,mgagne/nova,yosshy/nova,cloudbase/nova,paulmathews/nova,JioCloud/nova_test_latest,savi-dev/nova,russellb/nova... |
cd9c6f96f68391cf333b68e1ea28e513e869aca3 | troposphere/detective.py | troposphere/detective.py | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
}
class MemberInvitation(AWSObject):
resource_type = "AWS::Detective::MemberInvitation"
... | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
}
class MemberInvitation(AWSObject):
resource_type = "AWS:... | Update Detective per 2021-03-15 changes | Update Detective per 2021-03-15 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
08a1bfc233dc44f40ee0b8a5950eda19bca1d6a6 | quran_tafseer/serializers.py | quran_tafseer/serializers.py | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... | Change serializer field name from ayah to ayah_number | Change serializer field name from ayah to ayah_number
| Python | mit | EmadMokhtar/tafseer_api |
31c79697db0d5c973cff9b845ed28845695ecb02 | website/addons/twofactor/views.py | website/addons/twofactor/views.py | # -*- coding: utf-8 -*-
import httplib as http
from framework import request
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.project.decorators import must_have_addon
@must_be_logged_in
@must_have_addon('twofactor', 'user')
def user_settings(user_addon... | # -*- coding: utf-8 -*-
import httplib as http
from framework import request
from framework.auth.decorators import must_be_logged_in
from framework.exceptions import HTTPError
from website.project.decorators import must_have_addon
@must_be_logged_in
@must_have_addon('twofactor', 'user')
def user_settings(user_addon... | Fix response when user successfully confirms 2fa | Fix response when user successfully confirms 2fa
| Python | apache-2.0 | CenterForOpenScience/osf.io,revanthkolli/osf.io,jnayak1/osf.io,mluo613/osf.io,caneruguz/osf.io,alexschiller/osf.io,adlius/osf.io,himanshuo/osf.io,CenterForOpenScience/osf.io,samanehsan/osf.io,jeffreyliu3230/osf.io,cslzchen/osf.io,cwisecarver/osf.io,billyhunt/osf.io,SSJohns/osf.io,cosenal/osf.io,GageGaskins/osf.io,kushG... |
8ce2cbff7063b97e249dd87dd2acb8d83bdbf509 | examples/py/fetch-ohlcv-sequentially.py | examples/py/fetch-ohlcv-sequentially.py | # -*- coding: utf-8 -*-
import os
import sys
import time
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)
# -----------------------------------------------------------------------... | # -*- coding: utf-8 -*-
import os
import sys
import time
# -----------------------------------------------------------------------------
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(root)
# -----------------------------------------------------------------------... | Add delay 3 times the rate limit to avoid API errors | Add delay 3 times the rate limit to avoid API errors
| Python | mit | tritoanst/ccxt,tritoanst/ccxt,ccxt/ccxt,ccxt/ccxt,tritoanst/ccxt,ccxt/ccxt,ccxt/ccxt,ccxt/ccxt,tritoanst/ccxt |
6e6c5bb9f02a4f9d380ee20216f710a6de0b0583 | fenum.py | fenum.py | #!/bin/env python
import os
import sys
def main():
if len(sys.argv) == 1 or sys.argv[1].lower() == "-h" or sys.argv[1].lower() == "--help":
print("Syntax: fenum.py [files...]")
print("\tEnumerate the given files (starting at 1) in the same order as they are passed to the script.")
return
... | #!/bin/env python
import os
import sys
import math
def main():
if len(sys.argv) == 1 or sys.argv[1].lower() == "-h" or sys.argv[1].lower() == "--help":
print("Syntax: fenum.py [files...]")
print("\tEnumerate the given files (starting at 1) in the same order as they are passed to the script.")
... | Use log10 to get the amount of digits | Use log10 to get the amount of digits
| Python | mit | mphe/scripts,mphe/scripts,mall0c/scripts,mall0c/scripts |
9e42514ac030cc2fa3aab89addfa48cf0342f991 | kremlin/utils.py | kremlin/utils.py | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | Use context manager for PIL Open | Use context manager for PIL Open
This is currently kind of buggy with Python3. A harmless warning is
emitted since the handle is still closed late inside PIL/Pillow.
| Python | bsd-2-clause | glasnost/kremlin,glasnost/kremlin,glasnost/kremlin |
12d2e8033c46f06f5442cba40a7c2c673196ad1c | akanda/horizon/routers/views.py | akanda/horizon/routers/views.py | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
ports = [api.quantum.Port(p)... | from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import exceptions
from openstack_dashboard import api
def get_interfaces_data(self):
try:
router_id = self.kwargs['router_id']
router = api.quantum.router_get(self.request, router_id)
# Note(rods): Right now we a... | Fix the router's interfaces listing view to show only the interfaces on the user's networks filtering out interfaces on the mgt and public networks. | Fix the router's interfaces listing view to show only the
interfaces on the user's networks filtering out interfaces
on the mgt and public networks.
DHC-1512
Change-Id: I9b68b75d5e8325c4c70090fa500a417e23b1836f
Signed-off-by: Rosario Di Somma <73b2fe5f91895aea2b4d0e8942a5edf9f18fa897@dreamhost.com>
| Python | apache-2.0 | dreamhost/akanda-horizon,dreamhost/akanda-horizon |
a2530b9cd2baf70591e377b6eb7d5104493989a1 | test/conftest.py | test/conftest.py | def pytest_addoption(parser):
parser.addoption("--domain", action="append", default=[],
help="list of stringinputs to pass to test functions")
def pytest_generate_tests(metafunc):
if 'domain' in metafunc.fixturenames:
metafunc.parametrize("domain",
metafunc.config.o... | def pytest_addoption(parser):
parser.addoption("--domain", action="append", default=[],
help="list of stringinputs to pass to test functions")
parser.addoption("--url", action="append", default=[],
help="list of stringinputs to pass to test functions")
def pytest_generate_tests(metafunc):
i... | Add test parameter for site url | Add test parameter for site url
| Python | mit | HIIT/mediacollection |
e0af42d5431c42ee5e12fb228978ac8ce9c62807 | server/modules/persistent.py | server/modules/persistent.py | #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.c... | #!/usr/bin/python3
import argparse
import os
import icon_lib
parser = argparse.ArgumentParser(description='iconograph persistent')
parser.add_argument(
'--chroot-path',
dest='chroot_path',
action='store',
required=True)
FLAGS = parser.parse_args()
def main():
module = icon_lib.IconModule(FLAGS.c... | Remove flags that drastically slow down writes | Remove flags that drastically slow down writes
| Python | apache-2.0 | robot-tools/iconograph,robot-tools/iconograph,robot-tools/iconograph,robot-tools/iconograph |
ec2092c683f721e32a2d1d9792f296e140d6ba45 | paperwork_parser/exceptions.py | paperwork_parser/exceptions.py |
class InvalidPDFError(ValueError):
pass
class FieldParseError(Exception):
pass
|
class InvalidPDFError(ValueError):
pass
class UnknownVariantError(Exception):
pass
class FieldParseError(Exception):
pass
| Add new exception type for unknown variants | Add new exception type for unknown variants
| Python | mit | loanzen/zen_document_parser |
0b49114a6b0830fa0b05d32803ae52526b8e48ca | gnsq/backofftimer.py | gnsq/backofftimer.py | from random import randint
class BackoffTimer(object):
def __init__(self, ratio=1, max_interval=None, min_interval=None):
self.c = 0
self.ratio = ratio
self.max_interval = max_interval
self.min_interval = min_interval
def is_reset(self):
return self.c == 0
def re... | import random
class BackoffTimer(object):
def __init__(self, ratio=1, max_interval=None, min_interval=None):
self.c = 0
self.ratio = ratio
self.max_interval = max_interval
self.min_interval = min_interval
def is_reset(self):
return self.c == 0
def reset(self):
... | Return float for interval instead of int. | Return float for interval instead of int.
| Python | bsd-3-clause | hiringsolved/gnsq,wtolson/gnsq,wtolson/gnsq |
1d74b003818e260ae1f453cb26f1c9efc29e8ba2 | scripts/run_unit_test.py | scripts/run_unit_test.py | #!/usr/bin/env python
import serial
import os
import sys
import time
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("\nPlease press the phsyical reset butto... | #!/usr/bin/env python
import serial
import os
import sys
import time
# Make and flash the unit test
FILE_LOCATION = os.path.dirname(os.path.abspath(__file__))
os.chdir(FILE_LOCATION + "/../")
print os.system("make flash_unit_test")
# Ask the user to reset the board
raw_input("""\nPlease press the phsyical reset butt... | Bring scripts folder up to pep8 standards | PEP8: Bring scripts folder up to pep8 standards
| Python | mit | fnivek/eecs567-final-project,fnivek/eecs567-final-project,fnivek/eecs567-final-project,fnivek/eecs567-final-project,fnivek/eecs567-final-project |
d498a9846567e4986ba2a2541b2b4e4719c2c83f | keras/__init__.py | keras/__init__.py | from __future__ import absolute_import
from . import activations
from . import applications
from . import backend
from . import datasets
from . import engine
from . import layers
from . import preprocessing
from . import utils
from . import wrappers
from . import callbacks
from . import constraints
from .... | from __future__ import absolute_import
from . import activations
from . import applications
from . import backend
from . import datasets
from . import engine
from . import layers
from . import preprocessing
from . import utils
from . import wrappers
from . import callbacks
from . import constraints
from .... | Make Input importable from root | Make Input importable from root
| Python | apache-2.0 | keras-team/keras,keras-team/keras |
8e20b56c4b91f673429697232926115db46e0c2d | spanky/commands/cmd_users.py | spanky/commands/cmd_users.py | import click
from spanky.cli import pass_context
from spanky.lib.users import UserInit
@click.command('users', short_help='creates users base on /etc/spanky/users')
@pass_context
def cli(ctx):
config = ctx.config.load('users.yml')()
user_init = UserInit(config)
user_init.build()
| import sys
import click
from spanky.cli import pass_context
from spanky.lib.users import UserInit
@click.command('users', short_help='creates users base on /etc/spanky/users')
@pass_context
def cli(ctx):
try:
config = ctx.config.load('users.yml')()
except IOError:
# no config lets bail
... | Return a 1 when we don't have user to install. | Return a 1 when we don't have user to install.
TODO: Make better return code
| Python | bsd-3-clause | pglbutt/spanky,pglbutt/spanky,pglbutt/spanky |
d0e139d286b18c9dcdc8c46161c4ebdf0f0f8d96 | examples/cooperative_binding.py | examples/cooperative_binding.py | import sys
import os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.realpath(__file__)), '..'))
from crnpy.crn import CRN, from_react_file
__author__ = "Elisa Tonello"
__copyright__ = "Copyright (c) 2016, Elisa Tonello"
__license__ = "BSD"
__version__ = "0.0.1"
# Cooperative binding
print "Creating mo... | import sys
import os
sys.path.insert(0, os.path.join(
os.path.dirname(os.path.realpath(__file__)), '..'))
from crnpy.crn import CRN, from_react_file
__author__ = "Elisa Tonello"
__copyright__ = "Copyright (c) 2016, Elisa Tonello"
__license__ = "BSD"
__version__ = "0.0.1"
# Cooperative binding
print "Creating mo... | Remove debug and adjusted print. | Remove debug and adjusted print.
| Python | bsd-3-clause | etonello/crnpy |
67d3193683d2215fdd660bdc086801fe761c7db7 | src/views.py | src/views.py | from flask import render_template
from app import app
@app.route('/')
def index():
return render_template('index.html', active='index')
@app.route('/contact/')
def contact():
return render_template('contact.html', active='contact')
@app.context_processor
def utility_processor():
def page_title(title=Non... | import os
from flask import render_template
from flask import send_from_directory
from app import app
@app.route('/')
def index():
return render_template('index.html', active='index')
@app.route('/contact/')
def contact():
return render_template('contact.html', active='contact')
@app.route('/favicon.ico')
de... | Make the favicon available at /favicon.ico | Make the favicon available at /favicon.ico
| Python | mit | matachi/MaTachi.github.io,matachi/MaTachi.github.io |
0cda8950a661a0d994d7b5824af949ec1e40f584 | setup.py | setup.py | from distutils.core import setup
setup(name="zutil",
version='0.1.4',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "... | from distutils.core import setup
setup(name="zutil",
version='0.1.5',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "... | Make mpi an optional dependency | Make mpi an optional dependency
| Python | mit | zCFD/zutil |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.