commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
dea1d0d957cdfc07a561b42125f49d0c1e1c4da6 | bingmaps/urlschema/location_by_point_schema.py | bingmaps/urlschema/location_by_point_schema.py | from .location_schema import Location
from marshmallow import Schema, fields, post_dump
from .location_api_url import LocationUrl
class LocationByPointQueryString(Schema):
point = fields.Str()
includeEntityTypes = fields.Str()
includeNeighborhood = fields.Int(
default=1
)
include = fields.... | from .location_schema import Location
from marshmallow import Schema, fields, post_dump
from .location_api_url import LocationUrl
class LocationByPointQueryString(Schema):
point = fields.Str()
includeEntityTypes = fields.Str()
includeNeighborhood = fields.Int(
default=0
)
include = fields.... | Change includeNeighborhood default value to 0 | Change includeNeighborhood default value to 0
| Python | mit | bharadwajyarlagadda/bingmaps | ---
+++
@@ -7,7 +7,7 @@
point = fields.Str()
includeEntityTypes = fields.Str()
includeNeighborhood = fields.Int(
- default=1
+ default=0
)
include = fields.Str(
default='ciso2' |
3816063967e03bc7b0cd3b7c95e74291ced04138 | tools/hash_funcs.py | tools/hash_funcs.py | """
A collection of utilities to see if new ReST files need to be automatically
generated from certain files in the project (examples, datasets).
"""
def get_hash(f):
"""
Gets hexadmecimal md5 hash of a string
"""
import hashlib
m = hashlib.md5()
m.update(f)
return m.hexdigest()
def update... | """
A collection of utilities to see if new ReST files need to be automatically
generated from certain files in the project (examples, datasets).
"""
import os
import pickle
file_path = os.path.dirname(__file__)
def get_hash(f):
"""
Gets hexadmecimal md5 hash of a string
"""
import hashlib
m = has... | Fix directory in hash funcs. | ENH: Fix directory in hash funcs.
| Python | bsd-3-clause | musically-ut/statsmodels,bavardage/statsmodels,nguyentu1602/statsmodels,kiyoto/statsmodels,detrout/debian-statsmodels,adammenges/statsmodels,kiyoto/statsmodels,adammenges/statsmodels,edhuckle/statsmodels,edhuckle/statsmodels,yarikoptic/pystatsmodels,kiyoto/statsmodels,rgommers/statsmodels,jstoxrocky/statsmodels,wayneni... | ---
+++
@@ -2,6 +2,10 @@
A collection of utilities to see if new ReST files need to be automatically
generated from certain files in the project (examples, datasets).
"""
+import os
+import pickle
+
+file_path = os.path.dirname(__file__)
def get_hash(f):
"""
@@ -17,12 +21,12 @@
Opens the pickled hash ... |
10b977303008ee59a5f5c39ccf0156222a5a58c5 | test_run.py | test_run.py | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 10.], [0.01, 1.5, 10]... | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 15:23:58 2015
@author: jensv
"""
import skin_core_scanner_simple as scss
reload(scss)
import equil_solver as es
reload(es)
import newcomb_simple as new
reload(new)
(lambda_a_mesh, k_a_mesh,
stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25]... | Increase lambda-k space to better differentiate bottlenecks from startup cost. | Increase lambda-k space to better differentiate bottlenecks from startup cost.
| Python | mit | jensv/fluxtubestability,jensv/fluxtubestability | ---
+++
@@ -13,7 +13,7 @@
reload(new)
(lambda_a_mesh, k_a_mesh,
- stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 10.], [0.01, 1.5, 10],
+ stability_maps) = scss.scan_lambda_k_space([0.01, 3.0, 25.], [0.01, 1.5, 25],
epsilon=0.11, core_radius_norm=0.9,
... |
d0791ccd79dea2ec30d890ad9060f58d1e8b1c7c | run_tests.py | run_tests.py | import pytest
from bs4 import BeautifulSoup as BS
pytest.main(['--durations', '10', '--cov-report', 'html'])
url = r'htmlcov/index.html'
page = open(url)
soup = BS(page.read(), features='html5lib')
aggregate_total = soup.find_all('tr', {'class': 'total'})
final = None
for x in aggregate_total:
pct = x.text.repl... | import pytest
from bs4 import BeautifulSoup as BS
pytest.main(['--durations', '10', '--cov-report', 'html', '--junit-xml', 'test-reports/results.xml', '--verbose'])
url = r'htmlcov/index.html'
page = open(url)
soup = BS(page.read(), features='html5lib')
aggregate_total = soup.find_all('tr', {'class': 'total'})
final... | Update test file - add flag for reports | Update test file - add flag for reports
| Python | mit | misachi/job_match,misachi/job_match,misachi/job_match | ---
+++
@@ -1,7 +1,7 @@
import pytest
from bs4 import BeautifulSoup as BS
-pytest.main(['--durations', '10', '--cov-report', 'html'])
+pytest.main(['--durations', '10', '--cov-report', 'html', '--junit-xml', 'test-reports/results.xml', '--verbose'])
url = r'htmlcov/index.html'
page = open(url)
soup = BS(page.r... |
9e4dc6763fbd0de0f17b4acaa8109a12cdff28d6 | orderedmodel/models.py | orderedmodel/models.py | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModelManager(models.Manager):
def swap(self, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
... | from django.db import models
from django.core.exceptions import ValidationError
class OrderedModelManager(models.Manager):
def swap(self, obj1, obj2):
tmp, obj2.order = obj2.order, 0
obj2.save(swapping=True)
obj2.order, obj1.order = obj1.order, tmp
obj1.save()
obj2.save()
... | Add fix_ordering method to OrderedModelManager | Add fix_ordering method to OrderedModelManager
| Python | bsd-3-clause | MagicSolutions/django-orderedmodel,MagicSolutions/django-orderedmodel | ---
+++
@@ -15,6 +15,15 @@
return self.order_by('-order').values_list('order', flat=True)[0]
except IndexError:
return 0
+
+ def fix_ordering(self):
+ """
+ This method must be executed only if this application is
+ added to existing project.
+ """
+ ... |
36065d77de34d0c8a0fc7443f01c2d9c8d63e0c4 | konstrukteur/__init__.py | konstrukteur/__init__.py | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
"""
**Konstrukteur - Static website generator**
Konstrukteur is a website generator that uses a template and content files
to create static website output.
"""
__version__ = "0.1.13"
__author__ = "Sebastian Fastner <mail@sebastianfastne... | #
# Konstrukteur - Static website generator
# Copyright 2013 Sebastian Fastner
#
"""
**Konstrukteur - Static website generator**
Konstrukteur is a website generator that uses a template and content files
to create static website output.
"""
__version__ = "0.1.14"
__author__ = "Sebastian Fastner <mail@sebastianfastne... | Change to new version number | Change to new version number
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur | ---
+++
@@ -10,7 +10,7 @@
to create static website output.
"""
-__version__ = "0.1.13"
+__version__ = "0.1.14"
__author__ = "Sebastian Fastner <mail@sebastianfastner.de>"
def info(): |
0ba57c8b908b5feb58af731c7b1c62a41ae84d8d | familyconnect_registration/testsettings.py | familyconnect_registration/testsettings.py | from familyconnect_registration.settings import * # flake8: noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_ALWAYS_... | from familyconnect_registration.settings import * # flake8: noqa
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'TESTSEKRET'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
CELERY_EAGER_PROPAGATES_EXCEPTIONS = True
CELERY_ALWAYS_... | Test run speedup by changing password hasher | Test run speedup by changing password hasher
| Python | bsd-3-clause | praekelt/familyconnect-registration,praekelt/familyconnect-registration | ---
+++
@@ -12,3 +12,7 @@
CELERY_ALWAYS_EAGER = True
BROKER_BACKEND = 'memory'
CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend'
+
+PASSWORD_HASHERS = (
+ 'django.contrib.auth.hashers.MD5PasswordHasher',
+) |
5978eedb3147bc0f124335d9e408d6c4895de3a7 | __init__.py | __init__.py | import os
import sys
import marshal
if sys.hexversion < 0x03030000:
raise ImportError('python >= 3.3 required')
if sys.implementation.cache_tag is None:
raise ImportError('python implementation does not use bytecode')
PY_TAG = sys.implementation.cache_tag
PY_VERSION = sys.hexversion
BUNDLE_DIR = os.p... | import os
import sys
import marshal
if not hasattr(sys, 'implementation'):
raise ImportError('python >= 3.3 required')
if sys.implementation.cache_tag is None:
raise ImportError('python implementation does not use bytecode')
PY_TAG = sys.implementation.cache_tag
PY_VERSION = sys.hexversion
BUNDLE_DIR ... | Use a different way of ensuring 3.3+. | Use a different way of ensuring 3.3+.
| Python | mit | pyos/dg | ---
+++
@@ -3,7 +3,7 @@
import marshal
-if sys.hexversion < 0x03030000:
+if not hasattr(sys, 'implementation'):
raise ImportError('python >= 3.3 required')
if sys.implementation.cache_tag is None: |
4b7065426447fb27322b81b283616c9242af41b9 | python_hospital_info_sys/com/pyhis/gui/main.py | python_hospital_info_sys/com/pyhis/gui/main.py | '''
Created on Jan 15, 2017
@author: Marlon_2
'''
import tkinter as tk # import
from tkinter import ttk # impork ttk from tkinter
win = tk.Tk(); # create instance
#add a title
win.title("Python Hospital Information System");
#add a label
#ttk.Label(win, text="Welcome to Python Hospital Informa... | '''
Created on Jan 15, 2017
@author: Marlon_2
'''
import tkinter as tk # import
from tkinter import ttk # impork ttk from tkinter
win = tk.Tk(); # create instance
#add a title
win.title("Python Hospital Information System");
#add a label
#ttk.Label(win, text="Welcome to Python Hospital Informa... | Stop experimenting on this project for the moment | Stop experimenting on this project for the moment | Python | mit | martianworm17/py_his | ---
+++
@@ -20,6 +20,14 @@
def clickMe():
action.configure(text="** I have been clicked **")
aLabel.configure(foreground='red',background='yellow')
+# action = ttk.Button(win, command=clickMeReset)
+# action.grid(column=0, row=1);
+
+def clickMeReset():
+ action.configure(text="** Click Me! ... |
7b15a9b510bce6a3866c0d3d7cd78c0c477cb69d | transformations/pig_latin/transformation.py | transformations/pig_latin/transformation.py | import piglatin
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class PigLatin(SentenceOperation):
tasks = [
TaskType.TEXT_CLASSIFICATION,
TaskType.TEXT_TO_TEXT_GENERATION,
TaskType.TEXT_TAGGING,
]
languages = ["en"]
def __init__... | import piglatin
import random
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
class PigLatin(SentenceOperation):
tasks = [
TaskType.TEXT_CLASSIFICATION,
TaskType.TEXT_TO_TEXT_GENERATION,
TaskType.TEXT_TAGGING,
]
languages = ["en"]
... | Add per-word replace probability, max outputs. | Add per-word replace probability, max outputs.
| Python | mit | GEM-benchmark/NL-Augmenter | ---
+++
@@ -1,4 +1,5 @@
import piglatin
+import random
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
@@ -11,13 +12,20 @@
]
languages = ["en"]
- def __init__(self, seed=0, max_outputs=1):
+ def __init__(self, seed=0, max_outputs=1, replace_prob=1... |
0f71f39a8634927b532c3f5b258720761f1d9c5c | mentorup/users/models.py | mentorup/users/models.py | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags fo... | # -*- coding: utf-8 -*-
# Import chosenforms for pretty search forms
from chosen import forms as chosenforms
# Import the AbstractUser model
from django.contrib.auth.models import AbstractUser
# Import the basic Django ORM models and forms library
from django.db import models
from django import forms
# Import tags fo... | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation | Create UserManager to ensure ForeignKey relation is saved and associated with User upon creation
| Python | bsd-3-clause | briandant/mentor_up,briandant/mentor_up,briandant/mentor_up,briandant/mentor_up | ---
+++
@@ -22,12 +22,24 @@
class LearnSkills(models.Model):
skills = TaggableManager()
+class UserManager(models.Manager):
+ def create(self, name):
+ new_user = Food()
+ new_user.name = name
+ new_user.teach = TeachSkills()
+ new_user.teach.save()
+ new_user.learn = Lea... |
23f95f0319c929006c89efdf0d113370a1a003b4 | moa/factory_registers.py | moa/factory_registers.py | from kivy.factory import Factory
r = Factory.register
r('MoaStage', module='moa.stage.base')
r('StageRender', module='moa.stage.base')
r('Delay', module='moa.stage.delay')
r('TreeRender', module='moa.render.treerender')
r('TreeRenderExt', module='moa.render.treerender')
r('StageTreeNode', module='moa.render.treerender... | from kivy.factory import Factory
r = Factory.register
r('MoaStage', module='moa.stage')
r('Delay', module='moa.stage.delay')
r('GateStage', module='moa.stage.gate')
r('StageRender', module='moa.stage.base')
r('TreeRender', module='moa.render.treerender')
r('TreeRenderExt', module='moa.render.treerender')
r('StageTree... | Update factory registers with stages. | Update factory registers with stages.
| Python | mit | matham/moa | ---
+++
@@ -1,9 +1,11 @@
from kivy.factory import Factory
r = Factory.register
-r('MoaStage', module='moa.stage.base')
+r('MoaStage', module='moa.stage')
+r('Delay', module='moa.stage.delay')
+r('GateStage', module='moa.stage.gate')
+
r('StageRender', module='moa.stage.base')
-r('Delay', module='moa.stage.delay'... |
67f5b1796d2595a5b3fa8449ca7badaf27510ded | test_passwd_change.py | test_passwd_change.py | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 't... | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 't... | Add MIT LICENSE. Fix test dir removing issue - re-raise exception after delete this dir. | Add MIT LICENSE. Fix test dir removing issue - re-raise exception after delete this dir.
| Python | mit | maxsocl/oldmailer | ---
+++
@@ -14,19 +14,22 @@
"""
subprocess.call(['mkdir', 'test'])
subprocess.call(['touch', 'test/rvv', 'test/max',
- 'test/mail'])
+ 'test/bdv' ,'test/mail'])
#TODO create passwd test file
#TODO create shadow test file
... |
b1bf5dfa91f1f7b84512f72d6e5e18c2109f3239 | addic7ed/__init__.py | addic7ed/__init__.py | from termcolor import colored
from .parser import Addic7edParser
from .file_crawler import FileCrawler
from .logger import init_logger
from .config import Config
def addic7ed():
try:
init_logger()
Config.load()
main()
except (EOFError, KeyboardInterrupt, SystemExit):
print(col... | from termcolor import colored
from .parser import Addic7edParser
from .file_crawler import FileCrawler
from .logger import init_logger
from .config import Config
def addic7ed():
try:
init_logger()
Config.load()
main()
except (EOFError, KeyboardInterrupt, SystemExit):
print(col... | Fix newline output of downloaded srt | Fix newline output of downloaded srt
| Python | mit | Jesus-21/addic7ed | ---
+++
@@ -46,12 +46,12 @@
if Config.rename != "sub":
filename = subs[int(version)].download()
if filename and Config.rename == "video":
- print(ep.rename(filename), end="\n\n")
+ print(ep.rename(filename))
... |
7b9ee45c0791d8368a0bb8af52652d3fcd482c79 | qubesadmin/__init__.py | qubesadmin/__init__.py | # -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Li... | # -*- encoding: utf8 -*-
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki
# <marmarek@invisiblethingslab.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public Li... | Choose QubesLocal or QubesRemote based on /etc/qubes-release presence | Choose QubesLocal or QubesRemote based on /etc/qubes-release presence
Do not check for qubesd socket (at module import time), because if not
running at this precise time, it will lead to wrong choice. And a weird
error message in consequence (looking for qrexec-client-vm in dom0).
Fixes QubesOS/qubes-issues#2917
| Python | lgpl-2.1 | marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client,marmarek/qubes-core-mgmt-client | ---
+++
@@ -28,7 +28,7 @@
DEFAULT = qubesadmin.base.DEFAULT
-if os.path.exists(qubesadmin.config.QUBESD_SOCKET):
+if os.path.exists('/etc/qubes-release'):
Qubes = qubesadmin.app.QubesLocal
else:
Qubes = qubesadmin.app.QubesRemote |
9daac0977933238929eda5e05c635e3a626cbe21 | tests/test_example.py | tests/test_example.py | import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
... | import os
import unittest
import object_storage_tensorflow as obj_tf
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_spli... | Add intelligent skip for missing secret info | Add intelligent skip for missing secret info
| Python | apache-2.0 | marshallford/ndsu-ibm-capstone,marshallford/ndsu-ibm-capstone | ---
+++
@@ -1,4 +1,6 @@
+import os
import unittest
+
import object_storage_tensorflow as obj_tf
@@ -21,6 +23,8 @@
class TestS3Connection(unittest.TestCase):
+ @unittest.skipUnless(os.environ.get("TRAVIS_PULL_REQUEST") == 'false',
+ "S3 tests will fail for Pull Requests due to lack of secrets.")
... |
cb03101afdd337f2840d3a439f4452c1083e09ff | utils/strings.py | utils/strings.py | # coding=utf-8
import string
from numbers import Number
__author__ = 'Gareth Coles'
FILENAME_SAFE_CHARS = (
"/\\-_.()#" +
string.digits +
string.letters +
string.whitespace
)
class EmptyStringFormatter(string.Formatter):
"""
EmptyStringFormatter - The same as the normal string formatter, exc... | # coding=utf-8
import string
from numbers import Number
__author__ = 'Gareth Coles'
FILENAME_SAFE_CHARS = (
"/\\-_.()#:" +
string.digits +
string.letters +
string.whitespace
)
class EmptyStringFormatter(string.Formatter):
"""
EmptyStringFormatter - The same as the normal string formatter, ex... | Allow colons in filenames for now | [Utils] Allow colons in filenames for now
| Python | artistic-2.0 | UltrosBot/Ultros,UltrosBot/Ultros | ---
+++
@@ -5,7 +5,7 @@
__author__ = 'Gareth Coles'
FILENAME_SAFE_CHARS = (
- "/\\-_.()#" +
+ "/\\-_.()#:" +
string.digits +
string.letters +
string.whitespace |
e689a09c7c6d20a7e6bbc5b81b864d1bdd406295 | src/setup.py | src/setup.py | #! /usr/bin/python
import os
import setuptools
import sys
# FIXME explain why this is here
sys.path.insert(0,
os.path.join(
os.path.dirname(__file__),
"lib",
))
import opensub
setuptools.setup(
author="Bence Romsics",
author_email="rubasov+opensub@gmail.com",
classifiers=[
... | #! /usr/bin/python
import os
import setuptools
import sys
# FIXME explain why this is here
sys.path.insert(0,
os.path.join(
os.path.dirname(__file__),
"lib",
))
import opensub
setuptools.setup(
author="Bence Romsics",
author_email="rubasov+opensub@gmail.com",
classifiers=[
... | Set package URL to where it'll be uploaded. | Set package URL to where it'll be uploaded.
| Python | bsd-2-clause | rubasov/opensub-utils,rubasov/opensub-utils | ---
+++
@@ -46,7 +46,7 @@
tests_require=[
"nose",
],
- url="http://github.com/rubasov/...", # FIXME
+ url="https://github.com/rubasov/opensub-utils",
version=opensub.__version__,
zip_safe=False,
) |
1a3ffe00bfdf8c61b4ff190beb2ee6a4e9db1412 | behave_django/environment.py | behave_django/environment.py | from django.core.management import call_command
from django.shortcuts import resolve_url
from behave_django.testcase import BehaveDjangoTestCase
def before_scenario(context, scenario):
# This is probably a hacky method of setting up the test case
# outside of a test runner. Suggestions are welcome. :)
c... | from django.core.management import call_command
try:
from django.shortcuts import resolve_url
except ImportError:
import warnings
warnings.warn("URL path supported only in get_url() with Django < 1.5")
resolve_url = lambda to, *args, **kwargs: to
from behave_django.testcase import BehaveDjangoTestCase
... | Support Django < 1.5 with a simplified version of `get_url()` | Support Django < 1.5 with a simplified version of `get_url()`
| Python | mit | nikolas/behave-django,nikolas/behave-django,behave/behave-django,bittner/behave-django,bittner/behave-django,behave/behave-django | ---
+++
@@ -1,5 +1,10 @@
from django.core.management import call_command
-from django.shortcuts import resolve_url
+try:
+ from django.shortcuts import resolve_url
+except ImportError:
+ import warnings
+ warnings.warn("URL path supported only in get_url() with Django < 1.5")
+ resolve_url = lambda to, *... |
005c6ceae1b80f5092e78231242b01af2ba64fed | tests/integration/api/conftest.py | tests/integration/api/conftest.py | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... | """
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
API-specific fixtures
"""
import pytest
from tests.base import create_admin_app
from tests.conftest import CONFIG_PATH_DATA_KEY
from .helpers import assemble_authorization_header
API_TOKEN = 'just-say-PLEASE!'
@pytes... | Use `make_admin_app`, document why `admin_app` is still needed | Use `make_admin_app`, document why `admin_app` is still needed
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -17,13 +17,13 @@
@pytest.fixture(scope='session')
-def app(admin_app, data_path):
+# `admin_app` fixture is required because it sets up the database.
+def app(admin_app, make_admin_app):
config_overrides = {
'API_TOKEN': API_TOKEN,
- CONFIG_PATH_DATA_KEY: data_path,
'SERV... |
8c4cdc174b502610943507d4e7ffee96ad9d611a | us_ignite/snippets/tests/models_tests.py | us_ignite/snippets/tests/models_tests.py | from nose.tools import eq_, ok_
from django.test import TestCase
from us_ignite.snippets.models import Snippet
class TestSnippetModel(TestCase):
def tearDown(self):
Snippet.objects.all().delete()
def get_instance(self):
data = {
'name': 'Gigabit snippets',
'slug': '... | from nose.tools import eq_, ok_
from django.test import TestCase
from us_ignite.snippets.models import Snippet
class TestSnippetModel(TestCase):
def tearDown(self):
Snippet.objects.all().delete()
def get_instance(self):
data = {
'name': 'Gigabit snippets',
'slug': '... | Fix Snippet failing test, ``image`` field is blank. | Fix Snippet failing test, ``image`` field is blank.
| Python | bsd-3-clause | us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite | ---
+++
@@ -25,7 +25,7 @@
eq_(instance.url, 'http://us-ignite.org/')
eq_(instance.url_text, '')
eq_(instance.body, '')
- eq_(instance.image, 'ad.png')
+ eq_(instance.image, '')
eq_(instance.is_featured, False)
ok_(instance.created)
ok_(instance.modif... |
7b14e846f08f69601372266ed82f91ba5bd306f6 | devito/core/__init__.py | devito/core/__init__.py | """
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
... | """
The ``core`` Devito backend is simply a "shadow" of the ``base`` backend,
common to all other backends. The ``core`` backend (and therefore the ``base``
backend as well) are used to run Devito on standard CPU architectures.
"""
from devito.dle import (BasicRewriter, AdvancedRewriter, AdvancedRewriterSafeMath,
... | Change autotuning 'none' to 'off' | core: Change autotuning 'none' to 'off'
| Python | mit | opesci/devito,opesci/devito | ---
+++
@@ -9,7 +9,7 @@
from devito.parameters import Parameters, add_sub_configuration
core_configuration = Parameters('core')
-core_configuration.add('autotuning', 'basic', ['none', 'basic', 'aggressive'])
+core_configuration.add('autotuning', 'basic', ['off', 'basic', 'aggressive'])
env_vars_mapper = {
... |
91f9ea76a1a48cf9e191b4f97818c105428bbbd6 | util/test_graph.py | util/test_graph.py | import urllib2
token = 'test_token'
channel = 'test_channel'
graphtype = 'test'
url = 'http://{}/ocpgraph/{}/{}/{}/'.format('localhost:8000', token, channel, graphtype)
try:
req = urllib2.Request(url)
resposne = urllib2.urlopen(req)
except Exception, e:
raise
| # Copyright 2014 Open Connectome Project (http://openconnecto.me)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... | Test file for Graph code | [util] Test file for Graph code
| Python | apache-2.0 | neurodata/ndstore,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,openconnectome/open-connectome,neurodata/ndstore,neurodata/ndstore,neurodata/ndstore | ---
+++
@@ -1,3 +1,17 @@
+# Copyright 2014 Open Connectome Project (http://openconnecto.me)
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICE... |
c4818066de3b428678fb03c70dcaa028227e0c00 | scripts/launch_app.py | scripts/launch_app.py | #! /usr/bin/env python3
"""Launch the flask-forecaster application."""
import logging
import sys
logging.basicConfig(
datefmt='%Y/%m/%d %H.%M.%S',
format='%(levelname)s:%(name)s:%(message)s',
level=logging.INFO,
stream=sys.stdout,
)
logger = logging.getLogger('launch_app')
if __name__ == '__main__'... | #! /usr/bin/env python3
"""Launch the flask-forecaster application."""
import logging
import sys
logging.basicConfig(
datefmt='%Y/%m/%d %H.%M.%S',
format='%(levelname)s:%(name)s:%(message)s',
level=logging.DEBUG,
stream=sys.stdout,
)
logger = logging.getLogger('launch_app')
if __name__ == '__main__... | Set global logging level to DEBUG | Set global logging level to DEBUG
| Python | isc | textbook/flask-forecaster,textbook/flask-forecaster | ---
+++
@@ -8,7 +8,7 @@
logging.basicConfig(
datefmt='%Y/%m/%d %H.%M.%S',
format='%(levelname)s:%(name)s:%(message)s',
- level=logging.INFO,
+ level=logging.DEBUG,
stream=sys.stdout,
)
|
e5b42db249dd94a0d7652881a8bba8ed78772d3e | examples/turnAndMove.py | examples/turnAndMove.py | import slither, pygame
snakey = slither.Sprite()
snakey.setCostumeByName("costume0")
snakey.goto(0, 0)
slither.slitherStage.setColor(40, 222, 40)
slither.setup() # Begin slither
def handlequit():
print("Quitting...")
return True
slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call ... | import slither, pygame
snakey = slither.Sprite()
snakey.setCostumeByName("costume0")
snakey.goto(0, 0)
slither.setup() # Begin slither
def handlequit():
print("Quitting...")
return True
slither.registerCallback(pygame.QUIT, handlequit) # This uses the direct call form
@slither.registerCallback(pygame.MOUSE... | Fix small test problem\nBTW rotation works now, thanks @BookOwl | Fix small test problem\nBTW rotation works now, thanks @BookOwl
| Python | mit | PySlither/Slither,PySlither/Slither | ---
+++
@@ -4,8 +4,6 @@
snakey.setCostumeByName("costume0")
snakey.goto(0, 0)
-
-slither.slitherStage.setColor(40, 222, 40)
slither.setup() # Begin slither
|
3ae63e055146ecb45b6943e661808b0546b42273 | tests/test_playsong/test_query.py | tests/test_playsong/test_query.py | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function, unicode_literals
import nose.tools as nose
from tests.utils import run_filter
def test_ignore_case():
"""should ignore case when querying songs"""
results = run_filter('playsong', 'mr Blue SKY')
nose.assert_equal(results[0]['ti... | #!/usr/bin/env python
# coding=utf-8
from __future__ import print_function, unicode_literals
import nose.tools as nose
from tests.utils import run_filter
def test_ignore_case():
"""should ignore case when querying songs"""
results = run_filter('playsong', 'mr Blue SKY')
nose.assert_equal(results[0]['ti... | Add extra description to partial match playsong test | Add extra description to partial match playsong test
| Python | mit | caleb531/play-song,caleb531/play-song | ---
+++
@@ -15,6 +15,6 @@
def test_partial():
- """should match partial queries"""
+ """should match partial queries when querying songs"""
results = run_filter('playsong', 'blue sky')
nose.assert_equal(results[0]['title'], 'Mr. Blue Sky') |
d0f092afc9534d25b5ebf81ff329ad296e30952e | numpy/distutils/setup.py | numpy/distutils/setup.py | #!/usr/bin/env python
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='',top_path=None):
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
confi... | #!/usr/bin/env python
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
def configuration(parent_package='',top_path=None):
config = Configuration('distutils',parent_package,top_path)
config.add_subpackage('command')
config.add_subpackage('fcompiler')
confi... | Add site.cfg to datafiles installed for numpy.distutils. | Add site.cfg to datafiles installed for numpy.distutils.
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2011 94b884b6-d6fd-0310-90d3-974f1d3f35e1
| Python | bsd-3-clause | teoliphant/numpy-refactor,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,teoliphant/numpy-refactor,Ademan/NumPy-GSoC,illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,illume/numpy3k,illume/numpy3k,jasonmccampbell/numpy-refactor-spr... | ---
+++
@@ -7,6 +7,7 @@
config.add_subpackage('command')
config.add_subpackage('fcompiler')
config.add_data_dir('tests')
+ config.add_data_files('site.cfg')
config.make_config_py()
return config.todict()
|
a2572d38eeaa7c004142a194b18fd6fdfff99f9a | test/test_translate.py | test/test_translate.py | from Bio import SeqIO
import logging
import unittest
from select_taxa import select_genomes_by_ids
import translate
class Test(unittest.TestCase):
def setUp(self):
self.longMessage = True
logging.root.setLevel(logging.DEBUG)
def test_translate_genomes(self):
# Select genomes
... | from Bio import SeqIO
import logging
import unittest
from select_taxa import select_genomes_by_ids
import translate
class Test(unittest.TestCase):
def setUp(self):
self.longMessage = True
logging.root.setLevel(logging.DEBUG)
def test_translate_genomes(self):
# Select genomes
... | Verify no header appears twice when translating 93125.2 | Verify no header appears twice when translating 93125.2 | Python | mit | ODoSE/odose.nl | ---
+++
@@ -25,3 +25,18 @@
self.assertEqual(first_header, first.id)
first = next(SeqIO.parse(aafiles[0], 'fasta'))
self.assertEqual(first_header, first.id)
+
+ # Verify no header appears twice
+ headers = [record.id for record in SeqIO.parse(aafiles[0], 'fasta')]
+ self... |
9cadf855a4506e29009a910206c6ce213279aafe | tests/test_configuration.py | tests/test_configuration.py | # -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_v... | # -*- coding: utf-8 -*-
"""
test_configuration
~~~~~~~~~~~~~~~~~~
Basic configuration tests
"""
import base64
import pytest
from utils import authenticate, logout
@pytest.mark.settings(
logout_url='/custom_logout',
login_url='/custom_login',
post_login_view='/post_login',
post_logout_v... | Adjust POST_LOGIN_VIEW and POST_LOGOUT_VIEW test | Adjust POST_LOGIN_VIEW and POST_LOGOUT_VIEW test
| Python | mit | tatataufik/flask-security,quokkaproject/flask-security,wjt/flask-security,mik3cap/private-flask-security,dlakata/flask-security,jonafato/flask-security,nfvs/flask-security,themylogin/flask-security,CodeSolid/flask-security,GregoryVigoTorres/flask-security,inveniosoftware/flask-security-fork,fuhrysteve/flask-security,Sa... | ---
+++
@@ -23,11 +23,13 @@
response = client.get('/custom_login')
assert b"<h1>Login</h1>" in response.data
- response = authenticate(client, endpoint='/custom_login', follow_redirects=True)
- assert b'Post Login' in response.data
+ response = authenticate(client, endpoint='/custom_login')
+ ... |
52bfbea4e2cb17268349b61c7f00b9253755e74d | example/books/models.py | example/books/models.py | from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_abs... | from __future__ import unicode_literals
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_l... | Add support for django 2 to example project | Add support for django 2 to example project
| Python | mit | spapas/django-generic-scaffold,spapas/django-generic-scaffold | ---
+++
@@ -1,6 +1,10 @@
from __future__ import unicode_literals
-from django.core.urlresolvers import reverse
+try:
+ from django.core.urlresolvers import reverse
+except ModuleNotFoundError:
+ from django.urls import reverse
+
from django.db import models
import generic_scaffold
@@ -11,3 +15,6 @@
... |
50d9c1494c5f14ccc7cb7fa32979e11e19ee1eb8 | utils/etc.py | utils/etc.py | def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
def default_channel(member):
return next((channel for channel in memb... | def reverse_insort(seq, val, lo=0, hi=None):
if hi is None:
hi = len(seq)
while lo < hi:
mid = (lo + hi) // 2
if val > seq[mid]:
hi = mid
else:
lo = mid + 1
seq.insert(lo, val)
def default_channel(member):
return next((channel for channel in memb... | Change default channel to send_messages | Change default channel to send_messages
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot | ---
+++
@@ -12,4 +12,4 @@
def default_channel(member):
return next((channel for channel in member.guild.text_channels
- if channel.permissions_for(member).read_messages), None)
+ if channel.permissions_for(member).send_messages), None) |
97811dc9b81d84ae1c074be00ebea1dac8c7f2fc | signac/gui/__init__.py | signac/gui/__init__.py | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and d... | # Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and d... | Make package more robust against PySide import errors. | Make package more robust against PySide import errors.
A bad PySide install may lead to exceptions other than
ImportErrors on import. In this case any attempt to
import the package will fail, even when the GUI is
not even used.
Any error occuring during the attempted import of the PySide
package will now be logged to... | Python | bsd-3-clause | csadorf/signac,csadorf/signac | ---
+++
@@ -12,14 +12,16 @@
try:
import PySide # noqa
import pymongo # noqa
-except ImportError as error:
- logger.debug("{}. The signac gui is not available.".format(error))
+except Exception as error:
+ msg = 'The signac gui is not available, because of an error: "{}".'
+ logger.debug(msg.form... |
e9c83d59fbb5b341e2126039109e306875db0490 | syweb/__init__.py | syweb/__init__.py | import os
with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| import os
def installed_location():
return __file__
with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip()
| Add an 'installed_location()' function so syweb can report its own location | Add an 'installed_location()' function so syweb can report its own location
| Python | apache-2.0 | williamboman/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,williamboman/matrix-angular-sdk,matrix-org/matrix-angular-sdk,matrix-org/matrix-angular-sdk | ---
+++
@@ -1,4 +1,7 @@
import os
-with open(os.path.join(os.path.dirname(__file__), "webclient/VERSION")) as f:
+def installed_location():
+ return __file__
+
+with open(os.path.join(os.path.dirname(installed_location()), "webclient/VERSION")) as f:
__version__ = f.read().strip() |
0a779f17e19f18c8f7e734e7e61367712fe9e52a | examples/worker_rush.py | examples/worker_rush.py | import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
class WorkerRushBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0:
for worker in self.workers:
await self.do(worker.attack(self.enemy_start_locations[0]))
def ma... | from sc2 import run_game, maps, Race, Difficulty, BotAI
from sc2.player import Bot, Computer
class WorkerRushBot(BotAI):
def __init__(self):
super().__init__()
self.actions = []
async def on_step(self, iteration):
self.actions = []
if iteration == 0:
target = self.... | Use do_actions() instead of do() in WorkerRushBot | Use do_actions() instead of do() in WorkerRushBot
| Python | mit | Dentosal/python-sc2 | ---
+++
@@ -1,12 +1,21 @@
-import sc2
-from sc2 import run_game, maps, Race, Difficulty
+from sc2 import run_game, maps, Race, Difficulty, BotAI
from sc2.player import Bot, Computer
-class WorkerRushBot(sc2.BotAI):
+class WorkerRushBot(BotAI):
+ def __init__(self):
+ super().__init__()
+ self.acti... |
258df4932fe937c0baf45d30de88c194f7f7718a | conftest.py | conftest.py |
import numba
import numpy
import pkg_resources
import pytest
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/release.html#ma... |
import numba
import numpy
import pkg_resources
import pytest
import scipy
# The first version of numpy that broke backwards compat and improved printing.
#
# We set the printing format to legacy to maintain our doctests' compatibility
# with both newer and older versions.
#
# See: https://docs.scipy.org/doc/numpy/re... | Add SciPy version to pytest header | Add SciPy version to pytest header
| Python | mit | dwillmer/fastats,fastats/fastats | ---
+++
@@ -3,6 +3,7 @@
import numpy
import pkg_resources
import pytest
+import scipy
# The first version of numpy that broke backwards compat and improved printing.
@@ -39,6 +40,6 @@
def pytest_report_header(config):
- return 'Testing fastats using: NumPy {}, numba {}'.format(
- numpy.__versio... |
50dea10e4b0dfac459a2e4229cfe2ccbe3500b11 | poradnia/config/local.py | poradnia/config/local.py | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
#... | # -*- coding: utf-8 -*-
'''
Local Configurations
- Runs in Debug mode
- Uses console backend for emails
- Use Django Debug Toolbar
'''
from configurations import values
from .common import Common
class Local(Common):
# DEBUG
DEBUG = values.BooleanValue(True)
TEMPLATE_DEBUG = DEBUG
# END DEBUG
#... | Add Virtualbox's/Vagrant's IP to Internal IP | Add Virtualbox's/Vagrant's IP to Internal IP
| Python | mit | watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,watchdogpolska/poradnia | ---
+++
@@ -31,7 +31,7 @@
MIDDLEWARE_CLASSES = Common.MIDDLEWARE_CLASSES + ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar', 'django_extensions', 'autofixture',)
- INTERNAL_IPS = ('127.0.0.1',)
+ INTERNAL_IPS = ('127.0.0.1', '10.0.2.2', )
DEBUG_TOOLBAR_C... |
ccb021e4f672b02d63236207573cc5f7746012e2 | apps/uploads/management/commands/process_uploads.py | apps/uploads/management/commands/process_uploads.py |
import logging
LOGGER = logging.getLogger('apps.uploads')
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile
class Command(BaseCommand):
help = """Regular run of new dropbox links:
manage.py process_uploads
"""
def... | """Download from urls any uploads from outside sources"""
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand, CommandError
from apps.uploads.models import DropboxUploadFile, ManualUploadFile, ResumableUploadFile
LOGGER = logging.getLogger('apps.uploads')
class Co... | Mark resuable uploads as broken if they are | Mark resuable uploads as broken if they are
| Python | agpl-3.0 | IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site | ---
+++
@@ -1,21 +1,31 @@
+"""Download from urls any uploads from outside sources"""
+import logging
-import logging
+from django.utils.timezone import now
+from django.core.management.base import BaseCommand, CommandError
+from apps.uploads.models import DropboxUploadFile, ManualUploadFile, ResumableUploadFile
+
... |
21ab4cb4bb50acd7598b09ebceec20c7302061da | scikits/learn/datasets/tests/test_20news.py | scikits/learn/datasets/tests/test_20news.py | """Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
... | """Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
def test_20news():
try:
data = datasets.fetch_20newsgroups(subset='all',
download_if_missing=... | Fix a bug introduced in rebasing | BUG: Fix a bug introduced in rebasing
| Python | bsd-3-clause | krez13/scikit-learn,ChanderG/scikit-learn,466152112/scikit-learn,ChanChiChoi/scikit-learn,belltailjp/scikit-learn,tdhopper/scikit-learn,krez13/scikit-learn,yyjiang/scikit-learn,schets/scikit-learn,TomDLT/scikit-learn,xubenben/scikit-learn,MohammedWasim/scikit-learn,0x0all/scikit-learn,mblondel/scikit-learn,aewhatley/sc... | ---
+++
@@ -1,7 +1,6 @@
"""Test the 20news downloader, if the data is available."""
import numpy as np
from nose.tools import assert_equal
-from nose.tools import assert_true
from nose.plugins.skip import SkipTest
from scikits.learn import datasets
@@ -33,6 +32,3 @@
entry2 = data.data[np.where(data.target... |
de7abaa3e1de7b7de1c10daa43b621daaee628fd | roundware/rw/fields.py | roundware/rw/fields.py | from django.forms import forms
from south.modelsinspector import add_introspection_rules
from validatedfile.fields import ValidatedFileField
import pyclamav
class RWValidatedFileField(ValidatedFileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_typ... | from django.forms import forms
from south.modelsinspector import add_introspection_rules
from validatedfile.fields import ValidatedFileField
class RWValidatedFileField(ValidatedFileField):
"""
Same as FileField, but you can specify:
* content_types - list containing allowed content_types.
Exa... | Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation | Move pyclamav import inside of clean method on RWValidatedFileField so that it doesn't get imported by streamscript or unless as needed for field validation
| Python | agpl-3.0 | IMAmuseum/roundware-server,Karlamon/roundware-server,IMAmuseum/roundware-server,jslootbeek/roundware-server,IMAmuseum/roundware-server,eosrei/roundware-server,IMAmuseum/roundware-server,eosrei/roundware-server,eosrei/roundware-server,Karlamon/roundware-server,probabble/roundware-server,yangjackascd/roundware-server,Kar... | ---
+++
@@ -1,7 +1,6 @@
from django.forms import forms
from south.modelsinspector import add_introspection_rules
from validatedfile.fields import ValidatedFileField
-import pyclamav
class RWValidatedFileField(ValidatedFileField):
@@ -25,6 +24,7 @@
# next scan with pyclamav
tmpfile = file.f... |
2c45c405887e415744ea0b447936848b9b6fd355 | makerbot_driver/Preprocessors/Preprocessor.py | makerbot_driver/Preprocessors/Preprocessor.py | """
An interface that all future preprocessors should inherit from
"""
import os
import re
from errors import *
from .. import Gcode
class Preprocessor(object):
def __init__(self):
pass
def process_file(self, input_path, output_path):
pass
def inputs_are_gcode(self, input_path, output_path):
for... | """
An interface that all future preprocessors should inherit from
"""
import os
import re
from errors import *
from .. import Gcode
class Preprocessor(object):
def __init__(self):
pass
def process_file(self, input_path, output_path):
pass
def inputs_are_gcode(self, input_path, output_path):
pass... | Disable check for .gcode file extension when preprocessing gcode. | Disable check for .gcode file extension when preprocessing gcode.
| Python | agpl-3.0 | makerbot/s3g,makerbot/s3g,makerbot/s3g,makerbot/s3g,Jnesselr/s3g,Jnesselr/s3g | ---
+++
@@ -9,7 +9,6 @@
from .. import Gcode
class Preprocessor(object):
-
def __init__(self):
pass
@@ -17,10 +16,7 @@
pass
def inputs_are_gcode(self, input_path, output_path):
- for path in (input_path, output_path):
- name, ext = os.path.splitext(path)
- if ext != '.gcode':
- ... |
84e20f231c6a9f8d6f5c76b3e2853f3860173fe0 | yarn_api_client/__init__.py | yarn_api_client/__init__.py | # -*- coding: utf-8 -*-
__version__ = '1.0.2'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| # -*- coding: utf-8 -*-
__version__ = '2.0.0.dev0'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster
from .history_server import HistoryServer
from .node_manager import NodeManager
from .resource_manager import ResourceManager
| Prepare for next development iteration | Prepare for next development iteration
| Python | bsd-3-clause | toidi/hadoop-yarn-api-python-client | ---
+++
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-__version__ = '1.0.2'
+__version__ = '2.0.0.dev0'
__all__ = ['ApplicationMaster', 'HistoryServer', 'NodeManager', 'ResourceManager']
from .application_master import ApplicationMaster |
7201a7f6c87efa74165ca22c4a2db9ce292bae62 | baseline.py | baseline.py | #/usr/bin/python
""" Baseline example that needs to be beaten """
import numpy as np
import matplotlib.pyplot as plt
x, y, yerr = np.loadtxt("data/data.txt", unpack=True)
A = np.vstack((np.ones_like(x), x)).T
C = np.diag(yerr * yerr)
cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A)))
b_ls, m_ls = np.dot(cov, n... | #/usr/bin/python
""" Baseline example that needs to be beaten """
import os
import numpy as np
import matplotlib.pyplot as plt
x, y, yerr = np.loadtxt("data/data.txt", unpack=True)
A = np.vstack((np.ones_like(x), x)).T
C = np.diag(yerr * yerr)
cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A)))
b_ls, m_ls = np.... | Add RESULT_M and RESULT_B to environment varaible | Add RESULT_M and RESULT_B to environment varaible [ci skip]
| Python | mit | arfon/dottravis,arfon/dottravis | ---
+++
@@ -2,6 +2,7 @@
""" Baseline example that needs to be beaten """
+import os
import numpy as np
import matplotlib.pyplot as plt
@@ -20,4 +21,9 @@
ax.set_ylabel("y")
fig.savefig("assets/result.png")
-print m_ls, b_ls
+print("Results of m, b: ({0:.4f} {1:.4f})".format(m_ls, b_ls))
+
+# Let's store r... |
dde82212ddf255ffb15b2b083352d7cf5b4b5b34 | tutorials/urls.py | tutorials/urls.py | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view()),
url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'),
url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tutorial'),
# This must be ... | from django.conf.urls import include, url
from tutorials import views
urlpatterns = [
url(r'^$', views.ListTutorials.as_view(), name='list_tutorials'),
url(r'add/', views.CreateNewTutorial.as_view(), name='add_tutorial'),
url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tut... | Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials | Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform | ---
+++
@@ -3,9 +3,10 @@
from tutorials import views
urlpatterns = [
- url(r'^$', views.ListTutorials.as_view()),
- url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'),
+ url(r'^$', views.ListTutorials.as_view(), name='list_tutorials'),
+ url(r'add/', views.CreateNewTutorial.as_view(), name... |
bc2b8d04398f9df9985452b2b8a016208cf216cd | salesforce/__init__.py | salesforce/__init__.py | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
A database backend for the Django ORM.
Allows access to all Salesforce objects accessible via the SOQL API.
"""
import logging
import warnings
import django
DJANGO_18_PLU... | # django-salesforce
#
# by Phil Christensen
# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org)
# See LICENSE.md for details
#
"""
A database backend for the Django ORM.
Allows access to all Salesforce objects accessible via the SOQL API.
"""
import logging
import warnings
import django
DJANGO_18_PLU... | Remove Django 1.8/1.9 warnings; much better supported now. | Remove Django 1.8/1.9 warnings; much better supported now.
| Python | mit | chromakey/django-salesforce,django-salesforce/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,hynekcer/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce | ---
+++
@@ -19,8 +19,5 @@
DJANGO_19_PLUS = django.VERSION[:3] >= (1, 9)
if not django.VERSION[:2] >= (1, 7):
raise ImportError("Django 1.7 or higher is required for django-salesforce.")
-if django.VERSION[:2] >= (1, 8):
- warnings.warn("Some methods working with Django 1.7 can be unimplemented for Django 1.8 and ... |
c5158020475e62d7e8b86a613a02c0a659038f88 | formish/tests/testish/testish/lib/xformish.py | formish/tests/testish/testish/lib/xformish.py | """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class ApproximateDateParts(widgets.DateParts):
_templat... | """
General purpose formish extensions.
"""
from formish import validation, widgets, Form
from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
def __init__(self, **k):
k['day_first'] = k.pop('l10n').is_day_first()
super(DateParts, self).__init__(**k)
class Approximat... | Fix custom widget to raise correct exception type. | Fix custom widget to raise correct exception type.
| Python | bsd-3-clause | ish/formish,ish/formish,ish/formish | ---
+++
@@ -3,6 +3,7 @@
"""
from formish import validation, widgets, Form
+from convertish.convert import ConvertError
class DateParts(widgets.DateParts):
@@ -27,15 +28,15 @@
# Collect all the parts from the request.
parts = (data['year'][0].strip(), data['month'][0], data['day'][0])
... |
8ffaeda7d9be151e20aef9c06518574c7c7a6727 | utils/__init__.py | utils/__init__.py | import time
def time_func(f):
def wrap(*args, **kwargs):
time1 = time.time()
ret = f(*args, **kwargs)
time2 = time.time()
print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
return ret
return wrap
| Add decorator for timing functions | Add decorator for timing functions
| Python | agpl-3.0 | kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu | ---
+++
@@ -0,0 +1,10 @@
+import time
+
+def time_func(f):
+ def wrap(*args, **kwargs):
+ time1 = time.time()
+ ret = f(*args, **kwargs)
+ time2 = time.time()
+ print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
+ return ret
+ return wrap | |
750dc7d4eddf691117cebf815e163a4d10af39cb | src/TulsiGenerator/Scripts/bazel_options.py | src/TulsiGenerator/Scripts/bazel_options.py | # Copyright 2017 The Tulsi 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 ... | # Copyright 2017 The Tulsi 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 ... | Support enabling tsan and ubsan from Xcode UI | Support enabling tsan and ubsan from Xcode UI
Xcode won't let you enable ubsan from the UI as it requires a
'Compile Sources' phase with (Objective-)C(++) sources, but if you
manually edit the scheme and enable it or equivalently add the phase
with a dummy file, enable it from the UI, and then remove the phase,
ubsan ... | Python | apache-2.0 | pinterest/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,pinterest/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,pinterest/tulsi,pinterest/tulsi,pinterest/tulsi,pinterest/tulsi | ---
+++
@@ -33,8 +33,10 @@
"""Returns a list of bazel flags for the current Xcode env configuration."""
flags = []
if self.xcode_env.get('ENABLE_ADDRESS_SANITIZER') == 'YES':
- flags.extend([
- '--features=asan',
- ])
+ flags.append('--features=asan')
+ if self.xcode_env.get(... |
1e90db8de39bd8c4b1a4d58148b991af8b5c32dd | storage/models/fighter.py | storage/models/fighter.py | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = Column(String(STR_SIZE... | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = Column(String(STR_SIZE... | Add restriction for specialization string in db | Add restriction for specialization string in db
| Python | apache-2.0 | Some1Nebo/ufcpy | ---
+++
@@ -13,7 +13,7 @@
height = Column(Integer) # centimeters
weight = Column(Integer) # kg
reach = Column(Integer) # centimeters
- specialization = Column(String)
+ specialization = Column(String(STR_SIZE))
fights = relationship(
"Fight", |
146463512e17a6bae0dfc0e8f3aa8d99200a5e9c | transfers/examples/pre-transfer/archivesspace_ids.py | transfers/examples/pre-transfer/archivesspace_ids.py | #!/usr/bin/env python
from __future__ import print_function
import csv
import errno
import os
import sys
def main(transfer_path):
"""
Generate archivesspaceids.csv with reference IDs based on filenames.
"""
as_ids = []
for dirpath, _, filenames in os.walk(transfer_path):
for filename in ... | #!/usr/bin/env python
from __future__ import print_function
import csv
import errno
import os
import sys
def main(transfer_path):
"""
Generate archivesspaceids.csv with reference IDs based on filenames.
"""
archivesspaceids_path = os.path.join(transfer_path, 'metadata', 'archivesspaceids.csv')
if... | Automate transfers: archivesspace example checks if output file already exists | Automate transfers: archivesspace example checks if output file already exists
Check if archivesspaceids.csv already exists (presumably user provided). Do
not generate one automatically in that case.
| Python | agpl-3.0 | artefactual/automation-tools,artefactual/automation-tools | ---
+++
@@ -11,6 +11,11 @@
"""
Generate archivesspaceids.csv with reference IDs based on filenames.
"""
+ archivesspaceids_path = os.path.join(transfer_path, 'metadata', 'archivesspaceids.csv')
+ if os.path.exists(archivesspaceids_path):
+ print(archivesspaceids_path, 'already exists, exit... |
1c19d7fb5914554b470a6d067902a9c61882ff4a | packs/softlayer/actions/destroy_instance.py | packs/softlayer/actions/destroy_instance.py | from lib.softlayer import SoftlayerBaseAction
class SoftlayerDeleteInstance(SoftlayerBaseAction):
def run(self, name):
driver = self._get_driver()
# go from name to Node Object
node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0]
# destroy the node
self... | from lib.softlayer import SoftlayerBaseAction
class SoftlayerDeleteInstance(SoftlayerBaseAction):
def run(self, name):
driver = self._get_driver()
# go from name to Node Object
try:
node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0]
except IndexEr... | Return a sane error if there is no Nodes with that name instead of IndexError | Return a sane error if there is no Nodes with that name instead of IndexError
| Python | apache-2.0 | tonybaloney/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib,pidah/st2contrib,digideskio/st2contrib,digideskio/st2contrib,psychopenguin/st2contrib,meirwah/st2contrib,lmEshoo/st2contrib,pinterb/st2contrib,tonybaloney/st2contrib,pidah/st2cont... | ---
+++
@@ -5,7 +5,10 @@
def run(self, name):
driver = self._get_driver()
# go from name to Node Object
- node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0]
+ try:
+ node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0]
+ ... |
0219907b3351fea2467ad961fef750481b62e205 | dask_ndmeasure/_test_utils.py | dask_ndmeasure/_test_utils.py | # -*- coding: utf-8 -*-
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
import dask.array.utils
def _assert_eq_nan(a, b, **kwargs):
a = a.copy()
b = b.copy()
a_nan = (a != a)
b_nan = (b != b)
a[a_nan] = 0
b[b_nan] = 0
dask.array.utils.assert_eq(a_nan, b_nan, **kwargs)
dask.array.utils.asse... | Add _assert_eq_nan to compare arrays that have NaN | Add _assert_eq_nan to compare arrays that have NaN
As comparisons with NaN are false even if both values are NaN, using the
`assert_eq` does not work correctly in this case. To fix it, we add this
shim function around `assert_eq`. First we verify that they have the
same NaN values using a duck type friendly strategy (... | Python | bsd-3-clause | dask-image/dask-ndmeasure | ---
+++
@@ -1 +1,19 @@
# -*- coding: utf-8 -*-
+
+from __future__ import absolute_import
+
+import dask.array.utils
+
+
+def _assert_eq_nan(a, b, **kwargs):
+ a = a.copy()
+ b = b.copy()
+
+ a_nan = (a != a)
+ b_nan = (b != b)
+
+ a[a_nan] = 0
+ b[b_nan] = 0
+
+ dask.array.utils.assert_eq(a_nan,... |
1c494f21cde384b611998d237baa430384dcefbc | Challenges/chall_22.py | Challenges/chall_22.py | #!/usr/local/bin/python3
# Python Challenge - 22
# http://www.pythonchallenge.com/pc/hex/copper.html
# http://www.pythonchallenge.com/pc/hex/white.gif
# Username: butter; Password: fly
# Keyword:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source ... | #!/usr/local/bin/python3
# Python Challenge - 22
# http://www.pythonchallenge.com/pc/hex/copper.html
# http://www.pythonchallenge.com/pc/hex/white.gif
# Username: butter; Password: fly
# Keyword:
'''
Uses Anaconda environment with Pillow for image processing
- Python 3.7, numpy, and Pillow (PIL)
- Run `source ... | Refactor image open to with block | Refactor image open to with block
| Python | mit | HKuz/PythonChallenge | ---
+++
@@ -11,8 +11,7 @@
- Run `source activate imgPIL`, `python chall_22.py`
'''
-from PIL import Image
-import numpy as np
+from PIL import Image, ImageDraw
def main():
@@ -23,10 +22,12 @@
square, download has 133 pages in preview (frames?)
'''
img_path = './joystick_chall_22/white.... |
26934dae71cb006baf0dcf77ddec4938b8c4fdbd | pinry/settings/docker.py | pinry/settings/docker.py | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check"
)
SECRET_KEY = os.environ.get('SECRET_KEY', "PLEASE_REPLACE_ME")
# SECURITY WARNING: don't r... | import logging
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
"No SECRET_KEY given in environ, please have a check."
"If you have a local_settings file, please ignore this warning."
)
SECRET_KEY = os.e... | Add ignore info for secret-key env-test | Doc: Add ignore info for secret-key env-test
| Python | bsd-2-clause | lapo-luchini/pinry,pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,lapo-luchini/pinry,pinry/pinry | ---
+++
@@ -6,7 +6,8 @@
# SECURITY WARNING: keep the secret key used in production secret!
if 'SECRET_KEY' not in os.environ:
logging.warning(
- "No SECRET_KEY given in environ, please have a check"
+ "No SECRET_KEY given in environ, please have a check."
+ "If you have a local_settings fi... |
24207f3681b0e546937a1d59ecffa1aa6630b825 | todolist.py | todolist.py | # -*- coding: utf-8 -*-
from app import create_app, db
app = create_app('development')
@app.cli.command()
def test():
"""Run the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""F... | # -*- coding: utf-8 -*-
from app import create_app, db
app = create_app('development')
@app.cli.command()
def test():
"""Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@app.cli.command()
def fill_db():
"""... | Fix grammar in doc comments | Fix grammar in doc comments
| Python | mit | rtzll/flask-todolist,rtzll/flask-todolist,0xfoo/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,polyfunc/flask-todolist,0xfoo/flask-todolist,rtzll/flask-todolist,polyfunc/flask-todolist,rtzll/flask-todolist | ---
+++
@@ -7,7 +7,7 @@
@app.cli.command()
def test():
- """Run the unit tests."""
+ """Runs the unit tests."""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)
@@ -15,7 +15,7 @@
@app.cli.command()
def fill_db():
- """Fill ... |
cc839453b88b4cd5f2b4f7f4c007405eabb02679 | release.py | release.py | CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved
Programming Language :: Python
Topic :: Software Development
Topic :: Scientific/Engineering
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Operating Syste... | CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved
Programming Language :: Python
Topic :: Software Development
Topic :: Scientific/Engineering
Operating System :: Microsoft :: Windows
Operating System :: POSIX
Operating Syste... | Update distutils version to 0.3.3 | Update distutils version to 0.3.3 | Python | bsd-3-clause | cournape/numscons,cournape/numscons,cournape/numscons | ---
+++
@@ -13,7 +13,7 @@
"""
NAME = 'numscons'
-VERSION = '0.3.3dev'
+VERSION = '0.3.3'
DESCRIPTION = 'Enable to use scons within distutils to build extensions'
CLASSIFIERS = filter(None, CLASSIFIERS.split('\n'))
AUTHOR = 'David Cournapeau' |
f7a8f66047e2277cd95b553cd7aadfa24fbaad95 | scuole/stats/models.py | scuole/stats/models.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=9)
def __str__(self):
return sel... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class SchoolYear(models.Model):
name = models.CharField(max_length=9)
def __str__(self):
return sel... | Add two more fields to StatsBase | Add two more fields to StatsBase
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole | ---
+++
@@ -29,10 +29,14 @@
# Student counts
all_students_count = models.IntegerField('Number of students')
+ african_american_count = models.IntegerField(
+ 'Number of African American students')
asian_count = models.IntegerField('Number of Asian students')
hispanic_count = models.Int... |
06f045d51b24ee834f7bbb572ccce304431fc602 | merlin/engine/battle.py | merlin/engine/battle.py |
class Prepare(object):
"""
Prepare the champions for the battle!
Usage:
hero = Prepare(name="Aragorn", base_attack=100, base_hp=100)
or like this:
aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100}
hero = Prepare(**aragorn)
"""
def __init__(self, name, b... |
class Prepare(object):
"""
Prepare the champions for the battle!
Usage:
hero = Prepare(name="Aragorn", base_attack=100, base_hp=100)
or like this:
aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100}
hero = Prepare(**aragorn)
"""
def __init__(self, name, b... | Add property status in Prepare | Add property status in Prepare
| Python | mit | lerrua/merlin-engine | ---
+++
@@ -15,6 +15,10 @@
self.base_attack = base_attack
self.base_hp = base_hp
+ @property
+ def status(self):
+ return self.__dict__
+
def attack(self, foe):
if not isinstance(foe, Prepare):
raise TypeError('foe should be a Prepare object') |
542bd2696f75ad58cf8b0015024b3011af14851c | config.py | config.py | import os
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
DEBUG = True
# Secret key for session management. You can generate random strings here:
# http://clsc.net/tools-old/random-string-generator.php
SECRET_KEY = 'my precious'
# Connect to the da... | import os
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Enable debug mode.
DEBUG = True
# Secret key for session management. You can generate random strings here:
# http://clsc.net/tools-old/random-string-generator.php
SECRET_KEY = '-%\4~3(_6*'
# Connect to the dat... | Include randomized string for secret key | Include randomized string for secret key
| Python | apache-2.0 | AntiPiracy/webapp,AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp,tcyrus-hackathon/scurvy-webapp,AntiPiracy/webapp,tcyrus-hackathon/scurvy-webapp | ---
+++
@@ -8,7 +8,7 @@
# Secret key for session management. You can generate random strings here:
# http://clsc.net/tools-old/random-string-generator.php
-SECRET_KEY = 'my precious'
+SECRET_KEY = '-%\4~3(_6*'
# Connect to the database
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'database.d... |
c201fc0feef5f7eeede327d6239fc3082ae24180 | server/worker/queue.py | server/worker/queue.py | """Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for ... | """Process queues."""
from datetime import datetime
from server.extensions import db
from server.models import QueueEntry
def finished_entries():
"""Process finished entries."""
queue_entries = db.session.query(QueueEntry) \
.filter(QueueEntry.finishes_at <= datetime.now()) \
.all()
for ... | Set research level in ticker | Set research level in ticker
| Python | mit | Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival | ---
+++
@@ -18,7 +18,7 @@
entry.module.pod.update_resources()
elif entry.research:
- entry.research.level += 1
+ entry.research.level = entry.level
entry.research.researched = True
db.session.add(entry.research)
|
eb169af3b56ef44d50a6f4596debf0c0c9efa532 | config.py | config.py | import os
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
class BaseConfig(object):
DEBUG = False
TESTING = False
FREEZER_REMOVE_EXTRA_FILES = True
FREEZER_DESTINATION = os.path.join(ROOT_DIR, 'html')
FREEZER_RELATIVE_URLS = True
class ProductionConfig(BaseConfig):
GOOGLE_API_KEY = os.... | import os
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
class BaseConfig(object):
DEBUG = False
TESTING = False
FREEZER_REMOVE_EXTRA_FILES = True
FREEZER_DESTINATION = os.path.join(ROOT_DIR, 'html')
FREEZER_RELATIVE_URLS = True
class ProductionConfig(BaseConfig):
GOOGLE_API_KEY = os.... | Change location of development data file. | Change location of development data file.
| Python | mit | JamesRiverHomeBrewers/WaterTesting,JamesRiverHomeBrewers/WaterTesting,JamesRiverHomeBrewers/WaterTesting,JamesRiverHomeBrewers/WaterTesting | ---
+++
@@ -16,7 +16,7 @@
class DevelopmentConfig(BaseConfig):
- DATA_FILE = os.path.join(ROOT_DIR, 'WaterTesting', 'data.csv')
+ DATA_FILE = os.path.join(ROOT_DIR, 'data.csv')
DEBUG = True
TESTING = True
|
738d080512f36939ce4a23f3d3db0b378550564a | tests/test_build_chess.py | tests/test_build_chess.py | # -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
piece... | # -*- coding: utf-8 -*-
from app.chess.chess import Chess
import unittest
class TestBuildChess(unittest.TestCase):
"""
`TestBuildChess()` class is unit-testing the class
Chess().
"""
# ///////////////////////////////////////////////////
def setUp(self):
params = [4, 4]
piece... | Add a TDD funct to test the solution (only kings) | Add a TDD funct to test the solution (only kings) | Python | mit | aymguesmi/ChessChallenge | ---
+++
@@ -24,7 +24,15 @@
self.assertEqual(self.chess.pieces_types == ['K', 'K', 'Q'], True)
self.assertEqual(self.chess.number_pieces == 3, True)
# self.assertEqual(self.chess.solutions == 1, True)
-
+
+ def test_solution_only_kings(self):
+ params = [5, 5]
+ pi... |
64feb1fe3eafc7fae4b9894f5e240d4c05eebb78 | lava_server/__init__.py | lava_server/__init__.py | # Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software F... | # Copyright (C) 2010, 2011 Linaro Limited
#
# Author: Zygmunt Krynicki <zygmunt.krynicki@linaro.org>
#
# This file is part of LAVA Server.
#
# LAVA Server is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License version 3
# as published by the Free Software F... | Bump version to beta 3 | Bump version to beta 3
| Python | agpl-3.0 | OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server | ---
+++
@@ -17,4 +17,4 @@
# along with LAVA Server. If not, see <http://www.gnu.org/licenses/>.
-__version__ = (0, 3, 0, "beta", 2)
+__version__ = (0, 3, 0, "beta", 3) |
7a7cd83b5d49961e8d0cdd851caf11b7110c2779 | app.py | app.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from flask import Flask, request, json
from flask.ext.cors import CORS
import database
import rsser
# Update data before application is allowed to start
database.update_database()
app = Flask(__name__)
CORS(app)
@app.route('/speakercast/speakers')
def speakers():
... | Handle OPTION requests for generate | Handle OPTION requests for generate
Just return nothing. Chrome seems to be happy with that response.
| Python | bsd-3-clause | philipbl/talk_feed,philipbl/SpeakerCast | ---
+++
@@ -22,10 +22,14 @@
@app.route('/speakercast/generate', methods=['POST', 'OPTIONS'])
def generate():
+ if request.method == 'OPTIONS':
+ return ""
+
data = json.loads(request.data)
speakers = data['speakers']
id_ = database.generate_id(speakers)
+ print("Generating id ({}) fo... |
0817bdcd26de6627ee36edcee2072727f3174d4c | cfsite/settings/prod.py | cfsite/settings/prod.py | """Development settings and globals."""
from common import *
import dj_database_url
########## DEBUG CONFIGURATION
DEBUG = True
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': {
'ENGINE':'django.db.backends.postgresql_p... | """Development settings and globals."""
from common import *
import dj_database_url
########## DEBUG CONFIGURATION
DEBUG = False
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
# Parse database configuration from $DATABASE_URL
DATABASES = {
'default': {
'ENGINE':'django.db.backends.postgresql_... | Revert to debug=false for deployment | Revert to debug=false for deployment
| Python | mit | susanctu/Crazyfish-Public,susanctu/Crazyfish-Public | ---
+++
@@ -5,7 +5,7 @@
import dj_database_url
########## DEBUG CONFIGURATION
-DEBUG = True
+DEBUG = False
TEMPLATE_DEBUG = DEBUG
########## END DEBUG CONFIGURATION
|
baca7b88893f175a222d7130ef1889893ed6b970 | iterm2_tools/images.py | iterm2_tools/images.py | """
Functions for displaying images inline in iTerm2.
See https://iterm2.com/images.html.
"""
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def display_image_bytes(b, filename=None, ... | """
Functions for displaying images inline in iTerm2.
See https://iterm2.com/images.html.
"""
from __future__ import print_function, division, absolute_import
import sys
import os
import base64
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def display_image_bytes(b, filename=None, ... | Add a deprecation message to the docstring of image_bytes() | Add a deprecation message to the docstring of image_bytes()
| Python | mit | asmeurer/iterm2-tools | ---
+++
@@ -26,6 +26,13 @@
}
return (IMAGE_CODE.format(**data))
+# Backwards compatibility
+def image_bytes(b, filename=None, inline=1):
+ """
+ **DEPRECATED**: Use display_image_bytes.
+ """
+ return display_image_file(b, filename=filename, inline=inline)
+
def display_image_file(fn):
... |
a2f1cdc05e63b7b68c16f3fd1e5203608888b059 | traits/util/deprecated.py | traits/util/deprecated.py | """ A decorator for marking methods/functions as deprecated. """
# Standard library imports.
import logging
# We only warn about each function or method once!
_cache = {}
def deprecated(message):
""" A factory for decorators for marking methods/functions as deprecated.
"""
def decorator(fn):
... | # Test the 'trait_set', 'trait_get' interface to
# the HasTraits class.
#
# Copyright (c) 2014, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# License included in /LICENSE.txt and may be redistributed only under the
# conditions described in the... | Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging. | Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
| Python | bsd-3-clause | burnpanck/traits,burnpanck/traits | ---
+++
@@ -1,45 +1,37 @@
+# Test the 'trait_set', 'trait_get' interface to
+# the HasTraits class.
+#
+# Copyright (c) 2014, Enthought, Inc.
+# All rights reserved.
+#
+# This software is provided without warranty under the terms of the BSD
+# License included in /LICENSE.txt and may be redistributed only unde... |
3900c8173bff6c3b1175ff9d6cffec1b98db7c74 | address_book/address_book.py | address_book/address_book.py | __all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
| from person import Person
__all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
def __contains__(self, item):
if isinstance(item, Person):
return item in self.persons
... | Add ability to check is the Person in AddressBook or not | Add ability to check is the Person in AddressBook or not
| Python | mit | dizpers/python-address-book-assignment | ---
+++
@@ -1,3 +1,5 @@
+from person import Person
+
__all__ = ['AddressBook']
@@ -8,3 +10,8 @@
def add_person(self, person):
self.persons.append(person)
+
+ def __contains__(self, item):
+ if isinstance(item, Person):
+ return item in self.persons
+ return False |
d08e8144b90d3fe89fd449d31bdb655d62f3a749 | serfclient/connection.py | serfclient/connection.py | import socket
import sys
class SerfConnectionError(Exception):
pass
class SerfConnection(object):
"""
Manages RPC communication to and from a Serf agent.
"""
def __init__(self, host='localhost', port=7373):
self.host, self.port = host, port
self._socket = None
def __repr__(... | import socket
import sys
class SerfConnectionError(Exception):
pass
class SerfConnection(object):
"""
Manages RPC communication to and from a Serf agent.
"""
def __init__(self, host='localhost', port=7373):
self.host, self.port = host, port
self._socket = None
def __repr__(... | Move all 'connect' logic into a private method | Move all 'connect' logic into a private method
| Python | mit | charleswhchan/serfclient-py,KushalP/serfclient-py | ---
+++
@@ -28,10 +28,14 @@
initial handshake.
"""
if self._socket:
- return
+ return True
+ else:
+ self._socket = self._connect()
+ return True
+
+ def _connect(self):
try:
- self._socket = socket.create_connection(... |
14c41706d6437247bbe69e0e574c03863fbe5bda | api/v2/views/maintenance_record.py | api/v2/views/maintenance_record.py | from rest_framework.serializers import ValidationError
from core.models import MaintenanceRecord
from api.permissions import CanEditOrReadOnly
from api.v2.serializers.details import MaintenanceRecordSerializer
from api.v2.views.base import AuthOptionalViewSet
class MaintenanceRecordViewSet(AuthOptionalViewSet):
... | import django_filters
from rest_framework import filters
from rest_framework.serializers import ValidationError
from core.models import AtmosphereUser, MaintenanceRecord
from core.query import only_current
from api.permissions import CanEditOrReadOnly
from api.v2.serializers.details import MaintenanceRecordSerialize... | Add '?active=' filter for Maintenance Record | [ATMO-1200] Add '?active=' filter for Maintenance Record
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -1,11 +1,27 @@
+import django_filters
+
+from rest_framework import filters
from rest_framework.serializers import ValidationError
-from core.models import MaintenanceRecord
+from core.models import AtmosphereUser, MaintenanceRecord
+from core.query import only_current
from api.permissions import Can... |
611c34eee4b5aa263669f1b7321b97fab9a98b5e | dask/distributed/tests/test_ipython_utils.py | dask/distributed/tests/test_ipython_utils.py | from dask.distributed import dask_client_from_ipclient
def test_dask_client_from_ipclient():
from IPython.parallel import Client
c = Client()
dc = dask_client_from_ipclient(c)
assert 2 == dc.get({'a': 1, 'b': (lambda x: x + 1, 'a')}, 'b')
dc.close(close_workers=True, close_scheduler=True)
| from dask.distributed import dask_client_from_ipclient
import numpy as np
from numpy.testing import assert_array_almost_equal
import dask.array as da
def test_dask_client_from_ipclient():
from IPython.parallel import Client
c = Client()
dask_client = dask_client_from_ipclient(c)
# data
a = np.ara... | Remove lambda test. Add dask array tests. | Remove lambda test. Add dask array tests.
| Python | bsd-3-clause | PhE/dask,clarkfitzg/dask,jayhetee/dask,simudream/dask,mikegraham/dask,vikhyat/dask,PhE/dask,wiso/dask,jcrist/dask,esc/dask,mraspaud/dask,esc/dask,marianotepper/dask,vikhyat/dask,pombredanne/dask,simudream/dask,freeman-lab/dask,cpcloud/dask,blaze/dask,marianotepper/dask,jcrist/dask,hainm/dask,ContinuumIO/dask,blaze/dask... | ---
+++
@@ -1,8 +1,29 @@
from dask.distributed import dask_client_from_ipclient
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+import dask.array as da
+
def test_dask_client_from_ipclient():
from IPython.parallel import Client
c = Client()
- dc = dask_client_from_ipclient(c... |
6fbf3edb489059f93cee6684bf5046386f538391 | src/attendance/wsgi.py | src/attendance/wsgi.py | """
WSGI config for openservices project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "attendance.settings")
application = get_wsgi_application()
| """
WSGI config for openservices project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import os
import sys
sys.path.append(os.path.abspath(os.path.join(__file__, '../..')))
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "atte... | Append source path in WSGI mode. | Append source path in WSGI mode.
| Python | bsd-2-clause | OpenServicesEU/python-attendance | ---
+++
@@ -5,6 +5,9 @@
"""
import os
+import sys
+
+sys.path.append(os.path.abspath(os.path.join(__file__, '../..')))
from django.core.wsgi import get_wsgi_application
|
1629d6d369bce079c33986aa62a12a1ad3a8a47d | test/test_grequest.py | test/test_grequest.py | from mpi4py import MPI
import mpiunittest as unittest
class GReqCtx(object):
source = 1
tag = 7
completed = False
free_called = False
def query(self, status):
status.Set_source(self.source)
status.Set_tag(self.tag)
def free(self):
self.free_called = True
def canc... | from mpi4py import MPI
import mpiunittest as unittest
class GReqCtx(object):
source = 1
tag = 7
completed = False
free_called = False
def query(self, status):
status.Set_source(self.source)
status.Set_tag(self.tag)
def free(self):
self.free_called = True
def canc... | Remove commented-out line in testcase | Remove commented-out line in testcase | Python | bsd-2-clause | pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,pressel/mpi4py | ---
+++
@@ -14,7 +14,6 @@
self.free_called = True
def cancel(self, completed):
if completed is not self.completed:
- #raise AssertionError()
raise MPI.Exception(MPI.ERR_PENDING)
class TestGrequest(unittest.TestCase): |
1c22ac91789c2e7230f1c97e9d4def0dfcf13638 | app/drivers/mslookup/base.py | app/drivers/mslookup/base.py | from app.lookups import base as lookups
from app.drivers.base import BaseDriver
class LookupDriver(BaseDriver):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.lookupfn = kwargs.get('lookup', None)
self.initialize_lookup()
def initialize_lookup(self):
if self.loo... | import os
from app.lookups import base as lookups
from app.drivers.base import BaseDriver
class LookupDriver(BaseDriver):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.lookupfn = kwargs.get('lookup', None)
self.initialize_lookup()
def initialize_lookup(self):
... | Add out directory to path to new sqlite lookup | Add out directory to path to new sqlite lookup
| Python | mit | glormph/msstitch | ---
+++
@@ -1,3 +1,5 @@
+import os
+
from app.lookups import base as lookups
from app.drivers.base import BaseDriver
@@ -14,7 +16,8 @@
else:
# FIXME MUST be a set or mzml lookup? here is place to assert
# correct lookuptype!
- self.lookupfn = 'msstitcher_lookup.sqlite... |
8c2a52ce4eb47e89450677d0beed9c3d45b417e0 | tests/test_default.py | tests/test_default.py | import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
'.molecule/ansible_inventory').get_hosts('all')
def test_hosts_file(File):
f = File('/etc/hosts')
assert f.exists
assert f.user == 'root'
assert f.group == 'root'
| import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
'.molecule/ansible_inventory').get_hosts('all')
def test_service_running_and_enabled(Service):
collectd = Service("collectd")
collectd.is_running
collectd.is_enabled
| Write a sensible (if post hoc) test. | Write a sensible (if post hoc) test.
I had a hard time getting this test to fail so I could prove it works, but
it's a simple test and its main purpose is to provide an example for
later tests, so I'm calling it Good Enough.
| Python | mit | idi-ops/ansible-collectd | ---
+++
@@ -4,9 +4,7 @@
'.molecule/ansible_inventory').get_hosts('all')
-def test_hosts_file(File):
- f = File('/etc/hosts')
-
- assert f.exists
- assert f.user == 'root'
- assert f.group == 'root'
+def test_service_running_and_enabled(Service):
+ collectd = Service("collectd")
+ collectd.i... |
a72b20a7c614c86a196585a6703b218613f6d74b | modules/githubsearch.py | modules/githubsearch.py | import requests
import simplejson as json
class GithubSearch(object):
def __init__(self):
self.api_url = "https://api.github.com/search/code?q="
self.repo = "OpenTreeOfLife/treenexus"
def search(self,term):
search_url = "%s+repo:%s" % (self.api_url, self.repo)
r = requests.ge... | import requests
import simplejson as json
class GithubSearch(object):
def __init__(self):
self.api_url = "https://api.github.com/search/code?q="
self.repo = "OpenTreeOfLife/treenexus"
def search(self,term):
search_url = "%s%s+repo:%s" % (self.api_url, term, self.repo)
print "... | Add a simple search controller which wraps around the Github code search API | Add a simple search controller which wraps around the Github code search API
| Python | bsd-2-clause | OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api | ---
+++
@@ -6,7 +6,9 @@
self.api_url = "https://api.github.com/search/code?q="
self.repo = "OpenTreeOfLife/treenexus"
def search(self,term):
- search_url = "%s+repo:%s" % (self.api_url, self.repo)
+ search_url = "%s%s+repo:%s" % (self.api_url, term, self.repo)
+ print "R... |
519cba447e9fed9eb40d5328376442e75936fd4a | encbox.py | encbox.py | #!/usr/bin/python
#lets import the dropbox module
import dropbox
#taking the app key and secret
key=raw_input('Enter your app key : ')
secret=raw_input('Enter your app secret : ')
#initializing the flow
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(key,secret)
#we are ready to start the connection, so we can ge... | Set the connection to Dropbox API | Set the connection to Dropbox API
| Python | mit | Aris-Breezy/encbox | ---
+++
@@ -0,0 +1,25 @@
+#!/usr/bin/python
+#lets import the dropbox module
+import dropbox
+
+#taking the app key and secret
+key=raw_input('Enter your app key : ')
+secret=raw_input('Enter your app secret : ')
+#initializing the flow
+flow = dropbox.client.DropboxOAuth2FlowNoRedirect(key,secret)
+
+#we are ready... | |
7ad9930afd6cfd70e8fdf48dc4b2ecadba6426ea | abcpy/distributions.py | abcpy/distributions.py | # -*- coding: utf-8 -*-
import scipy.stats as ss
import numpy.random as npr
from functools import partial
from . import core
def npr_op(distribution, size, input):
prng = npr.RandomState(0)
prng.set_state(input['random_state'])
distribution = getattr(prng, distribution)
size = (input['n'], *size)
... | # -*- coding: utf-8 -*-
import scipy.stats as ss
import numpy.random as npr
from functools import partial
from . import core
def npr_op(distribution, size, input):
prng = npr.RandomState(0)
prng.set_state(input['random_state'])
distribution = getattr(prng, distribution)
size = (input['n'],)+tuple(siz... | Change tuple concatenation to be py3 compatible | Change tuple concatenation to be py3 compatible
| Python | mit | akangasr/elfi | ---
+++
@@ -10,7 +10,7 @@
prng = npr.RandomState(0)
prng.set_state(input['random_state'])
distribution = getattr(prng, distribution)
- size = (input['n'], *size)
+ size = (input['n'],)+tuple(size)
data = distribution(*input['data'], size=size)
return core.to_output(input, data=data, ran... |
41ad0f842320161c45079f7a75d64df6c8716e5d | london_commute_alert.py | london_commute_alert.py | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | import datetime
import os
import requests
def update():
requests.packages.urllib3.disable_warnings()
resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json()
return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp}
def email(lines):
with open('curl_raw_c... | Move from python anywhere to webfaction | Move from python anywhere to webfaction
| Python | mit | noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit | ---
+++
@@ -21,10 +21,7 @@
subject = 'Good service for commute'
body = 'Good service on all lines'
- # We must have this running on PythonAnywhere - Monday to Sunday.
- # Ignore Saturday and Sunday
- if datetime.date.today().isoweekday() in range(1, 6):
- os.system(raw_command.form... |
3eb57619a4e8a669cf879b67d96377ccb21de204 | babel_util/scripts/wos_to_pajek.py | babel_util/scripts/wos_to_pajek.py | #!/usr/bin/env python3
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
... | #!/usr/bin/env python3
from parsers.wos import WOSStream
from util.PajekFactory import PajekFactory
from util.misc import open_file, Checkpoint
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
... | Add wos-only option to script | Add wos-only option to script
| Python | agpl-3.0 | jevinw/rec_utilities,jevinw/rec_utilities | ---
+++
@@ -7,6 +7,7 @@
import argparse
parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML")
parser.add_argument('outfile')
+ parser.add_argument('--wos-only', action="store_true", help="Only include nodes/edges in WOS")
parser.add_argument('infile', nargs='+'... |
557e634a3b68c13b1a19151ec3b96f456e17d347 | penelophant/database.py | penelophant/database.py | """ Database Module """
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
| """ Database Module """
from flask_sqlalchemy import SQLAlchemy
from penelophant import app
db = SQLAlchemy(app)
| Attach app to SQLAlchemy properly | Attach app to SQLAlchemy properly
| Python | apache-2.0 | kevinoconnor7/penelophant,kevinoconnor7/penelophant | ---
+++
@@ -1,4 +1,5 @@
""" Database Module """
from flask_sqlalchemy import SQLAlchemy
-db = SQLAlchemy()
+from penelophant import app
+db = SQLAlchemy(app) |
32c676e727845c62e8958514d3c61ea56569a77b | tests/test_settings.py | tests/test_settings.py | DEBUG = True
TEMPLATE_DEBUG = DEBUG
SECRET_KEY = 'fake_secret'
ROOT_URLCONF = 'tests.test_urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'irrelevant.db'
}
}
INSTALLED_APPS = (
'djproxy',
)
STATIC_ROOT = ''
STATIC_URL = '/'
APPEND_SLASH = False
| DEBUG = True
TEMPLATE_DEBUG = DEBUG
SECRET_KEY = 'fake_secret'
ROOT_URLCONF = 'tests.test_urls'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'irrelevant.db'
}
}
MIDDLEWARE_CLASSES = []
INSTALLED_APPS = (
'djproxy',
)
STATIC_ROOT = ''
STATIC_URL = '/'
APPE... | Add empty middleware setting to quiet warning | Add empty middleware setting to quiet warning
Before this change, starting a dev server would give this warning:
```
Performing system checks...
System check identified some issues:
WARNINGS:
?: (1_7.W001) MIDDLEWARE_CLASSES is not set.
HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES... | Python | mit | thomasw/djproxy | ---
+++
@@ -12,6 +12,8 @@
}
}
+MIDDLEWARE_CLASSES = []
+
INSTALLED_APPS = (
'djproxy',
) |
f76a2070d91d60a261e8f6120a01075491eb785f | conftest.py | conftest.py | # -*- coding: utf-8 -*-
pytest_plugins = [
u'ckan.tests.pytest_ckan.ckan_setup',
u'ckan.tests.pytest_ckan.fixtures',
]
| # -*- coding: utf-8 -*-
pytest_plugins = [
]
| Remove pytest plugins from archiver | Remove pytest plugins from archiver
| Python | mit | ckan/ckanext-archiver,ckan/ckanext-archiver,ckan/ckanext-archiver | ---
+++
@@ -1,6 +1,4 @@
# -*- coding: utf-8 -*-
pytest_plugins = [
- u'ckan.tests.pytest_ckan.ckan_setup',
- u'ckan.tests.pytest_ckan.fixtures',
] |
67d08aff211ae1edbae202819f39be7c34812137 | hggithub.py | hggithub.py |
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.0"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mir... |
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.0"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mir... | Allow for extra slashes in project paths, such as mq patch queues. | Allow for extra slashes in project paths, such as mq patch queues.
| Python | bsd-2-clause | stephenmcd/hg-github | ---
+++
@@ -21,7 +21,10 @@
bb = "ssh://hg@bitbucket.org/"
for pathname, path in ui.configitems("paths"):
if path.startswith(bb):
- user, project = path.replace(bb, "").rstrip("/").split("/")
+ user, project = path.replace(bb, "").split("/", 1)
+ # Strip slash and ev... |
0d3740cef051ed08a307dc2b42fe022ce2f1ba28 | bot/utils/attributeobject.py | bot/utils/attributeobject.py | class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, v... | class AttributeObject:
def __init__(self, *excluded_keys):
self._excluded_keys = excluded_keys
def __getattr__(self, item):
return self._getattr(item)
def __setattr__(self, key, value):
if key == "_excluded_keys" or key in self._excluded_keys:
super().__setattr__(key, v... | Allow to specify initial items on DictionaryObject constructor | Allow to specify initial items on DictionaryObject constructor
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -19,9 +19,9 @@
class DictionaryObject(AttributeObject):
- def __init__(self):
+ def __init__(self, initial_items={}):
super().__init__("_dictionary")
- self._dictionary = {}
+ self._dictionary = dict(initial_items)
def _getattr(self, item):
return self._dic... |
7bbec0e5306766741b22341a100db046d76b82a8 | apps/books/models.py | apps/books/models.py | from django.db import models
from apps.categories.models import Category
from apps.users.models import UserProfile
from apps.reviews.models import Review
class Book(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=500)
author = models.CharField(max_length=255)
... | from django.db import models
from apps.categories.models import Category
from apps.users.models import UserProfile
from apps.reviews.models import Review
class Book(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=500)
author = models.CharField(max_length=255)
... | Fix get_rating in Book model | Fix get_rating in Book model
| Python | mit | vuonghv/brs,vuonghv/brs,vuonghv/brs,vuonghv/brs | ---
+++
@@ -20,10 +20,11 @@
def get_rating(self):
reviews = Review.objects.filter(book=self)
+ total = reviews.count()
rating = 0
for review in reviews:
rating += review.rating
- return round(rating / Review.MAX_STARS)
+ return round(rating / total)
... |
12dbfcbdf35f8d846f39eee4898d032aa6729ab9 | hack/boilerplate/boilerplate_test.py | hack/boilerplate/boilerplate_test.py | #!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 appli... | #!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 appli... | Fix up failing boilerplate test | Fix up failing boilerplate test
| Python | apache-2.0 | cblecker/kubernetes,pmorie/kubernetes,mfojtik/kubernetes,feiskyer/kubernetes,frodenas/kubernetes,Lion-Wei/kubernetes,fanzhangio/kubernetes,chestack/kubernetes,rnaveiras/kubernetes,andrewsykim/kubernetes,intelsdi-x/kubernetes,GulajavaMinistudio/kubernetes,micahhausler/kubernetes,humblec/kubernetes,brendandburns/kubernet... | ---
+++
@@ -16,7 +16,7 @@
import boilerplate
import unittest
-import StringIO
+from io import StringIO
import os
import sys
|
d6b3c47169082eeee6f1f01458b8791de2573849 | kolibri/plugins/management/kolibri_plugin.py | kolibri/plugins/management/kolibri_plugin.py |
from __future__ import absolute_import, print_function, unicode_literals
from kolibri.plugins.base import KolibriFrontEndPluginBase
class ManagementModule(KolibriFrontEndPluginBase):
"""
The Management module.
"""
entry_file = "assets/src/management.js"
base_url = "management"
template = "... | from __future__ import absolute_import, print_function, unicode_literals
from kolibri.core.webpack import hooks as webpack_hooks
from kolibri.plugins.base import KolibriPluginBase
class ManagementPlugin(KolibriPluginBase):
""" Required boilerplate so that the module is recognized as a plugin """
pass
class... | Use new plugin classes for management | Use new plugin classes for management
| Python | mit | 66eli77/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,jtamiace/kolibri,learningequality/kolibri,aronasorman/kolibri,jamalex/kolibri,christianmemije/kolibri,rtibbles/kolibri,benjaoming/kolibri,jtamiace/kolibri,jayoshih/kolibri,MingDai/kolibri,DXCanas/kolibri,jamalex/kolibri,rtibbles/kolibri,mrpau/... | ---
+++
@@ -1,36 +1,19 @@
-
from __future__ import absolute_import, print_function, unicode_literals
-from kolibri.plugins.base import KolibriFrontEndPluginBase
+from kolibri.core.webpack import hooks as webpack_hooks
+from kolibri.plugins.base import KolibriPluginBase
-class ManagementModule(KolibriFrontEndPl... |
7b73d73b7b61830b955f7ec686570c7371bb16d1 | comics/crawler/utils/lxmlparser.py | comics/crawler/utils/lxmlparser.py | #encoding: utf-8
from lxml.html import parse, fromstring
class LxmlParser(object):
def __init__(self, url=None, string=None):
if url:
self.root = parse(url).getroot()
self.root.make_links_absolute(url)
elif string:
self.root = fromstring(string)
def text(se... | #encoding: utf-8
from lxml.html import parse, fromstring
class LxmlParser(object):
def __init__(self, url=None, string=None):
if url is not None:
self.root = parse(url).getroot()
self.root.make_links_absolute(url)
elif string is not None:
self.root = fromstring(... | Update exception handling in LxmlParser | Update exception handling in LxmlParser
Signed-off-by: Stein Magnus Jodal <e14d2e665cf0bcfd7f54daa10a36c228abaf843a@jodal.no> | Python | agpl-3.0 | datagutten/comics,jodal/comics,datagutten/comics,klette/comics,jodal/comics,jodal/comics,klette/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics | ---
+++
@@ -4,11 +4,13 @@
class LxmlParser(object):
def __init__(self, url=None, string=None):
- if url:
+ if url is not None:
self.root = parse(url).getroot()
self.root.make_links_absolute(url)
- elif string:
+ elif string is not None:
self.r... |
62586dc0e4e9ca8d0fee6c72e296c74875f3a65c | api/swd6/api/app.py | api/swd6/api/app.py | import logging
import os
import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi
from swd6 import config
from swd6.db.models import db
CONF = config.CONF
DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf'
app = None
def start():
# pylint: disable=global-statement
global app
a... | import logging
import os
import flask
import flask_cors
from sqlalchemy_jsonapi import flaskext as flask_jsonapi
from swd6 import config
from swd6.db.models import db
CONF = config.CONF
DEFAULT_CONF_PATH = '/opt/swd6/api/api.conf'
app = None
def start():
# pylint: disable=global-statement
global app
a... | Fix CORS to allow for credentials | Fix CORS to allow for credentials
Something changed in the client code requiring this
setting.
| Python | apache-2.0 | jimbobhickville/swd6,jimbobhickville/swd6,jimbobhickville/swd6 | ---
+++
@@ -24,7 +24,7 @@
app.logger.setLevel(logging.DEBUG)
- flask_cors.CORS(app, origins=CONF.api.cors_hosts)
+ flask_cors.CORS(app, origins=CONF.api.cors_hosts, supports_credentials=True)
logging.getLogger('flask_cors').level = logging.DEBUG
|
072d5bf150ff3f8d743a84c636929e7a326bf8ea | src/python/tensorflow_cloud/tuner/constants.py | src/python/tensorflow_cloud/tuner/constants.py | # Lint as: python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | # Lint as: python3
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | Fix path to API doc | Fix path to API doc
| Python | apache-2.0 | tensorflow/cloud,tensorflow/cloud | ---
+++
@@ -14,8 +14,12 @@
# limitations under the License.
"""Constants definitions for tuner sub module."""
+import os
+
# API definition of Cloud AI Platform Optimizer service
-OPTIMIZER_API_DOCUMENT_FILE = "api/ml_public_google_rest_v1.json"
+OPTIMIZER_API_DOCUMENT_FILE = os.path.join(
+ os.path.dirname(o... |
5a6ff9a69a2d769f6ac363f20afb89a23dd2290d | homeassistant/components/device_tracker/mqtt.py | homeassistant/components/device_tracker/mqtt.py | """
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT platform for the device tracker.
device_tracker:
platform: mqtt
qos: 1
devices:
paulus_oneplus: /location/paulus
annetherese_n4: /location/annetherese
"""
import logging
from homeassistant import util
impo... | """
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MQTT platform for the device tracker.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.mqtt.html
"""
import logging
from homeassistant import util
... | Move configuration details to docs | Move configuration details to docs
| Python | mit | emilhetty/home-assistant,mikaelboman/home-assistant,alexmogavero/home-assistant,devdelay/home-assistant,nevercast/home-assistant,shaftoe/home-assistant,srcLurker/home-assistant,tboyce021/home-assistant,instantchow/home-assistant,DavidLP/home-assistant,Julian/home-assistant,jnewland/home-assistant,florianholzapfel/home-... | ---
+++
@@ -1,15 +1,10 @@
"""
homeassistant.components.device_tracker.mqtt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
MQTT platform for the device tracker.
-device_tracker:
- platform: mqtt
- qos: 1
- devices:
- paulus_oneplus: /location/paulus
- annetherese_n4: /location/annetherese
+For more deta... |
f9b9023549adf4ee9923ac8ed4b6a0fc0b6a89a5 | core/management/commands/delete_old_sessions.py | core/management/commands/delete_old_sessions.py | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
"""
>>> def clean(count):
... for idx, s in enumerate(Session.objects.filter(expire_date__lt=now)[:count+1]):
... s.delete()
... if str(idx).endswith('000'): print idx
... p... | Add delete old sessions command | Add delete old sessions command
| Python | mit | QLGu/djangopackages,QLGu/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages | ---
+++
@@ -28,7 +28,7 @@
for index, session in enumerate(old_sessions):
session.delete()
if str(idx).endswith('000'):
- self.stdout.write("{0} records deleted".format(index)
+ self.stdout.write("{0} records deleted".format(index))
self.stdou... |
6a07b94f9c84741fcc399f9dee3945d0339b19e0 | download.py | download.py | import youtube_dl, os
from multiprocessing.pool import ThreadPool
from youtube_dl.utils import DownloadError
from datetime import datetime
from uuid import uuid4
class Download:
link = ""
done = False
error = False
started = None
uuid = ""
total = 0
finished = 0
title = ""
def __i... | import youtube_dl, os
from multiprocessing.pool import ThreadPool
from youtube_dl.utils import DownloadError
from datetime import datetime
from uuid import uuid4
class Download:
link = ""
done = False
error = False
started = None
uuid = ""
total = 0
finished = 0
title = ""
def __i... | Add function to get files for playlist | Add function to get files for playlist
| Python | mit | pielambr/PLDownload,pielambr/PLDownload | ---
+++
@@ -32,6 +32,10 @@
finally:
self.done = True
+ def get_files(self):
+ file_path = os.path.dirname(os.path.abspath(__file__)) + "/downloads/" + self.uuid
+ return [f for f in os.listdir(file_path) if os.isfile(os.join(file_path, f))]
+
def start(self):
... |
181c80532d54f2cccf092f8785be0604fda3b99d | derrida/__init__.py | derrida/__init__.py | __version_info__ = (1, 3, 0, 'dev')
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environ... | __version_info__ = (1, 2, 3, None)
# Dot-connect all but the last. Last is dash-connected if not None.
__version__ = '.'.join([str(i) for i in __version_info__[:-1]])
if __version_info__[-1] is not None:
__version__ += ('-%s' % (__version_info__[-1],))
# context processor to add version to the template environm... | Set version to 1.2.3 release | Set version to 1.2.3 release
| Python | apache-2.0 | Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django,Princeton-CDH/derrida-django | ---
+++
@@ -1,4 +1,4 @@
-__version_info__ = (1, 3, 0, 'dev')
+__version_info__ = (1, 2, 3, None)
# Dot-connect all but the last. Last is dash-connected if not None. |
4eeec96f3c79b9584278639293631ab787132f67 | custom/ewsghana/reminders/third_soh_reminder.py | custom/ewsghana/reminders/third_soh_reminder.py | from corehq.apps.locations.models import SQLLocation
from corehq.apps.users.models import CommCareUser
from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder
class ThirdSOHReminder(SecondSOHReminder):
def get_users_messages(self):
for sql_location in SQLLocation.objects.filter(domain... | from corehq.apps.locations.dbaccessors import get_web_users_by_location
from corehq.apps.locations.models import SQLLocation
from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient
from corehq.apps.users.models import CommCareUser
from custom.ewsghana.reminders.second_soh_reminder import SecondS... | Send third soh also to web users | Send third soh also to web users
| Python | bsd-3-clause | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -1,20 +1,36 @@
+from corehq.apps.locations.dbaccessors import get_web_users_by_location
from corehq.apps.locations.models import SQLLocation
+from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient
from corehq.apps.users.models import CommCareUser
from custom.ewsghana.reminders.s... |
859cd49b628bb430a721ba89883c3a0efbbbdbbc | tensorflow/python/autograph/core/config.py | tensorflow/python/autograph/core/config.py | # Copyright 2016 The TensorFlow 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 applica... | # Copyright 2016 The TensorFlow 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 applica... | Fix breakage: conversion of tf.data was allowed too soon and broke the autograph notebook. | Fix breakage: conversion of tf.data was allowed too soon and broke the autograph notebook.
PiperOrigin-RevId: 250764059
| Python | apache-2.0 | renyi533/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,xzturn/tensorflow,arborh/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tens... | ---
+++
@@ -28,8 +28,6 @@
# This list is evaluated in order and stops at the first rule that tests True
# for a definitely_convert of definitely_bypass call.
CONVERSION_RULES = (
- Convert('tensorflow.python.data.ops'),
-
DoNotConvert('tensorflow'),
# TODO(b/133417201): Remove. |
172372000f121b31daa0965dca3bf28976b6cba9 | aiodocker/exceptions.py | aiodocker/exceptions.py | class DockerError(Exception):
def __init__(self, status, data, *args):
super().__init__(*args)
self.status = status
self.message = data['message']
def __repr__(self):
return 'DockerError({self.status}, {self.message!r})'.format(self=self)
def __str__(self):
return ... | class DockerError(Exception):
def __init__(self, status, data, *args):
super().__init__(*args)
self.status = status
self.message = data['message']
def __repr__(self):
return 'DockerError({self.status}, {self.message!r})'.format(self=self)
def __str__(self):
return ... | Fix flake8 error (too long line) | Fix flake8 error (too long line)
| Python | mit | barrachri/aiodocker,gaopeiliang/aiodocker,paultag/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker | ---
+++
@@ -19,7 +19,11 @@
self.container_id = container_id
def __repr__(self):
- return 'DockerContainerError({self.status}, {self.message!r}, {self.container_id!r})'.format(self=self)
+ return ('DockerContainerError('
+ '{self.status}, {self.message!r}, '
+ ... |
540273ac75880925934e69275c9da1de61fbd699 | PyBingWallpaper.py | PyBingWallpaper.py | #! /usr/bin/python3
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
#Variables:
saveDir = 'C:\BingWallPaper\\'
i = 0
while i<1:
try:
usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
ex... | #! /usr/bin/python3
import win32gui
from urllib.request import urlopen, urlretrieve
from xml.dom import minidom
from PIL import Image
import os
if __name__=="__main__":
#Variables:
saveDir = "C:\\BingWallPaper\\"
if (not os.path.exists(saveDir)):
os.mkdir(saveDir)
i = 0
while i<1... | Create directory in case not exist | Create directory in case not exist | Python | mit | adamadanandy/PyBingWallpaper | ---
+++
@@ -6,30 +6,35 @@
from PIL import Image
import os
-
-#Variables:
-saveDir = 'C:\BingWallPaper\\'
-i = 0
-while i<1:
- try:
- usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN')
- except:
- i = 0
- else:
- i = 1
-xmldoc = minidom.parse(uso... |
e752a0ab47da9d9b34b5ce6f5cd40ac98977ec6e | symUtil.py | symUtil.py | import os
import re
def mkdir_p(path):
if not os.path.exists(path):
os.makedirs(path)
def GetSymbolFileName(libName):
# Guess the name of the .sym file on disk
if libName[-4:] == ".pdb":
return re.sub(r"\.[^\.]+$", ".sym", libName)
return libName + ".sym"
| import os
def mkdir_p(path):
if not os.path.exists(path):
os.makedirs(path)
def GetSymbolFileName(libName):
# Guess the name of the .sym file on disk
if libName[-4:] == ".pdb":
return libName[:-4] + ".sym"
return libName + ".sym"
| Refactor out the re. It's not necessary to regex the replacement of an explicitly checked string in an explicit location. This should be simpler. | Refactor out the re. It's not necessary to regex the replacement of an explicitly checked string in an explicit location. This should be simpler.
| Python | mpl-2.0 | bytesized/Snappy-Symbolication-Server | ---
+++
@@ -1,5 +1,4 @@
import os
-import re
def mkdir_p(path):
if not os.path.exists(path):
@@ -8,6 +7,6 @@
def GetSymbolFileName(libName):
# Guess the name of the .sym file on disk
if libName[-4:] == ".pdb":
- return re.sub(r"\.[^\.]+$", ".sym", libName)
+ return libName[:-4] + ".sym"
return ... |
2b1cd9a58aa51ef53996dc1897a7a0e50f29d7ca | isitopenaccess/plugins/bmc.py | isitopenaccess/plugins/bmc.py | import requests
from copy import deepcopy
from datetime import datetime
from isitopenaccess.plugins import string_matcher
def page_license(record):
"""
To respond to the provider identifier: http://www.biomedcentral.com
This should determine the licence conditions of the BMC article and populate
... | import requests
from copy import deepcopy
from datetime import datetime
from isitopenaccess.plugins import string_matcher
def page_license(record):
"""
To respond to the provider identifier: http://www.biomedcentral.com
This should determine the licence conditions of the BMC article and populate
... | ADD MISSING FILE TO PREV COMMIT "modify BMC plugin: overwrite URL for CC-BY license. We have a MORE specific URL (from the license statement on the BMC pages) than the Open Definition one" | ADD MISSING FILE TO PREV COMMIT "modify BMC plugin: overwrite URL for CC-BY license. We have a MORE specific URL (from the license statement on the BMC pages) than the Open Definition one"
| Python | bsd-3-clause | CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge | ---
+++
@@ -18,7 +18,9 @@
# and meaning['version'] identifies the license version (if available)
lic_statements = [
{"This is an Open Access article distributed under the terms of the Creative Commons Attribution License (<a href='http://creativecommons.org/licenses/by/2.0'>http://creativecommons.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.