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 |
|---|---|---|---|---|---|---|---|---|
18e5a088eecf371bf06c7ff61e08cafcccbd7d27 | Replace easy_install with setuptools in test_lssitepackages | berdario/pew,berdario/pew | tests/test_ls.py | tests/test_ls.py | from pathlib import Path
import re
from pew._utils import invoke_pew as invoke
def test_ls(workon_home):
r = invoke('ls')
assert not r.out and not r.err
def test_get_site_packages_dir(workon_home):
invoke('new', 'env', '-d')
d = invoke('in', 'env', 'pew', 'sitepackages_dir').out
assert Path(d).e... | from pathlib import Path
from pew._utils import invoke_pew as invoke
def test_ls(workon_home):
r = invoke('ls')
assert not r.out and not r.err
def test_get_site_packages_dir(workon_home):
invoke('new', 'env', '-d')
d = invoke('in', 'env', 'pew', 'sitepackages_dir').out
assert Path(d).exists
... | mit | Python |
4d3ca5cdf03840528d354b147c6baa85de090ece | remove useless code | staugur/EauDouce,staugur/EauDouce,staugur/EauDouce,staugur/EauDouce | src/cli.py | src/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
EauDouce.cli
~~~~~~~~~~~~
Cli Entrance
:copyright: (c) 2017 by Mr.tao.
:license: MIT, see LICENSE for more details.
"""
from libs.base import ServiceBase
sb = ServiceBase()
if __name__ == "__main__":
import argparse
parser = argparse.Arg... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
EauDouce.cli
~~~~~~~~~~~~
Cli Entrance
:copyright: (c) 2017 by Mr.tao.
:license: MIT, see LICENSE for more details.
"""
from libs.base import ServiceBase
sb = ServiceBase()
blogPvKey = "EauDouce:AccessCount:pv:blogs"
if __name__ == "__main__":
... | bsd-3-clause | Python |
eb3466653ba47b23de83d5606c9088b27c4de263 | Simplify API | fabriziodemaria/LeetCode-Tree-Parser | LC-Parser/lcparser.py | LC-Parser/lcparser.py | # -*- coding: utf-8 -*-
import sys
import ast
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def TreeGenerator(string):
s = string
if (s == "[]"):
return None
list = s[1:-1].split(',')
head = Tree... | # -*- coding: utf-8 -*-
import sys
import ast
from collections import deque
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class TreeGenerator:
def __init__(self, input_string):
self.s = input_string
def generateTree(self):
i... | bsd-3-clause | Python |
65198ab88a1504e43223d4e2c8e6d45df00a855f | Bump version | marceloslacerda/password_generator,marceloslacerda/password_generator | password_generator/__init__.py | password_generator/__init__.py | __version__ = '1.0.1'
| __version__ = '1.0.0'
| bsd-3-clause | Python |
67f4a38663b6797a9a1193540ae6e79cfd8b1c44 | fix path namings | jokey2k/ShockGsite,jokey2k/ShockGsite | trackmaniawars/settings.py | trackmaniawars/settings.py | # -*- coding: utf-8 -*-
from django.conf import settings
def get(key, default):
return getattr(settings, key, default)
TRACK_UPLOAD_TO = get('TRACKMANIAWARS_TRACK_UPLOAD_TO', 'trackmaniawars/tracks')
THUMBS_UPLOAD_TO = get('TRACKMANIAWARS_THUMBS_UPLOAD_TO', 'trackmaniawars/thumbs')
IMG_WIDTH=get('GAMESERVER_IMG_... | # -*- coding: utf-8 -*-
from django.conf import settings
def get(key, default):
return getattr(settings, key, default)
TRACK_UPLOAD_TO = get('TRACKMANIAWARS_TRACK_UPLOAD_TO', 'tracknamiawars/tracks')
THUMBS_UPLOAD_TO = get('TRACKMANIAWARS_THUMBS_UPLOAD_TO', 'tracknamiawars/thumbs')
IMG_WIDTH=get('GAMESERVER_IMG_... | bsd-3-clause | Python |
a6dccd7faed98556fd22b344ca7491fa46ae5716 | remove doctest code in __init__.py | cedar101/twitter-korean-py | twitter_korean/__init__.py | twitter_korean/__init__.py | # -*- coding: utf-8 -*-
import os.path
JAR_DIR = 'data/lib'
RESOURCES_ROOT = os.path.join(JAR_DIR, 'com/twitter/penguin/korean/util')
from .normalizer.KoreanNormalizer import normalize, normalize_coda_n
from .util.KoreanDictionaryProvider import correct_typo
def tokenize(normalized):
raise NotImplementedError
d... | # -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
"""
>>> text = "한국어를 처리하는 예시입니닼ㅋㅋㅋㅋㅋ #한국어"
>>> # Normalize
>>> normalized = normalize(text)
>>> print(normalized)
한국어를 처리하는 예시입니다ㅋㅋ #한국어
>>> # Tokenize
>>> tokens = tokenize(normalized) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most ... | apache-2.0 | Python |
c338333d7ffdc2c7addd8f8bbafe54f689aeb770 | Add punctuation stripping, implement del command. | geekofalltrades/quora-coding-challenges | typeahead_search/search.py | typeahead_search/search.py | import sys
import string
from trie import TypeaheadSearchTrie
class Entry(object):
"""Simple container class for data entries."""
def __init__(self, type, id, score, data):
self.type = type
self.id = id
self.score = score
self.data = data
class TypeAheadSearchSession(object):... | import sys
from trie import TypeaheadSearchTrie
class Entry(object):
"""Simple container class for data entries."""
def __init__(self, type, id, score, data):
self.type = type
self.id = id
self.score = score
self.data = data
class TypeAheadSearchSession(object):
"""Class ... | mit | Python |
45a1ab213e4cfd94061348c7c3de20dcc7de94e8 | Update FindMax.py | TheAlgorithms/Python | Maths/FindMax.py | Maths/FindMax.py | # NguyenU
import math
def find_max(nums):
max = 0
for x in nums:
if x > max:
max = x
print(max)
def main():
find_max([2, 4, 9, 7, 19, 94, 5])
if __name__ == '__main__':
main()
| # NguyenU
import math
def find_max(nums):
max = 0
for x in nums:
if x > max:
max = x
print max
| mit | Python |
73ff22f4905ca3ac48581a2437d1e7522f3604c0 | support get or post. | soasme/rio,soasme/rio,soasme/rio | rio/blueprints/api_v1/views.py | rio/blueprints/api_v1/views.py | # -*- coding: utf-8 -*-
"""
rio.blueprints.api_v1.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implement of rio api v1 view functions.
"""
from flask import jsonify
from flask import request
from sqlalchemy.exc import IntegrityError
from celery.task.http import URL
from rio.core import celery
from rio.models import Webhook
fro... | # -*- coding: utf-8 -*-
"""
rio.blueprints.api_v1.views
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implement of rio api v1 view functions.
"""
from flask import jsonify
from flask import request
from sqlalchemy.exc import IntegrityError
from celery.task.http import URL
from rio.core import celery
from rio.models import Webhook
fro... | mit | Python |
326729956336b31e0a43b1358ead8171e9678b7b | Bump to version 2.5.1 | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/email/__init__.py | Lib/email/__init__.py | # Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '2.5.1'
__all__ = [
'base64MIME',
'Charset',
'Encoders',
'Errors',
'Generator',
'Header',
'Iterators',
'Mes... | # Copyright (C) 2001,2002 Python Software Foundation
# Author: barry@zope.com (Barry Warsaw)
"""A package for parsing, handling, and generating email messages.
"""
__version__ = '2.5+'
__all__ = [
'base64MIME',
'Charset',
'Encoders',
'Errors',
'Generator',
'Header',
'Iterators',
'Mess... | mit | Python |
d25fca72ab36407389308ab6e85d5cd921c9322d | change the redis returner to be called just redis | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/returners/redis_return.py | salt/returners/redis_return.py | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... | '''
Return data to a redis server
To enable this returner the minion will need the python client for redis
installed and the following values configured in the minion or master
config, these are the defaults:
redis.db: '0'
redis.host: 'salt'
redis.port: 6379
'''
# Import python libs
import json
try:
... | apache-2.0 | Python |
54421c59a69c6a7ef5a3455b99bfacea7c512653 | remove dbsession engine | sacrud/sacrud,ITCase/sacrud | sacrud/pyramid_ext/__init__.py | sacrud/pyramid_ext/__init__.py | # -*- coding: utf-8 -*-
import sqlalchemy
import sqlalchemy.orm as orm
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.engine import create_engine
pkg_name = 'sacrud'
DBSession = orm.scoped_session(orm.sessionmaker(extension=ZopeTransactionExtension()))
DBSession.remove()
def add_routes(config... | # -*- coding: utf-8 -*-
import sqlalchemy
import sqlalchemy.orm as orm
from zope.sqlalchemy import ZopeTransactionExtension
from sqlalchemy.engine import create_engine
pkg_name = 'sacrud'
engine = create_engine('sqlite:///:memory:')
DBSession = orm.scoped_session(orm.sessionmaker(extension=ZopeTransactionExtension()... | mit | Python |
0e4db2ae09a81e1ad440eb984523f218ce94bbd9 | change figsizes for better animations | maojrs/riemann_book,maojrs/riemann_book,maojrs/riemann_book | utils/jsanimate_widgets.py | utils/jsanimate_widgets.py |
"""
Alternative interact function that creates a JSAnimation figure that can
be viewed online, e.g. on Github or nbviewer.
"""
from __future__ import print_function
print("Will create JSAnimation figures instead of interactive widget")
def interact(f, **kwargs):
from utils import animation_tools
from IPytho... |
"""
Alternative interact function that creates a JSAnimation figure that can
be viewed online, e.g. on Github or nbviewer.
"""
from __future__ import print_function
print("Will create JSAnimation figures instead of interactive widget")
def interact(f, **kwargs):
from utils import animation_tools
from IPytho... | bsd-3-clause | Python |
e254df81c825b2ff0069379018a37eac85b867af | clarify private pools instructions (#268) | googleapis/python-cloudbuild,googleapis/python-cloudbuild | samples/snippets/quickstart.py | samples/snippets/quickstart.py | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2021 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | apache-2.0 | Python |
8403e7a40ad552d70bafdc0156ed1816145b51f9 | bump repo version to 2.0.0rc13 | omry/omegaconf | omegaconf/version.py | omegaconf/version.py | import sys # pragma: no cover
__version__ = "2.0.0rc13"
msg = """OmegaConf 2.0 and above is compatible with Python 3.6 and newer.
You have the following options:
1. Upgrade to Python 3.6 or newer.
This is highly recommended. new features will not be added to OmegaConf 1.4.
2. Continue using OmegaConf 1.4:
You... | import sys # pragma: no cover
__version__ = "2.0.0rc12"
msg = """OmegaConf 2.0 and above is compatible with Python 3.6 and newer.
You have the following options:
1. Upgrade to Python 3.6 or newer.
This is highly recommended. new features will not be added to OmegaConf 1.4.
2. Continue using OmegaConf 1.4:
You... | bsd-3-clause | Python |
a34a7648e8d44c8fa77d192a2eda1d5dd0eeeb5b | update worker queue name | BeanYoung/push-turbo | src/run.py | src/run.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import gevent
import config
from worker import Worker
from turbo import Pipe
pipes = dict()
class PushWorker(Worker):
def execute_job(self, job):
job_body = json.loads(job.body)
if job_body['app_name'] not in pipes:
return
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import gevent
import config
from worker import Worker
from turbo import Pipe
pipes = dict()
class PushWorker(Worker):
def execute_job(self, job):
job_body = json.loads(job.body)
if job_body['app_name'] not in pipes:
return
... | mit | Python |
1201c214b2f9dbed9280a6a625292d5647730196 | add working url_to_frames | iRapha/search_within_videos,iRapha/search_within_videos,iRapha/search_within_videos | url_to_frames.py | url_to_frames.py | import re
import requests
import shutil
import time
def url_to_frames(url):
"""given a url, get a list of timestamped frames"""
r = requests.get(url)
match = re.search('\"storyboard_spec\":\"([^\"]*)\"', str(r.content)).group(1).replace('\\\\', '')
sighs = re.findall('\$M#([^\|$]+)(?:\||$)', match)
... | import re
import requests
def url_to_frames(url):
"""given a url, get a list of timestamped frames"""
r = requests.get(url)
match = re.search('\"storyboard_spec\":\"([^\"]*)\"', str(r.content)).group(1)
match = match.replace('\\\\', '')
base_url = match[:match.find('|')]
# in order of prefere... | mit | Python |
29e348ddceedba267bdf2b54880e5c272ebf73a0 | Update ipc_lista4.04.py | any1m1c/ipc20161 | lista4-thiago/ipc_lista4.04.py | lista4-thiago/ipc_lista4.04.py | #ipc_lista4.04
#Thiago Santos Borges - Matrícula - 1615310023
#
consoantes = []
letras = []
acm = 0
for i in range(1,11):
letraind = input("Digite letra:")
letras.append(letraind)
if letraind == "a" or letraind == "e" or letraind == "i" or letraind == "o" or letraind == "u":
acm = acm
else:
... | #ipc_lista4.01
#Thiago Santos Borges - Matrícula - 1615310023
#
consoantes = []
letras = []
acm = 0
for i in range(1,11):
letraind = input("Digite letra:")
letras.append(letraind)
if letraind == "a" or letraind == "e" or letraind == "i" or letraind == "o" or letraind == "u":
acm = acm
else:
... | apache-2.0 | Python |
49105af886f3eb7e76db56a8a1678ead9c774a27 | Remove untested code from VerifyUserAdmin | incuna/django-user-management,incuna/django-user-management | user_management/models/admin.py | user_management/models/admin.py | from collections import OrderedDict
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from . import admin_forms
User = get_user_model()
class UserAdmin(BaseUserAdmin):
form = admin_forms.UserChangeForm
add_form = admin_forms.UserCreationForm
... | from collections import OrderedDict
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from . import admin_forms
User = get_user_model()
class UserAdmin(BaseUserAdmin):
form = admin_forms.UserChangeForm
add_form = admin_forms.UserCreationForm
... | bsd-2-clause | Python |
ba98874be9370ec49c2c04e89d456f723b5d083c | Adjust tests for python-monascaclient >= 1.3.0 | openstack/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui | monitoring/test/test_data/exceptions.py | monitoring/test/test_data/exceptions.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... | apache-2.0 | Python |
8f6c5bd9d9228913ab8a5c5a69addd9a96537487 | Fix url | pbdeuchler/deaddrop,pbdeuchler/deaddrop,pbdeuchler/deaddrop | deaddrop/urls.py | deaddrop/urls.py | from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
from .web.views import specific_secret
from .api.urls import router
admin.autodiscover()
urlpatterns = pattern... | from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic import TemplateView
from .web.views import specific_secret
from .api.urls import router
admin.autodiscover()
urlpatterns = pattern... | bsd-3-clause | Python |
8ef41f9ac8ec8a7b7fc9e63b2ff6453782c41d62 | Deploy Travis CI build 381 to GitHub | jacebrowning/template-python-demo | demo/__init__.py | demo/__init__.py | """Package for PythonTemplateDemo."""
__project__ = 'PythonTemplateDemo'
__version__ = '0.0.0'
VERSION = __project__ + '-' + __version__
PYTHON_VERSION = 3, 4
import sys
if not sys.version_info >= PYTHON_VERSION: # pragma: no cover (manual test)
exit("Python {}.{}+ is required.".format(*PYTHON_VERSION))
| """Package for PythonTemplateDemo."""
__project__ = 'PythonTemplateDemo'
__version__ = '0.0.0'
VERSION = __project__ + '-' + __version__
| mit | Python |
464c5cc7b8dae8ef01bdce78e7a8df33192618eb | Update coco.py | delftrobotics/keras-retinanet | keras_retinanet/callbacks/coco.py | keras_retinanet/callbacks/coco.py | """
Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | """
Copyright 2017-2018 Fizyr (https://fizyr.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | apache-2.0 | Python |
c2f882f63baff7cc876f97eba07574c5f5d4a8ef | Convert header dependency scanner to Python3 | spiiroin/mce,spiiroin/mce,spiiroin/mce,spiiroin/mce | depend_filter.py | depend_filter.py | #!/usr/bin/env python3
# -*- encoding: utf8 -*-
# ----------------------------------------------------------------------------
# Copyright (C) 2012 Jolla Ltd.
# Contact: Simo Piiroinen <simo.piiroinen@jollamobile.com>
# License: GPLv2
# ----------------------------------------------------------------------------
impo... | #!/usr/bin/env python
# -*- encoding: utf8 -*-
# ----------------------------------------------------------------------------
# Copyright (C) 2012 Jolla Ltd.
# Contact: Simo Piiroinen <simo.piiroinen@jollamobile.com>
# License: GPLv2
# ----------------------------------------------------------------------------
impor... | lgpl-2.1 | Python |
d77313663b83a8e8f8732b3f4fe0fcd209eb0b67 | Correct `__version__` string. | SunDwarf/curious | curious/__init__.py | curious/__init__.py | """
Curious - A Curio-based Python 3.5+ library for Discord bots.
.. currentmodule:: curious
.. autosummary::
:toctree:
core
commands
dataclasses
ext.loapi
ext.paginator
voice
exc
util
"""
from pkg_resources import DistributionNotFound, get_distribution
try:
__vers... | """
Curious - A Curio-based Python 3.5+ library for Discord bots.
.. currentmodule:: curious
.. autosummary::
:toctree:
core
commands
dataclasses
ext.loapi
ext.paginator
voice
exc
util
"""
from pkg_resources import DistributionNotFound, get_distribution
try:
__vers... | mit | Python |
bd33bfaec781dd5f809e1a81c3dec44155f937c2 | remove extra intent examples | treethought/flask-assistant | samples/hello_world/webhook.py | samples/hello_world/webhook.py | import logging
from flask import Flask
from flask_assistant import Assistant, ask, tell, context_manager, permission, event
app = Flask(__name__)
assist = Assistant(app)
logging.getLogger("flask_assistant").setLevel(logging.DEBUG)
app.config["INTEGRATIONS"] = ["ACTIONS_ON_GOOGLE"]
@assist.action("greeting")
def gre... | import logging
from flask import Flask
from flask_assistant import Assistant, ask, tell, context_manager, permission, event
app = Flask(__name__)
assist = Assistant(app)
logging.getLogger("flask_assistant").setLevel(logging.DEBUG)
app.config["INTEGRATIONS"] = ["ACTIONS_ON_GOOGLE"]
@assist.action("greeting")
def gre... | apache-2.0 | Python |
468e87857dd989c823f9b177a080956aaaf9981c | Remove old initial guess plotting from main | PlasmaControl/DESC,PlasmaControl/DESC | desc/__main__.py | desc/__main__.py | import sys
import warnings
from termcolor import colored
from desc.io import InputReader
def main(cl_args=sys.argv[1:]):
"""Run the main DESC code from the command line.
Reads and parses user input from command line, runs the code,
and prints and plots the resulting equilibrium.
"""
ir = InputR... | import sys
import warnings
from termcolor import colored
from desc.io import InputReader
def main(cl_args=sys.argv[1:]):
"""Run the main DESC code from the command line.
Reads and parses user input from command line, runs the code,
and prints and plots the resulting equilibrium.
"""
ir = InputR... | mit | Python |
db1aaa7f7e28c901b2b427236f9942aa78d5ae34 | Add an alias !tous for !all | ningirsu/taemin,ningirsu/taemin | taemin/plugins/cafe/plugin.py | taemin/plugins/cafe/plugin.py | #!/usr/bin/env python2
# -*- coding: utf8 -*-
from taemin import plugin
class TaeminCafe(plugin.TaeminPlugin):
helper = {"all": "Envoie un message à tout le monde",
"cafe": "Appelle tout le monde pour prendre un café ;)"}
def on_pubmsg(self, msg):
if msg.key not in ("all", 'tous', "caf... | #!/usr/bin/env python2
# -*- coding: utf8 -*-
from taemin import plugin
class TaeminCafe(plugin.TaeminPlugin):
helper = {"all": "Envoie un message à tout le monde",
"cafe": "Appelle tout le monde pour prendre un café ;)"}
def on_pubmsg(self, msg):
if msg.key not in ("all", "cafe"):
... | mit | Python |
edf151feea948ebf4a9f00a0248ab1f363cacfac | Remove __init__ method, not needed. | goliatone/minions | scaffolder/commands/install.py | scaffolder/commands/install.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from optparse import make_option
from optparse import OptionParser
from scaffolder import get_minion_path
from scaffolder.core.template import TemplateManager
from scaffolder.core.commands import BaseCommand
class InstallCommand(BaseCommand):
option_list = BaseCommand... | mit | Python |
378b820bd2a474640974ccefc7b224caebc9400f | Add more info to the permission denied exception | mociepka/saleor,UITools/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor | saleor/graphql/order/resolvers.py | saleor/graphql/order/resolvers.py | from django.core.exceptions import PermissionDenied
from ...order import models
from ..utils import get_node
from .types import Order
def resolve_orders(info):
user = info.context.user
if user.is_anonymous:
raise PermissionDenied('You have no permission to see this order.')
if user.get_all_permis... | from django.core.exceptions import PermissionDenied
from ...order import models
from ..utils import get_node
from .types import Order
def resolve_orders(info):
user = info.context.user
if user.is_anonymous:
raise PermissionDenied('You have no permission to see this')
if user.get_all_permissions()... | bsd-3-clause | Python |
bc47862e89f73ec152a57bf43126653a981cd411 | Undo member changes in test | MeirKriheli/Open-Knesset,jspan/Open-Knesset,navotsil/Open-Knesset,navotsil/Open-Knesset,DanaOshri/Open-Knesset,alonisser/Open-Knesset,jspan/Open-Knesset,noamelf/Open-Knesset,daonb/Open-Knesset,habeanf/Open-Knesset,noamelf/Open-Knesset,DanaOshri/Open-Knesset,OriHoch/Open-Knesset,otadmor/Open-Knesset,alonisser/Open-Kness... | suggestions/tests.py | suggestions/tests.py | from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
... | from django.test import TestCase
from django.contrib.auth.models import User
from mks.models import Member
from .models import Suggestion
class SuggestionsTests(TestCase):
def setUp(self):
self.member = Member.objects.create(name='mk_1')
self.regular_user = User.objects.create_user('reg_user')
... | bsd-3-clause | Python |
ecfc45443670515ad39d154e3d2b45c1643d4528 | update NDCG defaults | Evfro/polara | polara/recommender/defaults.py | polara/recommender/defaults.py | import sys
#DATA
#properties that require rebuilding test data:
test_ratio = 0.2 #split 80% of users for training, 20% for test
test_fold = 5 #which fold to use for test data
shuffle_data = False #randomly permute all records in initial data
test_sample = None #sample a fraction of test data; negative value will samp... | import sys
#DATA
#properties that require rebuilding test data:
test_ratio = 0.2 #split 80% of users for training, 20% for test
test_fold = 5 #which fold to use for test data
shuffle_data = False #randomly permute all records in initial data
test_sample = None #sample a fraction of test data; negative value will samp... | mit | Python |
74ff895eb01331295e33e2cdc4938378fd697a50 | Update local.py | 20tab/twentytab_project,20tab/twentytab_project,20tab/twentytab_project | project_name/settings/local.py | project_name/settings/local.py | from {{ project_name }}.settings.base import *
import socket
ALLOWED_HOSTS = ('localhost', '127.0.0.1')
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True
USE_DEBUG_TOOLBAR = True
INTERNAL_IPS = ('127.0.0.1', socket.gethostbyname(socket.gethostname()))
DATABASES = {
'default': {
'ENGINE': 'django.db.ba... | from {{ project_name }}.settings.base import *
import socket
ALLOWED_HOSTS = ('localhost', '127.0.0.1')
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True
USE_DEBUG_TOOLBAR = True
INTERNAL_IPS = ('127.0.0.1', socket.gethostbyname(socket.gethostname()))
DATABASES = {
'default': {
'ENGINE': 'django.db.ba... | mit | Python |
517813795af69056673ca5b7ab45b3590d3b7ef0 | clean up theharvester | bharshbarger/AutOSINT | modules/theharvester.py | modules/theharvester.py | #!/usr/bin/env python
"""module to run the harvester"""
import subprocess
class Theharvester():
"""module class"""
def __init__(self):
#init lists
self.theharvester_result = []
self.harvester_sources = 'google, linkedin'
def run(self, args, lookup, report_directory):
"""ma... | #!/usr/bin/env python
import subprocess
class Theharvester():
"""module to use theharvester"""
def run(self, args, lookup, reportDir):
"""main function"""
#init lists
theharvester_result = []
#based on domain or ip, enumerate with index and value
for i, l in enumerate(... | mit | Python |
2dbf9215f0b5a100c5bcfe0a73e211762fecc924 | Fix a magnificent error in the deferred handler | wangjun/djangae,kirberich/djangae,pablorecio/djangae,jscissr/djangae,jscissr/djangae,martinogden/djangae,grzes/djangae,armirusco/djangae,stucox/djangae,kirberich/djangae,chargrizzle/djangae,SiPiggles/djangae,leekchan/djangae,armirusco/djangae,wangjun/djangae,pablorecio/djangae,stucox/djangae,trik/djangae,asendecka/djan... | djangae/views.py | djangae/views.py | import os
import logging
from django.conf import settings
from django.http import HttpResponse
from django.utils.importlib import import_module
from django.views.decorators.csrf import csrf_exempt
from djangae.utils import on_production
def warmup(request):
"""
Provides default procedure for handling war... | import os
import logging
from django.conf import settings
from django.http import HttpResponse
from django.utils.importlib import import_module
from django.views.decorators.csrf import csrf_exempt
from djangae.utils import on_production
def warmup(request):
"""
Provides default procedure for handling war... | bsd-3-clause | Python |
732db22a302854fea617748b085ce7e468ff5abe | use new neutronclient | openstack/networking-bagpipe-l2,stackforge/networking-bagpipe-l2,openstack/networking-bagpipe-l2,openstack/networking-bagpipe,openstack/networking-bagpipe,stackforge/networking-bagpipe-l2 | networking_bagpipe/tests/fullstack/resources/bgpvpn/client.py | networking_bagpipe/tests/fullstack/resources/bgpvpn/client.py | # Copyright (c) 2016 Orange.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | # Copyright (c) 2016 Orange.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | apache-2.0 | Python |
1368c8e89d23af172db8ebb462a5307630690d0c | Use single ThreadPool in dask.threaded.get | jayhetee/dask,PhE/dask,marianotepper/dask,dask/dask,minrk/dask,jakirkham/dask,pombredanne/dask,blaze/dask,gameduell/dask,cowlicks/dask,jcrist/dask,mraspaud/dask,esc/dask,vikhyat/dask,clarkfitzg/dask,wiso/dask,freeman-lab/dask,dask/dask,ContinuumIO/dask,jakirkham/dask,hainm/dask,clarkfitzg/dask,blaze/dask,jcrist/dask,fr... | dask/threaded.py | dask/threaded.py | """
A threaded shared-memory scheduler
See async.py
"""
from __future__ import absolute_import, division, print_function
from multiprocessing.pool import ThreadPool
from .async import get_async, inc, add
from .compatibility import Queue
from .context import _globals
default_pool = ThreadPool()
def get(dsk, result... | """
A threaded shared-memory scheduler
See async.py
"""
from __future__ import absolute_import, division, print_function
from multiprocessing.pool import ThreadPool
import psutil
from .async import get_async, inc, add
from .compatibility import Queue
from .context import _globals
NUM_CPUS = psutil.cpu_count()
def... | bsd-3-clause | Python |
91ce8fdc418aed6a5a554d5b68ea92a0fd01102a | fix __init.py | SergejPr/NooLite-F | NooLite_F/__init__.py | NooLite_F/__init__.py | from NooLite_F.NooLiteFController import NooLiteFController, Direction, NooLiteFListener, BatteryState, ModuleMode
from NooLite_F.NooLiteFController import ModuleInfo, ModuleBaseStateInfo, ModuleExtraStateInfo, ModuleChannelsStateInfo, ModuleState, ServiceModeState, InputMode, \
DimmerCorrectionConfig, ModuleConfig... | from NooLite_F.NooLiteFController import NooLiteFController, Direction, NooLiteFListener, BatteryState, ModuleMode
from NooLite_F.NooLiteFController import ModuleInfo, ModuleBaseStateInfo, ModuleExtraStateInfo, ModuleChannelsStateInfo, ModuleState, ServiceModeState, InputMode, \
DimmerCorrectionConfig, ModuleConfig... | mit | Python |
e873d57f431f296f8dbb671c365d7d7a12a76566 | fix type hint | locustio/locust,locustio/locust,locustio/locust,locustio/locust | locust/util/load_locustfile.py | locust/util/load_locustfile.py | import importlib
import inspect
import os
import sys
from typing import Dict, Optional, Tuple
from ..shape import LoadTestShape
from ..user import User
def is_user_class(item):
"""
Check if a variable is a runnable (non-abstract) User class
"""
return bool(inspect.isclass(item) and issubclass(item, Us... | import importlib
import inspect
import os
import sys
from typing import Dict, Any, Optional
from ..shape import LoadTestShape
from ..user import User
def is_user_class(item):
"""
Check if a variable is a runnable (non-abstract) User class
"""
return bool(inspect.isclass(item) and issubclass(item, User... | mit | Python |
3956fbc95fdceac2ec28ccecffbd3ded4150bd64 | use `*` for list unpacking | avinassh/nightreads,avinassh/nightreads | nightreads/user_manager/user_service.py | nightreads/user_manager/user_service.py | from django.contrib.auth.models import User
from nightreads.posts.models import Tag
from .models import UserTags
def update_user_tags(user, tags):
tags_objs = Tag.objects.filter(name__in=tags)
user.usertags.tags.add(*tags_objs)
user.save()
def get_user(email):
user, created = User.objects.get_or_cr... | from django.contrib.auth.models import User
from nightreads.posts.models import Tag
from .models import UserTags
def update_user_tags(user, tags):
tags_objs = Tag.objects.filter(name__in=tags)
user.usertags.tags.add(**tags_objs)
user.save()
def get_user(email):
user, created = User.objects.get_or_c... | mit | Python |
d72fe55ce4e07b8dba67519ebd4a060ba7b7fc94 | Update dependency com_github_mattn_go_isatty to v0.0.12 | bazelbuild/rules_nodejs,alexeagle/rules_nodejs,bazelbuild/rules_nodejs,bazelbuild/rules_nodejs,bazelbuild/rules_nodejs,alexeagle/rules_nodejs,alexeagle/rules_nodejs,alexeagle/rules_nodejs,bazelbuild/rules_nodejs | packages/typescript/src/internal/internal_ts_repositories.bzl | packages/typescript/src/internal/internal_ts_repositories.bzl | # Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | # Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | apache-2.0 | Python |
d774347795925a03103f84f0a94b7e15d4bb4857 | Use ticks instead of double quotes | atlassian/cookiecutter,cichm/cookiecutter,ramiroluz/cookiecutter,sp1rs/cookiecutter,vincentbernat/cookiecutter,ionelmc/cookiecutter,luzfcb/cookiecutter,benthomasson/cookiecutter,lgp171188/cookiecutter,ionelmc/cookiecutter,0k/cookiecutter,pjbull/cookiecutter,dajose/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutt... | tests/test_get_user_config.py | tests/test_get_user_config.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
TestGetUserConfig.test_get_user_config_valid
"""
import os
import shutil
import pytest
from cookiecutter import config
@pytest.fixture(scope='module')
d... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_get_user_config
--------------------
Tests formerly known from a unittest residing in test_config.py named
"""
import os
import shutil
import pytest
from cookiecutter import config
@pytest.fixture(scope='module')
def user_config_path():
return os.path.exp... | bsd-3-clause | Python |
cfba26ef5e782000736bdc93648169fcea9a4236 | Work in a tmpdir for test that creates files | jstutters/Plumbium | tests/test_output_recorder.py | tests/test_output_recorder.py | from __future__ import print_function
from copy import copy
import json
import pytest
import sys
from plumbium.processresult import OutputRecorder, record, pipeline
@pytest.fixture
def recorded_pipeline():
@record('an_output')
def recorded_function():
print('test output')
return 'test_result'
... | from __future__ import print_function
from copy import copy
import json
import pytest
import sys
from plumbium.processresult import OutputRecorder, record, pipeline
@pytest.fixture
def recorded_pipeline():
@record('an_output')
def recorded_function():
print('test output')
return 'test_result'
... | mit | Python |
e1cfcae44fcbb78640a6d613f80d999595a5217b | Add test for --no-echo | borntyping/python-riemann-client | tests/test_riemann_command.py | tests/test_riemann_command.py | from __future__ import absolute_import, unicode_literals
import re
import socket
import click.testing
import riemann_client.command
def run_cli(args):
args = ['-T', 'none'] + list(args)
runner = click.testing.CliRunner()
result = runner.invoke(riemann_client.command.main, args)
assert result.exit_c... | from __future__ import absolute_import, unicode_literals
import re
import socket
import click.testing
import riemann_client.command
def run_cli(args):
args = ['-T', 'none'] + list(args)
runner = click.testing.CliRunner()
result = runner.invoke(riemann_client.command.main, args)
assert result.exit_c... | mit | Python |
17c2fd2fad08336c2d526956a7e1b27a0d6d24f6 | transform tests verbose | dajusc/trimesh,mikedh/trimesh,dajusc/trimesh,mikedh/trimesh,mikedh/trimesh,mikedh/trimesh | tests/test_transformations.py | tests/test_transformations.py | import generic as g
class TransformTest(g.unittest.TestCase):
def test_doctest(self):
'''
Run doctests on transformations, which checks docstrings for
interactive sessions and then verifies they execute correctly.
This is how the upstream transformations unit tests.
'''
... | import generic as g
class TransformTest(g.unittest.TestCase):
def test_doctest(self):
'''
Run doctests on transformations, which checks docstrings for
interactive sessions and then verifies they execute correctly.
This is how the upstream transformations unit tests.
'''
... | mit | Python |
9f331d18867911ef831120ac0afdcd8ea5c962aa | complete xmlextract.py | joeryan/web-data | xml-extract/xmlextract.py | xml-extract/xmlextract.py | # simple script to take a url from stdin, read XML using urllib, parse using
# ElementTree, and sum up the numbers in count tags
# Joe Ryan, 11/23/2015
# completed as part of UofM class "Using Python to access Web Data" on coursera
import urllib
import xml.etree.ElementTree as ET
dataurl = raw_input("Enter URL of XML... | # simple script to take a url from stdin, read XML using urllib, parse using
# ElementTree, and sum up the numbers in comments
# Joe Ryan, 11/23/2015
# completed as part of UofM class "Using Python to access Web Data" on coursera
import urllib
import xml.etree.ElementTree as ET
| mit | Python |
feeb561abc865f5a7fdb77cbf008a182021a09b4 | Update decode-ways.py | yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,kamyu104/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015... | Python/decode-ways.py | Python/decode-ways.py | # Time: O(n)
# Space: O(1)
#
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
#
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given an encoded message containing digits, determine the total number of ways to decode it.
#
# For example,
# Given encoded message "12", it coul... | # Time: O(n)
# Space: O(1)
#
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
#
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given an encoded message containing digits, determine the total number of ways to decode it.
#
# For example,
# Given encoded message "12", it coul... | mit | Python |
1055782c77bca1ec5a0a5f9f1250533c7295c7c1 | Update 02-02_cleanse.py | mrkowalski/kaggle_santander | scikit/src/nosql/02-02_cleanse.py | scikit/src/nosql/02-02_cleanse.py |
import commons, sys, os
import logging as log
import pandas as pd
import xgboost as xgb
import numpy as np
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matr... |
import commons, sys, os
import logging as log
import pandas as pd
import xgboost as xgb
import numpy as np
from sklearn.externals import joblib
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matr... | mit | Python |
2729c30d8ac0ce32a22aae549c07dc2db1c03fa1 | Add RATE_LIMIT to make_a_plea.settings.docker | ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas | make_a_plea/settings/docker.py | make_a_plea/settings/docker.py | from .base import *
import os
DEBUG = os.environ.get("DJANGO_DEBUG", "") == "True"
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('POSTGRES_DB', ''),
'USER': os.environ.get('DB_USERNAME', ''),
'PASSWORD'... | from .base import *
import os
DEBUG = os.environ.get("DJANGO_DEBUG", "") == "True"
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('POSTGRES_DB', ''),
'USER': os.environ.get('DB_USERNAME', ''),
'PASSWORD'... | mit | Python |
f19e389c5614099ad25ffa3069b05ccbfff0d284 | add this | cloudify-incubator/cloudify-utilities-plugin,cloudify-incubator/cloudify-utilities-plugin | .circleci/test_examples.py | .circleci/test_examples.py | ########
# Copyright (c) 2014-2019 Cloudify Platform Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | ########
# Copyright (c) 2014-2019 Cloudify Platform Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | apache-2.0 | Python |
3b4be3996f5706a56c83086f597ff6d8d02680d0 | fix flake8 | lovato/machete,lovato/machete,lovato/machete | machete/templates/_base/packagesample/__init__.py | machete/templates/_base/packagesample/__init__.py | # -*- coding: UTF-8 -*-
# pep8: disable-msg=E501
# pylint: disable=C0301
import os
import logging
import getpass
import tempfile
__version__ = '{{ packagesample.version }}'
__author__ = 'Your Name'
__author_username__ = 'your_username'
__author_email__ = 'yourname@gmail.com'
__description__ = 'Generated from a templat... | # -*- coding: UTF-8 -*-
# pep8: disable-msg=E501
# pylint: disable=C0301
import os
import logging
import getpass
import tempfile
__version__ = '{{ packagesample.version }}'
__author__ = 'Your Name'
__author_username__ = 'your_username'
__author_email__ = 'yourname@gmail.com'
__description__ = 'Generated from a templat... | mit | Python |
0876c4aa04f910bae0effcc40657c0da1308c639 | Create a session token on password update in case none is persisted for the user (this means session token database records are incomplete, but let's recover from that this way) | m-ober/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | byceps/services/authentication/password/service.py | byceps/services/authentication/password/service.py | # -*- coding: utf-8 -*-
"""
byceps.services.authentication.password.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from werkzeug.security import check_password_hash as _check_passwo... | # -*- coding: utf-8 -*-
"""
byceps.services.authentication.password.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from werkzeug.security import check_password_hash as _check_passwo... | bsd-3-clause | Python |
70c636feea84b96af306fb2c01448c1d696f44a8 | Fix shtest-output-printing.py on Windows by matching either / or \\ | GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen... | utils/lit/tests/shtest-output-printing.py | utils/lit/tests/shtest-output-printing.py | # Check the various features of the ShTest format.
#
# RUN: not %{lit} -j 1 -v %{inputs}/shtest-output-printing > %t.out
# RUN: FileCheck --input-file %t.out %s
#
# END.
# CHECK: -- Testing:
# CHECK: FAIL: shtest-output-printing :: basic.txt
# CHECK-NEXT: *** TEST 'shtest-output-printing :: basic.txt' FAILED ***
# CH... | # Check the various features of the ShTest format.
#
# PR33938
# XFAIL: windows
#
# RUN: not %{lit} -j 1 -v %{inputs}/shtest-output-printing > %t.out
# RUN: FileCheck --input-file %t.out %s
#
# END.
# CHECK: -- Testing:
# CHECK: FAIL: shtest-output-printing :: basic.txt
# CHECK-NEXT: *** TEST 'shtest-output-printing ... | apache-2.0 | Python |
e30afc4c01f18904973abd9f86a28823e3bc0dd7 | add exception type | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/unit/fileclient_test.py | tests/unit/fileclient_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email: `Bo Maryniuk <bo@suse.de>`
'''
# Import Python libs
from __future__ import absolute_import
import errno
from mock import Mock
try:
ERRIO = errno.EREMOTEIO
except AttributeError:
ERRIO = errno.EIO
# Import Salt Testing libs
from salttesting import TestCase
... | # -*- coding: utf-8 -*-
'''
:codeauthor: :email: `Bo Maryniuk <bo@suse.de>`
'''
# Import Python libs
from __future__ import absolute_import
import errno
from mock import Mock
try:
ERRIO = errno.EREMOTEIO
except:
ERRIO = errno.EIO
# Import Salt Testing libs
from salttesting import TestCase
from salttestin... | apache-2.0 | Python |
2e2d697f57482db8eb562bc4ba1c63c271f4818d | Update base_vae.py | probml/pyprobml,probml/pyprobml,probml/pyprobml,probml/pyprobml | scripts/vae/models/base_vae.py | scripts/vae/models/base_vae.py | import torch
from torch import nn
from typing import Callable
class VAE(nn.Module):
"""
Standard VAE with Gaussian Prior and approx posterior.
"""
def __init__(
self,
name: str,
loss: Callable,
encoder: Callable,
decoder: Callable,
**kwargs
):
... | import torch
from torch import nn
from typing import Callable
class VAE(nn.Module):
"""
Standard VAE with Gaussian Prior and approx posterior.
"""
def __init__(
self,
loss: Callable,
encoder: Callable,
decoder: Callable,
**kwargs
):
super(VAE, self)... | mit | Python |
f69bc50985a644f90c3f59d06cb7b99a6aeb3b53 | Move data back before dropping the column for downgrade | alphagov/notifications-api,alphagov/notifications-api | migrations/versions/0209_email_branding_update.py | migrations/versions/0209_email_branding_update.py | """
Revision ID: 0209_email_branding_update
Revises: 84c3b6eb16b3
Create Date: 2018-07-25 16:08:15.713656
"""
from alembic import op
import sqlalchemy as sa
revision = '0209_email_branding_update'
down_revision = '84c3b6eb16b3'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
o... | """
Revision ID: 0209_email_branding_update
Revises: 84c3b6eb16b3
Create Date: 2018-07-25 16:08:15.713656
"""
from alembic import op
import sqlalchemy as sa
revision = '0209_email_branding_update'
down_revision = '84c3b6eb16b3'
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
o... | mit | Python |
675c46eb16ec0457031b9f6086736bd2956398b7 | Add comments | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode | serfnode/build/handler/serf.py | serfnode/build/handler/serf.py | import json
import subprocess
import sys
import info
import utils
def serf(*args):
"""Call serf with output in json format"""
args = list(args)
rpc_port = info.NODE_INFO['rpc_port']
args[1:1] = ['-rpc-addr', '127.0.0.1:{}'.format(rpc_port)]
cmd = ['serf'] + args + ['-format=json']
return jso... | import json
import subprocess
import sys
import info
import utils
def serf(*args):
args = list(args)
rpc_port = info.NODE_INFO['rpc_port']
args[1:1] = ['-rpc-addr', '127.0.0.1:{}'.format(rpc_port)]
cmd = ['serf'] + args + ['-format=json']
return json.loads(subprocess.check_output(cmd))
serf_jso... | mit | Python |
c2c9359d466e545799aebaa2b6c6e353f5f5c833 | Fix destdir_join | mesonbuild/meson,mesonbuild/meson,pexip/meson,pexip/meson,mesonbuild/meson,pexip/meson,mesonbuild/meson,mesonbuild/meson,mesonbuild/meson,mesonbuild/meson,pexip/meson,pexip/meson,mesonbuild/meson,pexip/meson,mesonbuild/meson,mesonbuild/meson,pexip/meson,pexip/meson,pexip/meson,pexip/meson | mesonbuild/scripts/__init__.py | mesonbuild/scripts/__init__.py | # Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | # Copyright 2016 The Meson development team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to ... | apache-2.0 | Python |
a97c6ebda62762501fdf5f18326c8c518d73635f | Use @dachary's much clearer regex to validate codenames | micahflee/securedrop,conorsch/securedrop,garrettr/securedrop,heartsucker/securedrop,conorsch/securedrop,heartsucker/securedrop,conorsch/securedrop,ehartsuyker/securedrop,micahflee/securedrop,garrettr/securedrop,ehartsuyker/securedrop,garrettr/securedrop,garrettr/securedrop,micahflee/securedrop,ehartsuyker/securedrop,co... | securedrop/source_app/forms.py | securedrop/source_app/forms.py | from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import PasswordField
from wtforms.validators import InputRequired, Regexp, Length
from db import Source
class LoginForm(FlaskForm):
codename = PasswordField('codename', validators=[
InputRequired(message=gettext('This field is r... | from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import PasswordField
from wtforms.validators import InputRequired, Regexp, Length
from db import Source
class LoginForm(FlaskForm):
codename = PasswordField('codename', validators=[
InputRequired(message=gettext('This field is r... | agpl-3.0 | Python |
342c5bae6adfeb4ba4020d345fedbe1e903539cd | modify build_native_module | glizer/nw.js,advisory/nw.js,advisory/nw.js,angeliaz/nw.js,GabrielNicolasAvellaneda/nw.js,p5150j/nw.js,lidxgz/nw.js,artBrown/nw.js,AustinKwang/nw.js,Sunggil/nw.js,fancycode/node-webkit,eprincev-egor/nw.js,pztrick/nw.js,280455936/nw.js,initialjk/node-webkit,RobertoMalatesta/nw.js,jqk6/nw.js,mvinan/nw.js,ysjian/nw.js,Womb... | tools/build_native_modules.py | tools/build_native_modules.py | #!/usr/bin/env python
import os, re, sys
import subprocess
native_modules = ['nw_test_loop_without_handle',
'bignum',
];
script_dir = os.path.dirname(__file__)
native_root = os.path.join(script_dir, os.pardir, 'tests', 'node_modules')
native_root = os.path.normpath(native_root)
nat... | #!/usr/bin/env python
import os, re, sys
import subprocess
native_modules = ['nw_test_loop_without_handle',
'bignum',
];
script_dir = os.path.dirname(__file__)
native_root = os.path.join(script_dir, os.pardir, 'tests', 'node_modules')
native_root = os.path.normpath(native_root)
nat... | mit | Python |
9ff9b994bcf852b700527a1ebe42176b817a24e2 | Fix only_in_release_mode.py's subcommand paths on Windows. | dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dartin... | tools/only_in_release_mode.py | tools/only_in_release_mode.py | #!/usr/bin/env python
#
# Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Wrapper around a build action that should only be executed in release mode.
T... | #!/usr/bin/env python
#
# Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Wrapper around a build action that should only be executed in release mode.
T... | bsd-3-clause | Python |
fbe5a5e4a734b40f83d842105b5bf6652d73c197 | remove trailing spaces in script | est31/godot,godotengine/godot,iap-mutant/godot,Paulloz/godot,vnen/godot,josempans/godot,JoshuaGrams/godot,ex/godot,exabon/godot,zicklag/godot,opmana/godot,huziyizero/godot,Brickcaster/godot,RandomShaper/godot,ex/godot,iap-mutant/godot,agusbena/godot,mcanders/godot,Max-Might/godot,DmitriySalnikov/godot,Zylann/godot,tomr... | tools/translations/extract.py | tools/translations/extract.py | #!/bin/python
import fnmatch
import os
import re
matches = []
for root, dirnames, filenames in os.walk('.'):
for filename in fnmatch.filter(filenames, '*.cpp'):
if (filename.find("collada")!=-1):
continue
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.h'):
if (fil... | #!/bin/python
import fnmatch
import os
import re
matches = []
for root, dirnames, filenames in os.walk('.'):
for filename in fnmatch.filter(filenames, '*.cpp'):
if (filename.find("collada")!=-1):
continue
matches.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.h'):
if (fil... | mit | Python |
8355731aa4dfbda14220217e3de59186513b05bc | fix internal server error on partial urls | deathping1994/treeherder,deathping1994/treeherder,wlach/treeherder,avih/treeherder,gbrmachado/treeherder,kapy2010/treeherder,gbrmachado/treeherder,deathping1994/treeherder,parkouss/treeherder,moijes12/treeherder,KWierso/treeherder,vaishalitekale/treeherder,vaishalitekale/treeherder,sylvestre/treeherder,moijes12/treeher... | treeherder/webapp/api/urls.py | treeherder/webapp/api/urls.py | from django.conf.urls import patterns, include, url
from treeherder.webapp.api import (refdata, objectstore, jobs, resultset,
artifact, note, revision, bug)
from rest_framework import routers
# router for views that are bound to a project
# i.e. all those views that don't involve re... | from django.conf.urls import patterns, include, url
from treeherder.webapp.api import (refdata, objectstore, jobs, resultset,
artifact, note, revision, bug)
from rest_framework import routers
# router for views that are bound to a project
# i.e. all those views that don't involve re... | mpl-2.0 | Python |
5488ecdda1fa4323b1e3187f93d3871222eea327 | update logging04.py | devlights/try-python | trypython/stdlib/logging04.py | trypython/stdlib/logging04.py | """
logging モジュールのサンプルです。
最も基本的な使い方について (日付書式の指定)
"""
import logging
from trypython.common.commoncls import SampleBase
class Sample(SampleBase):
def exec(self):
"""サンプルの処理を実行します。"""
# -----------------------------------------------------------------------------------
# logging モジュールは、pyth... | """
logging モジュールのサンプルです。
最も基本的な使い方について (日付書式の指定)
""" | mit | Python |
1d1d50769b23d041e58492ddcef3c20c4374d4bf | fix migration | c3nav/c3nav,c3nav/c3nav,c3nav/c3nav,c3nav/c3nav | src/c3nav/mapdata/migrations/0060_accesspermissiontoken_id.py | src/c3nav/mapdata/migrations/0060_accesspermissiontoken_id.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-18 13:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
def remove_all_tokens(apps, schema_editor):
apps.get_model('mapdata', 'AccessPermissionToken').objects.all().delet... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-12-18 13:49
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
def remove_all_tokens(apps, schema_editor):
apps.get_model('mapdata', 'AccessPermissionToken').objects.all().delet... | apache-2.0 | Python |
52a3ab97f888734db3c602ac69a33660e6026bb6 | Remove linked list class and implement algorithm just using single method | derekmpham/interview-prep,derekmpham/interview-prep | linked-list/remove-k-from-list.py | linked-list/remove-k-from-list.py | # Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def remove_k_from_list(l, k):
fake_head = Node(None)
fake_head.next = l
current_node = fake_head
while ... | # Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def add(... | mit | Python |
6ddd46ccc0377c1f44c869ffda79e9eb72daea78 | make it work with extjs6 (i.e. without extensible) | lino-framework/avanti,lino-framework/avanti | lino_avanti/lib/avanti/layouts.py | lino_avanti/lib/avanti/layouts.py | # -*- coding: UTF-8 -*-
# Copyright 2017 Luc Saffre
"""The default :attr:`custom_layouts_module
<lino.core.site.Site.custom_layouts_module>` for Lino Avanti.
"""
from lino.api import dd, rt, _
rt.actors.system.SiteConfigs.detail_layout = dd.DetailLayout("""
site_company next_partner_id:10
default_build_method simul... | # -*- coding: UTF-8 -*-
# Copyright 2017 Luc Saffre
"""The default :attr:`custom_layouts_module
<lino.core.site.Site.custom_layouts_module>` for Lino Avanti.
"""
from lino.api import dd, rt, _
rt.actors.system.SiteConfigs.detail_layout = dd.DetailLayout("""
site_company next_partner_id:10
default_build_method simul... | bsd-2-clause | Python |
d0a39a60a4bc54f323f329ee483430a7c968e0ab | Add a simple test for basic view code | nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi,nickgzzjr/simplecoin_multi | simplecoin/tests/test_views.py | simplecoin/tests/test_views.py | import datetime
from simplecoin import db, cache
from simplecoin.scheduler import leaderboard
from simplecoin.utils import anon_users
from simplecoin.tests import RedisUnitTest, UnitTest
import simplecoin.models as m
class TestViewsRedis(RedisUnitTest):
def test_basic_not_500(self):
for view in ['/',
... | import datetime
from simplecoin import db, cache
from simplecoin.scheduler import leaderboard
from simplecoin.utils import anon_users
from simplecoin.tests import RedisUnitTest, UnitTest
import simplecoin.models as m
class TestViewsRedis(RedisUnitTest):
def test_leaderboard_anon(self):
s = m.UserSettings... | mit | Python |
34cd9a0468d698e4b97c3c0ad7bd61c07616d397 | Add main function | ma8ma/yanico | yanico/command/__init__.py | yanico/command/__init__.py | """Command entry point."""
# Copyright 2015 Masayuki Yamamoto
#
# 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 a... | """Command entry point."""
# Copyright 2015 Masayuki Yamamoto
#
# 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 a... | apache-2.0 | Python |
2de6cc79c027ca32de8187faa96054e48253e0d7 | Cover case where register tracking is disabled in puti | iamahuman/angr,chubbymaggie/simuvex,axt/angr,angr/angr,f-prettyland/angr,schieb/angr,axt/angr,schieb/angr,f-prettyland/angr,angr/simuvex,schieb/angr,tyb0807/angr,chubbymaggie/simuvex,tyb0807/angr,f-prettyland/angr,chubbymaggie/angr,iamahuman/angr,chubbymaggie/angr,axt/angr,chubbymaggie/angr,angr/angr,tyb0807/angr,angr/... | simuvex/vex/statements/puti.py | simuvex/vex/statements/puti.py | from . import SimIRStmt
from .. import size_bytes
from ... import s_options as o
from ...s_action_object import SimActionObject
from ...s_action import SimActionData
from ...s_variable import SimRegisterVariable
class SimIRStmt_PutI(SimIRStmt):
def _execute(self):
#pylint:disable=attribute-defined-outside-... | from . import SimIRStmt
from .. import size_bytes
from ... import s_options as o
from ...s_action_object import SimActionObject
from ...s_action import SimActionData
from ...s_variable import SimRegisterVariable
class SimIRStmt_PutI(SimIRStmt):
def _execute(self):
#pylint:disable=attribute-defined-outside-... | bsd-2-clause | Python |
6ffdeee13b61cda6352ab5af628bce1b1c01748d | fix text color doc | guiniol/py3status,docwalter/py3status,alexoneill/py3status,valdur55/py3status,Andrwe/py3status,valdur55/py3status,ultrabug/py3status,guiniol/py3status,tobes/py3status,vvoland/py3status,ultrabug/py3status,Andrwe/py3status,ultrabug/py3status,valdur55/py3status,tobes/py3status | py3status/modules/backlight.py | py3status/modules/backlight.py | # -*- coding: utf-8 -*-
"""
Display the current screen backlight level.
Configuration parameters:
cache_timeout: how often we refresh this module in seconds (default: 10s)
device: The backlight device (default: "acpi_video0")
If you are unsure try: `ls /sys/class/backlight`
color: The text col... | # -*- coding: utf-8 -*-
"""
Display the current screen backlight level.
Configuration parameters:
cache_timeout: how often we refresh this module in seconds (default: 10s)
device: The backlight device (default: "acpi_video0")
If you are unsure try: `ls /sys/class/backlight`
Format status string pa... | bsd-3-clause | Python |
d16c419fee029f54248d562c54af8e89400ab9c5 | upgrade milk | jackytu/newbrandx,jackytu/newbrandx,jackytu/newbrandx,jackytu/newbrandx,jackytu/newbrandx,jackytu/newbrandx | sites/newbrandx/rankx/views.py | sites/newbrandx/rankx/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import Milk
from .models import Brand
from .models import Company
def rankx(request):
#return HttpResponse("Hello, world. You're at the polls index.")
return render(request, 'rankx/rankx.html')
def milk(request):
context... | from django.shortcuts import render
from django.http import HttpResponse
from .models import Milk
from .models import Brand
from .models import Company
def rankx(request):
#return HttpResponse("Hello, world. You're at the polls index.")
return render(request, 'rankx/rankx.html')
def milk(request):
context... | bsd-3-clause | Python |
bdfa468b4d60f326d6744b9a4766c228e8b1d692 | Use a different default port | nelhage/taktician,nelhage/taktician,nelhage/taktician,nelhage/taktician | python/tak/alphazero/config.py | python/tak/alphazero/config.py | from attrs import define, field
from tak import mcts
import torch
from typing import Optional
@define(slots=False)
class Config:
device: str = "cuda"
server_port: int = 5432
lr: float = 1e-3
size: int = 3
rollout_config: mcts.Config = field(
factory=lambda: mcts.Config(
simu... | from attrs import define, field
from tak import mcts
import torch
from typing import Optional
@define(slots=False)
class Config:
device: str = "cuda"
server_port: int = 5001
lr: float = 1e-3
size: int = 3
rollout_config: mcts.Config = field(
factory=lambda: mcts.Config(
simu... | mit | Python |
e08428105460b208e151dd83f242e843ddae200c | update import code | finch2kt/Pyhtonian | python/tests/Pythonian_test.py | python/tests/Pythonian_test.py | import pytest
from Pythonian import Calculate
from Pythonian import addArray
#import somefile
#from somefile import *
#from somefile import className
def test_it_is_callable():
assert callable(Calculate)
assert callable(addArray)
test = [5, 5, 5, 5, 5]
def test_size5_with_5_5_5_5_5_input():
as... | import pytest
import Caculate
#import use actual file name
from Pythonian import *
from Pythonian import Calculate
from Pythonian import addArray
#import somefile
#from somefile import *
#from somefile import className
def test_it_is_callable():
assert callable(Calculate)
assert callable(addArray)
... | mit | Python |
3e1ce45dc6b9f718e8234b40ad6b7cba4cd7d2bb | remove git merge issues | bordeltabernacle/python_koans,bordeltabernacle/python_koans | python3/koans/about_asserts.py | python3/koans/about_asserts.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutAsserts(Koan):
def test_assert_truth(self):
"""
We shall contemplate truth by testing reality, via asserts.
"""
# Confused? This video should help:
#
# http://bit.ly/about_assert... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutAsserts(Koan):
def test_assert_truth(self):
"""
We shall contemplate truth by testing reality, via asserts.
"""
# Confused? This video should help:
#
# http://bit.ly/about_assert... | mit | Python |
c92dfdf239151d5a17db7eeb7871c846829e7d40 | Use absolute imports | wkerzendorf/wsynphot | wsynphot/io/tests/test_get_filter_data.py | wsynphot/io/tests/test_get_filter_data.py | import pytest
from wsynphot.io import get_filter_data as gfd
def test_get_filter_index():
table = gfd.get_filter_index()
# Check if column for Filter ID (named 'filterID') exists in table
assert 'filterID' in table.to_table().colnames
@pytest.mark.parametrize(('test_filter_id'),
... | import pytest
from .. import get_filter_data as gfd
def test_get_filter_index():
table = gfd.get_filter_index()
# Check if column for Filter ID (named 'filterID') exists in table
assert 'filterID' in table.to_table().colnames
@pytest.mark.parametrize(('test_filter_id'),
['HST/NIC... | bsd-3-clause | Python |
5dd48acb2f56de72187ae1d47ccd404eb244202c | Add new answer to #2 | dawran6/project-euler | 2-even-fibonacci-numbers.py | 2-even-fibonacci-numbers.py | from utils import fibonacci_gen
import itertools
import timeit
def fib_gen(num=10000):
n_minus_2 = 0
n_minus_1 = 1
for i in range(num):
n = n_minus_2 + n_minus_1
yield n
n_minus_2 = n_minus_1
n_minus_1 = n
def solve_1():
fibs = fib_gen()
even_fibs = (n for n in fibs... | def fib_gen(num=10000):
n_minus_2 = 0
n_minus_1 = 1
for i in range(num):
n = n_minus_2 + n_minus_1
yield n
n_minus_2 = n_minus_1
n_minus_1 = n
if __name__ == '__main__':
fibs = fib_gen()
even_fibs = (n for n in fibs if n % 2 == 0)
small_even_fibs = filter(lambda ... | mit | Python |
375eb5cdd2a815ea6f2946c023293b367d223909 | Change field of archive in image form. | opps/opps,YACOWS/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,williamroot/opps,opps/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps | opps/images/forms.py | opps/images/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from opps.core.widgets import OppsEditor
from .models import Image
from .widgets import CropExample
class ImageModelForm(forms.ModelForm):
crop_example = forms.CharField(label=_('Crop E... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Image
from .widgets import CropExample
from opps.core.widgets import OppsEditor
class ImageModelForm(forms.ModelForm):
crop_example = forms.CharField(label=_('Crop E... | mit | Python |
dcfa1fdcea8d272c185a16025615c7c74b222b86 | rewrite IcsError to show message at backend | lielongxingkong/ics_demo,lielongxingkong/ics_demo | ics_demo/helpers/exc.py | ics_demo/helpers/exc.py | import tornado.web
class IcsError(tornado.web.HTTPError):
"""
Unknown ics error
"""
def __init__(self, status_code):
super(tornado.web.HTTPError, self).__init__(status_code, log_message=self.message, reason=self.message)
def __str__(self):
return self.message
class NotFoundError(I... | import tornado.web
class IcsError(tornado.web.HTTPError):
"""
Unknown ics error
"""
def __init__(self, status_code, message):
super(tornado.web.HTTPError, self).__init__(status_code, log_message=message, reason=message)
def __str__(self):
doc = self.__doc__.strip()
return '... | mit | Python |
2e1d16cfbd39fcb7dc71003918443f52e94fc796 | Fix failing functionality | masschallenge/django-accelerator,masschallenge/django-accelerator | accelerator/migrations/0074_update_url_to_community.py | accelerator/migrations/0074_update_url_to_community.py | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
from itertools import chain
def update_url_to_community(apps, schema_editor):
people_url = ["/people", "/people/"]
mentor_url = "/directory"
community_url = "/community"
mentor... | # Generated by Django 2.2.10 on 2021-11-05 12:29
from django.db import migrations
from django.db.models.query_utils import Q
def update_url_to_community(apps, schema_editor):
people_url = ["/people", "/people/"]
mentor_url = "/directory"
community_url = "/community"
mentor_refinement_url = """/direct... | mit | Python |
9dbfad571b2287cd61b2ad2d4cedf115616342bb | Comment cleanup and spacing | mattsmart/biomodels,mattsmart/biomodels,mattsmart/biomodels | agent_based_models/abm_conjugation_simple/plot_data.py | agent_based_models/abm_conjugation_simple/plot_data.py | import matplotlib.pyplot as plt
# note:
# dict keys are iters, time, E, R, D
def data_plotter(grid_dict, datafile_dir, plot_dir):
N = grid_dict['E'][0] + grid_dict['R'][0] + grid_dict['D'][0]
n = int(N**0.5)
plt.figure(1)
plt.plot(grid_dict['time'], grid_dict['E'], label='Empty grid cells')
plt... | import matplotlib.pyplot as plt
# note dict keys are: iters, time, E, R, D
def data_plotter(grid_dict, datafile_dir, plot_dir):
N = grid_dict['E'][0] + grid_dict['R'][0] + grid_dict['D'][0]
n = int(N**0.5)
plt.figure(1)
plt.plot(grid_dict['time'],grid_dict['E'],label='Empty grid cells')
plt.plo... | mit | Python |
ec0b7b868e70e0d2eab13fe236b7f82958f51402 | Add getFirstName() to MockAvatar | DirkHoffmann/indico,mvidalgarcia/indico,ThiefMaster/indico,mvidalgarcia/indico,mvidalgarcia/indico,indico/indico,mic4ael/indico,DirkHoffmann/indico,pferreir/indico,ThiefMaster/indico,mic4ael/indico,indico/indico,OmeGak/indico,indico/indico,indico/indico,pferreir/indico,mic4ael/indico,OmeGak/indico,mvidalgarcia/indico,D... | indico/testing/mocks.py | indico/testing/mocks.py | ## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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... | ## This file is part of Indico.
## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN).
##
## Indico 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... | mit | Python |
77c4b1326a9c805fb88c85afd132fabd2f562bee | fix whitespace | guykisel/inline-plz,guykisel/inline-plz,guykisel/inline-plz | inlineplz/env/travis.py | inlineplz/env/travis.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from inlineplz.env.base import EnvBase
# https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
class Travis(EnvBase):
def __init__(self):
self.pull_request = os.environ.get('TRAVIS_PULL_REQUEST')
... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from inlineplz.env.base import EnvBase
# https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
class Travis(EnvBase):
def __init__(self):
self.pull_request = os.environ.get('TRAVIS_PULL_REQUEST')
... | isc | Python |
ae2a9d5c7813bc59e2b81054bb39e60b1bcb7fea | Add CAN_DETECT info | Asnelchristian/coala-bears,Vamshi99/coala-bears,kaustubhhiware/coala-bears,gs0510/coala-bears,damngamerz/coala-bears,arjunsinghy96/coala-bears,ankit01ojha/coala-bears,SanketDG/coala-bears,aptrishu/coala-bears,dosarudaniel/coala-bears,coala/coala-bears,dosarudaniel/coala-bears,arjunsinghy96/coala-bears,dosarudaniel/coal... | bears/c_languages/codeclone_detection/ClangCloneDetectionBear.py | bears/c_languages/codeclone_detection/ClangCloneDetectionBear.py | from bears.c_languages.ClangBear import clang_available, ClangBear
from bears.c_languages.codeclone_detection.ClangFunctionDifferenceBear import (
ClangFunctionDifferenceBear)
from coalib.bears.GlobalBear import GlobalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SE... | from bears.c_languages.ClangBear import clang_available, ClangBear
from bears.c_languages.codeclone_detection.ClangFunctionDifferenceBear import (
ClangFunctionDifferenceBear)
from coalib.bears.GlobalBear import GlobalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SE... | agpl-3.0 | Python |
9dafa4632ce8575fe558b2295091b1ed1252f27f | fix norm sync bug (#6852) | open-mmlab/mmdetection,open-mmlab/mmdetection | mmdet/core/hook/sync_norm_hook.py | mmdet/core/hook/sync_norm_hook.py | # Copyright (c) OpenMMLab. All rights reserved.
from collections import OrderedDict
from mmcv.runner import get_dist_info
from mmcv.runner.hooks import HOOKS, Hook
from torch import nn
from ..utils.dist_utils import all_reduce_dict
def get_norm_states(module):
async_norm_states = OrderedDict()
for name, chi... | # Copyright (c) OpenMMLab. All rights reserved.
from collections import OrderedDict
from mmcv.runner import get_dist_info
from mmcv.runner.hooks import HOOKS, Hook
from torch import nn
from ..utils.dist_utils import all_reduce_dict
def get_norm_states(module):
async_norm_states = OrderedDict()
for name, chi... | apache-2.0 | Python |
270517f5416e462915bc5423dd3f8dfb8e79457b | simplify grid search | reinvantveer/Topology-Learning,reinvantveer/Topology-Learning,reinvantveer/Topology-Learning | model/neighborhood_grid_search.py | model/neighborhood_grid_search.py | import os
from sklearn.model_selection import ParameterGrid
from topoml_util.slack_send import notify
SCRIPT_VERSION = '0.0.4'
HYPERPARAMS = {
'BATCH_SIZE': [16],
'REPEAT_DEEP_ARCH': [1],
'LSTM_SIZE': [64, 128],
'DENSE_SIZE': [32],
'EPOCHS': [20],
'LEARNING_RATE': [1e-4]
}
grid = list(Paramete... | import os
from sklearn.model_selection import ParameterGrid
from topoml_util.slack_send import notify
SCRIPT_VERSION = '0.0.4'
HYPERPARAMS = {
'BATCH_SIZE': [8, 16],
'REPEAT_DEEP_ARCH': [0, 1],
'LSTM_SIZE': [64, 128],
'DENSE_SIZE': [16, 64],
'EPOCHS': [20],
'LEARNING_RATE': [1e-4, 3e-4, 1e-3]
... | mit | Python |
629ac2f66c231e506065d7ab1c6d8a24ea6c51ac | refactor of getSpec... call | samdmarshall/xcparse,samdmarshall/xcparse,samdmarshall/xcparse,samdmarshall/xcparse,samdmarshall/xcparse | PBX/PBXSourcesBuildPhase.py | PBX/PBXSourcesBuildPhase.py | from __future__ import absolute_import
import Cocoa
import Foundation
import os
from .PBXResolver import *
from .PBX_Base_Phase import *
class PBXSourcesBuildPhase(PBX_Base_Phase):
# buildActionMask = 0;
# files = [];
# runOnlyForDeploymentPostprocessing = 0;
def __init__(self, lookup_func, dicti... | from __future__ import absolute_import
import Cocoa
import Foundation
import os
from .PBXResolver import *
from .PBX_Base_Phase import *
class PBXSourcesBuildPhase(PBX_Base_Phase):
# buildActionMask = 0;
# files = [];
# runOnlyForDeploymentPostprocessing = 0;
def __init__(self, lookup_func, dicti... | bsd-3-clause | Python |
02f23e818b8591985e7610c82e3afd6c56449a24 | reduce filesize of fake pngs | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets | tensorflow_datasets/testing/fake_data_utils.py | tensorflow_datasets/testing/fake_data_utils.py | # coding=utf-8
# Copyright 2019 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | # coding=utf-8
# Copyright 2019 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | apache-2.0 | Python |
0a4b09df26cea71cd02e79c8e6e6e915ec35b2f4 | Disable event delete cascade behavior when removing a space | ppapadeas/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents,yvan-sraka/wprevents,ppapadeas/wprevents,yvan-sraka/wprevents | mozcal/events/models.py | mozcal/events/models.py | from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from uuslug import uuslug as slugify
class FunctionalArea(models.Model):
name = models.CharField(max_length=120)
def __unicode__(self):
return self.name
class Space(models.Model):
name = models.CharFie... | from datetime import datetime
from django.contrib.auth.models import User
from django.db import models
from uuslug import uuslug as slugify
class FunctionalArea(models.Model):
name = models.CharField(max_length=120)
def __unicode__(self):
return self.name
class Space(models.Model):
name = models.CharFie... | bsd-3-clause | Python |
cad2233c6e9a443e134e1e2a70f568163ad6b73b | Fix logistic regression example | tshadley/examples,adamlerer/examples,bmccann/examples,BestSonny/examples,tshadley/examples,adamlerer/examples,chuckbasstan123/pyTorch_project,edgarriba/examples | logreg/main.py | logreg/main.py | #!/usr/bin/env python
"""
Logistic regression example
Trains a single fully-connected layer to learn a quadratic function.
"""
from __future__ import print_function
import torch
import torch.autograd
import torch.nn
WEIGHTS = torch.randn(2, 1) * 5
BIAS = torch.randn(1) * 5
def get_features(xs):
return torch.F... | #!/usr/bin/env python
"""
Logistic regression example
Trains a single fully-connected layer to learn a quadratic function.
"""
from __future__ import print_function
import torch
import torch.autograd
import torch.nn
WEIGHTS = torch.randn(2, 1) * 5
BIAS = torch.randn(1) * 5
def get_features(xs):
return torch.F... | bsd-3-clause | Python |
a1e0dad2884e6d5174c99357d3060e79c2b01a6b | Switch to next development version | goldmann/dogen,goldmann/dogen,goldmann/dogen,jboss-container-images/concreate,jboss-container-images/concreate,jboss-container-images/concreate | dogen/version.py | dogen/version.py | version = "2.4.0rc1.dev"
| version = "2.3.0"
| mit | Python |
38a35805637ca0e5f63af2717ea79d67219cb5d6 | remove csrf_exempt import | safwanrahman/readthedocs.org,soulshake/readthedocs.org,wanghaven/readthedocs.org,clarkperkins/readthedocs.org,davidfischer/readthedocs.org,cgourlay/readthedocs.org,stevepiercy/readthedocs.org,istresearch/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,sils1297/readthedocs.org,asampat3090/readthedoc... | readthedocs/bookmarks/views.py | readthedocs/bookmarks/views.py | import simplejson
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic import ListView
from django.core.urlresolvers import reverse
from django.template import Re... | import simplejson
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic import ListView
from django.core.urlresolvers import reverse
from django.template import Re... | mit | Python |
1d2cabd421f244998cf8258db8c79d69980d2594 | Fix missing param when setting up MaryTTS and how it validates a connection | forslund/mycroft-core,Dark5ide/mycroft-core,Dark5ide/mycroft-core,MycroftAI/mycroft-core,forslund/mycroft-core,MycroftAI/mycroft-core | mycroft/tts/mary_tts.py | mycroft/tts/mary_tts.py | # Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | # Copyright 2017 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | apache-2.0 | Python |
1238b23b8c9b825e4ee335c0cb7397bcdfa44516 | Add simplecsv.Reader class Rename simplecsv.CSV to Writer | limbera/django-nap,MarkusH/django-nap | nap/extras/simplecsv.py | nap/extras/simplecsv.py |
import re
try:
import chardet
except ImportError:
chardet = None
class Writer(object):
'''
A generator friendly, unicode aware CSV encoder class built for speed.
'''
# What to put between fields
SEP = u','
# What to wrap fields in, if they contain SEP
QUOTE = u'"'
# What to r... |
class CSV(object):
'''
A generator friendly, unicode aware CSV encoder class built for speed.
'''
# What to put between fields
SEP = u','
# What to wrap fields in, if they contain SEP
QUOTE = u'"'
# What to replace a QUOTE in a field with
ESCQUOTE = QUOTE + QUOTE
# What to put ... | bsd-3-clause | Python |
03d07a20928997ecc136884110311453217443c3 | Add PageBegin to pkg exports | makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile,makinacorpus/reportlab-ecomobile | reportlab/platypus/__init__.py | reportlab/platypus/__init__.py | #copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.13 2002/03/15 09:03:37 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.13 2002/03/15... | #copyright ReportLab Inc. 2000
#see license.txt for license details
#history http://cvs.sourceforge.net/cgi-bin/cvsweb.cgi/reportlab/platypus/__init__.py?cvsroot=reportlab
#$Header: /tmp/reportlab/reportlab/platypus/__init__.py,v 1.12 2000/11/29 17:28:50 rgbecker Exp $
__version__=''' $Id: __init__.py,v 1.12 2000/11/29... | bsd-3-clause | Python |
3fc9e076ca88675a2af9c8953333eae08a094adf | add team player | jaebradley/nba_data | nba_data/data/player.py | nba_data/data/player.py | from nba_data.data.base_query_parameter import BaseQueryParameter
from nba_data.data.team import Team
class Player(BaseQueryParameter):
def __init__(self, name, id):
self.name = name
self.id = id
def __unicode__(self):
return '{0} | {1}'.format(self.get_additional_unicode(), self.get_... | from nba_data.data.base_query_parameter import BaseQueryParameter
from nba_data.data.team import Team
class Player(BaseQueryParameter):
def __init__(self, name, id):
self.name = name
self.id = id
def __unicode__(self):
return 'name: {0} | id: {1}'.format(self.name, self.id)
@stat... | mit | Python |
726bab4db0ae08d1d4b684d19cd1b83e6daa02b0 | Update ndlibTest.py | GiulioRossetti/ndlib | ndlib_test/ndlibTest.py | ndlib_test/ndlibTest.py | import unittest
import networkx as nx
import sys
sys.path.append("..")
import ndlib.VoterModel as vm
import ndlib.SznajdModel as sm
import ndlib.MajorityRuleModel as mrm
import ndlib.QVoterModel as qvm
import CognitiveOpDynModel as cm
__author__ = 'rossetti'
__license__ = "GPL"
__email__ = "giulio.rossetti@gmail.com"
... | import unittest
import networkx as nx
import sys
sys.path.append("..")
import ndlib.VoterModel as vm
import ndlib.SznajdModel as sm
import ndlib.MajorityRuleModel as mrm
import ndlib.QVoterModel as qvm
import CognitiveOpDynModel as cm
__author__ = 'rossetti'
__license__ = "GPL"
__email__ = "giulio.rossetti@gmail.com"
... | bsd-2-clause | Python |
d1707c28077340b48ef446a42627c94a6cbceef7 | Reduce worker task frequency. | MSPARP/newparp,MSPARP/newparp,MSPARP/newparp | newparp/tasks/config.py | newparp/tasks/config.py | import os
from datetime import timedelta
from kombu import Exchange, Queue
# Debug
if "DEBUG" in os.environ:
CELERY_REDIRECT_STDOUTS_LEVEL = "DEBUG"
# Broker and Result backends
BROKER_URL = os.environ.get("CELERY_BROKER", "redis://localhost/1")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT", "redis://lo... | import os
from datetime import timedelta
from kombu import Exchange, Queue
# Debug
if "DEBUG" in os.environ:
CELERY_REDIRECT_STDOUTS_LEVEL = "DEBUG"
# Broker and Result backends
BROKER_URL = os.environ.get("CELERY_BROKER", "redis://localhost/1")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT", "redis://lo... | agpl-3.0 | Python |
4905951bc2829dbd90ae28b8c31520e48a834279 | Update conf_base.py | sdpython/python3_module_template | _doc/sphinxdoc/source/conf_base.py | _doc/sphinxdoc/source/conf_base.py | import sphinx_gallery
import sphinx_rtd_theme
from pyquickhelper.helpgen.default_conf import set_sphinx_variables, get_default_stylesheet
try:
import python3_module_template
except ModuleNotFoundError:
raise ModuleNotFoundError("Cannot import python3_module_template\n{}".format(
"\n".join(sys.path)))
... | import sphinx_gallery
import sphinx_rtd_theme
from pyquickhelper.helpgen.default_conf import set_sphinx_variables, get_default_stylesheet
import python3_module_template
set_sphinx_variables(__file__, "python3_module_template", "sdpython", 2019,
"sphinx_rtd_theme", [
sphin... | mit | Python |
f678f5c1a197c504ae6703f3b4e5658f9e2db1f6 | Remove spurious reference to self. Remove debugging code. | pypa/setuptools,pypa/setuptools,pypa/setuptools | setuptools/tests/py26compat.py | setuptools/tests/py26compat.py | import sys
import unittest
import tarfile
try:
# provide skipIf for Python 2.4-2.6
skipIf = unittest.skipIf
except AttributeError:
def skipIf(condition, reason):
def skipper(func):
def skip(*args, **kwargs):
return
if condition:
return skip
return func
return skipper
def _tarfile_open_ex(*args... | import sys
import unittest
import tarfile
try:
# provide skipIf for Python 2.4-2.6
skipIf = unittest.skipIf
except AttributeError:
def skipIf(condition, reason):
def skipper(func):
def skip(*args, **kwargs):
return
if condition:
return skip
return func
return skipper
def _tarfile_open_ex(*args... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.