commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
54296c607b735ce06b3420efecb312f52876e012 | Replace warning message with deprecation warning | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags | django_react_templatetags/context_processors.py | django_react_templatetags/context_processors.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import warnings
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
warnings.warn(
"react_context_processor is no longer required.", DeprecationWarning
)
return {
'REACT_COMPONENTS': [],
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def react_context_processor(request):
"""Expose a global list of react components to be processed"""
print("react_context_processor is no longer required.")
return {
'REACT_COMPONENTS': [],
}
| mit | Python |
2b7e0d52a8a8764b66d8698800bf18e8adc9dae7 | fix crash when running fix_loop_duplicates.py | rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo,rackerlabs/django-DefectDojo | dojo/management/commands/fix_loop_duplicates.py | dojo/management/commands/fix_loop_duplicates.py | from django.core.management.base import BaseCommand
from dojo.utils import fix_loop_duplicates
"""
Author: Marian Gawron
This script will identify loop dependencies in findings
"""
class Command(BaseCommand):
help = 'No input commands for fixing Loop findings.'
def handle(self, *args, **options):
fi... | from django.core.management.base import BaseCommand
from pytz import timezone
from dojo.utils import fix_loop_duplicates
locale = timezone(get_system_setting('time_zone'))
"""
Author: Marian Gawron
This script will identify loop dependencies in findings
"""
class Command(BaseCommand):
help = 'No input commands ... | bsd-3-clause | Python |
e776ac5b08fa2a7ce299ec68697d330fb8a02fd5 | upgrade __version__ in __init__.py to 1.4.0 | millerdev/django-nose,krinart/django-nose,dgladkov/django-nose,sociateru/django-nose,harukaeru/django-nose,Deepomatic/django-nose,millerdev/django-nose,Deepomatic/django-nose,dgladkov/django-nose,alexhayes/django-nose,sociateru/django-nose,brilliant-org/django-nose,franciscoruiz/django-nose,brilliant-org/django-nose,ar... | django_nose/__init__.py | django_nose/__init__.py | VERSION = (1, 4, 0)
__version__ = '.'.join(map(str, VERSION))
from django_nose.runner import *
from django_nose.testcases import *
# Django < 1.2 compatibility.
run_tests = run_gis_tests = NoseTestSuiteRunner
| VERSION = (1, 3, 0)
__version__ = '.'.join(map(str, VERSION))
from django_nose.runner import *
from django_nose.testcases import *
# Django < 1.2 compatibility.
run_tests = run_gis_tests = NoseTestSuiteRunner
| bsd-3-clause | Python |
eec67d43d208b490c9d219b3c38e586597b1fa73 | Refactor generate_module_objects | alexamici/pytest-nodev,nodev-io/pytest-nodev,alexamici/pytest-wish | pytest_wish.py | pytest_wish.py | # -*- coding: utf-8 -*-
import importlib
import inspect
import re
import sys
import pytest
def pytest_addoption(parser):
group = parser.getgroup('wish')
group.addoption('--wish-modules', default=(), nargs='+',
help="Space separated list of module names.")
group.addoption('--wish-incl... | # -*- coding: utf-8 -*-
import importlib
import inspect
import re
import sys
import pytest
def pytest_addoption(parser):
group = parser.getgroup('wish')
group.addoption('--wish-modules', default=(), nargs='+',
help="Space separated list of module names.")
group.addoption('--wish-incl... | mit | Python |
93e12746d19161b30e2dade0d71f22242603b0bd | Address fix | hopkira/k9-chess-angular,hopkira/k9-chess-angular,hopkira/k9-chess-angular,hopkira/k9-chess-angular | python/test.py | python/test.py | import math
from roboclaw import Roboclaw
address = 0x80
rc = Roboclaw("/dev/roboclaw",115200)
rc.Open()
version = rc.ReadVersion(address)
if version[0]==False:
print "GETVERSION Failed"
else:
print repr(version[1])
rc.SetM1VelocityPID(address,3000,300,0,708)
rc.SetM2VelocityPID(address,3000,300,0,720)
rc.WriteNVM(ad... | import math
from roboclaw import Roboclaw
address = 0x80
rc = Roboclaw("/dev/roboclaw",115200)
rc.Open()
version = rc.ReadVersion(address)
if version[0]==False:
print "GETVERSION Failed"
else:
print repr(version[1])
rc.SetM1VelocityPID(rc_address,3000,300,0,708)
rc.SetM2VelocityPID(rc_address,3000,300,0,720)
rc.Write... | unlicense | Python |
b860606c2ce654044131228ddfb741c517ab282e | make QLibraryInfo.location works | spyder-ide/qtpy | qtpy/QtCore.py | qtpy/QtCore.py | #
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtCore classes and functions.
"""
from . import PYQT6, PYQT5, PYSIDE2, PYSIDE6, PythonQtError
if PYQT6:
from PyQt6 import QtCore
... | #
# Copyright © 2014-2015 Colin Duquesnoy
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
"""
Provides QtCore classes and functions.
"""
from . import PYQT6, PYQT5, PYSIDE2, PYSIDE6, PythonQtError
if PYQT6:
from PyQt6 import QtCore
... | mit | Python |
34b6d5c04e51e95874141d746dbfc6e16fcca967 | Use capital letters in all view name words | Nikola-K/django_reddit,Nikola-K/django_reddit,Nikola-K/django_reddit | reddit/urls.py | reddit/urls.py | """django_reddit URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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')
Cla... | """django_reddit URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/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')
Cla... | apache-2.0 | Python |
21102267231fbdc171b670d62f5ee8baf7d4d4c4 | Add multiplication operation | MelSchlemming/calc | calc.py | calc.py | import sys
def add_all(nums):
return sum(nums)
def multiply_all(nums):
return reduce(lambda a, b: a * b, nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums))
elif command == 'multiply':
print(multiply_... | import sys
def add_all(nums):
return sum(nums)
if __name__ == '__main__':
command = sys.argv[1]
nums = map(float, sys.argv[2:])
if command == 'add':
print(add_all(nums)) | bsd-3-clause | Python |
f6fdbdc1176cffa0a145170cab583387f26f8649 | Add module docstring | anchavesb/pyCalc | calc.py | calc.py | """calc.py: A simple python calculator."""
import sys
if __name__ == '__main__':
print(sum(map(int, sys.argv[1:])))
| import sys
if __name__ == '__main__':
print(sum(map(int, sys.argv[1:])))
| bsd-3-clause | Python |
5fd51adbbc136adc28725688c7bf1ecf56e978c1 | Develop (#105) | ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints,ritstudentgovernment/PawPrints | auth/auth_backend.py | auth/auth_backend.py | """
auth_backend.py
Peter Zujko (@zujko)
Defines Django authentication backend for shibboleth.
04/05/17
"""
from django.contrib.auth.models import User
class Attributes():
EDU_AFFILIATION = 'urn:oid:1.3.6.1.4.1.4447.1.41'
FIRST_NAME = 'urn:oid:2.5.4.42'
LAST_NAME = 'urn:oid:2.5.4.4'
USERNAME = 'urn:... | """
auth_backend.py
Peter Zujko (@zujko)
Defines Django authentication backend for shibboleth.
04/05/17
"""
from django.contrib.auth.models import User
class Attributes():
EDU_AFFILIATION = 'urn:oid:1.3.6.1.4.1.4447.1.41'
FIRST_NAME = 'urn:oid:2.5.4.42'
LAST_NAME = 'urn:oid:2.5.4.4'
USERNAME = 'urn:... | apache-2.0 | Python |
95ead630018870f293613febc599a50e8c69c792 | Change in field length | hydroshare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,FescueFungiShare/hydroshare,RENCI/xDCIShare,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,FescueFungiS... | hs_core/migrations/0030_resourcefile_file_folder.py | hs_core/migrations/0030_resourcefile_file_folder.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hs_core', '0029_auto_20161123_1858'),
]
operations = [
migrations.AddField(
model_name='resourcefile',
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hs_core', '0029_auto_20161123_1858'),
]
operations = [
migrations.AddField(
model_name='resourcefile',
... | bsd-3-clause | Python |
9b9d6db9d99bec69e61070a743d0b2194c35e375 | Mark as dead | vuolter/pyload,vuolter/pyload,vuolter/pyload | module/plugins/hoster/FreevideoCz.py | module/plugins/hoster/FreevideoCz.py | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo
class FreevideoCz(DeadHoster):
__name__ = "FreevideoCz"
__version__ = "0.3"
__type__ = "hoster"
__pattern__ = r'http://(?:www\.)?freevideo\.cz/vase-videa/.+'
__description__ = """Freevideo.cz hoste... | # -*- coding: utf-8 -*-
"""
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
This program is distributed in... | agpl-3.0 | Python |
1fed9f26010f24af14abff9444862ed0861adb63 | Add simplification between parsing and execution | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang | thinglang/runner.py | thinglang/runner.py | from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
from thinglang.parser.simplifier import simplify
def run(source):
if not source:
raise ValueError('Source cannot be empty')
source = source.strip().replace(' ' *... | from thinglang.execution.execution import ExecutionEngine
from thinglang.lexer.lexer import lexer
from thinglang.parser.parser import parse
def run(source):
if not source:
raise ValueError('Got empty source')
source = source.strip().replace(' ' * 4, '\t')
lexical_groups = list(lexer(source))
... | mit | Python |
e57e003b85f0a88ac6e3c19d5765144f95ac9959 | Increase version to 0.3.2rc | TissueMAPS/TmServer | tmserver/version.py | tmserver/version.py | # TmServer - TissueMAPS server application.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version... | # TmServer - TissueMAPS server application.
# Copyright (C) 2016 Markus D. Herrmann, University of Zurich and Robin Hafen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version... | agpl-3.0 | Python |
c09bfe422d6dd705e5e38402dd8754f461fabe59 | Support filtering by list of jobNo | gis-rpd/pipelines,gis-rpd/pipelines,gis-rpd/pipelines | tools/accounting.py | tools/accounting.py | #!/usr/bin/env python3
"""
collection: gisds.accountinglogs
"""
#--- standard library imports
#
from argparse import ArgumentParser
from datetime import datetime
import os
from pprint import PrettyPrinter
import sys
from time import gmtime, strftime
#--- project specific imports
#
# add lib dir for this pipeline ins... | #!/usr/bin/env python3
"""
collection: gisds.accountinglogs
"""
#--- standard library imports
#
from argparse import ArgumentParser
from datetime import datetime
import os
from pprint import PrettyPrinter
import sys
from time import gmtime, strftime
#--- project specific imports
#
# add lib dir for this pipeline ins... | mit | Python |
5ac6c93073c98ea17a0786e6e1a1de3837e460d9 | Handle RSS feeds for blogs that don't have dates | rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,rcos/Observatory,natestedman/Observatory,natestedman/Observatory,natestedman/Observatory,rcos/Observatory | observatory/dashboard/models/Blog.py | observatory/dashboard/models/Blog.py | # Copyright (c) 2010, Nate Stedman <natesm@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT... | # Copyright (c) 2010, Nate Stedman <natesm@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUT... | isc | Python |
ff30fbd3adef0de27c7b3f690fff1c47c6d42b6a | set tree self.depth to minDepth | FermiDirak/RandomForest | DecisionTree.py | DecisionTree.py | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self, dataset, minDepth):
self.root = None
self.left = None
self.right = None
self.data = dataset
self.depth = minDepth
... | class Node:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class Tree: # passing (object ) into class is no longer needed in python3
def __init__(self, dataset, minDepth, depth = 3):
self.root = None
self.left = None
self.rig... | mit | Python |
a5bef7ac44a688b9d4493c28210a1a3fbcb64ffe | Fix channel comparison with # prefix | slackapi/python-slackclient,slackapi/python-slackclient,slackapi/python-slackclient,slackhq/python-slackclient | slackclient/_channel.py | slackclient/_channel.py | class Channel(object):
def __init__(self, server, name, channel_id, members=None):
self.server = server
self.name = name
self.id = channel_id
self.members = [] if members is None else members
def __eq__(self, compare_str):
if self.name == compare_str or "#" + self.name =... | class Channel(object):
def __init__(self, server, name, channel_id, members=None):
self.server = server
self.name = name
self.id = channel_id
self.members = [] if members is None else members
def __eq__(self, compare_str):
if self.name == compare_str or self.name == "#" ... | mit | Python |
a2a652620fa4d7504baa42f08fc80bd2a7db1341 | Make frozendict peristently-hasheable | edgedb/edgedb,edgedb/edgedb,edgedb/edgedb | edgedb/lang/common/datastructures/immutables.py | edgedb/lang/common/datastructures/immutables.py | ##
# Copyright (c) 2008-2010, 2014 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
import abc
import collections
from metamagic.utils.algos.persistent_hash import persistent_hash
class ImmutableMeta(type):
def __new__(mcls, name, bases, dct):
if '_shadowed_methods_' in dct:
... | ##
# Copyright (c) 2008-2010 Sprymix Inc.
# All rights reserved.
#
# See LICENSE for details.
##
import abc
import collections
class ImmutableMeta(type):
def __new__(mcls, name, bases, dct):
if '_shadowed_methods_' in dct:
shadowed = dct['_shadowed_methods_']
del dct['_shadowed_m... | apache-2.0 | Python |
4cda993213fce2b4567ba31f2dc6a116445ce664 | rollback on dummy database now has no effect (previously raised an error). This means that custom 500 error pages (and e-mailed exceptions) now work even if a database has not been configured. Fixes #4429. | apollo13/django,krishna-pandey-git/django,BMJHayward/django,pquentin/django,risicle/django,jylaxp/django,h4r5h1t/django-hauthy,baylee/django,frishberg/django,tcwicklund/django,programadorjc/django,andreif/django,MarcJoan/django,Proggie02/TestRepo,gdub/django,zsiciarz/django,Leila20/django,shaib/django,ptoraskar/django,... | django/db/backends/dummy/base.py | django/db/backends/dummy/base.py | """
Dummy database backend for Django.
Django uses this if the DATABASE_ENGINE setting is empty (None or empty string).
Each of these API functions, except connection.close(), raises
ImproperlyConfigured.
"""
from django.core.exceptions import ImproperlyConfigured
def complain(*args, **kwargs):
raise Improperly... | """
Dummy database backend for Django.
Django uses this if the DATABASE_ENGINE setting is empty (None or empty string).
Each of these API functions, except connection.close(), raises
ImproperlyConfigured.
"""
from django.core.exceptions import ImproperlyConfigured
def complain(*args, **kwargs):
raise Improperly... | bsd-3-clause | Python |
1ec9d3b5d7a2fdfd6e7d0e763c95e1a3117cd96d | Update middleware to be django1.10-compatible | selwin/django-user_agents,selwin/django-user_agents | django_user_agents/middleware.py | django_user_agents/middleware.py | from django.utils.functional import SimpleLazyObject
from django.utils.deprecation import MiddlewareMixin
from .utils import get_user_agent
class UserAgentMiddleware(MiddlewareMixin):
# A middleware that adds a "user_agent" object to request
def process_request(self, request):
request.user_agent = Si... | from django.utils.functional import SimpleLazyObject
from .utils import get_user_agent
class UserAgentMiddleware(object):
# A middleware that adds a "user_agent" object to request
def process_request(self, request):
request.user_agent = SimpleLazyObject(lambda: get_user_agent(request))
| mit | Python |
9fe4b5fee790b7e21eb5810176a2cfa49abde7b2 | Create author obj only for active users | AvadootNachankar/gstudio,AvadootNachankar/gstudio,gnowledge/gstudio,gnowledge/gstudio,gnowledge/gstudio,gnowledge/gstudio,AvadootNachankar/gstudio,gnowledge/gstudio,AvadootNachankar/gstudio | doc/deployer/create_auth_objs.py | doc/deployer/create_auth_objs.py | from gnowsys_ndf.ndf.models import *
from django.contrib.auth.models import User
all_users = User.objects.all()
auth_gst = node_collection.one({'_type': u'GSystemType', 'name': u'Author'})
new_auth_instances = 0
for each_user in all_users:
auth = node_collection.one({'_type': u"Author", 'created_by': int(each_user.id)... | from gnowsys_ndf.ndf.models import *
from django.contrib.auth.models import User
all_users = User.objects.all()
auth_gst = node_collection.one({'_type': u'GSystemType', 'name': u'Author'})
new_auth_instances = 0
for each_user in all_users:
auth = node_collection.one({'_type': u"Author", 'created_by': int(each_user.id)... | agpl-3.0 | Python |
69f28c471935d5e8136a4b32f51310f1f46046f0 | set lower for envvar keys | dockU/build | docku/build/__init__.py | docku/build/__init__.py | import json
import os
class BuildConfig(dict):
def __init__(self, path):
cc = {}
with open(path) as fh:
cc = json.load(fh)
super().__init__(cc)
self.populate_envvars()
def populate_envvars(self):
keys = ['BINTRAY_TOKEN', 'BINTRAY_USER', 'BINTRAY_REPO']
... | import json
import os
class BuildConfig(dict):
def __init__(self, path):
cc = {}
with open(path) as fh:
cc = json.load(fh)
super().__init__(cc)
self.populate_envvars()
def populate_envvars(self):
keys = ['BINTRAY_TOKEN', 'BINTRAY_USER', 'BINTRAY_REPO']
... | mit | Python |
b289569a228ff574f2c469d0d2a7fbb019c19c9e | Update version | snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills,snipsco/snipsskills | snipsskills/__init__.py | snipsskills/__init__.py | # -*-: coding utf-8 -*-
""" snipsskills module """
__version__ = '0.1.4.935'
| # -*-: coding utf-8 -*-
""" snipsskills module """
__version__ = '0.1.4.934'
| mit | Python |
0d6f7da3de63de55d8aa96532e072626f3198ed5 | Sort by date | Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org | Instanssi/ext_blog/templatetags/blog_tags.py | Instanssi/ext_blog/templatetags/blog_tags.py | # -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id__lte=int(event_id), public=True).order_by('-date')[:10]
... | # -*- coding: utf-8 -*-
from django import template
from Instanssi.ext_blog.models import BlogEntry
register = template.Library()
@register.inclusion_tag('ext_blog/blog_messages.html')
def render_blog(event_id):
entries = BlogEntry.objects.filter(event_id__lte=int(event_id), public=True)[:10]
return {'entrie... | mit | Python |
bc7c3322e027578f79119e6836111244ba1445cc | revert out | sk2/autonetkit | autonetkit/config.py | autonetkit/config.py | import pkg_resources
import ConfigParser
from configobj import ConfigObj, flatten_errors
import os
import validate
validator = validate.Validator()
import os.path
# from http://stackoverflow.com/questions/4028904
ank_user_dir = os.path.join(os.path.expanduser("~"), ".autonetkit")
def load_config():
settings = C... | import pkg_resources
import ConfigParser
from configobj import ConfigObj, flatten_errors
import os
import validate
validator = validate.Validator()
import os.path
#TODO: check this works on Windows
ank_user_dir = os.path.join(os.environ['HOME'], ".autonetkit")
def load_config():
settings = ConfigParser.RawConfi... | bsd-3-clause | Python |
080b967c0854d416532449dba96bbbd8f0318d8a | remove time_per_record since it does not make real sense | enthought/pikos,enthought/pikos,enthought/pikos | pikos/benchmark/monitors.py | pikos/benchmark/monitors.py | # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Package: Pikos toolkit
# File: benchmark/monitors.py
# License: LICENSE.TXT
#
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#---------------------------------------------------------------------... | # -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Package: Pikos toolkit
# File: benchmark/monitors.py
# License: LICENSE.TXT
#
# Copyright (c) 2012, Enthought, Inc.
# All rights reserved.
#---------------------------------------------------------------------... | bsd-3-clause | Python |
a477de34625f9fc4076eaa093b606463063e33b3 | add check if TwitterAPI was installed and installed it if not | J216/gimp_be,J216/gimp_be | gimp_be/network/twitter.py | gimp_be/network/twitter.py | from gimp_be.settings.settings import *
from gimp_be.utils.string_tools import *
from gimp_be.utils.pip import *
try:
import TwitterAPI
except:
pipInstall("TwitterAPI")
def tweetImage(message,image_file):
"""
Tweet image with message
:param message:
:param image_file:
:return:
"""
f... | from gimp_be.settings.settings import *
from gimp_be.utils.string_tools import *
def tweetImage(message,image_file):
"""
Tweet image with message
:param message:
:param image_file:
:return:
"""
from TwitterAPI import TwitterAPI
global settings_data
CONSUMER_KEY = settings_data['twi... | mit | Python |
6138f02896bc865a98480be36300bf670a6defa8 | Replace re by os.path utils | justmao945/vim-clang,justmao945/vim-clang | plugin/complete_database.py | plugin/complete_database.py | import vim
import re
import json
from os import path
curr_file = vim.eval("expand('%:p')")
curr_file_noext = path.splitext(curr_file)[0]
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
# Search for the right entry in the database matching file names
for d in json.load(database):
# This ... | import vim
import re
import json
from os import path
current = vim.eval("expand('%:p')")
ccd = vim.eval("l:ccd")
opts = []
with open(ccd) as database:
data = json.load(database)
for d in data:
# hax for headers
fmatch = re.search(r'(.*)\.(\w+)$', current)
dmatch = re.search(r'(.*)\.(\... | isc | Python |
7903c7604a54a8786a5d4b658c224b6d28ed43af | Add iterator for lists | Dalloriam/engel,Dalloriam/engel,Dalloriam/engel | popeui/widgets/structure.py | popeui/widgets/structure.py | from .base import BaseContainer
from .abstract import HeadLink
class Document(BaseContainer):
"""
A document. Analogous to the HTML ``<html>`` element.
"""
html_tag = "html"
def __init__(self, id, view, classname=None, parent=None, **kwargs):
"""
:param view: :class:`~.application.View` in which t... | from .base import BaseContainer
from .abstract import HeadLink
class Document(BaseContainer):
"""
A document. Analogous to the HTML ``<html>`` element.
"""
html_tag = "html"
def __init__(self, id, view, classname=None, parent=None, **kwargs):
"""
:param view: :class:`~.application.View` in which t... | mit | Python |
c4b408bdf84333a5e41d10ee3d46f926069b5548 | Delete deprecated with_coverage task | Turupawn/website,lutris/website,lutris/website,Turupawn/website,Turupawn/website,Turupawn/website,lutris/website,lutris/website | lutrisweb/settings/test.py | lutrisweb/settings/test.py | from base import * # noqa
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS += (
'django_jenkins',
)
JENKINS_TASKS = (
'django_jenkins.tasks.run_pylint',
'django_jenkins.tasks.run_pep8',
)
PROJECT_APPS = (
... | from base import * # noqa
DEBUG = False
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS += (
'django_jenkins',
)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
'django_jenkins.tasks.run_pylint',
'django_jenkin... | agpl-3.0 | Python |
421ace15d779cc686aa83489c0e965bbeabe49b9 | Update script to repeat test set experiment 10 times | NLeSC/cptm,NLeSC/cptm | cptm/experiment_testset_without_perspectives.py | cptm/experiment_testset_without_perspectives.py | """Script to extract a document/topic matrix for a set of text documents.
The corpus is not divided in perspectives.
Used to calculate theta for the CAP vragenuurtje data.
"""
import logging
import argparse
import pandas as pd
import os
from CPTCorpus import CPTCorpus
from cptm.utils.experiment import get_sampler, t... | """Script to extract a document/topic matrix for a set of text documents.
The corpus is not divided in perspectives.
Used to calculate theta for the CAP vragenuurtje data.
"""
import logging
import argparse
import pandas as pd
import os
from CPTCorpus import CPTCorpus
from cptm.utils.experiment import get_sampler, t... | apache-2.0 | Python |
0fe7cd8cf316dc6d4ef547d733b634de64fc768c | Add more options on filters | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | dbaas/dbaas_services/analyzing/admin/analyze.py | dbaas/dbaas_services/analyzing/admin/analyze.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = ... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django_services import admin
from dbaas_services.analyzing.service import AnalyzeRepositoryService
from dbaas_services.analyzing.forms import AnalyzeRepositoryForm
class AnalyzeRepositoryAdmin(admin.DjangoServicesAdmin):
form = ... | bsd-3-clause | Python |
4605dfb434d7a934e2fce39f96d73e66f17a682b | Handle missing settings file | e2gal/antisarubot,e2gal/i2vbot,e2gal/i2vbot,e2gal/antisarubot | i2vbot/settings.py | i2vbot/settings.py | #!/usr/bin/env python2
# Ampuni aku... :(
import pickle
SETTINGS_FILE = "data/settings.pickle"
def loadSettings(settingsFile = SETTINGS_FILE):
try:
with open(settingsFile, 'r') as f:
return pickle.load(f)
except:
return {}
def saveSettings(settings, settingsFile = SETTINGS_FILE):... | #!/usr/bin/env python2
# Ampuni aku... :(
import pickle
SETTINGS_FILE = "data/settings.pickle"
def loadSettings(settingsFile = SETTINGS_FILE):
with open(settingsFile, 'r') as f:
try:
return pickle.load(f)
except:
return {}
def saveSettings(settings, settingsFile = SETTING... | mit | Python |
8bc3e371690ef28609f1999a4a3dabc0dd453850 | Correct serve() to call serve_one() not listen_one() | PinkInk/upylib,PinkInk/upylib | uhttpsrv/uhttpsrv.py | uhttpsrv/uhttpsrv.py | import socket
class uHTTPsrv:
PROTECTED = [b'__init__', b'listen_once', b'listen', b'response_header', b'__qualname__', b'__module__', b'address', b'port', b'backlog', b'in_buffer_len', b'debug']
def __init__(self, address='', port=80, backlog=1, in_buffer_len=1024, debug=False):
self.address = address
self.po... | import socket
class uHTTPsrv:
PROTECTED = [b'__init__', b'listen_once', b'listen', b'response_header', b'__qualname__', b'__module__', b'address', b'port', b'backlog', b'in_buffer_len', b'debug']
def __init__(self, address='', port=80, backlog=1, in_buffer_len=1024, debug=False):
self.address = address
self.po... | mit | Python |
d69aa85c74482354ff8788fb7b9692f0aee6d311 | Fix it. | mrshu/iepy,mrshu/iepy,machinalis/iepy,machinalis/iepy,mrshu/iepy,machinalis/iepy | iepy/preprocess.py | iepy/preprocess.py | import logging
logger = logging.getLogger(__name__)
class PreProcessPipeline(object):
"""Coordinates the pre-processing tasks on a set of documents"""
def __init__(self, step_runners, documents_manager):
"""Takes a list of callables and a documents-manager.
Step Runners may be any calla... | import logging
logger = logging.getLogger(__name__)
class PreProcessPipeline(object):
"""Coordinates the pre-processing tasks on a set of documents"""
def __init__(self, step_runners, documents_manager):
"""Takes a list of callables and a documents-manager.
Step Runners may be any calla... | bsd-3-clause | Python |
42743ac90ede1d9d78c892f1cee033c5e5a66c9b | fix typo in docker update script | dune-community/dune-gdt-super | .travis/docker/update_image.py | .travis/docker/update_image.py | #!/usr/bin/env python3
import os
import subprocess
import sys
cc_mapping = {'gcc': 'g++', 'clang': 'clang++'}
thisdir = os.path.dirname(os.path.abspath(__file__))
def update(commit, cc):
gdt_super_dir = os.path.join(thisdir, '..', '..',)
dockerfile = os.path.join(thisdir, 'dune-gdt-testing', 'Dockerfile')
... | #!/usr/bin/env python3
import os
import subprocess
import sys
cc_mapping = {'gcc': 'g++', 'clang': 'clang++'}
thisdir = os.path.dirname(os.path.abspath(__file__))
def update(commit, cc):
gdt_super_dir = os.path.join(thisdir, '..', '..',)
dockerfile = os.path.join(thisdir, 'dune-gdt-testing', 'Dockerfile')
... | bsd-2-clause | Python |
45ee385204d4a38ea904228d2648d266309332ab | fix shutdown command | TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control,TurtleRover/Turtle-Rover-Mission-Control | server/sockets.py | server/sockets.py | import asyncio
from aiohttp import web
import socketio
import hexdump
from log import logname
import frame
from hardware import Hardware
from version import version_info
import os
import subprocess
logger = logname("sockets")
class WSnamespace(socketio.AsyncNamespace):
def __init__(self, namespace='/sockets'):
... | import asyncio
from aiohttp import web
import socketio
import hexdump
from log import logname
import frame
from hardware import Hardware
from version import version_info
import os
logger = logname("sockets")
class WSnamespace(socketio.AsyncNamespace):
def __init__(self, namespace='/sockets'):
super().__in... | mit | Python |
d4a2632a0dcdd6731a5930f321135ec7f9864460 | Use new API, which requires being explicit about tracking ODF model. | yeatmanlab/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ,arokem/pyAFQ | AFQ/tests/test_tractography.py | AFQ/tests/test_tractography.py | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel.tmpdirs as nbtmp
from AFQ.csd import fit_csd
from AFQ.dti import fit_dti
from AFQ.tractography import track
from AFQ.utils.testing import make_tracking_data
seeds = np.array([[-80., -120., -60.],
[-81, -121, -61],
... | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel.tmpdirs as nbtmp
from AFQ.csd import fit_csd
from AFQ.dti import fit_dti
from AFQ.tractography import track
from AFQ.utils.testing import make_tracking_data
seeds = np.array([[-80., -120., -60.],
[-81, -121, -61],
... | bsd-2-clause | Python |
705cb5cf3eec171baf3a8b91b8cc77d9987a1414 | Fix ImproperlyConfigured exception | FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management,FreeCodeCampRoma/precision_school-management | precision/accounts/views.py | precision/accounts/views.py | from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic.base import TemplateResponseMixin, View
from .forms import LoginForm
class SignInView(TemplateResponseMixin, View):
template_name = 'accounts/sign_in.ht... | from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from django.views.generic.base import TemplateResponseMixin, View
from .forms import LoginForm
class SignInView(TemplateResponseMixin, View):
def get(self, request):
tem... | mit | Python |
c0684358b217318327d71470ee86074b3556148a | Use double quotes consistently | fdev/bc125csv | bc125csv/__main__.py | bc125csv/__main__.py | from bc125csv.handler import main
if __name__ == "__main__":
main()
| from bc125csv.handler import main
if __name__ == '__main__':
main() | mit | Python |
32537dafa3c13761b910ab8449ff80d60df6f02b | Bump version to 2.3.4-dev | indico/indico,ThiefMaster/indico,DirkHoffmann/indico,pferreir/indico,DirkHoffmann/indico,pferreir/indico,indico/indico,pferreir/indico,pferreir/indico,ThiefMaster/indico,DirkHoffmann/indico,indico/indico,DirkHoffmann/indico,ThiefMaster/indico,ThiefMaster/indico,indico/indico | indico/__init__.py | indico/__init__.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import warnings
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.3.4-dev'
... | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
import warnings
from indico.util.mimetypes import register_custom_mimetypes
__version__ = '2.3.3'
regi... | mit | Python |
862f81d54624ea198d6351f5ea7c88b66bc02019 | Make the Nick an argument to Client.py | JacobAMason/Boa | src/Client.py | src/Client.py | #!python
__author__ = 'JacobAMason'
import sys
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
import StringIO
class Bot(irc.IRCClient):
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
se... | #!python
__author__ = 'JacobAMason'
import sys
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor
import StringIO
class Bot(irc.IRCClient):
def _get_nickname(self):
return self.factory.nickname
nickname = property(_get_nickname)
def signedOn(self):
se... | mit | Python |
ecf71bd004d99b679936e07453f5a938e19f71dc | Add aiohttp as a execution requirement | google/megalista,google/megalista | megalist_dataflow/setup.py | megalist_dataflow/setup.py | # Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | apache-2.0 | Python |
8ffb2beea77897e3fa40691f35f2e089dbc5df9a | Add more documentation | Shade5/coala,impmihai/coala,Tanmay28/coala,svsn2117/coala,SambitAcharya/coala,d6e/coala,arjunsinghy96/coala,Balaji2198/coala,jayvdb/coala,SambitAcharya/coala,Nosferatul/coala,coala/coala,svsn2117/coala,scriptnull/coala,sophiavanvalkenburg/coala,yashtrivedi96/coala,rresol/coala,NalinG/coala,karansingh1559/coala,MariosPa... | coalib/bearlib/languages/LanguageDefinition.py | coalib/bearlib/languages/LanguageDefinition.py | import os
from coalib.bearlib.abstractions.SectionCreatable import SectionCreatable
from coalib.misc.StringConstants import StringConstants
from coalib.parsing.ConfParser import ConfParser
class LanguageDefinition(SectionCreatable):
def __init__(self, language_family: str, language: str):
"""
Cre... | import os
from coalib.bearlib.abstractions.SectionCreatable import SectionCreatable
from coalib.misc.StringConstants import StringConstants
from coalib.parsing.ConfParser import ConfParser
class LanguageDefinition(SectionCreatable):
def __init__(self, language_family: str, language: str):
"""
Cre... | agpl-3.0 | Python |
74272b9916c29bb9e97d4761801ee3730b053b87 | comment fix | heurezjusz/Athenet,heurezjusz/Athena | athenet/sparsifying/utils/numlike.py | athenet/sparsifying/utils/numlike.py | """Template class with arithmetic operations that can be passed through neural
network.
All classes that are being used for derest should inherit from this class."""
class Numlike(object):
"""Template class with arithmetic operations that can be passed through
neural network.
All classes that are being ... | """Template class with arithmetic operations that can be passed through neural
network.
All classes that are being used for derest should inherit from this class."""
class Numlike(object):
"""Template class with arithmetic operations that can be passed through
neural network.
All classes that are being ... | bsd-2-clause | Python |
9ba255886ca5315be1b95ccac28d496e3941f155 | Bump alpha version | prkumar/uplink | uplink/__about__.py | uplink/__about__.py | """
This module is the single source of truth for any package metadata
that is used both in distribution (i.e., setup.py) and within the
codebase.
"""
__version__ = "0.8.0a1"
| """
This module is the single source of truth for any package metadata
that is used both in distribution (i.e., setup.py) and within the
codebase.
"""
__version__ = "0.8.0a0"
| mit | Python |
ec665be1811b458f849cbed09ef3d3c61f9e4533 | Change order of environment setup | metabolite-atlas/metatlas,metabolite-atlas/metatlas,metabolite-atlas/metatlas | metatlas/tools/notebook.py | metatlas/tools/notebook.py | """Jupyter notebook helper functions"""
import logging
import os
import shutil
import sys
from pathlib import Path
import pandas as pd
from IPython.core.display import display, HTML
from metatlas.tools.logging import activate_logging
logger = logging.getLogger(__name__)
def configure_environment(log_level):
""... | """Jupyter notebook helper functions"""
import logging
import os
import shutil
import sys
from pathlib import Path
import pandas as pd
from IPython.core.display import display, HTML
from metatlas.tools.logging import activate_logging
logger = logging.getLogger(__name__)
def configure_environment(log_level):
""... | bsd-3-clause | Python |
646416efa7378b645af56031c06e7544cb72627f | Delete comment | fushime2/recommenblr | user_recommender.py | user_recommender.py | from tumblr_manager import TumblrManager, TumblrScraper
class UserRecommender(object):
user_counter = {}
def __init__(self, consumer_key=None, consumer_secret=None, oauth_token=None, oauth_token_secret=None):
self.tm = TumblrManager(consumer_key, consumer_secret, oauth_token, oauth_token_secret)
... | from tumblr_manager import TumblrManager, TumblrScraper
class UserRecommender(object):
user_counter = {}
def __init__(self, consumer_key=None, consumer_secret=None, oauth_token=None, oauth_token_secret=None):
self.tm = TumblrManager(consumer_key, consumer_secret, oauth_token, oauth_token_secret)
... | mit | Python |
906d765e387367654a02a36e9b5ba7aca4480ed6 | Check if zip only contains one file | manly-man/moodle-destroyer-tools,manly-man/moodle-destroyer-tools | util/zipwrangler.py | util/zipwrangler.py | from pathlib import Path
from zipfile import ZipFile
from tempfile import TemporaryDirectory
import shutil
ignore = ['__MACOSX', '.DS_Store']
def get_cleaned_contents(zipfile, ignore_list=ignore, verbose=False):
contents = []
for info in zipfile.infolist():
if not any(ignored in info.filename for ign... | from pathlib import Path
from zipfile import ZipFile
from tempfile import TemporaryDirectory
import shutil
ignore = ['__MACOSX', '.DS_Store']
def get_cleaned_contents(zipfile, ignore_list=ignore, verbose=False):
contents = []
for info in zipfile.infolist():
if not any(ignored in info.filename for ign... | mit | Python |
2d09314ab58bb766372dc6e263fb17428b1fd3cd | Fix check for existing pools. | danielballan/photomosaic | doc/pool_scripts/cats.py | doc/pool_scripts/cats.py | import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile(os.path.expanduser('~/pools/cats/pool.json')):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/... | import os
import photomosaic.flickr
import photomosaic as pm
if not os.path.isfile('~/pools/cats/pool.json'):
FLICKR_API_KEY = os.environ['FLICKR_API_KEY']
pm.set_options(flickr_api_key=FLICKR_API_KEY)
photomosaic.flickr.from_search('cats', '~/pools/cats/')
pool = pm.make_pool('~/pools/cats/*.jpg')
... | bsd-3-clause | Python |
e83be594507c994069d20d5f2cd86c52905a52a6 | Fix personal brain damage. | mk23/snmpy,mk23/snmpy | lib/plugin/disk_utilization.py | lib/plugin/disk_utilization.py | import datetime
import logging
import os
import snmpy.plugin
import subprocess
class disk_utilization(snmpy.plugin.TablePlugin):
def __init__(self, conf):
conf['table'] = [
{'dev': 'string'},
{'wait': 'integer'},
{'util': 'integer'},
]
snmpy.plugin.Tabl... | import datetime
import logging
import os
import snmpy.plugin
import subprocess
class disk_utilization(snmpy.plugin.TablePlugin):
def __init__(self, conf):
conf['table'] = [
{'dev': 'string'},
{'wait': 'integer'},
{'util': 'integer'},
]
snmpy.plugin.Tabl... | mit | Python |
f4ace89a0ee029a276f5dba95b54731a15883c4f | hide warning | nimbis/django-shop,khchine5/django-shop,jrief/django-shop,awesto/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,divio/django-shop,khchine5/django-shop,khchine5/django-shop,nimbis/django-shop,nimbis/django-shop,divio/django-shop,jrief/django-shop,khchine5/django-... | example/myshop/admin/__init__.py | example/myshop/admin/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import admin
from shop.admin.customer import CustomerProxy, CustomerAdmin
from shop.models.order import OrderModel
__all__ = ['OrderModel', 'commodity']
# models defined by the myshop instance itself
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.contrib import admin
from shop.admin.customer import CustomerProxy, CustomerAdmin
from shop.models.order import OrderModel
# models defined by the myshop instance itself
if settings.SHOP_TUTORIAL == 'commodit... | bsd-3-clause | Python |
4ceeed0eceff9d75b0bc3047c9a8e2fcb6877e31 | Fix tasks reading of different course_id | marcore/edx-platform,marcore/edx-platform,dcosentino/edx-platform,marcore/edx-platform,dcosentino/edx-platform,dcosentino/edx-platform,dcosentino/edx-platform,dcosentino/edx-platform,marcore/edx-platform | lms/djangoapps/ecoapi/tasks.py | lms/djangoapps/ecoapi/tasks.py | from celery.task import task
from instructor.offline_gradecalc import student_grades , offline_grade_calculation
from opaque_keys.edx.keys import CourseKey
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import SlashSeparatedCourseKey
#TODO: add a better task management to prevent concurrent tas... |
from celery.task import task
from instructor.offline_gradecalc import student_grades , offline_grade_calculation
#TODO: add a better task management to prevent concurrent task execution with some course_id
@task()
def offline_calc(course_id):
offline_grade_calculation(course_id)
| agpl-3.0 | Python |
6d84f7eb25352c50e40950d0585c33bd1193649e | fix bug in init | onelab-eu/sfa,yippeecw/sfa,yippeecw/sfa,yippeecw/sfa,onelab-eu/sfa,onelab-eu/sfa | sfa/util/osxrn.py | sfa/util/osxrn.py | import re
from sfa.util.xrn import Xrn
from sfa.util.config import Config
class OSXrn(Xrn):
def __init__(self, name=None, type=None, **kwds):
config = Config()
if name is not None:
self.type = type
self.hrn = config.SFA_INTERFACE_HRN + "." + name
self.h... | import re
from sfa.util.xrn import Xrn
from sfa.util.config import Config
class OSXrn(Xrn):
def __init__(self, name=None, type=None, *args, **kwds):
config = Config()
if name is not None:
self.type = type
self.hrn = config.SFA_INTERFACE_HRN + "." + name
self.hrn... | mit | Python |
3aba768c7a3c11f2941db36d0292cd5810433596 | fix python2.7.9 | nkrode/RedisLive,merlian/RedisLive,udomsak/RedisLive,udomsak/RedisLive,YongMan/RedisLive,jiejieling/RdsMonitor,fengshao0907/RedisLive,udomsak/RedisLive,jiejieling/RdsMonitor,fengshao0907/RedisLive,fengshao0907/RedisLive,nkrode/RedisLive,merlian/RedisLive,nkrode/RedisLive,YongMan/RedisLive,YongMan/RedisLive,merlian/Redi... | src/api/util/timeutils.py | src/api/util/timeutils.py | import datetime
def total_seconds(td):
# Keep backward compatibility with Python 2.6 which doesn't have
# this method
if hasattr(td, 'total_seconds'):
return td.total_seconds()
else:
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
def convert_to_epoch(times... | from datetime import datetime
def total_seconds(td):
# Keep backward compatibility with Python 2.6 which doesn't have
# this method
if hasattr(td, 'total_seconds'):
return td.total_seconds()
else:
return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
def convert... | mit | Python |
f98b30583fb9fca4674ad93afd242ffae7ac9f36 | Fix tests | recognai/spaCy,oroszgy/spaCy.hu,oroszgy/spaCy.hu,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,explosion/spaCy,oroszgy/spaCy.hu,explosion/spaCy,recognai/spaCy,Gregory-Howard/spaCy,oroszgy/spaCy.hu,spacy-io/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,Gregory-H... | spacy/tests/conftest.py | spacy/tests/conftest.py | # coding: utf-8
from __future__ import unicode_literals
from ..en import English
from ..de import German
from ..es import Spanish
from ..it import Italian
from ..fr import French
from ..pt import Portuguese
from ..nl import Dutch
from ..sv import Swedish
from ..hu import Hungarian
from ..fi import Finnish
from ..bn im... | # coding: utf-8
from __future__ import unicode_literals
from ..en import English
from ..de import German
from ..es import Spanish
from ..it import Italian
from ..fr import French
from ..pt import Portuguese
from ..nl import Dutch
from ..sv import Swedish
from ..hu import Hungarian
from ..fi import Finnish
from ..bn im... | mit | Python |
d6b69f7d5868597426f7718165d4933af72e154d | Fix typo in command-line | nafraf/spreads,miloh/spreads,miloh/spreads,adongy/spreads,nafraf/spreads,gareth8118/spreads,DIYBookScanner/spreads,adongy/spreads,DIYBookScanner/spreads,gareth8118/spreads,DIYBookScanner/spreads,gareth8118/spreads,miloh/spreads,nafraf/spreads,adongy/spreads | spreadsplug/pdfbeads.py | spreadsplug/pdfbeads.py | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Johannes Baiter <johannes.baiter@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | # -*- coding: utf-8 -*-
# Copyright (C) 2014 Johannes Baiter <johannes.baiter@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your ... | agpl-3.0 | Python |
20cf0f2b6647b7a03fb5a9808f9d854975feb651 | add shebang line to demo.py | jomag/prettytask | demo.py | demo.py | #!/usr/bin/env python3
from prettytask import Task, TaskGroup, Error, prompt
def main():
with Task("A quick task"):
pass
with Task("A task with a custom success message") as task:
task.ok("that went well!")
with Task("A task that fails") as task:
raise Error
with Task("A tas... | from prettytask import Task, TaskGroup, Error, prompt
def main():
with Task("A quick task"):
pass
with Task("A task with a custom success message") as task:
task.ok("that went well!")
with Task("A task that fails") as task:
raise Error
with Task("A task that fails with a cus... | mit | Python |
a6aec17cff730914c0901db9e9ab9bb4da660306 | Switch elm-formato to post save | deadfoxygrandpa/Elm.tmLanguage,sekjun9878/Elm.tmLanguage,deadfoxygrandpa/Elm.tmLanguage,sekjun9878/Elm.tmLanguage | elm_format.py | elm_format.py | from __future__ import print_function
import subprocess
import os, os.path
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
settings = sublime.load_settings('Elm Language Support.sublime-settings')
path = settings.get('elm_paths', '')
if path:
... | from __future__ import print_function
import subprocess
import os, os.path
import re
import sublime, sublime_plugin
class ElmFormatCommand(sublime_plugin.TextCommand):
def run(self, edit):
settings = sublime.load_settings('Elm Language Support.sublime-settings')
path = settings.get('elm_paths', '')
if path:
... | mit | Python |
d679f7dbedd3decc7cd4abc782d4c0fae0b872ea | Enable the ability to import H264 SubMe, MotionEstimationMethod and Trellis | bitmovin/bitmovin-python | bitmovin/resources/enums/__init__.py | bitmovin/resources/enums/__init__.py | from .status import Status
from .aac_channel_layout import AACChannelLayout
from .ac3_channel_layout import AC3ChannelLayout
from .aws_cloud_region import AWSCloudRegion
from .badapt import BAdapt
from .cloud_region import CloudRegion
from .crop_filter_unit import CropFilterUnit
from .google_cloud_region import GoogleC... | from .status import Status
from .aac_channel_layout import AACChannelLayout
from .ac3_channel_layout import AC3ChannelLayout
from .aws_cloud_region import AWSCloudRegion
from .badapt import BAdapt
from .cloud_region import CloudRegion
from .crop_filter_unit import CropFilterUnit
from .google_cloud_region import GoogleC... | unlicense | Python |
b4a2bf0ee660aab40a885cd8b84c18c8b4a8580b | make host, ip and type dynamic | missionpinball/mpf,missionpinball/mpf | mpf/core/bcp/bcp_server.py | mpf/core/bcp/bcp_server.py | """Bcp server for clients which connect and disconnect randomly."""
import asyncio
import logging
from mpf.core.utility_functions import Util
class BcpServer():
"""Server socket which listens for incoming BCP clients."""
def __init__(self, machine, ip, port, type):
self.machine = machine
se... | """Bcp server for clients which connect and disconnect randomly."""
import asyncio
from mpf.core.bcp.bcp_socket_client import BCPClientSocket
class BcpServer():
"""Server socket which listens for incoming BCP clients."""
def __init__(self, machine):
self.machine = machine
self._server = Non... | mit | Python |
61d8ced0d46bb0e351b8c488814b75b1de2ddab3 | Update Ejemplos.py | AnhellO/DAS_Sistemas,AnhellO/DAS_Sistemas,AnhellO/DAS_Sistemas | Ago-Dic-2018/Ejemplos/Ejemplos.py | Ago-Dic-2018/Ejemplos/Ejemplos.py | import collections
potenciaPares = 2
potenciaImpares = 3
# print(2 / 3)
#for i in range(0, 10):
#if i % 2:
# Estilo de formateo 1:
# print("Impar: %d" % (i))
# Estilo de formateo 2:
# print("El impar #{} ^ {} es = {}".format(i, potenciaImpares, i ** potenciaImpares))
#else:
... | import collections
potenciaPares = 2
potenciaImpares = 3
# print(2 / 3)
#for i in range(0, 10):
#if i % 2:
# Estilo de formateo 1:
# print("Impar: %d" % (i))
# Estilo de formateo 2:
# print("El impar #{} ^ {} es = {}".format(i, potenciaImpares, i ** potenciaImpares))
#else:
... | mit | Python |
4b545d2e72080537672bb4ebb990708cad678344 | Debug Google Cloud Run support | diodesign/diosix | entrypoint.py | entrypoint.py | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax... | #!/usr/bin/python3
#
# Define containerized environment for running Diosix on Qemu
#
# On Google Cloud Run: Creates HTTP server on port 8080
# or whatever was specified using the PORT system variable.
# Outputs via the HTTP port. This requires K_SERVICE to be set.
#
# On all other environments: Log to stdout
#
# syntax... | mit | Python |
6c3929806a19fbaac0c17887e697bba7ddeaa92d | create cache dir if it does not exist | biocore/micronota,biocore/micronota,RNAer/micronota,RNAer/micronota | micronota/commands/database.py | micronota/commands/database.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ---------------------------------------------... | bsd-3-clause | Python |
07874ee51375b7597d79288e85acc68294d4b007 | customize the JSON dump for Event objects | OAButton/OAButton_old,OAButton/OAButton_old,OAButton/OAButton_old | oabutton/apps/web/views.py | oabutton/apps/web/views.py | from django.shortcuts import render_to_response
from django.conf import settings
from django.core.context_processors import csrf
from oabutton.common import SigninForm
import json
def homepage(req):
# Need to lazy import the Event model so that tests work with
# mocks
c = {}
c.update(csrf(req))
f... | from django.shortcuts import render_to_response
from django.conf import settings
from django.core.context_processors import csrf
from oabutton.common import SigninForm
def homepage(req):
# Need to lazy import the Event model so that tests work with
# mocks
c = {}
c.update(csrf(req))
from oabutton... | mit | Python |
371ddf2c4beb79b82b1154abfa1efdd6bc5e379a | Change version to 0.5.dev | einvalentin/elasticutils,mozilla/elasticutils,einvalentin/elasticutils,mozilla/elasticutils,mozilla/elasticutils,einvalentin/elasticutils | elasticutils/_version.py | elasticutils/_version.py | # follow pep-386
# Examples:
# * 0.3 - released version
# * 0.3a1 - alpha version
# * 0.3.dev - version in developmentv
__version__ = '0.5.dev'
__releasedate__ = ''
| # follow pep-386
# Examples:
# * 0.3 - released version
# * 0.3a1 - alpha version
# * 0.3.dev - version in developmentv
__version__ = '0.4'
__releasedate__ = '20120731'
| bsd-3-clause | Python |
ba6b5c50e5ea1875e117d72675fb58092325b193 | add moves: left, right and down | hard7/Tetris | game.py | game.py | #using python2
import Tkinter
from visual import Visual
from relief import Relief
from figure import Figure
from random import randint
class Game:
def __init__(self):
self.root= Tkinter.Tk()
self.vis= Visual(self.root)
self.relief= Relief()
self.figure= None
self.relief.extend([(0,0), (0,3)])
self.ro... | #using python2
import Tkinter
from visual import Visual
from relief import Relief
from figure import Figure
from random import randint
class Game:
def __init__(self):
self.root= Tkinter.Tk()
self.vis= Visual(self.root)
self.relief= Relief()
self.figure= None
self.root.after_idle(self.tick)
self.root.bin... | apache-2.0 | Python |
95eeefa9b8cf7decd51265eaf624ff4551ac6a15 | add feature to create a new app from command line, remove commands that are not implemented | aacanakin/glim | glim.py | glim.py | from termcolor import colored
from glim.app import start as appify
# glim with use of click
import click
import shutil, errno
import os
@click.group()
def glim():
pass
@click.command()
@click.option('--host', default = '127.0.0.1', help = 'enter ip')
@click.option('--port', default = '8080', help = 'enter port')
... | from termcolor import colored
from glim.app import start as appify
# glim with use of click
import click
@click.group()
def glim():
pass
@click.command()
@click.option('--host', default = '127.0.0.1', help = 'enter ip')
@click.option('--port', default = '8080', help = 'enter port')
@click.option('--env', default ... | mit | Python |
fc7d83eda95aa20f0782644cd4076a51e60cc46d | Remove unused properties from models.isolate.Isolate. | catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult,catapult-project/catapult | dashboard/dashboard/pinpoint/models/isolate.py | dashboard/dashboard/pinpoint/models/isolate.py | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Model for storing information to look up isolates.
An isolate is a way to describe the dependencies of a specific build.
More about isolates:
https://gi... | # Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Model for storing information to look up isolates.
An isolate is a way to describe the dependencies of a specific build.
More about isolates:
https://gi... | bsd-3-clause | Python |
4a25286506cc8e50b5e1225b12015f4d0da3ccfc | Put api token auth endpoint under v1. | City-of-Helsinki/smbackend,City-of-Helsinki/smbackend | smbackend/urls.py | smbackend/urls.py | from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all... | from django.conf.urls import patterns, include, url
from services.api import all_views as services_views
from services.api import AccessibilityRuleView
from observations.api import views as observations_views
from rest_framework import routers
from observations.views import obtain_auth_token
from munigeo.api import all... | agpl-3.0 | Python |
94764b8daed7ef6df8ac47462013b08d30de7e8f | refactor for less ugliness, resolves #7 | IanDCarroll/xox | source/display.py | source/display.py | class Display():
def __init__(self):
self.start = "Welcome"
self.draw = "Draw"
self.computer = "Computer Wins"
self.human = "You Win"
self.next_move = "What is your next move?"
self.bad_move = "That is not a legal move."
def show(self, text):
print t... | class Display():
def __init__(self):
self.start = "Welcome"
self.draw = "Draw"
self.computer = "Computer Wins"
self.human = "You Win"
self.next_move = "What is your next move?"
self.bad_move = "That is not a legal move."
def show(self, text):
print t... | mit | Python |
b6b99dff989fb6662f795a95895e070424f59822 | Add test for login button instead of edit buttons if not logged | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | candidates/tests/test_person_view.py | candidates/tests/test_person_view.py | from __future__ import unicode_literals
import re
from django.test.utils import override_settings
from django_webtest import WebTest
from .dates import processors_before, processors_after
from .factories import (
CandidacyExtraFactory, PersonExtraFactory
)
from .uk_examples import UK2015ExamplesMixin
class Tes... | # Smoke tests for viewing a candidate's page
from __future__ import unicode_literals
import re
from django.test.utils import override_settings
from django_webtest import WebTest
from .dates import processors_before, processors_after
from .factories import (
CandidacyExtraFactory, PersonExtraFactory
)
from .uk_e... | agpl-3.0 | Python |
45c17681bfdfc374e94b086f9cdda4f314be5045 | Add entries and preamble arguments to BibliographyData.__init__(). | live-clones/pybtex | pybtex/database/__init__.py | pybtex/database/__init__.py | # Copyright (C) 2006, 2007, 2008, 2009 Andrey Golovizin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pr... | # Copyright (C) 2006, 2007, 2008, 2009 Andrey Golovizin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pr... | mit | Python |
581b49ad98616b7450c12be1d86960e8f38df9ac | Update lca_calculations.py | architecture-building-systems/CEAforArcGIS,architecture-building-systems/CEAforArcGIS | cea/optimization/lca_calculations.py | cea/optimization/lca_calculations.py | # -*- coding: utf-8 -*-
"""
This file imports the price details from the cost database as a class. This helps in preventing multiple importing
of the corresponding values in individual files.
"""
from __future__ import division
import warnings
import pandas as pd
warnings.filterwarnings("ignore")
__author__ = "Sree... | # -*- coding: utf-8 -*-
"""
This file imports the price details from the cost database as a class. This helps in preventing multiple importing
of the corresponding values in individual files.
"""
from __future__ import division
import warnings
import pandas as pd
warnings.filterwarnings("ignore")
__author__ = "Sree... | mit | Python |
7d69bcc6474d954b311251bf077750e0418170cb | Fix typo and execute JS script found in local folder. | henne-/guest-password-printer,henne-/guest-password-printer | button.py | button.py | import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to G... | import RPi.GPIO as GPIO
import time
import os
from optparse import OptionParser
# Parse input arguments
parser = OptionParser()
parser.add_option("-t", "--testGPIO", action="store_true", help="Test GPIO connection, does not call the JS script.")
# The option --pin sets the Input Pin for your Button
# It default to G... | mit | Python |
b4ea95dc2dc1591e96d22b5058cef440416477e0 | Bump version to 0.10.0b (#740) | stellargraph/stellargraph,stellargraph/stellargraph | stellargraph/version.py | stellargraph/version.py | # -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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 applicabl... | # -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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 applicabl... | apache-2.0 | Python |
e4be1ad0b1bf575743280d9ae07e74efcf2530bb | Change to class | studiawan/pygraphc | pygraphc/misc/LogCluster.py | pygraphc/misc/LogCluster.py | import datetime
import hashlib
import textwrap
class LogCluster(object):
def __init__(self, wsize, csize):
self.wsize = wsize
self.csize = csize
self.wsketch = []
# This function logs the message given with parameter2,++,parameterN to
# syslog, using the level parameter1+ The mess... | import datetime
import hashlib
import textwrap
# This function logs the message given with parameter2,++,parameterN to
# syslog, using the level parameter1+ The message is also written to stderr+
def log_msg(*parameters):
level = parameters[0]
msg = ' '.join(parameters[1:])
now = datetime.datetime.now()
... | mit | Python |
221e45828b9cc33d9ae02d08d94dfaa89977d3e7 | update import_reading for Courtney | jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk | vehicles/management/commands/import_reading.py | vehicles/management/commands/import_reading.py | from ciso8601 import parse_datetime
from django.utils.timezone import make_aware
from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
... | from ciso8601 import parse_datetime
from django.utils.timezone import make_aware
from django.contrib.gis.geos import Point
from busstops.models import Service
from ...models import VehicleLocation, VehicleJourney
from ..import_live_vehicles import ImportLiveVehiclesCommand
class Command(ImportLiveVehiclesCommand):
... | mpl-2.0 | Python |
13489726a9b3f9ce9dcd2ff9c3086279db7704fe | increment build id | SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32,SHA2017-badge/micropython-esp32 | esp32/modules/version.py | esp32/modules/version.py | build = 8
name = "Maffe Maniak"
| build = 7
name = "Maffe Maniak"
| mit | Python |
66056c97972011831fb36ce0ae37cc9bd490ddba | Swap In New Function | masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api | web/impact/impact/v1/helpers/program_helper.py | web/impact/impact/v1/helpers/program_helper.py | from impact.models import Program
from impact.v1.helpers.model_helper import (
FLOAT_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAM_FIELDS = {
"id": PK_FIELD,
"name": STRING_FIELD,
"program_family_id": INTEGER_FIELD,
"program_family_name": STRING_FIELD,
"cy... | from impact.models import Program
from impact.v1.helpers.model_helper import (
FLOAT_FIELD,
INTEGER_FIELD,
ModelHelper,
PK_FIELD,
STRING_FIELD,
)
PROGRAM_FIELDS = {
"id": PK_FIELD,
"name": STRING_FIELD,
"program_family_id": INTEGER_FIELD,
"program_family_name": STRING_FIELD,
"cy... | mit | Python |
fe6d37efa59cbf222dd703a52456de2aa628fecf | Update random-pick-with-weight.py | tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015 | Python/random-pick-with-weight.py | Python/random-pick-with-weight.py | # Time: O(logn)
# Space: O(n)
# Given an array w of positive integers,
# where w[i] describes the weight of index i,
# write a function pickIndex which randomly picks an index in proportion to its weight.
#
# Note:
#
# 1 <= w.length <= 10000
# 1 <= w[i] <= 10^5
# pickIndex will be called at most 10000 times.
# Exampl... | # Time: O(logn)
# Space: O(n)
# Given an array w of positive integers,
# where w[i] describes the weight of index i,
# write a function pickIndex which randomly picks an index in proportion to its weight.
#
# Note:
#
# 1 <= w.length <= 10000
# 1 <= w[i] <= 10^5
# pickIndex will be called at most 10000 times.
# Exampl... | mit | Python |
ea660e370b05cfe34dc819211b2f28992a924194 | Update random-pick-with-weight.py | kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode | Python/random-pick-with-weight.py | Python/random-pick-with-weight.py | # Time: ctor: O(n)
# pickIndex: O(logn)
# Space: O(n)
# Given an array w of positive integers,
# where w[i] describes the weight of index i,
# write a function pickIndex which randomly picks an index in proportion to its weight.
#
# Note:
#
# 1 <= w.length <= 10000
# 1 <= w[i] <= 10^5
# pickIndex will be calle... | # Time: O(logn)
# Space: O(n)
# Given an array w of positive integers,
# where w[i] describes the weight of index i,
# write a function pickIndex which randomly picks an index in proportion to its weight.
#
# Note:
#
# 1 <= w.length <= 10000
# 1 <= w[i] <= 10^5
# pickIndex will be called at most 10000 times.
# Exampl... | mit | Python |
056a1b769db7f05402b41ffdcb565585db06bf97 | Update top-k-frequent-elements.py | kamyu104/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu10... | Python/top-k-frequent-elements.py | Python/top-k-frequent-elements.py | # Time: O(n)
# Space: O(n)
# Given a non-empty array of integers,
# return the k most frequent elements.
#
# For example,
# Given [1,1,1,2,2,3] and k = 2, return [1,2].
#
# Note:
# You may assume k is always valid,
# 1 <= k <= number of unique elements.
# Your algorithm's time complexity must be better
# than O(n lo... | # Time: O(n)
# Space: O(n)
# Given a non-empty array of integers,
# return the k most frequent elements.
#
# For example,
# Given [1,1,1,2,2,3] and k = 2, return [1,2].
#
# Note:
# You may assume k is always valid,
# 1 <= k <= number of unique elements.
# Your algorithm's time complexity must be better
# than O(n lo... | mit | Python |
3a156a11cd7b8a9bfc40b515a2f1d1351969ce3a | Simplify loading config for instagram middleware | lord63/me-api | me_api/middleware/instagram.py | me_api/middleware/instagram.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import requests
from flask import Blueprint, jsonify, request, redirect
from me_api.cache import cache
from me_api.middleware.utils import MiddlewareConfig
config = MiddlewareConfig('instagram')
instagram_api = Blueprint... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import requests
from flask import Blueprint, jsonify, request, redirect
from me_api.configs import Config
from me_api.cache import cache
config = Config.modules['modules']['instagram']
path = config['path']
client_secret... | mit | Python |
aeeb62f47a7211d945aafd294edb3d39d5d5cf6e | Modify error message | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader | pytablereader/_validator.py | pytablereader/_validator.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import os.path
import dataproperty
import pathvalidate as pv
import six
from six.moves.urllib.parse import urlparse
from ._constant import SourceType
from .error import EmptyDataError
... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import abc
import os.path
import dataproperty
import pathvalidate as pv
import six
from six.moves.urllib.parse import urlparse
from ._constant import SourceType
from .error import EmptyDataError
... | mit | Python |
6c095c0e14c084666b9417b4bd269f396804bfab | Update interface with the latest changes in functionality. | bolsote/py-cd-talk,bolsote/py-cd-talk | src/ensign/_interfaces.py | src/ensign/_interfaces.py | # pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value... | # pylint: skip-file
from zope.interface import Attribute, Interface
class IFlag(Interface):
"""
Flag Interface.
Any kind of flag must implement this interface.
"""
TYPE = Attribute("""Flag type""")
store = Attribute("""Flag storage backend""")
name = Attribute("""Flag name""")
value... | isc | Python |
a9253d6382c8eeb4261d0fc533d943046b51d109 | Remove unused variable | pedrobaeza/account-financial-tools,dvitme/account-financial-tools,open-synergy/account-financial-tools,syci/account-financial-tools,pedrobaeza/account-financial-tools,Pexego/account-financial-tools,yelizariev/account-financial-tools,andhit-r/account-financial-tools,factorlibre/account-financial-tools,credativUK/account... | account_tax_analysis/account_tax_analysis.py | account_tax_analysis/account_tax_analysis.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville. Copyright 2013-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# p... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author Vincent Renaville. Copyright 2013-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# p... | agpl-3.0 | Python |
c433c649a9a4b32095a170f75c7e4aae9382089b | use absolute imports | geoscixyz/em_examples | em_examples/__init__.py | em_examples/__init__.py | import .Attenuation
import .BiotSavart
import .CondUtils
import .DC_cylinder
import .DCLayers
import .DCsphere
import .DCWidget
import .DCWidgetPlate2_5D
import .DCWidgetPlate_2D
import .DCWidgetResLayer2_5D
import .DCWidgetResLayer2D
import .DipoleWidget1D
import .DipoleWidgetFD
import .DipoleWidgetTD
import .EMcircui... | import Attenuation
import BiotSavart
import CondUtils
import DC_cylinder
import DCLayers
import DCsphere
import DCWidget
import DCWidgetPlate2_5D
import DCWidgetPlate_2D
import DCWidgetResLayer2_5D
import DCWidgetResLayer2D
import DipoleWidget1D
import DipoleWidgetFD
import DipoleWidgetTD
import EMcircuit
import FDEMDi... | mit | Python |
c55e9136ee9c86dcd4088ba416043dbff7e65eac | Fix Fast.com autoupdate (#57552) | nkgilley/home-assistant,home-assistant/home-assistant,toddeye/home-assistant,mezz64/home-assistant,nkgilley/home-assistant,w1ll1am23/home-assistant,GenericStudent/home-assistant,w1ll1am23/home-assistant,lukas-hetzenecker/home-assistant,aronsky/home-assistant,jawilson/home-assistant,jawilson/home-assistant,toddeye/home-... | homeassistant/components/fastdotcom/__init__.py | homeassistant/components/fastdotcom/__init__.py | """Support for testing internet speed via Fast.com."""
from __future__ import annotations
from datetime import datetime, timedelta
import logging
from typing import Any
from fastdotcom import fast_com
import voluptuous as vol
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssis... | """Support for testing internet speed via Fast.com."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any
from fastdotcom import fast_com
import voluptuous as vol
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant, Serv... | apache-2.0 | Python |
717db7509b586e59c06d06ad60be3ca5671e1c35 | add support for circleci | sdpython/pyquickhelper,sdpython/pyquickhelper,sdpython/pyquickhelper,sdpython/pyquickhelper | src/pyquickhelper/pycode/ci_helper.py | src/pyquickhelper/pycode/ci_helper.py | """
@file
@brief Helpers for CI
.. versionadded:: 1.3
"""
def is_travis_or_appveyor():
"""
tells if is a travis environment or appveyor
@return ``'travis'``, ``'appveyor'`` or ``None``
The function should rely more on environement variables
``CI``, ``TRAVIS``, ``APPVEYOR``.
.. versi... | """
@file
@brief Helpers for CI
.. versionadded:: 1.3
"""
def is_travis_or_appveyor():
"""
tells if is a travis environment or appveyor
@return ``'travis'``, ``'appveyor'`` or ``None``
The function should rely more on environement variables
``CI``, ``TRAVIS``, ``APPVEYOR``.
.. versi... | mit | Python |
e6e68143e39dcc14833065b388f65879f2aa81f2 | Update import export TestCase | jmakov/ggrc-core,andrei-karalionak/ggrc-core,andrei-karalionak/ggrc-core,VinnieJohns/ggrc-core,hyperNURb/ggrc-core,selahssea/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,jmakov/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,hasanalom/ggrc-core,NejcZupec/ggrc-core,AleksNeS... | src/tests/ggrc/converters/__init__.py | src/tests/ggrc/converters/__init__.py | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from flask import json
from os.path import abspath
from os.path import dirname
f... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from flask import json
from os.path import abspath
from os.path import dirname
f... | apache-2.0 | Python |
671e877bc14eb2034bc4ff735c56c2d3aeb2e43d | Update a test | mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | examples/raw_parameter_script.py | examples/raw_parameter_script.py | """ The main purpose of this file is to demonstrate running SeleniumBase
scripts without the use of Pytest by calling the script directly
with Python or from a Python interactive interpreter. Based on
whether relative imports work or don't, the script can autodetect
how this file was run. With pure Pyth... | """ The main purpose of this file is to demonstrate running SeleniumBase
scripts without the use of Pytest by calling the script directly
with Python or from a Python interactive interpreter. Based on
whether relative imports work or don't, the script can autodetect
how this file was run. With pure Pyth... | mit | Python |
02a3fb6e1d7bde7b9f9d20089e8dd11040388e80 | remove testing code | zacchiro/debsources,sophiejjj/debsources,sophiejjj/debsources,zacchiro/debsources,matthieucan/debsources,oorestisime/debsources,zacchiro/debsources,oorestisime/debsources,oorestisime/debsources,sophiejjj/debsources,devoxel/debsources,Debian/debsources,sophiejjj/debsources,vivekanand1101/debsources,oorestisime/debsource... | python/app/extract_stats.py | python/app/extract_stats.py | # Copyright (C) 2014 Matthieu Caneill <matthieu.caneill@gmail.com>
#
# This file is part of Debsources.
#
# Debsources is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, o... | # Copyright (C) 2014 Matthieu Caneill <matthieu.caneill@gmail.com>
#
# This file is part of Debsources.
#
# Debsources is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, o... | agpl-3.0 | Python |
adfb7518b47c36396c14a513f547fd5055a29883 | add bootstrap3 | CooloiStudio/Django_MobileFoodOrderServer,CooloiStudio/Django_MobileFoodOrderServer,CooloiStudio/Django_MobileFoodOrderServer | MobileFoodOrderServer/settings.py | MobileFoodOrderServer/settings.py | """
Django settings for MobileFoodOrderServer project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BAS... | """
Django settings for MobileFoodOrderServer project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BAS... | mit | Python |
d06fa1c8bfa5c782a5c28403caf44736620a3706 | add get_instruction method modified: qaamus/test_angka_parser.py | ihfazhillah/qaamus-python | qaamus/test_angka_parser.py | qaamus/test_angka_parser.py | import unittest
from bs4 import BeautifulSoup
from ind_ara_parser import BaseParser
class AngkaParser(BaseParser):
"""Handle terjemah angka page."""
def get_instruction(self):
"""Return the instruction text.
text is returning 'Terjemah angka adalah menterjemahkan angka
kedalam bahasa ... | import unittest
from bs4 import BeautifulSoup
from ind_ara_parser import BaseParser
class AngkaParser(BaseParser):
pass
class AngkaParserTestCase(unittest.TestCase):
with open("../html/angka123", "rb") as f:
f = f.read()
soup = BeautifulSoup(f)
def setUp(self):
self.angka_parser = A... | mit | Python |
6509a1c1e9ee92841378d0b6f546ebf64991bbea | add xyz to exportable formats | rcpedersen/stl-to-voxel | stltovoxel.py | stltovoxel.py | import argparse
from PIL import Image
import numpy as np
import os.path
import slice
import stl_reader
import perimeter
from util import arrayToPixel
def doExport(inputFilePath, outputFilePath, resolution):
mesh = list(stl_reader.read_stl_verticies(inputFilePath))
(scale, shift, bounding_box) = slice.calcula... | import argparse
from PIL import Image
import numpy as np
import os.path
import slice
import stl_reader
import perimeter
from util import arrayToPixel
def doExport(inputFilePath, outputFilePath, resolution):
mesh = list(stl_reader.read_stl_verticies(inputFilePath))
(scale, shift, bounding_box) = slice.calcula... | mit | Python |
21f53bee1bfba8ef82b82898693c2cc09a7873c7 | add get_weight() to Keras interface | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | syft/interfaces/keras/models/sequential.py | syft/interfaces/keras/models/sequential.py | import syft
import syft.nn as nn
import sys
from syft.interfaces.keras.layers import Log
class Sequential(object):
def __init__(self):
self.syft = nn.Sequential()
self.layers = list()
self.compiled = False
def add(self, layer):
if(len(self.layers) > 0):
# look to the previous layer to get the input sh... | import syft
import syft.nn as nn
import sys
from syft.interfaces.keras.layers import Log
class Sequential(object):
def __init__(self):
self.syft = nn.Sequential()
self.layers = list()
self.compiled = False
def add(self, layer):
if(len(self.layers) > 0):
# look to the previous layer to get the input sh... | apache-2.0 | Python |
cb0ba85a56c163436d6a4180413f0228407458d8 | Correct path specification error | SKA-ScienceDataProcessor/algorithm-reference-library,SKA-ScienceDataProcessor/algorithm-reference-library,SKA-ScienceDataProcessor/algorithm-reference-library,SKA-ScienceDataProcessor/algorithm-reference-library,SKA-ScienceDataProcessor/algorithm-reference-library | tests/workflows/test_component_wrappers.py | tests/workflows/test_component_wrappers.py | """ Unit tests for json helpers
"""
import os
import unittest
from data_models.parameters import arl_path
from workflows.wrappers.component_wrapper import component_wrapper
class TestComponentWrappers(unittest.TestCase):
def test_run_components(self):
files = ["test_results/test_pipeline.log",
... | """ Unit tests for json helpers
"""
import os
import unittest
from data_models.parameters import arl_path
from workflows.wrappers.component_wrapper import component_wrapper
class TestComponentWrappers(unittest.TestCase):
def test_run_components(self):
files = ["test_results/test_pipeline.log",
... | apache-2.0 | Python |
f535228e38f33263289f28d46e910ccb0a98a381 | Use list comprehension to evaluate PYTZ_TIME_ZONE_CHOICES | goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic,goodtune/vitriolic | tournamentcontrol/competition/constants.py | tournamentcontrol/competition/constants.py | import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winn... | import pytz
from dateutil.rrule import DAILY, WEEKLY
from django.utils.translation import ugettext_lazy as _
GENDER_CHOICES = (
('M', _('Male')),
('F', _('Female')),
('X', _('Unspecified')),
)
SEASON_MODE_CHOICES = (
(WEEKLY, _("Season")),
(DAILY, _("Tournament")),
)
WIN_LOSE = {
'W': _("Winn... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.