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 |
|---|---|---|---|---|---|---|---|---|---|
bdcecb3c96cef5b663b1ada22efa952b0882f1f0 | spacy/tests/regression/test_issue600.py | spacy/tests/regression/test_issue600.py | from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
def test_issue600():
doc = Doc(Vocab(tag_map={'NN': {'pos': 'NOUN'}}), words=['hello'])
doc[0].tag_ = u'NN'
| from __future__ import unicode_literals
from ...tokens import Doc
from ...vocab import Vocab
from ...attrs import POS
def test_issue600():
doc = Doc(Vocab(tag_map={'NN': {'pos': 'NOUN'}}), words=['hello'])
doc[0].tag_ = u'NN'
| Add import in regression test | Add import in regression test
| Python | mit | Gregory-Howard/spaCy,spacy-io/spaCy,raphael0202/spaCy,explosion/spaCy,oroszgy/spaCy.hu,Gregory-Howard/spaCy,banglakit/spaCy,banglakit/spaCy,raphael0202/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,Gregory-Howard/spaCy,Gregory-Howard/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,oroszgy/spaCy.hu,recognai/sp... |
ff13cc4b7ef29c4454abb41b8e9a525d12c9ff7d | tailorscad/tests/test_arg_parser.py | tailorscad/tests/test_arg_parser.py |
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args)
def test_parse_args_inknown(self):
args = []
argv = ['... |
import unittest
from tailorscad.arg_parser import parse_args
class TestArgParser(unittest.TestCase):
def test_parse_args_none(self):
args = []
argv = []
args = parse_args(argv)
self.assertFalse(args.config)
def test_parse_args_inknown(self):
args = []
ar... | Fix unit tests for arg_parser | Fix unit tests for arg_parser
| Python | mit | savorywatt/tailorSCAD |
f17310e0fcf5d7ea7ceab2b9243f106eb1222b69 | desertbot/datastore.py | desertbot/datastore.py | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = None
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.data = {}
self.save()
... | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open... | Allow using DataStore class as if dict | Allow using DataStore class as if dict
| Python | mit | DesertBot/DesertBot |
8a9a2a860772ec71c517c4ae4dd93aa4ab2ea342 | git_gutter_events.py | git_gutter_events.py | import sublime
import sublime_plugin
import view_collection
class GitGutterEvents(sublime_plugin.EventListener):
def on_new(self, view):
view_collection.ViewCollection.add(view)
def on_load(self, view):
view_collection.ViewCollection.add(view)
def on_modified(self, view):
view_collection.ViewCollec... | import sublime
import sublime_plugin
import view_collection
class GitGutterEvents(sublime_plugin.EventListener):
def on_load(self, view):
view_collection.ViewCollection.add(view)
def on_modified(self, view):
if view.settings().get('git_gutter_live_mode', True):
view_collection.ViewCollection.add(vi... | Add settings to turn off live mode | Add settings to turn off live mode
| Python | mit | michaelhogg/GitGutter,akpersad/GitGutter,bradsokol/VcsGutter,biodamasceno/GitGutter,robfrawley/sublime-git-gutter,natecavanaugh/GitGutter,natecavanaugh/GitGutter,biodamasceno/GitGutter,michaelhogg/GitGutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,ariofrio/VcsGutter,tushortz/GitGutter,natecav... |
fb87194d6409149e71d6ee52c620fe04f8ca482f | scrapi/processing/osf/collision.py | scrapi/processing/osf/collision.py | from __future__ import unicode_literals
import requests
from scrapi import settings
from scrapi.processing.osf.hashing import REPORT_HASH_FUNCTIONS
from scrapi.processing.osf.hashing import RESOURCE_HASH_FUNCTIONS
def detect_collisions(hashlist, additional=''):
uuids = 'uuid:{}'.format(','.join(hashlist))
u... | from __future__ import unicode_literals
import json
import requests
from scrapi import settings
from scrapi.processing.osf.hashing import REPORT_HASH_FUNCTIONS
from scrapi.processing.osf.hashing import RESOURCE_HASH_FUNCTIONS
def detect_collisions(hashlist, is_resource=False):
if is_resource:
_filter =... | Update to the latest osf API | Update to the latest osf API
| Python | apache-2.0 | felliott/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,jeffreyliu3230/scrapi,erinspace/scrapi,mehanig/scrapi,ostwald/scrapi,CenterForOpenScience/scrapi,icereval/scrapi,fabianvf/scrapi,mehanig/scrapi,alexgarciac/scrapi,felliott/scrapi,fabianvf/scrapi |
a39c288e9beb506d62de66d72fc95750e54d833b | social_core/backends/universe.py | social_core/backends/universe.py | from .oauth import BaseOAuth2
class UniverseOAuth2(BaseOAuth2):
"""Universe Ticketing OAuth2 authentication backend"""
name = 'universe'
AUTHORIZATION_URL = 'https://www.universe.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://www.universe.com/oauth/token'
BASE_API_URL = 'https://www.universe.com... | from .oauth import BaseOAuth2
class UniverseOAuth2(BaseOAuth2):
"""Universe Ticketing OAuth2 authentication backend"""
name = 'universe'
AUTHORIZATION_URL = 'https://www.universe.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://www.universe.com/oauth/token'
BASE_API_URL = 'https://www.universe.com... | Remove f-string for pre-Python 3.6 support. | Remove f-string for pre-Python 3.6 support.
| Python | bsd-3-clause | python-social-auth/social-core,python-social-auth/social-core |
ef38b68aa288bb43bc33a860ac995836f892854e | usr/examples/99-Tests/unittests.py | usr/examples/99-Tests/unittests.py | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = ... | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = ... | Move GC collect after loading unit test function. | Move GC collect after loading unit test function.
| Python | mit | kwagyeman/openmv,openmv/openmv,openmv/openmv,kwagyeman/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,iabdalkader/openmv |
8aff9605a91f1041a1040c2cfc000dbc588c0503 | biobox_cli/util.py | biobox_cli/util.py | import sys, yaml, os.path
def select_module(module, name):
"""
Select and return a biobox module
"""
mod_name = ".".join(["biobox_cli", module, name])
try:
__import__(mod_name)
except ImportError:
err_exit('unknown_command',
{'command_type': str.replace(module, '... | import sys, yaml, os.path
def select_module(module, name):
"""
Select and return a biobox module
"""
mod_name = ".".join(["biobox_cli", module, name])
try:
__import__(mod_name)
except ImportError:
err_exit('unknown_command',
{'command_type': str.replace(module, '... | Use resource_string for error messages | Use resource_string for error messages
Signed-off-by: Michael Barton <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@michaelbarton.me.uk>
| Python | mit | pbelmann/command-line-interface,pbelmann/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface,fungs/bbx-cli,fungs/bbx-cli,bioboxes/command-line-interface,michaelbarton/command-line-interface |
e09414c101d49c70c6da4fcdabf3e985fb92f468 | passenger_wsgi.py | passenger_wsgi.py | import os
import subprocess
import sys
try:
from flask import Flask
import flask_login
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
import requests
except ImportError:
INTERP = "venv/bin/python"
if os.path.relpath(sys.executable, os.getcwd()) != INTERP:
... | import os
import subprocess
import sys
try:
from flask import Flask
import flask_login
from flask_restless import APIManager
from flask_sqlalchemy import SQLAlchemy
import requests
except ImportError:
INTERP = "venv/bin/python"
if os.path.relpath(sys.executable, os.getcwd()) != INTERP:
... | Improve error catching logic for update | Improve error catching logic for update
| Python | mit | GregBrimble/boilerplate-web-service,GregBrimble/boilerplate-web-service |
12a61da411134d2fc02e91d41b6687de8763a374 | modules/pipetruncate.py | modules/pipetruncate.py | # pipetruncate.py
#
from pipe2py import util
def pipe_truncate(context, _INPUT, conf, **kwargs):
"""This operator truncates the number of items in a feed.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
kwargs -- terminal, if the truncation value is wired in
conf:
... | # pipetruncate.py
#
from pipe2py import util
def pipe_truncate(context, _INPUT, conf, **kwargs):
"""This operator truncates the number of items in a feed.
Keyword arguments:
context -- pipeline context
_INPUT -- source generator
kwargs -- terminal, if the truncation value is wired in
conf:
... | Fix for taking feed from a split output | Fix for taking feed from a split output
| Python | mit | nerevu/riko,nerevu/riko |
cad0f1ebeeaac1af296930bc98cf892395293112 | grako/rendering.py | grako/rendering.py | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **field... | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **field... | Use 'fields' instead of 'kwargs' to document intent. | Use 'fields' instead of 'kwargs' to document intent.
| Python | bsd-2-clause | vmuriart/grako,frnknglrt/grako |
c617083fa413a0d45ff26c96751210901dfad7cf | cab/urls/search.py | cab/urls/search.py | from django.conf.urls import url
from haystack.views import SearchView, search_view_factory
from ..forms import AdvancedSearchForm
search_view = search_view_factory(view_class=SearchView,
template='search/advanced_search.html',
form_class=AdvancedSea... | from django.conf.urls import url
from haystack.views import SearchView, basic_search, search_view_factory
from ..forms import AdvancedSearchForm
from ..views.snippets import autocomplete
search_view = search_view_factory(view_class=SearchView,
template='search/advanced_search.html',
... | Remove string views in urlpatterns | Remove string views in urlpatterns
| Python | bsd-3-clause | django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org |
ce939b6f03260a57268a8371a2e05e531b36bce2 | hoomd/typeparam.py | hoomd/typeparam.py | from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getitem__(self, key):
return self.param_dict[key]
def __setitem_... | from hoomd.parameterdicts import AttachedTypeParameterDict
class TypeParameter:
def __init__(self, name, type_kind, param_dict):
self.name = name
self.type_kind = type_kind
self.param_dict = param_dict
def __getattr__(self, attr):
try:
return getattr(self.param_dic... | Allow TypeParameters to 'grap' attr from param_dict | Allow TypeParameters to 'grap' attr from param_dict
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue |
6d848c4b86913d71b986ef032348a8fa8720cfc7 | src/idea/utility/state_helper.py | src/idea/utility/state_helper.py | from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
return State.objects.get(previous__isnull=True)
| from idea.models import State
def get_first_state():
""" Get the first state for an idea. """
#return State.objects.get(previous__isnull=True)
# previous__isnull breaks functionality if someone creates a new state
# without a previous state set. since we know the initial state
# is id=1 per fixtur... | Fix add_idea when multiple States have no previous | Fix add_idea when multiple States have no previous
| Python | cc0-1.0 | CapeSepias/idea-box,m3brown/idea-box,geomapdev/idea-box,cmc333333/idea-box,18F/idea-box,CapeSepias/idea-box,18F/idea-box,geomapdev/idea-box,18F/idea-box,cmc333333/idea-box,CapeSepias/idea-box,m3brown/idea-box,cmc333333/idea-box,geomapdev/idea-box |
efc792de5225f3a21fab6d3f299fea07c63f6d0d | incident/models.py | incident/models.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Issue(models.Model):
title = models.CharField(_('Title'), max_length=150)
description = models.TextField(_('Description'))
contract = models.ForeignKey('structure.Contract')
assigned_team = models.ForeignKey('str... | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Issue(models.Model):
title = models.CharField(_('Title'), max_length=150)
description = models.TextField(_('Description'))
contract = models.ForeignKey('structure.Contract')
assigned_team = models.ForeignKey('str... | Add created_at to Issue model | Add created_at to Issue model
| Python | bsd-3-clause | RocknRoot/LIIT |
355a3a34b9a264734c1f5f2ec365a5873f000b77 | open_skin_as_project.py | open_skin_as_project.py | import os
import subprocess
import sublime
import sublime_plugin
from .path.skin_path_provider import get_cached_skin_path
class RainmeterOpenSkinAsProjectCommand(sublime_plugin.ApplicationCommand):
def run(self):
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
subli... | import os
import subprocess
import sublime
import sublime_plugin
from .path.skin_path_provider import get_cached_skin_path
class RainmeterOpenSkinAsProjectCommand(sublime_plugin.ApplicationCommand):
def run(self):
skins_path = get_cached_skin_path()
skins = os.listdir(skins_path)
subli... | Handle in case user cancels open skin as project command | Handle in case user cancels open skin as project command
| Python | mit | thatsIch/sublime-rainmeter |
a18e6aa3647779de3963e6781afaeea3732d100e | similarities.py | similarities.py | #!/usr/bin/env python
import argparse
import sys
from gensim.models.word2vec import Word2Vec
import csv
from signal import signal, SIGINT
signal(SIGINT, lambda signum, frame: sys.exit(1))
parser = argparse.ArgumentParser()
parser.add_argument('--sim', type=float, default=.3)
parser.add_argument('w2v', type=argparse.... | #!/usr/bin/env python
import argparse
import sys
import csv
from gensim.models import KeyedVectors
from signal import signal, SIGINT
signal(SIGINT, lambda signum, frame: sys.exit(1))
parser = argparse.ArgumentParser()
parser.add_argument('--sim', type=float, default=.3)
parser.add_argument('w2v', type=argparse.FileT... | Update the Gensim API usage | Update the Gensim API usage
| Python | mit | dustalov/watset,dustalov/watset |
795b661962915221ddab186b66523896316b2a79 | jobs/jobs/items.py | jobs/jobs/items.py | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
def single_item_serializer(value):
# values are nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fist value w... | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
def single_item_serializer(value):
# values are sometimes nested inside a list: (u'Viltu vaxa me\xf0 Alvogen?',)
# so need to return just the fi... | Fix rendering of alfred.is data to json file | Fix rendering of alfred.is data to json file
| Python | apache-2.0 | multiplechoice/workplace |
06ee9c73fed7a9b8488d800859f65c28ad63eb57 | angr/extern_obj.py | angr/extern_obj.py | from cle.absobj import AbsObj
class AngrExternObject(AbsObj):
def __init__(self, alloc_size=0x1000):
super(AngrExternObject, self).__init__('##angr_externs##')
self._next_addr = 0
self._lookup_table = {}
self._alloc_size = alloc_size
self.memory = 'please never look at this'... | from cle.absobj import AbsObj
class AngrExternObject(AbsObj):
def __init__(self, alloc_size=0x1000):
super(AngrExternObject, self).__init__('##angr_externs##')
self._next_addr = 0
self._lookup_table = {}
self._alloc_size = alloc_size
self.memory = 'please never look at this'... | Make the extrn object use the convention for rebased addresses | Make the extrn object use the convention for rebased addresses
| Python | bsd-2-clause | angr/angr,xurantju/angr,zhuyue1314/angr,haylesr/angr,axt/angr,tyb0807/angr,terry2012/angr,avain/angr,xurantju/angr,lowks/angr,iamahuman/angr,iamahuman/angr,tyb0807/angr,iamahuman/angr,angr/angr,haylesr/angr,avain/angr,terry2012/angr,chubbymaggie/angr,cureHsu/angr,f-prettyland/angr,tyb0807/angr,schieb/angr,GuardianRG/an... |
a339ee67b9a2f1effcedf836f26657f628a842ee | employees/admin.py | employees/admin.py | from django.contrib import admin
from .models import Employee, Role
class RoleAdmin(admin.ModelAdmin):
list_display = ("name",)
class EmployeeAdmin(admin.ModelAdmin):
list_display = ("username", "first_name", "last_name", "email", 'level', 'score',)
fieldsets = (
(None, {'fields': ('username', '... | from django import forms
from django.contrib import admin
from .models import Employee, Role
class UserCreationForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('username', 'password',)
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
... | Fix employee form error about password hashing | Fix employee form error about password hashing
| Python | apache-2.0 | belatrix/BackendAllStars |
ebf3f4a73aaab3aa2ea3e760bb44cfcbd7ca8d7f | src/main.py | src/main.py | #!/usr/bin/python
#coding=utf8
from Tkinter import *
import sys
from ui import Gui
if __name__ == '__main__':
Root = Tk()
App = Gui(Root)
App.pack(expand='yes',fill='both')
Root.geometry('320x240+10+10')
Root.title('Mid!Magic')
Root.mainloop() | #!/usr/bin/python
#coding=utf8
from Tkinter import *
import sys
from ui import Gui
if __name__ == '__main__':
Root = Tk()
App = Gui(Root)
App.pack(expand='yes',fill='both')
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
Root.overrideredirect(1)
Root.geometry("%dx%d+0+0" % (w, h... | Add support for full screen. | Add support for full screen. | Python | apache-2.0 | doino-gretchenliev/Mid-Magic,doino-gretchenliev/Mid-Magic |
d1d53bf2c2e719f2ff90d4260bb2521d0ee4af01 | main.py | main.py | import argparse
from config import app_config as cfg
from libraries.database_init import DataBase
from libraries.tweetimporter import TweetImporter
from libraries.twitterclient import TwitterClient
# Twitter API configuration
consumer_key = cfg.twitter["consumer_key"]
consumer_secret = cfg.twitter["consumer_secret"]... | import argparse
from config import app_config as cfg
from libraries.database_init import DataBase
from libraries.tweetimporter import TweetImporter
from libraries.twitterclient import TwitterClient
# Twitter API configuration
consumer_key = cfg.twitter["consumer_key"]
consumer_secret = cfg.twitter["consumer_secret"]... | Add option to create/drop the database | Add option to create/drop the database
| Python | mit | franckbrignoli/twitter-bot-detection |
2b0bcbb7ce82171965b22cf657439d6263fa9d91 | geojson_scraper.py | geojson_scraper.py | import json
import os
import urllib.request
from retry import retry
from urllib.error import HTTPError
from common import store_history, truncate, summarise
# hack to override sqlite database filename
# see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148
os.environ['SCRAPERWIKI_DATABASE_NAME'] ... | import json
import os
import urllib.request
from retry import retry
from urllib.error import HTTPError
from common import store_history, truncate, summarise
# hack to override sqlite database filename
# see: https://help.morph.io/t/using-python-3-with-morph-scraperwiki-fork/148
os.environ['SCRAPERWIKI_DATABASE_NAME'] ... | Add key param to geojson scraper | Add key param to geojson scraper
Sometimes we encounter a geojson file with no 'id' attribute
This allows us to specify a property to use as a key instead
| Python | mit | wdiv-scrapers/dc-base-scrapers |
78807533031cf46acb5e73b695c0e492cf2c3e20 | gnsq/httpclient.py | gnsq/httpclient.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import urllib3
try:
import simplejson as json
except ImportError:
import json # pyflakes.ignore
from .errors import NSQHttpError
class HTTPClient(object):
base_url = None
__http = None
@property
def http(self):
if self... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import urllib3
try:
import simplejson as json
except ImportError:
import json # pyflakes.ignore
from .decorators import cached_property
from .errors import NSQHttpError
class HTTPClient(object):
@cached_property
def http(self):
... | Use cached property decorator connection pool. | Use cached property decorator connection pool.
| Python | bsd-3-clause | hiringsolved/gnsq,wtolson/gnsq,wtolson/gnsq |
f8f1dc94bc7d48bbe9a36c7b1ffa8117ba458cba | lobster/sandbox.py | lobster/sandbox.py | from itertools import imap
import os
import re
import sys
import tarfile
def dontpack(fn):
return '/.' in fn or '/CVS/' in fn
def package(indir, outfile):
try:
tarball = tarfile.open(outfile, 'w:bz2')
tarball.dereference = True
rtname = os.path.split(os.path.normpath(indir))[1]
... | from itertools import imap
import os
import re
import sys
import tarfile
def dontpack(fn):
res = ('/.' in fn and not '/.SCRAM' in fn) or '/CVS/' in fn
if res:
return True
print fn
return False
def package(indir, outfile):
try:
tarball = tarfile.open(outfile, 'w:bz2')
tarbal... | Add the bits that cmsenv/cmsRun actually need. | Add the bits that cmsenv/cmsRun actually need.
| Python | mit | matz-e/lobster,matz-e/lobster,matz-e/lobster |
b5d3b84d4d2554882632fa9b10f44bd6ffb94b40 | recipyCommon/libraryversions.py | recipyCommon/libraryversions.py | import sys
import pkg_resources
import warnings
import numbers
import six
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename... | import sys
import pkg_resources
import warnings
import numbers
import six
def get_version(modulename):
"Return a string containing the module name and the library version."
version = '?'
# Get the root module name (in case we have something like `recipy.open`
# or `matplotlib.pyplot`)
modulename... | Add fallback method for finding library versions | Add fallback method for finding library versions
For library 'iris' the version number cannot be found in the pkg_resources
working set. It is unclear why.
The version number can be found using iris.__version__, so re-added the old
version finding code as a fallback.
| Python | apache-2.0 | recipy/recipy,recipy/recipy |
7c0c349656e6f02be0f3f0044f5d225f3688be08 | bong/parse_args.py | bong/parse_args.py | from .settings import BongSettings, DEFAULT_MESSAGE
from .metadata import VERSION, SUMMARY
import argparse
PARSER = argparse.ArgumentParser(description=SUMMARY)
PARSER.add_argument('-V', '--version', action='version', version=VERSION,
help='Show version')
PARSER.add_argument('-s', '--short-break', ... | from .settings import BongSettings, DEFAULT_MESSAGE
from .metadata import VERSION, SUMMARY
import argparse
PARSER = argparse.ArgumentParser(description=SUMMARY)
PARSER.add_argument('-V', '--version', action='version',
version='%(prog)s {}'.format(VERSION),
help='show version')
P... | Clean up the argument parsing | Clean up the argument parsing
| Python | mit | prophile/bong |
31f1c65d6505bc443fdb1d6ccd4849b175788f04 | gargbot_3000/config.py | gargbot_3000/config.py | #! /usr/bin/env python3.6
# coding: utf-8
import os
import datetime as dt
from pathlib import Path
import pytz
from dotenv import load_dotenv
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
slack_verification_token = os.environ["slack_verification_token"]
slack_bot_user_token = os.environ["slack_bot... | #! /usr/bin/env python3.6
# coding: utf-8
import os
import datetime as dt
from pathlib import Path
import pytz
from dotenv import load_dotenv
load_dotenv()
slack_verification_token = os.environ["slack_verification_token"]
slack_bot_user_token = os.environ["slack_bot_user_token"]
bot_id = os.environ["bot_id"]
bot_na... | Remove explicit path from load_dotenv call | Remove explicit path from load_dotenv call
| Python | mit | eirki/gargbot_3000,eirki/gargbot_3000,eirki/gargbot_3000,eirki/gargbot_3000 |
da3b2feab201782b3468e5e39232c366e0a3ebc0 | kolibri/core/discovery/serializers.py | kolibri/core/discovery/serializers.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from rest_framework import serializers
from rest_framework.serializers import ValidationError
from .models import NetworkLocation
from .utils.network import errors
from .utils.network.client import Net... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from rest_framework import serializers
from rest_framework.serializers import ValidationError
from .models import NetworkLocation
from .utils.network import errors
from .utils.network.client import Net... | Make some of the NetworkLocationSerializer fields read-only | Make some of the NetworkLocationSerializer fields read-only
| Python | mit | DXCanas/kolibri,lyw07/kolibri,DXCanas/kolibri,lyw07/kolibri,indirectlylit/kolibri,lyw07/kolibri,learningequality/kolibri,lyw07/kolibri,mrpau/kolibri,DXCanas/kolibri,mrpau/kolibri,indirectlylit/kolibri,DXCanas/kolibri,learningequality/kolibri,indirectlylit/kolibri,mrpau/kolibri,learningequality/kolibri,mrpau/kolibri,lea... |
6891981cd32a9dbf71346f95256f8447726672df | packages/pixman.py | packages/pixman.py | CairoGraphicsPackage ('pixman', '0.30.0')
| class PixmanPackage (CairoGraphicsPackage):
def __init__ (self):
CairoGraphicsPackage.__init__ (self, 'pixman', '0.30.0')
#This package would like to be built with fat binaries
if Package.profile.m64 == True:
self.fat_build = True
def arch_build (self, arch):
if arch == 'darwin-fat': #multi-arch build... | Enable fat binaries on pitman package | Enable fat binaries on pitman package
| Python | mit | mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild |
e81a54a5df2aaafae230084fe3b4d59c5b4f61cc | parallel/runner.py | parallel/runner.py | import Queue
from parallel import worker
class Runner(object):
def __init__(self, num_workers=4):
self.in_queue = Queue.Queue()
self.out_queue = Queue.Queue()
self.num_workers = num_workers
self.workers = None
self._start_workers()
def _start_workers(self):
se... | import Queue
from parallel import config
from parallel import worker
class Runner(object):
def __init__(self, num_workers=config.NUM_WORKERS):
self.in_queue = Queue.Queue()
self.out_queue = Queue.Queue()
self.num_workers = num_workers
self.workers = None
self._start_worker... | Use default number of workers from config | Use default number of workers from config
config does a better job at figuring out the optimal number of workers,
so it will be used instead.
| Python | mit | andersonvom/mparallel |
ddaf1a2b6744c9012546d6258b0378ab1b96d658 | zerver/lib/i18n.py | zerver/lib/i18n.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.utils import translation
from django.utils.translation import ugettext as _
from six import text_type
from typing import Any
import os
import ujson
def with_language(string, language):
# type: (text_type, text_type) -> text_type
old_languag... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.conf import settings
from django.utils import translation
from django.utils.translation import ugettext as _
from six import text_type
from typing import Any
import os
import ujson
def with_language(string, language):
# type: (text_type,... | Return unformatted list from get_language_list. | Return unformatted list from get_language_list.
| Python | apache-2.0 | grave-w-grave/zulip,amanharitsh123/zulip,kou/zulip,vikas-parashar/zulip,JPJPJPOPOP/zulip,ahmadassaf/zulip,andersk/zulip,vikas-parashar/zulip,andersk/zulip,hackerkid/zulip,kou/zulip,eeshangarg/zulip,ahmadassaf/zulip,dhcrzf/zulip,showell/zulip,punchagan/zulip,vabs22/zulip,peguin40/zulip,JPJPJPOPOP/zulip,shubhamdhama/zuli... |
308f1cd155e2db37fe5ff03e158e3d9fc32d6885 | lehrex/__init__.py | lehrex/__init__.py | # -*- coding: utf-8 -*-
"""Python package to support the research during
the annual Lehrexkursion at Universität Hamburg.
"""
from os.path import dirname, join
from . import csv
from . import math
from . import plots
from . import utils
__version__ = open(join(dirname(__file__), 'VERSION')).read().strip()
__all__ =... | # -*- coding: utf-8 -*-
"""Python package to support the research during
the annual Lehrexkursion at Universität Hamburg.
"""
from os.path import dirname, join
from . import csv
from . import math
from . import plots
from . import utils
__version__ = open(join(dirname(__file__), 'VERSION')).read().strip()
__all__ =... | Introduce Python 3.5 syntax error. | Introduce Python 3.5 syntax error.
| Python | mit | lkluft/lehrex |
b2657fd84c0d8fd4e1188a649bb2595651b83adb | kazoo/handlers/util.py | kazoo/handlers/util.py | """Handler utilities for getting non-monkey patched std lib stuff
Allows one to get an unpatched thread module, with a thread
decorator that uses the unpatching OS thread.
"""
try:
from gevent import monkey
[start_new_thread] = monkey.get_original('thread', ['start_new_thread'])
except ImportError:
from t... | """Handler utilities for getting non-monkey patched std lib stuff
Allows one to get an unpatched thread module, with a thread
decorator that uses the unpatching OS thread.
"""
from __future__ import absolute_import
try:
from gevent._threading import start_new_thread
except ImportError:
from thread import sta... | Make sure we use proper gevent with absolute import, pull the start_new_thread directly out. | Make sure we use proper gevent with absolute import, pull the start_new_thread directly out.
| Python | apache-2.0 | harlowja/kazoo,pombredanne/kazoo,rockerbox/kazoo,AlexanderplUs/kazoo,harlowja/kazoo,pombredanne/kazoo,rgs1/kazoo,Asana/kazoo,jacksontj/kazoo,kormat/kazoo,rackerlabs/kazoo,bsanders/kazoo,tempbottle/kazoo,python-zk/kazoo,rockerbox/kazoo,jacksontj/kazoo,rackerlabs/kazoo,python-zk/kazoo,rgs1/kazoo,tempbottle/kazoo,Alexande... |
534770cf0cc25c7aa0350570bc7a39d6239c7e05 | src/data/extractor/parsehtml.py | src/data/extractor/parsehtml.py | from urllib import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver
def getBeautifulSoupObject(link):
html = urlopen(link)
return BeautifulSoup(html)
def getDynamicContent(link):
driver = webdriver.PhantomJS()
driver.get(link)
link = "https://www.dnainfo.com/chicago/2017-chicago-... | import requests
from bs4 import BeautifulSoup
from selenium import webdriver
import logging
logging.basicConfig(filename='scrape.log',level=20)
logging.info('Initialized logger')
def getBeautifulSoupObject(link):
html = requests.get(link)
return BeautifulSoup(html)
def getDynamicContent(link):
try:
... | Add logging, requests and handle exceptions | Add logging, requests and handle exceptions
| Python | mit | craftbase/chicago-murders |
55378f71e8553eaad606433ae9e871983e99bd26 | pastalog/pastalog/__init__.py | pastalog/pastalog/__init__.py | '''
The pastalog Log class, which simply sends a POST request to a the server.
'''
import requests
class Log(object):
def __init__(self, url, model_name):
self.url = url
self.model_name = model_name
def post(self, series_name, value, step):
payload = {"modelName": self.model_name,
... | '''
The pastalog Log class, which simply sends a POST request to a the server.
'''
import requests
import os
class Log(object):
def __init__(self, url, model_name):
self.url = os.path.join(url, 'data')
self.model_name = model_name
def post(self, series_name, value, step):
payload = {"... | Update to post to correct endpoint | Update to post to correct endpoint
| Python | mit | rewonc/pastalog,rewonc/pastalog,rewonc/pastalog |
8e3d77675d65740776fc8f0fc93bb311cf62c632 | books/models.py | books/models.py | from django.db import models
from django.utils.translation import ugettext as _
from egielda import settings
class BookType(models.Model):
publisher = models.CharField(max_length=150)
title = models.CharField(max_length=150)
price = models.IntegerField()
def price_string(self):
return "%(pri... | from django.db import models
from django.utils.translation import ugettext as _
from egielda import settings
class BookType(models.Model):
publisher = models.CharField(max_length=150)
title = models.CharField(max_length=150)
price = models.IntegerField()
def price_string(self):
return "%(pri... | Fix __str__ method for BookType Model | Fix __str__ method for BookType Model
| Python | agpl-3.0 | m4tx/egielda,m4tx/egielda,m4tx/egielda |
580b5c48fc42f09459bcf63c0e2e239a550adb41 | calexicon/calendars/tests/calendar_testing.py | calexicon/calendars/tests/calendar_testing.py | import sys
if sys.hexversion < 0x02070000:
import unittest2 as unittest
else:
import unittest
from hypothesis import given, example
from hypothesis.extra.datetime import datetimes
from calexicon.calendars import ProlepticGregorianCalendar, JulianCalendar
from calexicon.dates import DateWithCalendar, Invalid... | import sys
if sys.hexversion < 0x02070000:
import unittest2 as unittest
else:
import unittest
from hypothesis import given, example
from hypothesis.extra.datetime import datetimes
from calexicon.calendars import ProlepticGregorianCalendar, JulianCalendar
from calexicon.dates import DateWithCalendar, Invalid... | Change name of test to avoid collision | Change name of test to avoid collision
This was spotted by coveralls. | Python | apache-2.0 | jwg4/calexicon,jwg4/qual |
520a23caae3bd4e1db60021025b5dc3f573b0873 | plugins/mediawiki.py | plugins/mediawiki.py | import ConfigParser
import datetime
from wikitools import wiki
from wikitools import category
from plugin import Plugin
class MediaWiki(Plugin):
def __init__(self, config=None):
if config:
try:
self.site = wiki.Wiki(config.get('MediaWiki', 'wikiapiurl'))
self.site.login(config.get('MediaWik... | import ConfigParser
import datetime
from wikitools import wiki
from wikitools import category
from plugin import Plugin
class MediaWiki(Plugin):
def __init__(self, config=None):
if config:
try:
self.site = wiki.Wiki(config.get('MediaWiki', 'wikiapiurl'))
self.site.login(config.get('MediaWik... | Mark wiki edits as bot edit | Mark wiki edits as bot edit | Python | mit | k4cg/Rezeptionistin |
6a9165a55d3238a40e368a348c6d7a7a7d133f34 | dockci/api/base.py | dockci/api/base.py | """ Base classes and data for building the API """
from flask_restful import reqparse, Resource
from .util import clean_attrs, set_attrs
from dockci.server import DB
AUTH_FORM_LOCATIONS = ('form', 'headers', 'json')
class BaseDetailResource(Resource):
""" Base resource for details API endpoints """
def han... | """ Base classes and data for building the API """
from flask_restful import reqparse, Resource
from .util import clean_attrs, set_attrs
from dockci.server import DB
AUTH_FORM_LOCATIONS = ('form', 'headers', 'json')
class BaseDetailResource(Resource):
""" Base resource for details API endpoints """
# pylin... | Allow handle_write to accept data | Allow handle_write to accept data
| Python | isc | RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI,RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI |
4ae0fccace6a3b2b640fd58c03fbd07341578acc | gen-android-icons.py | gen-android-icons.py | __author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_... | __author__ = 'Maksim Dmitriev'
import argparse
import os
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--source', help='the icon to be resized', required=True)
parser.add_argument('-d', '--dest', help='the directory where resized icons are saved')
parser.add_... | Use os.path.join instead of + | Use os.path.join instead of +
| Python | bsd-3-clause | MaksimDmitriev/Python-Scripts |
25e5070a575de1ae7e20d6ede71297ab424cea87 | bluegreen-example/app.py | bluegreen-example/app.py | import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello 0-downtime %s World!" % os.environ.get('BLUEGREEN', 'bland')
| import os
from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello 0-downtime %s World!" % os.environ.get('BLUEGREEN', 'bland')
@app.route("/parrots/<path:path>")
def parrot(path):
return send_from_directory(os.path.join('parrots', 'parrots'), path)
| Add a route to send parrot images | Add a route to send parrot images
| Python | mit | dbravender/gitric |
09b6f3e5cde6aeff69ea15fdc15c7db300ce3272 | python/web_socket.py | python/web_socket.py | #!/bin/python
try:
import urllib.request as urlrequest
except ImportError:
import urllib as urlrequest
import json
class RESTfulApi:
"""
Generic REST API call
"""
def __init__(self):
"""
Constructor
"""
pass
def request(self, url):
"""
Web... | #!/bin/python
try:
import urllib.request as urlrequest
except ImportError:
import urllib as urlrequest
import json
class RESTfulApi:
"""
Generic REST API call
"""
def __init__(self):
"""
Constructor
"""
pass
def request(self, url):
"""
Web... | Support python 2 and 3 compatability | Support python 2 and 3 compatability
| Python | apache-2.0 | Aurora-Team/BitcoinExchangeFH |
97a1c4979f8c46833b4ac89f6920138551ed2ee6 | pyuvdata/__init__.py | pyuvdata/__init__.py | # -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import ... | # -*- mode: python; coding: utf-8 -*-
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""init file for pyuvdata.
"""
from __future__ import absolute_import, division, print_function
from .uvdata import *
from .telescopes import *
from .uvcal import *
from .uvbeam import ... | Add comment about utils import | Add comment about utils import
| Python | bsd-2-clause | HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata,HERA-Team/pyuvdata |
5f7622824ac997228f83a894b451211fac4838ed | core/data/DataTransformer.py | core/data/DataTransformer.py | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | """
DataTransformer
:Authors:
Berend Klein Haneveld
"""
from vtk import vtkImageReslice
class DataTransformer(object):
"""DataTransformer is a class that can transform a given dataset"""
def __init__(self):
super(DataTransformer, self).__init__()
def TransformImageData(self, imageData, transform):
"""
:t... | Set the background color of the reslicer to the lowest value in the image data. | Set the background color of the reslicer to the lowest value in the image data.
| Python | mit | berendkleinhaneveld/Registrationshop,berendkleinhaneveld/Registrationshop |
73a9889f0e43d2b1dc94e2235a94cb888e0eda89 | zeus/utils/sentry.py | zeus/utils/sentry.py | from functools import wraps
from sentry_sdk import Hub
def span(op, desc_or_func=None):
def inner(func):
@wraps(func)
def wrapped(*args, **kwargs):
if callable(desc_or_func):
description = desc_or_func(*args, **kwargs)
else:
description = des... | import asyncio
from contextlib import contextmanager
from functools import wraps
from sentry_sdk import Hub
# https://stackoverflow.com/questions/44169998/how-to-create-a-python-decorator-that-can-wrap-either-coroutine-or-function
def span(op, desc_or_func=None):
def inner(func):
@contextmanager
... | Fix span decorator to work with asyncio | Fix span decorator to work with asyncio
| Python | apache-2.0 | getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus |
3304b539e0f4105b3ad2603b0676b25d7c96b606 | getconf/oldconf.py | getconf/oldconf.py | from oslo_config import cfg
from oslo_config import generator as gn
__all__ = ['get_conf']
def get_conf(conf_file=None, config_file=None):
conf_file = '/opt/stack/barbican/etc/oslo-config-generator/barbican.conf'
config_file = '/etc/barbican/barbican.conf'
conf = cfg.ConfigOpts()
gn.register_cli_opt... | from oslo_config import cfg
from oslo_config import generator as gn
__all__ = ['get_conf']
def get_conf(conf_file=None, config_file=None):
conf_file = '/opt/stack/barbican/etc/oslo-config-generator/barbican.conf'
config_file = '/etc/barbican/barbican.conf'
conf = cfg.ConfigOpts()
gn.register_cli_opt... | Add get not equal default options | Add get not equal default options
| Python | apache-2.0 | NguyenHoaiNam/Jump-Over-Release |
f5c19e5814763235f8abebba2239f64135dc3188 | python/shapes2json.py | python/shapes2json.py | import re
import numpy as np
infile = "shapes.txt"
filt = re.compile(r'^"?([^"]*)"?$')
converter = lambda x: filt.match(x.strip()).group(1)
data = np.recfromcsv(infile, delimiter=',')
shapes = np.array(map(int, [converter(x) for x in data["shape_id"]]))
lats = np.array(map(float, [converter(x) for x in data["shape_pt_l... | import re, sys
import numpy as np
infile = sys.argv[1]
filt = re.compile(r'^"?([^"]*)"?$')
converter = lambda x: filt.match(x.strip()).group(1)
data = np.recfromcsv(infile, delimiter=',')
shapes = np.array(map(int, [converter(x) for x in data["shape_id"]]))
lats = np.array(map(float, [converter(x) for x in data["shape_... | Print out an array of points | Print out an array of points
| Python | mit | acbecker/kcmetrod3 |
e2924f23c48a6e39b7c6e24ac19f73bd10181167 | say/say.py | say/say.py | # File: say.py
# Purpose: Write a program that will take a number from 0 to 999,999,999,999 and spell out that number in English.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Wednesday 8th September 2016, 10:00 PM
| # File: say.py
# Purpose: 0 to 999,999,999,999 and spell out that number in English.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Wednesday 8th September 2016, 10:00 PM
# #### Step 1
def say(num):
num_dict = {0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four',
5: 'five'... | Complete step 1 from problem Readme | Complete step 1 from problem Readme
| Python | mit | amalshehu/exercism-python |
80dcfaa7216ed0be88eb275316d135a1089e4dbe | simplesqlite/_error.py | simplesqlite/_error.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import sqlite3
class DatabaseError(sqlite3.DatabaseError):
"""
Exception raised for errors that are related to the database.
.. seealso::
- `sqlite3.DatabaseError <https://docs.python.org/3/library/sqlite3... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
import sqlite3
from tabledata import InvalidTableNameError
class DatabaseError(sqlite3.DatabaseError):
"""
Exception raised for errors that are related to the database.
.. seealso::
- `sqlite3.DatabaseErr... | Remove a duplicate error class definition | Remove a duplicate error class definition
| Python | mit | thombashi/SimpleSQLite,thombashi/SimpleSQLite |
79ef50191123c6e8a2e5e47efb8b15239a7acc5c | readux/__init__.py | readux/__init__.py | from django.conf import settings
__version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to a... | from django.conf import settings
__version_info__ = (1, 2, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to a... | Drop configured annotator store uri | Drop configured annotator store uri
| Python | apache-2.0 | emory-libraries/readux,emory-libraries/readux,emory-libraries/readux |
45f33dcf98b7b20fbedf3e05ca5c575ce3cbcbb3 | scripts/generate-invoice.py | scripts/generate-invoice.py | #!/usr/bin/env python3
import argparse
import yaml
import jinja2
import weasyprint
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='path to data directory', required=True)
parser.add_argument('--number', help='Invoice number', type=int, required=True)
args = parser.parse_args()
data_directory =... | #!/usr/bin/env python3
import argparse
import yaml
import jinja2
import weasyprint
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='path to data directory', required=True)
parser.add_argument('--number', help='Invoice number', type=int, required=True)
args = parser.parse_args()
data_directory =... | Move TODO items to GitHub issues | Move TODO items to GitHub issues
| Python | mit | pwaring/125-accounts,pwaring/125-accounts |
68c048f625aa0158f0117a737d94000da193df40 | astral/models/event.py | astral/models/event.py | import Queue
from elixir import Field, Unicode, Entity
from astral.models.base import BaseEntityMixin
import logging
log = logging.getLogger(__name__)
EVENT_QUEUE = Queue.Queue()
class Event(BaseEntityMixin, Entity):
message = Field(Unicode(96))
def __init__(self, *args, **kwargs):
super(Event, s... | import Queue
from elixir import Field, Unicode, Entity
from astral.models.base import BaseEntityMixin
import logging
log = logging.getLogger(__name__)
EVENT_QUEUE = Queue.Queue()
class Event(BaseEntityMixin, Entity):
message = Field(Unicode(96))
def __init__(self, *args, **kwargs):
kwargs['messag... | Convert JSON to unicode before saving to clear up a SQLAlchemy warning. | Convert JSON to unicode before saving to clear up a SQLAlchemy warning.
| Python | mit | peplin/astral |
f6c2f222db0f529d3f5906d5de7a7541e835ea77 | litecord/api/guilds.py | litecord/api/guilds.py | '''
guilds.py - All handlers under /guilds/*
'''
import json
import logging
from ..utils import _err, _json, strip_user_data
log = logging.getLogger(__name__)
class GuildsEndpoint:
def __init__(self, server):
self.server = server
async def h_post_guilds(self, request):
pass
| '''
guilds.py - All handlers under /guilds/*
'''
import json
import logging
from ..utils import _err, _json, strip_user_data
log = logging.getLogger(__name__)
class GuildsEndpoint:
def __init__(self, server):
self.server = server
async def h_post_guilds(self, request):
pass
async def h_... | Add some dummy routes in GuildsEndpoint | Add some dummy routes in GuildsEndpoint
| Python | mit | nullpixel/litecord,nullpixel/litecord |
e4e4db6c08612ba5b08224040d191eb83d27bf0d | scripts/prob_bedpe_to_bedgraph.py | scripts/prob_bedpe_to_bedgraph.py | #!/usr/bin/env python
import sys
import numpy as np
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-b",
"--bedpe_file",
dest="bedpe_file",
help="BEDPE file")
parser.add_option("-n",
"--name",
default="LUMPY BedGraph",
dest="name",
help="Name")
(options, ar... | #!/usr/bin/env python
import sys
import numpy as np
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-b",
"--bedpe_file",
dest="bedpe_file",
help="BEDPE file")
parser.add_option("-n",
"--name",
default="LUMPY BedGraph",
dest="name",
help="Name")
(options, ar... | Move fields for new output | Move fields for new output
| Python | mit | arq5x/lumpy-sv,glebkuznetsov/lumpy-sv,hall-lab/lumpy-sv,cc2qe/lumpy-sv,hall-lab/lumpy-sv,glebkuznetsov/lumpy-sv,arq5x/lumpy-sv,glebkuznetsov/lumpy-sv,arq5x/lumpy-sv,cc2qe/lumpy-sv,hall-lab/lumpy-sv,cc2qe/lumpy-sv,glebkuznetsov/lumpy-sv,glebkuznetsov/lumpy-sv,hall-lab/lumpy-sv,arq5x/lumpy-sv,cc2qe/lumpy-sv,arq5x/lumpy-s... |
8de10efd931e397af9c6b4c405a58af27940608a | lwr/lwr_client/util.py | lwr/lwr_client/util.py | from threading import Lock, Event
class TransferEventManager(object):
def __init__(self):
self.events = dict()
self.events_lock = Lock()
def acquire_event(self, path, force_clear=False):
with self.events_lock:
if path in self.events:
event_holder = self.ev... | from threading import Lock, Event
from weakref import WeakValueDictionary
class TransferEventManager(object):
def __init__(self):
self.events = WeakValueDictionary(dict())
self.events_lock = Lock()
def acquire_event(self, path, force_clear=False):
with self.events_lock:
i... | Fix logic related to GC of Event references using weakref.WeakValueDictionary. | Fix logic related to GC of Event references using weakref.WeakValueDictionary.
| Python | apache-2.0 | galaxyproject/pulsar,galaxyproject/pulsar,jmchilton/pulsar,jmchilton/lwr,ssorgatem/pulsar,natefoo/pulsar,ssorgatem/pulsar,natefoo/pulsar,jmchilton/lwr,jmchilton/pulsar |
90a8a55b4607e88e7e73f849250b4230185a18fd | integration-test/843-normalize-underscore.py | integration-test/843-normalize-underscore.py | # http://www.openstreetmap.org/way/219071307
assert_has_feature(
16, 10478, 25338, 'roads',
{ 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' })
# http://www.openstreetmap.org/way/258020271
assert_has_feature(
16, 11077, 25458, 'roads',
{ 'id': 258020271, 'kind': 'aerialway', 'kind_de... | # http://www.openstreetmap.org/way/219071307
assert_has_feature(
16, 10478, 25338, 'roads',
{ 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' })
# http://www.openstreetmap.org/way/258020271
assert_has_feature(
16, 11077, 25458, 'roads',
{ 'id': 258020271, 'kind': 'aerialway', 'kind_de... | Change test case item, as the previous one had been updated and fixed. | Change test case item, as the previous one had been updated and fixed.
| Python | mit | mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource |
e11d201c415eb86137194d93ac1fca7c20123ae9 | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | Add explicit setup for Django 1.7 | Add explicit setup for Django 1.7
| Python | bsd-3-clause | caktus/django-dry-choices |
c69da19e8316b1e1c6f55d3571917e85ba4fbf8d | src/member/admin.py | src/member/admin.py | from django.contrib import admin
from member.models import (Member, Client, Contact, Address,
Referencing, Route, Client_avoid_component,
Client_avoid_ingredient, Option,
Client_option, Restriction)
admin.site.register(Member)
admin.site.... | from django.contrib import admin
from member.models import (Member, Client, Contact, Address,
Referencing, Route, Client_avoid_component,
Client_avoid_ingredient, Option,
Client_option, Restriction)
from meal.models import Ingredient
cl... | Add ingredients to avoid as a TabularInline to Client | Add ingredients to avoid as a TabularInline to Client
Do not edit the ingredients to avoid directly, edit them through
a tabular form from the client form
| Python | agpl-3.0 | savoirfairelinux/santropol-feast,madmath/sous-chef,savoirfairelinux/santropol-feast,savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/sous-chef,savoirfairelinux/santropol-feast,madmath/sous-chef,madmath/sous-chef |
83c12d598221aac8e7173fb7d78083bc1c5ab64b | tests/test_commands.py | tests/test_commands.py | import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None,... | import unittest
from cobe.commands import LearnIrcLogCommand
class testIrcLogParsing(unittest.TestCase):
def setUp(self):
self.command = LearnIrcLogCommand()
def testNonPubmsg(self):
msg = "this is some non-pubmsg text found in a log"
cmd = self.command
self.assertEqual(None,... | Add a unit test for ignored nicks in _parse_irc_message | Add a unit test for ignored nicks in _parse_irc_message
| Python | mit | pteichman/cobe,wodim/cobe-ng,wodim/cobe-ng,DarkMio/cobe,tiagochiavericosta/cobe,meska/cobe,LeMagnesium/cobe,LeMagnesium/cobe,DarkMio/cobe,meska/cobe,tiagochiavericosta/cobe,pteichman/cobe |
3760005cec3174b14d3f0ee20327e1b8de9ce800 | ffflash/lib/container.py | ffflash/lib/container.py | from os import path
from ffflash import RELEASE, log, now, timeout
from ffflash.lib.clock import epoch_repr
from ffflash.lib.data import merge_dicts
from ffflash.lib.files import read_json_file, write_json_file
class Container:
def __init__(self, spec, filename):
self._spec = spec
self._location ... | from os import path
from ffflash import RELEASE, log, now, timeout
from ffflash.lib.clock import epoch_repr
from ffflash.lib.data import Element
from ffflash.lib.files import read_json_file, write_json_file
class Container:
def __init__(self, spec, filename):
self._spec = spec
self._location = pa... | Rewrite Container to dump/load two Elements (data,_info) into json file | Rewrite Container to dump/load two Elements (data,_info) into json file
| Python | bsd-3-clause | spookey/ffflash,spookey/ffflash |
a594c5154ca35590f2b793b89fc12e77d6b01537 | accounts/management/commands/clean_expired.py | accounts/management/commands/clean_expired.py | # coding=utf-8
from django.core.management.base import BaseCommand
from registration.models import RegistrationProfile
class Command(BaseCommand):
help = 'Cleanup expired registrations'
OPT_SIMULATE = 'dry-run'
def add_arguments(self, parser):
parser.add_argument(''.join(['--', self.OPT_SIMULAT... | # coding=utf-8
from django.core.management.base import BaseCommand
from registration.models import RegistrationProfile
class Command(BaseCommand):
help = 'Cleanup expired registrations'
OPT_SIMULATE = 'dry-run'
def add_arguments(self, parser):
parser.add_argument(''.join(['--', self.OPT_SIMULAT... | Make cleanup command less verbose | Make cleanup command less verbose
| Python | agpl-3.0 | volunteer-planner/volunteer_planner,volunteer-planner/volunteer_planner,coders4help/volunteer_planner,pitpalme/volunteer_planner,klinger/volunteer_planner,volunteer-planner/volunteer_planner,christophmeissner/volunteer_planner,volunteer-planner/volunteer_planner,klinger/volunteer_planner,klinger/volunteer_planner,pitpa... |
1636757f52a553c99fb40059f4461e97485d2199 | fits/make_fit_feedmes.py | fits/make_fit_feedmes.py | #!/usr/bin/env python
from glob import glob
import os
import re
def make_feedmes():
# Used to convert all the fit*.galfit files to fit*.diff
ids = glob('*/')
for id in ids:
os.chdir(id)
feedmes = glob('fit*diff')
# output starting models
for f in feedmes:
templa... | #!/usr/bin/env python
from glob import glob
import os
import re
def make_feedmes():
# Used to convert all the fit*.galfit files to fit*.diff
ids = glob('*/')
for id in ids:
feedmes = glob(id+'fit*diff')
# output starting models
for f in feedmes:
template = r'.*fit(.*)(\... | Fix to work with new patch | Fix to work with new patch
| Python | mit | MegaMorph/galfitm-illustrations,MegaMorph/galfitm-illustrations |
07f409bb6b8d008cf473aeb33fd0833dccfba402 | mm1_main.py | mm1_main.py | #!/usr/bin/env python
# encoding: utf-8
import mm1
import sim
### Params
# Mean interarrival rate of customers per second;
# hence, 0.05 <=> 3 people/minute
interarrival_rate = 0.05
# Mean service rate by the teller per second;
# hence, 0.1 <=> 6 people/minute
service_rate = 0.1
### Initialize
# Create new simula... | #!/usr/bin/env python
# encoding: utf-8
import argparse
import mm1
import sim
import time
### Parse command line arguments
parser = argparse.ArgumentParser(description="M/M/1 queue simulation -- Main script")
parser.add_argument('sim_duration', metavar='simulation_duration',
type=int, help='simul... | Add command line arguments to main script. | Add command line arguments to main script.
| Python | mit | kubkon/des-in-python |
471828d39ff256961bf48323feb43438901a4762 | orges/plugins/base.py | orges/plugins/base.py | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.D... | """This module provides an abstract base class for invocation plugins"""
from abc import abstractmethod, ABCMeta
class BasePlugin(object):
"""
Abstract base class for invocation plugins.
Plugin developers can either derive their objects directly from this class
or from :class:`orges.plugins.dummy.D... | Fix broken reference in documentation | Fix broken reference in documentation
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt |
35409711d9976ed44e25e314486f3f703b18c068 | packages/cardpay-subgraph-extraction/export.py | packages/cardpay-subgraph-extraction/export.py | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default='config',
)
@click.option(
"--database-string",
default="postgresql://grap... | from subgraph_extractor.cli import extract_from_config
import click
from cloudpathlib import AnyPath
import os
@click.command()
@click.option(
"--subgraph-config-folder",
help="The folder containing the subgraph config files",
default="config",
)
@click.option(
"--database-string",
default=os.envi... | Support environment variables for the extraction | Support environment variables for the extraction
| Python | mit | cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack,cardstack/cardstack |
b60cfdb2b338a4f87b4ac6ba7dd03c9c1d751b37 | scrapi/processing/base.py | scrapi/processing/base.py | class BaseProcessor(object):
NAME = None
def process_raw(self, raw_doc, **kwargs):
pass # pragma: no cover
def process_normalized(self, raw_doc, normalized, **kwargs):
pass # pragma: no cover
| import six
import json
from abc import abstractproperty, abstractmethod
from requests.structures import CaseInsensitiveDict
class BaseProcessor(object):
NAME = None
def process_raw(self, raw_doc, **kwargs):
pass # pragma: no cover
def process_normalized(self, raw_doc, normalized, **kwargs):
... | Add definition of abstract harvester model | Add definition of abstract harvester model
| Python | apache-2.0 | erinspace/scrapi,felliott/scrapi,fabianvf/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,erinspace/scrapi,felliott/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,mehanig/scrapi |
61e6c21e32a481be9b2c61d71b0faef3fe731ae6 | tests/rules_tests/RulesTest.py | tests/rules_tests/RulesTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 15.08.2017 15:31
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import *
from .grammar import *
class RulesTest(TestCase):
def test_oneRules(self):
class Tmp1(Rule):
rules = [([NFirst], [NSecond, ... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 15.08.2017 15:31
:Licence GNUv3
Part of grammpy
"""
from unittest import main, TestCase
from grammpy import *
from .grammar import *
class RulesTest(TestCase):
def setUp(self):
self.g = Grammar(terminals=[0, 1, 2,
... | Add test that check hash values of rule | Add test that check hash values of rule
| Python | mit | PatrikValkovic/grammpy |
e87fc9172b9d56fe9d64cfda2fb36a3f71e69e70 | tests/test_utils.py | tests/test_utils.py | # -*- coding: utf-8; -*-
import re
from jenkins_autojobs import main
def test_filter_jobs():
class Job:
def __init__(self, name):
self.name = name
class jenkins:
pass
names = ['feature-one', 'feature-two', 'release-one', 'release-two']
jenkins.jobs = [Job(i) for i in na... | # -*- coding: utf-8; -*-
import re
from jenkins_autojobs import main
def test_filter_jobs():
class Job:
def __init__(self, name):
self.name = name
class jenkins:
@staticmethod
def view_jobs(x):
return {
'v1': [Job('scratch-one'), Job('scratch-... | Fix tests on Python 2 | Fix tests on Python 2
| Python | bsd-3-clause | gvalkov/jenkins-autojobs,gvalkov/jenkins-autojobs |
1963012ba4628f1f66d495e777275243dc7248e4 | .CI/trigger_conda-forge.github.io.py | .CI/trigger_conda-forge.github.io.py | """
Trigger the conda-forge.github.io Travis job to restart.
"""
import os
import requests
import six
import conda_smithy.ci_register
def rebuild_travis(repo_slug):
headers = conda_smithy.ci_register.travis_headers()
# If we don't specify the API version, we get a 404.
# Also fix the accepted content... | """
Trigger the conda-forge.github.io Travis job to restart.
"""
import os
import requests
import six
import conda_smithy.ci_register
def rebuild_travis(repo_slug):
headers = conda_smithy.ci_register.travis_headers()
# If we don't specify the API version, we get a 404.
# Also fix the accepted content... | Add message to webpage repo trigger | Add message to webpage repo trigger
Should fix triggering builds on the webpage repo even when the most
recent commit message skip the CI build. Also should make it easier to
identify builds started by this trigger.
[ci skip]
[skip ci]
| Python | bsd-3-clause | jakirkham/staged-recipes,Cashalow/staged-recipes,dschreij/staged-recipes,scopatz/staged-recipes,stuertz/staged-recipes,conda-forge/staged-recipes,guillochon/staged-recipes,hadim/staged-recipes,SylvainCorlay/staged-recipes,mcs07/staged-recipes,scopatz/staged-recipes,sodre/staged-recipes,pmlandwehr/staged-recipes,sannykr... |
86e9e5a8da58b2902f5848353df9b05151bd08fa | turbustat/tests/test_cramer.py | turbustat/tests/test_cramer.py | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Cramer
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Cramer_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testCramer... | # Licensed under an MIT open source license - see LICENSE
'''
Test functions for Cramer
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Cramer_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class testCramer... | Add test for Cramer with different spatial sizes | Add test for Cramer with different spatial sizes
| Python | mit | Astroua/TurbuStat,e-koch/TurbuStat |
05240d24f6184b015422e2e1996fb90d7f6d7654 | twstock/cli/best_four_point.py | twstock/cli/best_four_point.py | import twstock
def main(argv):
print('四大買賣點判斷 Best Four Point')
print('------------------------------')
if len(argv) > 1:
sids = argv[1:]
for sid in sids:
bfp = twstock.BestFourPoint(twstock.Stock(sid))
bfp = bfp.best_four_point()
print('%s: ' % (sid), e... | import twstock
def run(argv):
print('四大買賣點判斷 Best Four Point')
print('------------------------------')
for sid in argv:
bfp = twstock.BestFourPoint(twstock.Stock(sid))
bfp = bfp.best_four_point()
print('%s: ' % (sid), end='')
if bfp:
if bfp[0]:
p... | Fix best four point cli | Fix best four point cli
| Python | mit | mlouielu/twstock,TCCinTaiwan/twstock |
ec2454626e22244c504bae528457fb8136c59feb | cooler/cli/__init__.py | cooler/cli/__init__.py | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import click
CONTEXT_SETTINGS = {
'help_option_names': ['-h', '--help'],
}
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
pass
from . import (
makebins,
digest,
csort,
cload,
load,
balance,
dump,
... | # -*- coding: utf-8 -*-
from __future__ import division, print_function
import click
# Monkey patch
click.core._verify_python3_env = lambda: None
CONTEXT_SETTINGS = {
'help_option_names': ['-h', '--help'],
}
@click.group(context_settings=CONTEXT_SETTINGS)
def cli():
pass
from . import (
makebins,
... | Stop Click from aborting due to misconfigured locale | Stop Click from aborting due to misconfigured locale
| Python | bsd-3-clause | mirnylab/cooler |
1594ab8d77e6522e0d85aa363ddc67d55d6ee81a | zc-list.py | zc-list.py | #!/usr/bin/env python
import sys
import argparse
import client_wrap
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--type", help="type of the cached data", default="double")
parser.add_argument("-c", "--connection", help="connection string", default="ipc:///var/run/zero-ca... | #!/usr/bin/env python
import sys
import argparse
import client_wrap
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--type", help="type of the cached data", default="double")
parser.add_argument("-c", "--connection", help="connection string", default="ipc:///var/run/zero-ca... | Implement the type specific values output | Implement the type specific values output
| Python | agpl-3.0 | ellysh/zero-cache-utils,ellysh/zero-cache-utils |
3816063967e03bc7b0cd3b7c95e74291ced04138 | tools/hash_funcs.py | tools/hash_funcs.py | """
A collection of utilities to see if new ReST files need to be automatically
generated from certain files in the project (examples, datasets).
"""
def get_hash(f):
"""
Gets hexadmecimal md5 hash of a string
"""
import hashlib
m = hashlib.md5()
m.update(f)
return m.hexdigest()
def update... | """
A collection of utilities to see if new ReST files need to be automatically
generated from certain files in the project (examples, datasets).
"""
import os
import pickle
file_path = os.path.dirname(__file__)
def get_hash(f):
"""
Gets hexadmecimal md5 hash of a string
"""
import hashlib
m = has... | Fix directory in hash funcs. | ENH: Fix directory in hash funcs.
| Python | bsd-3-clause | musically-ut/statsmodels,bavardage/statsmodels,nguyentu1602/statsmodels,kiyoto/statsmodels,detrout/debian-statsmodels,adammenges/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,edhuckle/statsmodels,edhuckle/statsmodels,yarikoptic/pystatsmodels,kiyoto/statsmodels,rgommers/statsmodels,jstoxrocky/statsmodels,wayneni... |
d0791ccd79dea2ec30d890ad9060f58d1e8b1c7c | run_tests.py | run_tests.py | import pytest
from bs4 import BeautifulSoup as BS
pytest.main(['--durations', '10', '--cov-report', 'html'])
url = r'htmlcov/index.html'
page = open(url)
soup = BS(page.read(), features='html5lib')
aggregate_total = soup.find_all('tr', {'class': 'total'})
final = None
for x in aggregate_total:
pct = x.text.repl... | import pytest
from bs4 import BeautifulSoup as BS
pytest.main(['--durations', '10', '--cov-report', 'html', '--junit-xml', 'test-reports/results.xml', '--verbose'])
url = r'htmlcov/index.html'
page = open(url)
soup = BS(page.read(), features='html5lib')
aggregate_total = soup.find_all('tr', {'class': 'total'})
final... | Update test file - add flag for reports | Update test file - add flag for reports
| Python | mit | misachi/job_match,misachi/job_match,misachi/job_match |
9e4dc6763fbd0de0f17b4acaa8109a12cdff28d6 | orderedmodel/models.py | orderedmodel/models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModelManager(models.Manager):
def swap(self, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModelManager(models.Manager):
def swap(self, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
... | Add fix_ordering method to OrderedModelManager | Add fix_ordering method to OrderedModelManager
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel |
5978eedb3147bc0f124335d9e408d6c4895de3a7 | __init__.py | __init__.py | import os
import sys
import marshal
if sys.hexversion < 0x03030000:
raise ImportError('python >= 3.3 required')
if sys.implementation.cache_tag is None:
raise ImportError('python implementation does not use bytecode')
PY_TAG = sys.implementation.cache_tag
PY_VERSION = sys.hexversion
BUNDLE_DIR = os.p... | import os
import sys
import marshal
if not hasattr(sys, 'implementation'):
raise ImportError('python >= 3.3 required')
if sys.implementation.cache_tag is None:
raise ImportError('python implementation does not use bytecode')
PY_TAG = sys.implementation.cache_tag
PY_VERSION = sys.hexversion
BUNDLE_DIR ... | Use a different way of ensuring 3.3+. | Use a different way of ensuring 3.3+.
| Python | mit | pyos/dg |
4b7065426447fb27322b81b283616c9242af41b9 | python_hospital_info_sys/com/pyhis/gui/main.py | python_hospital_info_sys/com/pyhis/gui/main.py | '''
Created on Jan 15, 2017
@author: Marlon_2
'''
import tkinter as tk # import
from tkinter import ttk # impork ttk from tkinter
win = tk.Tk(); # create instance
#add a title
win.title("Python Hospital Information System");
#add a label
#ttk.Label(win, text="Welcome to Python Hospital Informa... | '''
Created on Jan 15, 2017
@author: Marlon_2
'''
import tkinter as tk # import
from tkinter import ttk # impork ttk from tkinter
win = tk.Tk(); # create instance
#add a title
win.title("Python Hospital Information System");
#add a label
#ttk.Label(win, text="Welcome to Python Hospital Informa... | Stop experimenting on this project for the moment | Stop experimenting on this project for the moment | Python | mit | martianworm17/py_his |
7b15a9b510bce6a3866c0d3d7cd78c0c477cb69d | transformations/pig_latin/transformation.py | transformations/pig_latin/transformation.py | import piglatin
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class PigLatin(SentenceOperation):
tasks = [
TaskType.TEXT_CLASSIFICATION,
TaskType.TEXT_TO_TEXT_GENERATION,
TaskType.TEXT_TAGGING,
]
languages = ["en"]
def __init__... | import piglatin
import random
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class PigLatin(SentenceOperation):
tasks = [
TaskType.TEXT_CLASSIFICATION,
TaskType.TEXT_TO_TEXT_GENERATION,
TaskType.TEXT_TAGGING,
]
languages = ["en"]
... | Add per-word replace probability, max outputs. | Add per-word replace probability, max outputs.
| Python | mit | GEM-benchmark/NL-Augmenter |
0f71f39a8634927b532c3f5b258720761f1d9c5c | mentorup/users/models.py | mentorup/users/models.py | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags fo... | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags fo... | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
| Python | bsd-3-clause | briandant/mentor_up,briandant/mentor_up,briandant/mentor_up,briandant/mentor_up |
23f95f0319c929006c89efdf0d113370a1a003b4 | moa/factory_registers.py | moa/factory_registers.py | from kivy.factory import Factory
r = Factory.register
r('MoaStage', module='moa.stage.base')
r('StageRender', module='moa.stage.base')
r('Delay', module='moa.stage.delay')
r('TreeRender', module='moa.render.treerender')
r('TreeRenderExt', module='moa.render.treerender')
r('StageTreeNode', module='moa.render.treerender... | from kivy.factory import Factory
r = Factory.register
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('StageRender', module='moa.stage.base')
r('TreeRender', module='moa.render.treerender')
r('TreeRenderExt', module='moa.render.treerender')
r('StageTree... | Update factory registers with stages. | Update factory registers with stages.
| Python | mit | matham/moa |
b1bf5dfa91f1f7b84512f72d6e5e18c2109f3239 | addic7ed/__init__.py | addic7ed/__init__.py | from termcolor import colored
from .parser import Addic7edParser
from .file_crawler import FileCrawler
from .logger import init_logger
from .config import Config
def addic7ed():
try:
init_logger()
Config.load()
main()
except (EOFError, KeyboardInterrupt, SystemExit):
print(col... | from termcolor import colored
from .parser import Addic7edParser
from .file_crawler import FileCrawler
from .logger import init_logger
from .config import Config
def addic7ed():
try:
init_logger()
Config.load()
main()
except (EOFError, KeyboardInterrupt, SystemExit):
print(col... | Fix newline output of downloaded srt | Fix newline output of downloaded srt
| Python | mit | Jesus-21/addic7ed |
7b9ee45c0791d8368a0bb8af52652d3fcd482c79 | qubesadmin/__init__.py | qubesadmin/__init__.py | # -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Li... | # -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Li... | Choose QubesLocal or QubesRemote based on /etc/qubes-release presence | Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
Do not check for qubesd socket (at module import time), because if not
running at this precise time, it will lead to wrong choice. And a weird
error message in consequence (looking for qrexec-client-vm in dom0).
Fixes QubesOS/qubes-issues#2917
| Python | lgpl-2.1 | marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client |
9daac0977933238929eda5e05c635e3a626cbe21 | tests/test_example.py | tests/test_example.py | import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
... | import os
import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_spli... | Add intelligent skip for missing secret info | Add intelligent skip for missing secret info
| Python | apache-2.0 | marshallford/ndsu-ibm-capstone,marshallford/ndsu-ibm-capstone |
1a3ffe00bfdf8c61b4ff190beb2ee6a4e9db1412 | behave_django/environment.py | behave_django/environment.py | from django.core.management import call_command
from django.shortcuts import resolve_url
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
c... | from django.core.management import call_command
try:
from django.shortcuts import resolve_url
except ImportError:
import warnings
warnings.warn("URL path supported only in get_url() with Django < 1.5")
resolve_url = lambda to, *args, **kwargs: to
from behave_django.testcase import BehaveDjangoTestCase
... | Support Django < 1.5 with a simplified version of `get_url()` | Support Django < 1.5 with a simplified version of `get_url()`
| Python | mit | nikolas/behave-django,nikolas/behave-django,behave/behave-django,bittner/behave-django,bittner/behave-django,behave/behave-django |
005c6ceae1b80f5092e78231242b01af2ba64fed | tests/integration/api/conftest.py | tests/integration/api/conftest.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... | Use `make_admin_app`, document why `admin_app` is still needed | Use `make_admin_app`, document why `admin_app` is still needed
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
91f9ea76a1a48cf9e191b4f97818c105428bbbd6 | util/test_graph.py | util/test_graph.py | import urllib2
token = 'test_token'
channel = 'test_channel'
graphtype = 'test'
url = 'http://{}/ocpgraph/{}/{}/{}/'.format('localhost:8000', token, channel, graphtype)
try:
req = urllib2.Request(url)
resposne = urllib2.urlopen(req)
except Exception, e:
raise
| # Copyright 2014 Open Connectome Project (http://openconnecto.me)
#
# 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 app... | Test file for Graph code | [util] Test file for Graph code
| Python | apache-2.0 | neurodata/ndstore,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,neurodata/ndstore,neurodata/ndstore,neurodata/ndstore |
e5b42db249dd94a0d7652881a8bba8ed78772d3e | examples/turnAndMove.py | examples/turnAndMove.py | import slither, pygame
snakey = slither.Sprite()
snakey.setCostumeByName("costume0")
snakey.goto(0, 0)
slither.slitherStage.setColor(40, 222, 40)
slither.setup() # Begin slither
def handlequit():
print("Quitting...")
return True
slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call ... | import slither, pygame
snakey = slither.Sprite()
snakey.setCostumeByName("costume0")
snakey.goto(0, 0)
slither.setup() # Begin slither
def handlequit():
print("Quitting...")
return True
slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form
@slither.registerCallback(pygame.MOUSE... | Fix small test problem\nBTW rotation works now, thanks @BookOwl | Fix small test problem\nBTW rotation works now, thanks @BookOwl
| Python | mit | PySlither/Slither,PySlither/Slither |
3ae63e055146ecb45b6943e661808b0546b42273 | tests/test_playsong/test_query.py | tests/test_playsong/test_query.py | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function, unicode_literals
import nose.tools as nose
from tests.utils import run_filter
def test_ignore_case():
"""should ignore case when querying songs"""
results = run_filter('playsong', 'mr Blue SKY')
nose.assert_equal(results[0]['ti... | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function, unicode_literals
import nose.tools as nose
from tests.utils import run_filter
def test_ignore_case():
"""should ignore case when querying songs"""
results = run_filter('playsong', 'mr Blue SKY')
nose.assert_equal(results[0]['ti... | Add extra description to partial match playsong test | Add extra description to partial match playsong test
| Python | mit | caleb531/play-song,caleb531/play-song |
d0f092afc9534d25b5ebf81ff329ad296e30952e | numpy/distutils/setup.py | numpy/distutils/setup.py | #!/usr/bin/env python
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='',top_path=None):
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
confi... | #!/usr/bin/env python
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='',top_path=None):
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
confi... | Add site.cfg to datafiles installed for numpy.distutils. | Add site.cfg to datafiles installed for numpy.distutils.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2011 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,illume/numpy3k,illume/numpy3k,jasonmccampbell/numpy-refactor-spr... |
9cadf855a4506e29009a910206c6ce213279aafe | tests/test_configuration.py | tests/test_configuration.py | # -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_v... | # -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_v... | Adjust POST_LOGIN_VIEW and POST_LOGOUT_VIEW test | Adjust POST_LOGIN_VIEW and POST_LOGOUT_VIEW test
| Python | mit | tatataufik/flask-security,quokkaproject/flask-security,wjt/flask-security,mik3cap/private-flask-security,dlakata/flask-security,jonafato/flask-security,nfvs/flask-security,themylogin/flask-security,CodeSolid/flask-security,GregoryVigoTorres/flask-security,inveniosoftware/flask-security-fork,fuhrysteve/flask-security,Sa... |
52bfbea4e2cb17268349b61c7f00b9253755e74d | example/books/models.py | example/books/models.py | from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_abs... | from __future__ import unicode_literals
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_l... | Add support for django 2 to example project | Add support for django 2 to example project
| Python | mit | spapas/django-generic-scaffold,spapas/django-generic-scaffold |
e9c83d59fbb5b341e2126039109e306875db0490 | syweb/__init__.py | syweb/__init__.py | import os
with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| import os
def installed_location():
return __file__
with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| Add an 'installed_location()' function so syweb can report its own location | Add an 'installed_location()' function so syweb can report its own location
| Python | apache-2.0 | williamboman/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,matrix-org/matrix-angular-sdk |
0a779f17e19f18c8f7e734e7e61367712fe9e52a | examples/worker_rush.py | examples/worker_rush.py | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0:
for worker in self.workers:
await self.do(worker.attack(self.enemy_start_locations[0]))
def ma... | from sc2 import run_game, maps, Race, Difficulty, BotAI
from sc2.player import Bot, Computer
class WorkerRushBot(BotAI):
def __init__(self):
super().__init__()
self.actions = []
async def on_step(self, iteration):
self.actions = []
if iteration == 0:
target = self.... | Use do_actions() instead of do() in WorkerRushBot | Use do_actions() instead of do() in WorkerRushBot
| Python | mit | Dentosal/python-sc2 |
258df4932fe937c0baf45d30de88c194f7f7718a | conftest.py | conftest.py |
import numba
import numpy
import pkg_resources
import pytest
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/release.html#ma... |
import numba
import numpy
import pkg_resources
import pytest
import scipy
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/re... | Add SciPy version to pytest header | Add SciPy version to pytest header
| Python | mit | dwillmer/fastats,fastats/fastats |
ccb021e4f672b02d63236207573cc5f7746012e2 | apps/uploads/management/commands/process_uploads.py | apps/uploads/management/commands/process_uploads.py |
import logging
LOGGER = logging.getLogger('apps.uploads')
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile
class Command(BaseCommand):
help = """Regular run of new dropbox links:
manage.py process_uploads
"""
def... | """Download from urls any uploads from outside sources"""
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile, ResumableUploadFile
LOGGER = logging.getLogger('apps.uploads')
class Co... | Mark resuable uploads as broken if they are | Mark resuable uploads as broken if they are
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site |
21ab4cb4bb50acd7598b09ebceec20c7302061da | scikits/learn/datasets/tests/test_20news.py | scikits/learn/datasets/tests/test_20news.py | """Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
... | """Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=... | Fix a bug introduced in rebasing | BUG: Fix a bug introduced in rebasing
| Python | bsd-3-clause | krez13/scikit-learn,ChanderG/scikit-learn,466152112/scikit-learn,ChanChiChoi/scikit-learn,belltailjp/scikit-learn,tdhopper/scikit-learn,krez13/scikit-learn,yyjiang/scikit-learn,schets/scikit-learn,TomDLT/scikit-learn,xubenben/scikit-learn,MohammedWasim/scikit-learn,0x0all/scikit-learn,mblondel/scikit-learn,aewhatley/sc... |
de7abaa3e1de7b7de1c10daa43b621daaee628fd | roundware/rw/fields.py | roundware/rw/fields.py | from django.forms import forms
from south.modelsinspector import add_introspection_rules
from validatedfile.fields import ValidatedFileField
import pyclamav
class RWValidatedFileField(ValidatedFileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_typ... | from django.forms import forms
from south.modelsinspector import add_introspection_rules
from validatedfile.fields import ValidatedFileField
class RWValidatedFileField(ValidatedFileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_types.
Exa... | Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation | Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation
| Python | agpl-3.0 | IMAmuseum/roundware-server,Karlamon/roundware-server,IMAmuseum/roundware-server,jslootbeek/roundware-server,IMAmuseum/roundware-server,eosrei/roundware-server,IMAmuseum/roundware-server,eosrei/roundware-server,eosrei/roundware-server,Karlamon/roundware-server,probabble/roundware-server,yangjackascd/roundware-server,Kar... |
2c45c405887e415744ea0b447936848b9b6fd355 | makerbot_driver/Preprocessors/Preprocessor.py | makerbot_driver/Preprocessors/Preprocessor.py | """
An interface that all future preprocessors should inherit from
"""
import os
import re
from errors import *
from .. import Gcode
class Preprocessor(object):
def __init__(self):
pass
def process_file(self, input_path, output_path):
pass
def inputs_are_gcode(self, input_path, output_path):
for... | """
An interface that all future preprocessors should inherit from
"""
import os
import re
from errors import *
from .. import Gcode
class Preprocessor(object):
def __init__(self):
pass
def process_file(self, input_path, output_path):
pass
def inputs_are_gcode(self, input_path, output_path):
pass... | Disable check for .gcode file extension when preprocessing gcode. | Disable check for .gcode file extension when preprocessing gcode.
| Python | agpl-3.0 | makerbot/s3g,makerbot/s3g,makerbot/s3g,makerbot/s3g,Jnesselr/s3g,Jnesselr/s3g |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.