commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
aaa0f03a91f3326dc893175510a4ad35649ec371 | pltpreview/view.py | pltpreview/view.py | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
a... | """Convenience functions for matplotlib plotting and image viewing."""
import numpy as np
from matplotlib import pyplot as plt
def show(image, blocking=False, **kwargs):
"""Show *image*. If *blocking* is False the call is nonblocking.
*kwargs* are passed to matplotlib's ``imshow`` function. This command
a... | Create new figure in plot command | Create new figure in plot command
| Python | mit | tfarago/pltpreview |
48087c2cc8cd9d0bb84014ea4b91fe2f68f958c4 | gant/utils/docker_helper.py | gant/utils/docker_helper.py | # Helper functions for docker
import docker
import os
DEFAULT_DOCKER_API_VERSION = '1.10'
BASEIMAGETAG = "glusterbase:latest"
GLUSTERIMAGENAME = "gluster:latest"
BASEDIR=os.getcwd()
class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__ (self):
... | # Helper functions for docker
import docker
import os
DEFAULT_DOCKER_API_VERSION = '1.10'
BASEIMAGETAG = "glusterbase:latest"
GLUSTERIMAGENAME = "gluster:latest"
BASEDIR=os.getcwd()
class DockerHelper (docker.Client):
"""
Extended docker client with some helper functions
"""
def __init__ (self):
... | Add docker helper to get ip | Add docker helper to get ip
| Python | bsd-2-clause | kshlm/gant |
512ae6bd0ce42dc659f7cf4766fdc80587718909 | go/apps/jsbox/definition.py | go/apps/jsbox/definition.py | import json
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinition... | import json
from go.vumitools.conversation.definition import (
ConversationDefinitionBase, ConversationAction)
class ViewLogsAction(ConversationAction):
action_name = 'view_logs'
action_display_name = 'View Sandbox Logs'
redirect_to = 'jsbox_logs'
class ConversationDefinition(ConversationDefinition... | Remove ancient TODO that was resolved a long time ago. | Remove ancient TODO that was resolved a long time ago.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
1a211c264de52fbd4719aaa130129f73388a5dd4 | fore/hotswap.py | fore/hotswap.py | import os
import logging
import threading
log = logging.getLogger(__name__)
class Hotswap(threading.Thread):
def __init__(self, out, mod, *args, **kwargs):
self.out = out
self.mod = mod
self.gen = mod.generate(*args, **kwargs)
self.loaded = self.current_modtime
self.args =... | import os
import logging
import threading
log = logging.getLogger(__name__)
class Hotswap(threading.Thread):
def __init__(self, out, mod, *args, **kwargs):
self.out = out
self.gen = mod.generate(*args, **kwargs)
threading.Thread.__init__(self)
self.daemon = True
def run(self... | Remove all references to actually swapping | Hotswap: Remove all references to actually swapping
| Python | artistic-2.0 | Rosuav/appension,Rosuav/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,MikeiLL/appension,Rosuav/appension,Rosuav/appension |
0d5072aea49ed5c34bc3c140a5019e59506135a4 | menus/database_setup.py | menus/database_setup.py | import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
name = Column(String(80),... | import sys
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class Restaurant(Base):
__tablename__ = 'restaurant'
name = Column(String(80),... | Remove description from Restaurant class | bug: Remove description from Restaurant class
| Python | mit | gsbullmer/restaurant-menu-directory,gsbullmer/restaurant-menu-directory |
d1b7753fd29cb5c1f68b5ee121a511e43c99b5de | pmix/ppp/odkcalculate.py | pmix/ppp/odkcalculate.py | class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self):
return ""
def to_text(self):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
| class OdkCalculate:
def __init__(self, row):
self.row = row
def to_html(self, *args, **kwargs):
return ""
def to_text(self, *args, **kwargs):
return ""
def __repr__(self):
return '<OdkCalculate {}>'.format(self.row['name'])
| Update signature of to_text and to_html | Update signature of to_text and to_html
| Python | mit | jkpr/pmix |
d7e2f05d60aaba3d13337fd53add9fd50aafd6ee | tests/test_python_solutions.py | tests/test_python_solutions.py | import glob
import json
import os
import time
import pytest
from helpers import solutions_dir
# NOTE: If we make solution files a fixture instead of a normal attr/function,
# then we can't use it in pytest's parametrize
solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py"))
@pytest.mark.python... | import glob
import json
import os
import time
import pytest
from helpers import solutions_dir
# NOTE: If we make solution_files a fixture instead of a normal attr/function,
# then we can't use it in pytest's parametrize
solution_files = glob.glob(os.path.join(solutions_dir("python"), "*.py"))
@pytest.mark.python... | Add ids to parametrized tests | Add ids to parametrized tests
| Python | mit | project-lovelace/lovelace-engine,project-lovelace/lovelace-engine,project-lovelace/lovelace-engine |
53b519c4912d7b3cc32f000eea73bc4d9693967e | tests/test_basic.py | tests/test_basic.py | import pytest
import subprocess
import os
import sys
prefix = '.'
for i in range(0,3):
if os.path.exists(os.path.join(prefix, 'pyiso.py')):
sys.path.insert(0, prefix)
break
else:
prefix = '../' + prefix
import pyiso
def test_nofiles(tmpdir):
# First set things up, and generate the... | import pytest
import subprocess
import os
import sys
prefix = '.'
for i in range(0,3):
if os.path.exists(os.path.join(prefix, 'pyiso.py')):
sys.path.insert(0, prefix)
break
else:
prefix = '../' + prefix
import pyiso
def test_nofiles(tmpdir):
# First set things up, and generate the... | Add in more unit tests. | Add in more unit tests.
Signed-off-by: Chris Lalancette <281cd07d7578d97c83271fbbf2faddb83ab3791c@gmail.com>
| Python | lgpl-2.1 | clalancette/pycdlib,clalancette/pyiso |
f71dd9055ba04d8aa0024d66d0782107a4b1ca08 | lmod_proxy/tests/test_web.py | lmod_proxy/tests/test_web.py | # -*- coding: utf-8 -*-
"""
Test the root Web application
"""
import imp
from lmod_proxy.tests.common import CommonTest
class TestWeb(CommonTest):
"""Verify the root Web app. Currently it just redirects to edx_grades"""
def setUp(self):
"""Setup commonly needed objects like the flask test client"""... | # -*- coding: utf-8 -*-
"""
Test the root Web application
"""
import imp
import mock
from passlib.apache import HtpasswdFile
from lmod_proxy.tests.common import CommonTest
class TestWeb(CommonTest):
"""Verify the root Web app. Currently it just redirects to edx_grades"""
def setUp(self):
"""Setup ... | Verify we handle null HTPasswd files | Verify we handle null HTPasswd files
| Python | agpl-3.0 | mitodl/lmod_proxy,mitodl/lmod_proxy,mitodl/lmod_proxy |
f44630714ce1c20c88919a1ce8d9e4ad49ec9fde | nodeconductor/cloud/perms.py | nodeconductor/cloud/perms.py | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic
from nodeconductor.structure.models import CustomerRole
User = get_user_model()
PERMISSION_LOGICS = (
('cloud.Cloud', FilteredCollaboratorsPerm... | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from nodeconductor.core.permissions import FilteredCollaboratorsPermissionLogic
from nodeconductor.structure.models import CustomerRole
User = get_user_model()
PERMISSION_LOGICS = (
('cloud.Cloud', FilteredCollaboratorsPerm... | Fix permission path for customer role lookup | Fix permission path for customer role lookup
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
aaa8743c8610eb4b5ae7d08167715f3c1181d4d5 | app/sessions.py | app/sessions.py | from functools import wraps
from flask import request, abort, redirect, url_for, render_template
from flask.ext.login import LoginManager, login_user, logout_user, login_required
from app import app, db
from app.models import User
login_manager = LoginManager()
login_manager.init_app(app)
# required function for f... | from functools import wraps
from flask import request, abort, redirect, url_for, render_template
from flask.ext.login import LoginManager, login_user, logout_user, login_required
from app import app, db
from app.models import User
login_manager = LoginManager()
login_manager.init_app(app)
# required function for f... | Remove development auto admin user creation | Remove development auto admin user creation
| Python | mit | tjgavlick/whiskey-blog,tjgavlick/whiskey-blog,tjgavlick/whiskey-blog,tjgavlick/whiskey-blog |
28b067ab7fc7385ac5462eb6c9f9371cef9eb496 | ritter/dataprocessors/annotators.py | ritter/dataprocessors/annotators.py | import re
class ArtifactAnnotator:
def linkify_artifacts(marked_tree, artifacts):
big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)
for artifact in artifacts:
link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
for token in artifact['tokens']:
... | import re
class ArtifactAnnotator:
excluded_types = set(['heading', 'code'])
def linkify_artifacts(marked_tree, artifacts):
big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)
for artifact in artifacts:
link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
... | Improve annotating of code segements | feat: Improve annotating of code segements
| Python | mit | ErikGartner/ghostdoc-ritter |
8806f70fc5d38d5aa8a49fbe096deb778df3c247 | schemas.py | schemas.py | from models import Reservation
from setup import ma
from marshmallow import fields
class ReservationSchema(ma.ModelSchema):
user = fields.Method('get_user')
def get_user(self, reservation):
user = self.context
if user.admin or reservation.user == user:
return reservation.user.id
... | from models import Reservation
from setup import ma
from marshmallow import fields
class ReservationSchema(ma.ModelSchema):
user = fields.Method('get_user')
def get_user(self, reservation, **kwargs):
user = self.context['user']
if user.admin or reservation.user == user:
return res... | Fix user in reservations responses | Fix user in reservations responses
| Python | agpl-3.0 | CMU-Senate/tcc-room-reservation,CMU-Senate/tcc-room-reservation,CMU-Senate/tcc-room-reservation |
c67d9b1b45d64743698c52331e7fadc4ed5f8236 | properties/prandtl_meyer_function.py | properties/prandtl_meyer_function.py | #!/usr/bin/env python
from math import atan, pi, sqrt
from properties.constants import GAMMA
def nu_in_rad(m):
if m < 1:
raise ValueError('Mach number should be greater than or equal to 1')
a = (GAMMA+1) / (GAMMA-1)
b = m**2 - 1
c = a**-1 * b
return sqrt(a) * atan(sqrt(c)) - atan(sqrt(b... | #!/usr/bin/env python
from __future__ import absolute_import, division
from math import asin, atan, degrees, sqrt
from properties.constants import GAMMA
def nu_in_rad(m):
if m < 1:
raise ValueError('Mach number should be greater than or equal to 1')
a = (GAMMA+1) / (GAMMA-1)
b = m**2 - 1
c... | Add mu_in_rad and mu_in_deg, use built in method to convert rad to deg | Add mu_in_rad and mu_in_deg, use built in method to convert rad to deg
| Python | mit | iwarobots/TunnelDesign |
840efdbc3771f60881e4052feaea18a9ea7d8eda | SLA_bot/gameevent.py | SLA_bot/gameevent.py | class GameEvent:
def __init__(self, name, start, end = None):
self.name = name
self.start = start
self.end = end
@classmethod
def from_ical(cls, component):
n = component.get('summary')
s = component.get('dtstart').dt
e = getattr(component.get('dtend'... | class GameEvent:
def __init__(self, name, start, end = None):
self.name = name
self.start = start
self.end = end
@classmethod
def from_ical(cls, component):
n = component.get('summary')
s = component.get('dtstart').dt
e = getattr(component.get('dtend'... | Add functions to get external alerts | Add functions to get external alerts
For the purpose of getting unscheduled events
| Python | mit | EsqWiggles/SLA-bot,EsqWiggles/SLA-bot |
3fec4855d53a5077762892295582601cc193d068 | tests/scoring_engine/models/test_kb.py | tests/scoring_engine/models/test_kb.py | from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6")
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2,3,4,5,6'
... | from scoring_engine.models.kb import KB
from tests.scoring_engine.unit_test import UnitTest
class TestKB(UnitTest):
def test_init_property(self):
kb = KB(name="task_ids", value="1,2,3,4,5,6", round_num=100)
assert kb.id is None
assert kb.name == 'task_ids'
assert kb.value == '1,2... | Update kb test to check for port_num | Update kb test to check for port_num
Signed-off-by: Brandon Myers <9cda508be11a1ae7ceef912b85c196946f0ec5f3@mozilla.com>
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
b3975b4e5b855eb212cc5171e17ed93e315f1c30 | cheap_repr/utils.py | cheap_repr/utils.py | import traceback
from qualname import qualname
def safe_qualname(cls):
# type: (type) -> str
result = _safe_qualname_cache.get(cls)
if not result:
try:
result = qualname(cls)
except (AttributeError, IOError):
result = cls.__name__
if '<locals>' not in resul... | import traceback
from qualname import qualname
def safe_qualname(cls):
# type: (type) -> str
result = _safe_qualname_cache.get(cls)
if not result:
try:
result = qualname(cls)
except (AttributeError, IOError, SyntaxError):
result = cls.__name__
if '<locals>'... | Make safe_qualname more permissive (getting syntax errors on travis in 2.6) | Make safe_qualname more permissive (getting syntax errors on travis in 2.6)
| Python | mit | alexmojaki/cheap_repr,alexmojaki/cheap_repr |
94a128b7202c5629b77208a401222f3dcba92196 | anonymoustre/main.py | anonymoustre/main.py | from functools import reduce
import pprint
import time
import shodan
import requests
import api_key
from google_api import query_google_api
from shodan_api import query_shodan_api
from mxtoolbox_api import query_mxtoolbox_api
from utils import assoc_default_score, combine_scores
pp = pprint.PrettyPrinter(indent=2)
... | from functools import reduce
import pprint
import time
import shodan
import requests
import api_key
from google_api import query_google_api
from shodan_api import query_shodan_api
from mxtoolbox_api import query_mxtoolbox_api
from utils import assoc_default_score, combine_scores
pp = pprint.PrettyPrinter(indent=2)
... | Comment mxtoolbox because of limited requests | Comment mxtoolbox because of limited requests
| Python | mit | Dominionized/anonymoustre,Dominionized/anonymoustre |
a605e6b294e941d9278601c3af0330f0b802534e | src/controller.py | src/controller.py | #!/usr/bin/env python
import rospy
def compute_control_actions(msg):
pass
if __name__ == '__main__':
rospy.init_node('controller')
subscriber = rospy.Subscriber('odometry_10_hz', Odometry, compute_control_actions)
rospy.spin()
| #!/usr/bin/env python
import rospy
import tf
from nav_msgs.msg import Odometry
i = 0
def get_position(pose):
return pose.pose.position
def get_orientation(pose):
quaternion = (
pose.pose.orientation.x,
pose.pose.orientation.y,
pose.pose.orientation.z,
pose.pose.orientation.w
... | Implement functions to obtain position and orientation given a pose | Implement functions to obtain position and orientation given a pose
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking |
ee9b6b1640745bb7b757f1ec8603b19d4f678fb8 | core/observables/file.py | core/observables/file.py | from __future__ import unicode_literals
from mongoengine import *
from core.observables import Observable
from core.observables import Hash
class File(Observable):
value = StringField(verbose_name="SHA256 hash")
mime_type = StringField(verbose_name="MIME type")
hashes = DictField(verbose_name="Hashes"... | from __future__ import unicode_literals
from flask import url_for
from flask_mongoengine.wtf import model_form
from mongoengine import *
from core.observables import Observable
from core.database import StringListField
class File(Observable):
value = StringField(verbose_name="Value")
mime_type = StringFie... | Clean up File edit view | Clean up File edit view
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
0d6a8f3978188f3e343c364806e0bb6e6ac1e643 | tests/qtcore/qmetaobject_test.py | tests/qtcore/qmetaobject_test.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide.QtCore import *
class Foo(QFile):
pass
class qmetaobject_test(unittest.TestCase):
def test_QMetaObject(self):
qobj = QObject()
qobj_metaobj = qobj.metaObject()
... | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''Tests for static methos conflicts with class methods'''
import unittest
from PySide.QtCore import *
class Foo(QFile):
pass
class qmetaobject_test(unittest.TestCase):
def test_QMetaObject(self):
qobj = QObject()
qobj_metaobj = qobj.metaObject()
... | Fix qmentaobject test to work with dynamic metaobject. | Fix qmentaobject test to work with dynamic metaobject.
| Python | lgpl-2.1 | M4rtinK/pyside-android,pankajp/pyside,enthought/pyside,PySide/PySide,qtproject/pyside-pyside,PySide/PySide,gbaty/pyside2,enthought/pyside,RobinD42/pyside,enthought/pyside,PySide/PySide,BadSingleton/pyside2,M4rtinK/pyside-android,BadSingleton/pyside2,qtproject/pyside-pyside,BadSingleton/pyside2,RobinD42/pyside,pankajp/p... |
80638b2070f578408f00d7a263ccfb27fea5b1d4 | api/base/language.py | api/base/language.py | from django.utils.translation import ugettext_lazy as _
BEFORE_BULK_DELETE = _('Are you sure you want to delete these projects? They will no longer be '
'available to other contributors. Send delete request to new URL to confirm.')
| from django.utils.translation import ugettext_lazy as _
BEFORE_BULK_DELETE = _('Are you sure you want to delete these projects? They will no longer be '
'available to other contributors. Send delete request to new URL with same '
'query parameters to confirm.')
| Update delete warning to include instructions that same query parameters need to be in request | Update delete warning to include instructions that same query parameters need to be in request
| Python | apache-2.0 | cwisecarver/osf.io,emetsger/osf.io,rdhyee/osf.io,caseyrollins/osf.io,RomanZWang/osf.io,CenterForOpenScience/osf.io,TomBaxter/osf.io,sloria/osf.io,TomHeatwole/osf.io,GageGaskins/osf.io,monikagrabowska/osf.io,mluke93/osf.io,pattisdr/osf.io,acshi/osf.io,GageGaskins/osf.io,leb2dg/osf.io,zachjanicki/osf.io,amyshi188/osf.io,... |
b82cc421f0bd19caebc20900d774f40831746dab | numba/traits.py | numba/traits.py | """
Minimal traits implementation:
@traits
class MyClass(object):
attr = Instance(SomeClass)
my_delegation = Delegate('attr')
"""
import inspect
# from numba.utils import TypedProperty
def traits(cls):
"@traits class decorator"
for name, py_func in vars(cls).items():
if isin... | """
Minimal traits implementation:
@traits
class MyClass(object):
attr = Instance(SomeClass)
my_delegation = Delegate('attr')
"""
import inspect
# from numba.utils import TypedProperty
def traits(cls):
"@traits class decorator"
for name, py_func in vars(cls).items():
if isin... | Support deletion of trait delegate | Support deletion of trait delegate
| Python | bsd-2-clause | pitrou/numba,GaZ3ll3/numba,stefanseefeld/numba,GaZ3ll3/numba,seibert/numba,pitrou/numba,stonebig/numba,stefanseefeld/numba,gdementen/numba,GaZ3ll3/numba,stuartarchibald/numba,IntelLabs/numba,jriehl/numba,cpcloud/numba,gdementen/numba,jriehl/numba,pombredanne/numba,numba/numba,GaZ3ll3/numba,seibert/numba,ssarangi/numba,... |
0c6a5c55df5680bd8589f1040f2f16cf6aac86b3 | openprescribing/frontend/migrations/0030_add_ccg_centroids.py | openprescribing/frontend/migrations/0030_add_ccg_centroids.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-10-20 08:13
from __future__ import unicode_literals
from django.db import migrations
from frontend.management.commands.import_ccg_boundaries import set_centroids
import django.contrib.gis.db.models.fields
def set_centroids_without_args(*args):
set_cent... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-10-20 08:13
from __future__ import unicode_literals
from django.db import migrations
from frontend.management.commands.import_ccg_boundaries import set_centroids
import django.contrib.gis.db.models.fields
def set_centroids_without_args(*args):
set_cent... | Remove commented-out RunPython from migration | Remove commented-out RunPython from migration | Python | mit | ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing |
c4e1382773d1a77c0f76faf15561070f2c1b053f | product_management_group/models/ir_model_access.py | product_management_group/models/ir_model_access.py | ##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from odoo import api, models, tools, exceptions, _
class IrModelAccess(m... | ##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from odoo import api, models, tools, exceptions, _
class IrModelAccess(m... | Allow superuser to skip that restriction on products | [FIX] product_management_group: Allow superuser to skip that restriction on products
closes ingadhoc/product#409
Signed-off-by: Nicolas Mac Rouillon <8d34fe7b7c65100e706828a8c0d03426900ffb59@adhoc.com.ar>
| Python | agpl-3.0 | ingadhoc/product,ingadhoc/product |
98c207ea262e500ea4f5c338a9bb5642047b24b7 | alexandria/session.py | alexandria/session.py | from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000
... | from pyramid.session import SignedCookieSessionFactory
def includeme(config):
# Create the session factory, we are using the stock one
_session_factory = SignedCookieSessionFactory(
config.registry.settings['pyramid.secret.session'],
httponly=True,
max_age=864000,
... | Change the timeout, and reissue_time | Change the timeout, and reissue_time
We want to make sure that the session never expires, since this also
causes our CSRF token to expire, which causes issues...
| Python | isc | cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria,bertjwregeer/alexandria,cdunklau/alexandria |
f7bd83ddabcad10beeeca9b1fc1e07631e68d4e0 | src/models/c2w.py | src/models/c2w.py | from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to preserve the... | from keras.layers import LSTM, Input, Dense, TimeDistributed, Masking, Activation, merge
from keras.models import Model
from layers import Projection
def C2W(params, V_C):
one_hots = Input(shape=(params.maxlen, V_C.size), dtype='int8')
c_E = TimeDistributed(Projection(params.d_C))(one_hots)
# we want to ... | Use tanh activation for word C2W embeddings | Use tanh activation for word C2W embeddings | Python | mit | milankinen/c2w2c,milankinen/c2w2c |
0ef630bfee5a57ba2e5d487707249cdaa43ec63f | pseudorandom.py | pseudorandom.py | #!/usr/bin/env python
import os
from flask import Flask, render_template, request
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if request.headers.get('User-Agent', '')[:4].lower() == 'curl':
return u"{0}\n".format(get_full_name())
else:
return render_tem... | #!/usr/bin/env python
import os
from flask import Flask, render_template, request, make_response
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if (request.headers.get('User-Agent', '')[:4].lower() == 'curl' or
request.headers['Content-Type'] == 'text/plain'):
... | Send text response when Content-Type is text/plain | Send text response when Content-Type is text/plain
| Python | mit | treyhunner/pseudorandom.name,treyhunner/pseudorandom.name |
8bea1001922da415be24363e6fca677171c69f70 | guild/commands/shell_impl.py | guild/commands/shell_impl.py | # Copyright 2017-2018 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | # Copyright 2017-2018 TensorHub, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | Drop into repl without starting new Python process for shell cmd | Drop into repl without starting new Python process for shell cmd
| Python | apache-2.0 | guildai/guild,guildai/guild,guildai/guild,guildai/guild |
039c552b3674531a746c14d1c34bd2f13fd078e5 | Cura/util/removableStorage.py | Cura/util/removableStorage.py | import platform
import string
import glob
import os
import stat
def getPossibleSDcardDrives():
drives = []
if platform.system() == "Windows":
from ctypes import windll
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1 and windll.kernel32.GetDriveTypeA(letter + ':/')... | import platform
import string
import glob
import os
import stat
def getPossibleSDcardDrives():
drives = []
if platform.system() == "Windows":
from ctypes import windll
import ctypes
bitmask = windll.kernel32.GetLogicalDrives()
for letter in string.uppercase:
if bitmask & 1 and windll.kernel32.GetDriveType... | Enhance the SD card list with more info. | Enhance the SD card list with more info.
| Python | agpl-3.0 | alephobjects/Cura,alephobjects/Cura,alephobjects/Cura |
80d710269ff1d6421f4a29b9a0d424868cb5ec54 | flaskiwsapp/auth/jwt.py | flaskiwsapp/auth/jwt.py | from flaskiwsapp.users.controllers import get_user_by_id, get_user_by_email
from flaskiwsapp.snippets.customApi import DUMMY_ERROR_CODE
from flask_jwt import JWTError
from flask import jsonify
def authenticate(email, password):
user = get_user_by_email(email)
if user and user.check_password(password) and user... | from flaskiwsapp.users.controllers import get_user_by_id, get_user_by_email
from flaskiwsapp.snippets.customApi import DUMMY_ERROR_CODE
from flask_jwt import JWTError
from flask import jsonify
from flaskiwsapp.snippets.exceptions.userExceptions import UserDoesnotExistsException
from flask_api.status import HTTP_500_INT... | Raise JWTErrror into authentication handler | Raise JWTErrror into authentication handler | Python | mit | rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel,rafasis1986/EngineeringMidLevel |
45c773c0d2c90a57949a758ab3ac5c15e2942528 | resource_mgt.py | resource_mgt.py | """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_... | """Class to show file manipulations"""
import sys
original_file = open('wasteland.txt', mode='rt', encoding='utf-8')
file_to_write = open('wasteland-copy.txt', mode='wt', encoding='utf-8')
file_to_write.write("What are the roots that clutch, ")
file_to_write.write('what branches grow\n')
file_to_write.close()
file_r... | Add a words per line function | Add a words per line function
| Python | mit | kentoj/python-fundamentals |
f0bd7658b961daceaace56e4ada415c5c9410d54 | UM/Operations/ScaleToBoundsOperation.py | UM/Operations/ScaleToBoundsOperation.py | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Operations.Operation import Operation
from UM.Math.Vector import Vector
## Operation subclass that will scale a node to fit within the bounds provided.
class ScaleToBoundsOperation(Operation):
def __init__(... | # Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
from UM.Operations.Operation import Operation
from UM.Math.Vector import Vector
## Operation subclass that will scale a node to fit within the bounds provided.
class ScaleToBoundsOperation(Operation):
def __init__(... | Check depth before width since that is more likely to be the smaller dimension | Check depth before width since that is more likely to be the smaller dimension
Contributes to Asana issue 37107676459484
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
0e26a5764888a53859a5362afeaaccbd36ca62ac | gaesecure/decorators.py | gaesecure/decorators.py | from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(reques... | from functools import wraps
from django.http import HttpResponseForbidden
from google.appengine.api.users import is_current_user_admin
def task_queue_only(view_func):
""" View decorator that only allows requests which originate from the App Engine task queue.
"""
@wraps(view_func)
def new_view(reques... | Fix copy-paste-o in exception message. | Fix copy-paste-o in exception message.
| Python | mit | adamalton/django-gae-secure |
3f31234454949e7dca3b91d9884568da57ab9fcd | conftest.py | conftest.py | import pytest
import json
import os.path
from fixture.application import Application
fixture = None
target = None
@pytest.fixture
def app(request):
global fixture
global target
browser = request.config.getoption("--browser")
if target is None:
config_file = os.path.join(os.path.dirname(os.pat... | import pytest
import json
import os.path
import importlib
import jsonpickle
from fixture.application import Application
fixture = None
target = None
@pytest.fixture
def app(request):
global fixture
global target
browser = request.config.getoption("--browser")
if target is None:
config_file = ... | Add test data loading from file and test data parametrization | Add test data loading from file and test data parametrization
| Python | apache-2.0 | ujilia/python_training2,ujilia/python_training2,ujilia/python_training2 |
f3986b1c86d4fc8b0fa52fd2e7221b8d6a5e3cab | system/protocols/capabilities.py | system/protocols/capabilities.py | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... | # coding=utf-8
from enum import Enum, unique
__author__ = 'Sean'
__all__ = ["Capabilities"]
@unique
class Capabilities(Enum):
"""
An enum containing constants to declare what a protocol is capable of
You can use *protocol.get_capabilities()* or *protocol.has_capability(cap)*
to get all of a protocol... | Fix doc formatting; wasn't expecting <pre> | [Capabilities] Fix doc formatting; wasn't expecting <pre>
| Python | artistic-2.0 | UltrosBot/Ultros,UltrosBot/Ultros |
1a709d7240c0bbc1b1eab3c8803ed55b6657ec97 | serializers/json_serializer.py | serializers/json_serializer.py | from StringIO import StringIO
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder, DateTimeAwareJSONEncoder
from django.core.serializers.base import DeserializationError
from riv.serializers import base
class Serializer(base.Serializer):
internal_use_only = False
def get_... | from StringIO import StringIO
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder, DateTimeAwareJSONEncoder
from django.core.serializers.base import DeserializationError
from riv.serializers import base_serializer as base
class Serializer(base.Serializer):
internal_use_only... | Fix import in the json serializer | Fix import in the json serializer
| Python | mit | danrex/django-riv,danrex/django-riv |
7793f135808c1c133187f1d0a053b4f5549b58e8 | lgogwebui.py | lgogwebui.py | #!/usr/bin/env python3
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json')) as f:
data = json.load(f)
... | #!/usr/bin/env python3
import json
import os
import config
from models import Game, Status, session
from flask import Flask, render_template, redirect, url_for
app = Flask(__name__)
@app.route('/')
def library():
with open(os.path.join(config.lgog_cache, 'gamedetails.json'), encoding='utf-8') as f:
data =... | Correct UTF encoding of lgogdownloader json file. | Correct UTF encoding of lgogdownloader json file.
| Python | bsd-2-clause | graag/lgogwebui,graag/lgogwebui,graag/lgogwebui |
256bfb9e2d04fbd03ec2f4d3551e8a9d5ae11766 | cardbox/deck_urls.py | cardbox/deck_urls.py | from django.conf.urls import patterns, include, url
import deck_views
urlpatterns = patterns('',
url(r'^$', deck_views.index, name='index'),
)
| from django.conf.urls import patterns, include, url
import deck_views
urlpatterns = patterns('',
url(r'^$',
deck_views.DeckList.as_view(template_name="cardbox/deck/deck_list.html"),
name='deck_list'),
url(r'^new$', dec... | Add URL rules for deck CRUD | Add URL rules for deck CRUD
| Python | mit | DummyDivision/Tsune,DummyDivision/Tsune,DummyDivision/Tsune |
98e333bafafc0161a256b2df895d269825910aab | mopidy/backends/dummy.py | mopidy/backends/dummy.py | from mopidy.backends import BaseBackend
class DummyBackend(BaseBackend):
def __init__(self, *args, **kwargs):
super(DummyBackend, self).__init__(*args, **kwargs)
def url_handlers(self):
return [u'dummy:']
def _next(self):
return True
def _pause(self):
return True
... | from mopidy.backends import (BaseBackend, BaseCurrentPlaylistController,
BasePlaybackController, BaseLibraryController,
BaseStoredPlaylistsController)
class DummyBackend(BaseBackend):
def __init__(self):
self.current_playlist = DummyCurrentPlaylistController(backend=self)
self.library = Dum... | Update DummyBackend to adhere to new backend API | Update DummyBackend to adhere to new backend API
| Python | apache-2.0 | mopidy/mopidy,ZenithDK/mopidy,abarisain/mopidy,jcass77/mopidy,hkariti/mopidy,rawdlite/mopidy,glogiotatidis/mopidy,glogiotatidis/mopidy,abarisain/mopidy,dbrgn/mopidy,dbrgn/mopidy,rawdlite/mopidy,diandiankan/mopidy,priestd09/mopidy,SuperStarPL/mopidy,ZenithDK/mopidy,woutervanwijk/mopidy,hkariti/mopidy,mokieyue/mopidy,lia... |
914e419cd753f6815b2aa308b49d7ed357b523d6 | muzicast/web/__init__.py | muzicast/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
app.secret_key = os.urandom(24)
| import os
from flask import Flask
app = Flask(__name__)
from muzicast.web.admin import admin
app.register_module(admin, url_prefix='/admin')
#from muzicast.web.music import artist, album, track
#app.register_module(artist, url_prefix='/artist')
#app.register_module(album, url_prefix='/album')
#app.register_module(tr... | Add handler modules as required | Add handler modules as required
| Python | mit | nikhilm/muzicast,nikhilm/muzicast |
77500ad76ce321287bcd0b33ea5eac1766583bc7 | storage/mongo_storage.py | storage/mongo_storage.py | from storage import Storage
class MongoStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
self.password = config_dict['password']
... | from storage import Storage
TASKS = [
{'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
{'task_id': 2, 'task_status': 'Pending', 'report_id': None},
]
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163b62f583dbaff... | Add mock functionality for mongo storage | Add mock functionality for mongo storage
| Python | mpl-2.0 | jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,mitre/multiscanner,awest1339/multiscanner |
ba80f05525bcaa7a9192b6e161158af184c6d234 | treepace/trees.py | treepace/trees.py | """Tree interfaces and implementations."""
class Node:
"""A general tree node with references to children.
There is no distinction between a whole tree and a node - the tree is just
represented by a root node.
"""
def __init__(self, value, children=[]):
"""Construct a new tree nod... | """Tree interfaces and implementations."""
class Node:
"""A general tree node with references to children.
There is no distinction between a whole tree and a node - the tree is just
represented by a root node.
"""
def __init__(self, value, children=[]):
"""Construct a new tree nod... | Fix node list which was referenced, not copied | Fix node list which was referenced, not copied
| Python | mit | sulir/treepace |
f52318c12d89c2a415519d2d3869879c3edda887 | test/proper_noun_test.py | test/proper_noun_test.py |
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentence():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentence():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_... |
from jargonprofiler.util import tag_proper_nouns
from jargonprofiler.munroe import munroe_score
def test_proper_noun_in_sentence():
assert tag_proper_nouns("My name is Eilis.") == set(["Eilis"])
def test_proper_noun_begins_sentence():
assert tag_proper_nouns("Eilis is a girl") == set(["Eilis"])
def test_... | Work around quirk of POS tagger | Work around quirk of POS tagger
| Python | mit | ejh243/MunroeJargonProfiler,ejh243/MunroeJargonProfiler |
185906c1afc2bc38f0a7282e2b22e49262a73f9b | south/models.py | south/models.py | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
class Meta:
unique_together = (('app_name', 'migration'),)
@classmethod
def for_migrat... | from django.db import models
class MigrationHistory(models.Model):
app_name = models.CharField(max_length=255)
migration = models.CharField(max_length=255)
applied = models.DateTimeField(blank=True)
@classmethod
def for_migration(cls, migration):
try:
return cls.objects.get(app... | Remove unique_together on the model; the key length was too long on wide-character MySQL installs. | Remove unique_together on the model; the key length was too long on wide-character MySQL installs.
| Python | apache-2.0 | smartfile/django-south,smartfile/django-south |
3ab25e30e26ba7edf2f732ff0d4fa42b1446f6dc | txampext/test/test_axiomtypes.py | txampext/test/test_axiomtypes.py | try:
from txampext import axiomtypes; axiomtypes
from axiom import attributes
except ImportError:
axiomtypes = None
from twisted.protocols import amp
from twisted.trial import unittest
class TypeForTests(unittest.TestCase):
skip = axiomtypes is None
def _test_typeFor(self, attr, expectedType, **... | try:
from txampext import axiomtypes; axiomtypes
from axiom import attributes
except ImportError: # pragma: no cover
axiomtypes = None
from twisted.protocols import amp
from twisted.trial import unittest
class TypeForTests(unittest.TestCase):
skip = axiomtypes is None
def _test_typeFor(self, at... | Add 'no cover' pragma to hide bogus missing code coverage | Add 'no cover' pragma to hide bogus missing code coverage
| Python | isc | lvh/txampext |
4ae366e41c91191733e4715d00127f163e3a89b0 | influxalchemy/client.py | influxalchemy/client.py | """ InfluxAlchemy Client. """
from . import query
from .measurement import Measurement
class InfluxAlchemy(object):
""" InfluxAlchemy database session.
client (InfluxDBClient): Connection to InfluxDB database
"""
def __init__(self, client):
self.bind = client
# pylint: disable=p... | """ InfluxAlchemy Client. """
from . import query
from .measurement import Measurement
class InfluxAlchemy(object):
""" InfluxAlchemy database session.
client (InfluxDBClient): Connection to InfluxDB database
"""
def __init__(self, client):
self.bind = client
# pylint: disable=p... | Fix how to get tags and fields name | Fix how to get tags and fields name
The old implementation returns 'integer', 'float' in the result list.
| Python | mit | amancevice/influxalchemy |
1e8cc5743f32bb5f6e2e9bcbee0f78e3df357449 | tests/test_fastpbkdf2.py | tests/test_fastpbkdf2.py | import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
| import binascii
import pytest
from fastpbkdf2 import pbkdf2_hmac
def test_unsupported_algorithm():
with pytest.raises(ValueError):
pbkdf2_hmac("foo", b"password", b"salt", 1)
@pytest.mark.parametrize("password,salt,iterations,length,derived_key", [
(b"password", b"salt",
1, 20, b"0c60c80f961f... | Add test for RFC 6070 vectors. | Add test for RFC 6070 vectors.
| Python | apache-2.0 | Ayrx/python-fastpbkdf2,Ayrx/python-fastpbkdf2 |
90ade823700da61824c113759f847bf08823c148 | nova/objects/__init__.py | nova/objects/__init__.py | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | # Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | Add security_group_rule to objects registry | Add security_group_rule to objects registry
This adds the security_group_rule module to the objects registry,
which allows a service to make sure that all of its objects are
registered before any could be received over RPC.
We don't really have a test for any of these because of the nature
of how they're imported. Re... | Python | apache-2.0 | citrix-openstack-build/oslo.versionedobjects,openstack/oslo.versionedobjects |
d473ab017fb5f3e74705fbbd903ec4675d26730a | tests/test_util.py | tests/test_util.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from libvcs.util import mkdir_p, which
def test_mkdir_p(tmpdir):
path = tmpdir.join('file').ensure()
with pytest.raises(Exception) as excinfo:
mkdir_p(str(path))
excinfo.match(r'Could ... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import pytest
from libvcs.util import mkdir_p, which
def test_mkdir_p(tmpdir):
path = tmpdir.join('file').ensure()
with pytest.raises(Exception) as excinfo:
mkdir_p(str(path))
excinfo.match(r'Could ... | Fix test warning on python 2 envs | Fix test warning on python 2 envs
| Python | mit | tony/libvcs |
3a586e2d584de1a70dd62ca0c9548fbc7a092164 | calvin/runtime/south/calvinlib/textformatlib/Pystache.py | calvin/runtime/south/calvinlib/textformatlib/Pystache.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017 Ericsson AB
#
# 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 ... | # -*- coding: utf-8 -*-
# Copyright (c) 2017 Ericsson AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Fix erroneous schema naming & others | calvinlib: Fix erroneous schema naming & others
| Python | apache-2.0 | EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base |
0197553740ff6b542515cb53ce816d629e7b5648 | tspapi/__init__.py | tspapi/__init__.py | from __future__ import absolute_import
from tspapi.api_call import _ApiCall
from tspapi.api import API
from tspapi.measurement import Measurement
from tspapi.api_exception import ConnectionError
from tspapi.api_exception import HTTPResponseError
from tspapi.source import Source
from tspapi.event import RawEvent
from ts... | from __future__ import absolute_import
from tspapi.api_exception import ConnectionError
from tspapi.api_exception import HTTPResponseError
from tspapi.measurement import Measurement
from tspapi.source import Source
from tspapi.event import RawEvent
from tspapi.event import Event
from tspapi.metric import Metric
from ts... | Rearrange imports for proper dependencies | Rearrange imports for proper dependencies
| Python | apache-2.0 | jdgwartney/pulse-api-python |
f7b43e5bc14f7fc03d085d695dbad4d910a21453 | wordpop.py | wordpop.py | #!/usr/bin/env python
import os
import redis
import json
import random
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
key = redis_client.randomkey()
json_str = redis_client.get(key)
word_data = json.loads(json_str)
lexical_entries_length = len(word_data['results'][0]['lexicalEntries'])
random_en... | #!/usr/bin/env python
import os
import redis
import json
import random
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
#Oxford API usually returns a list of synonyms
#Here we are only returning the first one
def fetch_synonym(synonyms):
if synonyms != "none":
return synonyms.split(',')... | Append synonym of the word in notification's titie | Append synonym of the word in notification's titie
| Python | mit | sbmthakur/wordpop |
bbedbab40ba6fc6b958eb7bdc5b50cef58ad0240 | bijgeschaafd/settings_test.py | bijgeschaafd/settings_test.py | import os
from settings_base import *
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.dirname(APP_ROOT)+'/newsdiffs.db',
}
}
| import os
from settings_base import *
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.dirname(APP_ROOT)+'/newsdiffs.db',
}
}
SECRET_KEY='BULLSHIT'
| Add some SECRET_KEY to the test settings in order to make Travis run. | Add some SECRET_KEY to the test settings in order to make Travis run.
| Python | mit | flupzor/newsdiffs,flupzor/bijgeschaafd,flupzor/newsdiffs,flupzor/bijgeschaafd,flupzor/bijgeschaafd,flupzor/bijgeschaafd,flupzor/newsdiffs,flupzor/newsdiffs |
c88969f2e4a1459e6a66da3f75f8ea41ae9cea9c | rplugin/python3/denite/source/denite_gtags/tags_base.py | rplugin/python3/denite/source/denite_gtags/tags_base.py | import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
def __init__(self, vim):
super().__init__(vim)
@abstractmethod
def get_search_fl... | import re
from abc import abstractmethod
from denite_gtags import GtagsBase # pylint: disable=locally-disabled, wrong-import-position
class TagsBase(GtagsBase):
TAG_PATTERN = re.compile('([^\t]+)\t(\\d+)\t(.*)')
@abstractmethod
def get_search_flags(self):
return []
def get_search_word(self, ... | Fix error on words beginning with '-' | Fix error on words beginning with '-'
| Python | mit | ozelentok/denite-gtags |
71b07eddba9400eb9729da00fba5d88b0fcefe57 | cw/cw305/util/plot.py | cw/cw305/util/plot.py | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import itertools
from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
def save_plot_to_file(traces, num... | # Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
import itertools
from bokeh.plotting import figure, show
from bokeh.palettes import Dark2_5 as palette
from bokeh.io import output_file
from bokeh.models import tools
de... | Add crosshair and hover tools to bokeh html output | Add crosshair and hover tools to bokeh html output
Signed-off-by: Alphan Ulusoy <23b245cc5a07aacf75a9db847b24c67dee1707bf@google.com>
| Python | apache-2.0 | lowRISC/ot-sca,lowRISC/ot-sca |
c81d075dd11591e6b68f3f1444d80200db24bfad | install.py | install.py | #!/usr/bin/env python
import os
import stat
import config
TEMPLATE_FILE = 'powerline-shell.py.template'
OUTPUT_FILE = 'powerline-shell.py'
SEGMENTS_DIR = 'segments'
THEMES_DIR = 'themes'
def load_source(srcfile):
try:
return ''.join(open(srcfile).readlines()) + '\n\n'
except IOError:
print 'Co... | #!/usr/bin/env python
import os
import stat
import config
import shutil
TEMPLATE_FILE = 'powerline-shell.py.template'
OUTPUT_FILE = 'powerline-shell.py'
SEGMENTS_DIR = 'segments'
THEMES_DIR = 'themes'
def load_source(srcfile):
try:
return ''.join(open(srcfile).readlines()) + '\n\n'
except IOError:
... | Create a config.py rather than having people do it manually. | Create a config.py rather than having people do it manually.
| Python | mit | banga/powerline-shell,intfrr/powerline-shell,ceholden/powerline-shell,banga/powerline-shell,bitIO/powerline-shell,paulhybryant/powerline-shell,b-ryan/powerline-shell,LeonardoGentile/powerline-shell,yc2prime/powerline-shell,dtrip/powerline-shell,fellipecastro/powerline-shell,tswsl1989/powerline-shell,paulhybryant/powerl... |
6b17ac63c7bac79eea36733be32147f3867beda8 | cis/plugins/validation/mozilliansorg_publisher_plugin.py | cis/plugins/validation/mozilliansorg_publisher_plugin.py | import logging
logger = logging.getLogger(__name__)
def run(publisher, user, profile_json):
"""
Check if a user mozillian's profile properly namespaces mozillians groups
:publisher: The CIS publisher
:user: The user from the CIS vault
:profile_json: The user profile passed by the publisher
"... | import logging
logger = logging.getLogger(__name__)
def run(publisher, user, profile_json):
"""
Check if a user mozillian's profile properly namespaces mozillians groups
and whitelists which fields mozillians.org has authority over.
:publisher: The CIS publisher
:user: The user from the CIS vaul... | Add mozillians.org validation checks (tests passed) | Add mozillians.org validation checks (tests passed)
| Python | mpl-2.0 | mozilla-iam/cis,mozilla-iam/cis |
bf3218f9d125c9b4072fc99d108fe936578c79e0 | dbversions/versions/44dccb7b8b82_update_username_to_l.py | dbversions/versions/44dccb7b8b82_update_username_to_l.py | """update username to lowercase
Revision ID: 44dccb7b8b82
Revises: 9f274a38d84
Create Date: 2014-02-27 00:55:59.913206
"""
# revision identifiers, used by Alembic.
revision = '44dccb7b8b82'
down_revision = '9f274a38d84'
from alembic import op
import sqlalchemy as sa
def upgrade():
connection = op.get_bind()
... | """update username to lowercase
Revision ID: 44dccb7b8b82
Revises: 9f274a38d84
Create Date: 2014-02-27 00:55:59.913206
"""
# revision identifiers, used by Alembic.
revision = '44dccb7b8b82'
down_revision = '9f274a38d84'
from alembic import op
import sqlalchemy as sa
def upgrade():
connection = op.get_bind()
... | Fix the lowercase migration to work in other dbs | Fix the lowercase migration to work in other dbs
| Python | agpl-3.0 | wangjun/Bookie,bookieio/Bookie,charany1/Bookie,adamlincoln/Bookie,charany1/Bookie,wangjun/Bookie,GreenLunar/Bookie,teodesson/Bookie,GreenLunar/Bookie,bookieio/Bookie,adamlincoln/Bookie,bookieio/Bookie,wangjun/Bookie,skmezanul/Bookie,teodesson/Bookie,teodesson/Bookie,bookieio/Bookie,wangjun/Bookie,teodesson/Bookie,Green... |
1e55d82bee4360608d5053ac05c8a62f57d72bf7 | erpnext_ebay/custom_methods/website_slideshow_methods.py | erpnext_ebay/custom_methods/website_slideshow_methods.py | # -*- coding: utf-8 -*-
"""Custom methods for Item doctype"""
import frappe
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > 12:
frappe.throw('Number of eBay images must be 12 or fewer!')
if doc.number_of_ebay_images < 1:
... | # -*- coding: utf-8 -*-
"""Custom methods for Item doctype"""
import frappe
MAX_EBAY_IMAGES = 12
def website_slideshow_validate(doc, _method):
"""On Website Slideshow validate docevent."""
if doc.number_of_ebay_images > MAX_EBAY_IMAGES:
frappe.throw(
f'Number of eBay images must be {MAX... | Use parameter for maximum number of eBay images | fix: Use parameter for maximum number of eBay images
| Python | mit | bglazier/erpnext_ebay,bglazier/erpnext_ebay |
cb456cbdb8850fda4b438d7f60b3aa00365f7f9b | __init__.py | __init__.py | """Open Drug Discovery Toolkit
==============================
Universal and easy to use resource for various drug discovery tasks, ie docking, virutal screening, rescoring.
Attributes
----------
toolkit : module,
Toolkits backend module, currenlty OpenBabel [ob] and RDKit [rdk].
This settin... | """Open Drug Discovery Toolkit
==============================
Universal and easy to use resource for various drug discovery tasks, ie docking, virutal screening, rescoring.
Attributes
----------
toolkit : module,
Toolkits backend module, currenlty OpenBabel [ob] and RDKit [rdk].
This settin... | Make global utulity for setting random seed | Make global utulity for setting random seed
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery |
38bd32fdfa345799e510ee75021293c124a4d21c | api/base/settings/__init__.py | api/base/settings/__init__.py | # -*- coding: utf-8 -*-
'''Consolidates settings from defaults.py and local.py.
::
>>> from api.base import settings
>>> settings.API_BASE
'v2/'
'''
import os
import warnings
import itertools
from .defaults import * # noqa
try:
from .local import * # noqa
except ImportError as error:
warnings.w... | # -*- coding: utf-8 -*-
'''Consolidates settings from defaults.py and local.py.
::
>>> from api.base import settings
>>> settings.API_BASE
'v2/'
'''
import os
from urlparse import urlparse
import warnings
import itertools
from .defaults import * # noqa
try:
from .local import * # noqa
except Import... | Fix whitelist construction -Note: institutions are schemeless, causing furl and urlparse to parse the domain as `path`. PrePriPro domai ns are validated, so they necessarily have a scheme, causing the domain to end up in `netloc`. -Do some ugly magic to get only the domain. | Fix whitelist construction
-Note: institutions are schemeless, causing furl and urlparse
to parse the domain as `path`. PrePriPro domai ns are validated,
so they necessarily have a scheme, causing the domain to end up
in `netloc`.
-Do some ugly magic to get only the domain.
| Python | apache-2.0 | caneruguz/osf.io,chennan47/osf.io,aaxelb/osf.io,crcresearch/osf.io,mattclark/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,mfraezz/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,felliott/osf.io,adlius/osf.io,caseyrollins/osf.io,HalcyonChimera/osf.io,adlius/osf.io,mattclark/osf.io,brianjgeiger/osf.io... |
1944a78c3c224d78551c77bb7573efeba3d90351 | config/uwsgi/websiterunner.py | config/uwsgi/websiterunner.py | import os
import dotenv
import newrelic.agent
from syspath import git_root
dotenv.load_dotenv(os.path.join(git_root.path, '.env'))
# Set up NewRelic Agent
if os.environ['ENV'] in ['production', 'staging']:
newrelic_ini = os.path.join(git_root.path, 'config', 'newrelic.ini')
newrelic.agent.initialize(newrelic... | import os
import dotenv
from syspath import git_root
dotenv.load_dotenv(os.path.join(git_root.path, '.env'))
from app.serve import * # noqa
| Remove newrelic package from python app | Remove newrelic package from python app
| Python | mit | albertyw/base-flask,albertyw/base-flask,albertyw/base-flask,albertyw/base-flask |
b220f81dc6cfac4d75d923aa8d207d6ae756a134 | readthedocs/builds/forms.py | readthedocs/builds/forms.py | from django import forms
from readthedocs.builds.models import VersionAlias, Version
from readthedocs.projects.models import Project
from readthedocs.core.utils import trigger_build
class AliasForm(forms.ModelForm):
class Meta:
model = VersionAlias
fields = (
'project',
'... | from django import forms
from readthedocs.builds.models import VersionAlias, Version
from readthedocs.projects.models import Project
from readthedocs.core.utils import trigger_build
class AliasForm(forms.ModelForm):
class Meta:
model = VersionAlias
fields = (
'project',
'... | Fix issue where VersionForm wasn't returning object on save | Fix issue where VersionForm wasn't returning object on save
| Python | mit | pombredanne/readthedocs.org,tddv/readthedocs.org,espdev/readthedocs.org,pombredanne/readthedocs.org,davidfischer/readthedocs.org,tddv/readthedocs.org,espdev/readthedocs.org,safwanrahman/readthedocs.org,espdev/readthedocs.org,istresearch/readthedocs.org,istresearch/readthedocs.org,rtfd/readthedocs.org,stevepiercy/readth... |
1b4e7ebd4aaa7f506789a112a9338667e955954f | django_git/views.py | django_git/views.py | from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.formatters import HtmlFormatter
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django_git.utils im... | from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.formatters import HtmlFormatter
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.template import RequestContext
from django_git.utils im... | Add newline to end of file | Add newline to end of file
Signed-off-by: Seth Buntin <7fa3258757ee476d85f026594ec3f1563305da2c@gmail.com> | Python | bsd-3-clause | sethtrain/django-git,sethtrain/django-git |
72fd4e20a537ff5ff0f454ba552ecb6e4d09b76d | test/test_gn.py | test/test_gn.py | '''
GotoNewest tests
'''
import unittest
import sys
sys.path.append('../src/')
import gn
TEST_DIR_NO_SUB = '/tmp/testnosub'
TEST_DIR_ONE_SUB = '/tmp/testonesub'
class TestGotoNewest(unittest.TestCase):
''' Test class for GotoNewest
'''
def test_empty_base_dir(self):
''' If the base directory is ... | '''
GotoNewest tests
'''
import unittest
import sys
sys.path.append('../src/')
import gn
TEST_DIR_NO_SUB = '/tmp/testnosub'
TEST_DIR_ONE_SUB = '/tmp/testonesub'
TEST_DIR_TWO_SUB = '/tmp/testtwosub'
class TestGotoNewest(unittest.TestCase):
''' Test class for GotoNewest
'''
def test_empty_base_dir(self):
... | Add test for multiple subdirectories | Add test for multiple subdirectories
| Python | bsd-2-clause | ambidextrousTx/GotoNewest |
4f16a2bff6c7e972b0803fd3348408f13eddbf41 | bin/update/deploy_dev_base.py | bin/update/deploy_dev_base.py | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
# only ever run this one on demo and dev.
management_cmd(ctx, 'bedrock_truncate_database --yes-i-am-sure')
management_cmd(ctx, 'syncdb --migrate --noinput')
... | import logging
from commander.deploy import task
from deploy_base import * # noqa
log = logging.getLogger(__name__)
@task
def database(ctx):
# only ever run this one on demo and dev.
management_cmd(ctx, 'bedrock_truncate_database --yes-i-am-sure')
management_cmd(ctx, 'syncdb --migrate --noinput')
... | Update firefox os feeds on dev deploy | Update firefox os feeds on dev deploy
| Python | mpl-2.0 | analytics-pros/mozilla-bedrock,andreadelrio/bedrock,bensternthal/bedrock,petabyte/bedrock,SujaySKumar/bedrock,TheoChevalier/bedrock,malena/bedrock,chirilo/bedrock,gerv/bedrock,yglazko/bedrock,sylvestre/bedrock,gauthierm/bedrock,mozilla/bedrock,hoosteeno/bedrock,mozilla/bedrock,malena/bedrock,sgarrity/bedrock,jgmize/bed... |
3394278f379763dae9db34f3b528a229b8f06bc6 | tempora/tests/test_timing.py | tempora/tests/test_timing.py | import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to loo... | import datetime
import time
import contextlib
import os
from unittest import mock
import pytest
from tempora import timing
def test_IntervalGovernor():
"""
IntervalGovernor should prevent a function from being called more than
once per interval.
"""
func_under_test = mock.MagicMock()
# to loo... | Revert "Use pytest.mark to selectively skip test." | Revert "Use pytest.mark to selectively skip test."
Markers can not be applied to fixtures (https://docs.pytest.org/en/latest/reference/reference.html#marks). Fixes #16.
This reverts commit 14d532af265e35af33a28d61a68d545993fc5b78.
| Python | mit | jaraco/tempora |
1b189a8b96fb36de3f7438d14dd1ee6bf1c0980f | www/start.py | www/start.py | #!/usr/bin/python
# Launch a very light-HTTP server: Tornado
#
# Requirements (import from):
# - tornado
#
# Syntax:
# ./start.py <port=8080>
import tornado.ioloop
import tornado.web
import sys
from os import path
#sys.path.append(path.join(path.dirname(__file__), "../scripts/"))
#from generate_db import DEFAUL... | #!/usr/bin/python
# Launch a very light-HTTP server: Tornado
#
# Requirements (import from):
# - tornado
#
# Syntax:
# ./start.py <port=8080>
import tornado.ioloop
import tornado.web
import sys
from os import path
#sys.path.append(path.join(path.dirname(__file__), "../scripts/"))
#from generate_db import DEFAUL... | Declare tornado application outside __main__ block | Declare tornado application outside __main__ block
| Python | mit | dubzzz/py-run-tracking,dubzzz/py-run-tracking,dubzzz/py-run-tracking |
854fc85087c77dc1f4291f0811eecdf91da132aa | TorGTK/pref_handle.py | TorGTK/pref_handle.py | import ConfigParser
from gi.repository import Gtk
from pref_mapping import *
from var import *
def read_config_if_exists(filename):
if os.path.isfile(filename):
# Init config parser and read config
Config = ConfigParser.SafeConfigParser()
Config.read(filename)
section = "TorGTKprefs"
# Loop through options... | import ConfigParser
from gi.repository import Gtk
from pref_mapping import *
from var import *
def read_config_if_exists(filename):
if os.path.isfile(filename):
# Init config parser and read config
Config = ConfigParser.SafeConfigParser()
Config.read(filename)
section = "TorGTKprefs"
# Loop through options... | Add code for saving preferences correctly, but only for integers now | Add code for saving preferences correctly, but only for integers now
| Python | bsd-2-clause | neelchauhan/TorGTK,neelchauhan/TorNova |
b4d76c715810ddd30c0966df2614cd6ed7b03566 | tweets/views.py | tweets/views.py | from django.http import Http404
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.views.generic import ListView
from .models import Message
class MessageList(ListView):
template_name = "message_list.html"
model = Message
class MyMessageList(MessageList):
... | from django.http import Http404
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from django.utils.translation import ugettext as _
from django.views.generic import ListView
from .models import Message
class MessageList(ListView):
template_name = "message_list.... | Adjust user filtering logic to 404 only if user does not exist | Adjust user filtering logic to 404 only if user does not exist
| Python | mit | pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone,pennomi/openwest2015-twitter-clone |
7aeac3ee3429f5d98bc6fb6f475f0969ebabba1e | breakpad.py | breakpad.py | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Fix KeyboardInterrupt exception filtering. Add exception information and not just the stack trace. Make the url easier to change at runtime. | Fix KeyboardInterrupt exception filtering.
Add exception information and not just the stack trace.
Make the url easier to change at runtime.
Review URL: http://codereview.chromium.org/2109001
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@47179 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | aleonliao/depot_tools,duanwujie/depot_tools,fanjunwei/depot_tools,michalliu/chromium-depot_tools,duongbaoduy/gtools,smikes/depot_tools,jankeromnes/depot_tools,disigma/depot_tools,primiano/depot_tools,Midrya/chromium,cybertk/depot_tools,jankeromnes/depot_tools,fracting/depot_tools,disigma/depot_tools,yetu/repotools,mich... |
89c1530882c67a135687df389d0a96d2283873c8 | conda_smithy/tests/test_feedstock_io.py | conda_smithy/tests/test_feedstock_io.py | from __future__ import unicode_literals
import io
import os
import shutil
import tempfile
import unittest
import conda_smithy.feedstock_io as fio
class TestFeedstockIO(unittest.TestCase):
def setUp(self):
self.old_dir = os.getcwd()
self.tmp_dir = tempfile.mkdtemp()
os.chdir(self.tmp_dir... | from __future__ import unicode_literals
import io
import os
import shutil
import tempfile
import unittest
import git
import conda_smithy.feedstock_io as fio
def keep_dir(dirname):
keep_filename = os.path.join(dirname, ".keep")
with io.open(keep_filename, "w", encoding = "utf-8") as fh:
fh.write("")... | Add some tests for `get_repo`. | Add some tests for `get_repo`.
| Python | bsd-3-clause | shadowwalkersb/conda-smithy,ocefpaf/conda-smithy,conda-forge/conda-smithy,ocefpaf/conda-smithy,conda-forge/conda-smithy,shadowwalkersb/conda-smithy |
c1403cc8beac2a9142a21c2de555eb9e5e090f9b | python_hosts/__init__.py | python_hosts/__init__.py | # -*- coding: utf-8 -*-
"""
This package contains all of the modules utilised by the python-hosts library.
hosts: Contains the Hosts and HostsEntry classes that represent instances of a hosts file and it's individual lines/entries
utils: Contains helper functions to check the available operations on a hosts file and ... | # -*- coding: utf-8 -*-
"""
This package contains all of the modules utilised by the python-hosts library.
hosts: Contains the Hosts and HostsEntry classes that represent instances of a hosts file and it's individual lines/entries
utils: Contains helper functions to check the available operations on a hosts file and ... | Revert "refactor: remove unused imports." | Revert "refactor: remove unused imports."
This reverts commit ceb37d26a48d7d56b3d0ded0376eb9498ce7ef6f.
| Python | mit | jonhadfield/python-hosts |
76458ead1675025e3fbe3bed77b64466d4bbd079 | devicehive/transports/base_transport.py | devicehive/transports/base_transport.py | class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.d... | class BaseTransport(object):
"""Base transport class."""
def __init__(self, name, data_format_class, data_format_options,
handler_class, handler_options):
self.name = name
self._data_format = data_format_class(**data_format_options)
self._data_type = self._data_format.d... | Replace send_request and request methods with send_obj | Replace send_request and request methods with send_obj
| Python | apache-2.0 | devicehive/devicehive-python |
48d699fb7d1341dad182412dadd19ea9ee661b30 | localtv/management/commands/update_original_data.py | localtv/management/commands/update_original_data.py | import traceback
from django.core.management.base import NoArgsCommand
from localtv.management import site_too_old
from localtv import models
class Command(NoArgsCommand):
args = ''
def handle_noargs(self, **options):
if site_too_old():
return
for original in models.OriginalVideo... | import traceback
from django.core.management.base import NoArgsCommand
from localtv.management import site_too_old
from localtv import models
import vidscraper.errors
class Command(NoArgsCommand):
args = ''
def handle_noargs(self, **options):
if site_too_old():
return
for origina... | Add a filter for CantIdentifyUrl errors. | Add a filter for CantIdentifyUrl errors.
| Python | agpl-3.0 | pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity,pculture/mirocommunity |
b7acb1a7372c7b6c39c0b5bbfe61fb8e886ed5bc | fulfil_client/client.py | fulfil_client/client.py | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... | import json
import requests
from functools import partial
from trytond.protocols.jsonrpc import JSONDecoder, JSONEncoder
dumps = partial(json.dumps, cls=JSONEncoder)
loads = partial(json.loads, object_hook=JSONDecoder())
class Client(object):
def __init__(self, subdomain, api_key):
self.subdomain = sub... | Add method to create resource | Add method to create resource
| Python | isc | fulfilio/fulfil-python-api,sharoonthomas/fulfil-python-api |
d31382c666444c4947ca35bb67ddb851236e2e49 | automata/automaton.py | automata/automaton.py | #!/usr/bin/env python3
import abc
class AutomatonError(Exception):
"""the base class for all automaton-related errors"""
pass
class InvalidStateError(AutomatonError):
"""a state is not a valid state for this automaton"""
pass
class InvalidSymbolError(AutomatonError):
"""a symbol is not a vali... | #!/usr/bin/env python3
import abc
class Automaton(metaclass=abc.ABCMeta):
def __init__(self, states, symbols, transitions, initial_state,
final_states):
"""initialize a complete finite automaton"""
self.states = states
self.symbols = symbols
self.transitions = tr... | Move Automaton class above exception classes | Move Automaton class above exception classes
| Python | mit | caleb531/automata |
d42b826ea6105956511cfb8f5e8d13b61f7c8033 | Ratings-Counter.py | Ratings-Counter.py | from pyspark import SparkConf, SparkContext
import collections
conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)
lines = sc.textFile("ml-100k/u.data")
ratings = lines.map(lambda x: x.split()[2])
result = ratings.countByValue()
sortedResults = collections.Or... | # import os
# import sys
#
# # Path for spark source folder
# os.environ['SPARK_HOME'] = "/usr/local/Cellar/apache-spark/1.6.1"
#
# # Append pyspark to Python Path
# sys.path.append("/usr/local/Cellar/apache-spark/1.6.1/libexec/python")
# sys.path.append("/usr/local/Cellar/apache-spark/1.6.1/libexec/python/lib... | Test to make file run in IDE | Test to make file run in IDE
| Python | mit | tonirilix/apache-spark-hands-on |
04bf65fa025902f92cd80b87f95c276e32487af0 | tensorflow_datasets/image/binary_alpha_digits_test.py | tensorflow_datasets/image/binary_alpha_digits_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_datasets.image import binary_alpha_digits
import tensorflow_datasets.testing as tfds_test
class BinaryAlphaDigitsTest(tfds_test.DatasetBuilderTestCase):
DATASET_CLAS... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow_datasets.image import binary_alpha_digits
import tensorflow_datasets.testing as tfds_test
class BinaryAlphaDigitsTest(tfds_test.DatasetBuilderTestCase):
DATASET_CLAS... | Fix in test file for Binary Alpha Digit Dataset Issue-189 | Fix in test file for Binary Alpha Digit Dataset Issue-189
| Python | apache-2.0 | tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets,tensorflow/datasets |
d9e9f8f1968ecc62a22b53dc58367cd8698b8bdb | project_generator/util.py | project_generator/util.py | # Copyright 2014-2015 0xc0170
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2014-2015 0xc0170
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Remove all traces of ls. | Remove all traces of ls.
| Python | apache-2.0 | 0xc0170/project_generator,sarahmarshy/project_generator,project-generator/project_generator,hwfwgrp/project_generator,ohagendorf/project_generator,molejar/project_generator |
27f723226b2eca8cbfd4161d7993ebd78d329451 | workshopvenues/venues/tests.py | workshopvenues/venues/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from .models import Address
class ModelsTest(TestCase):
def test_create_address(self):
a ... | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from .models import Address, Venue
class ModelsTest(TestCase):
def test_create_address(self):
... | Add Venue model creation test case | Add Venue model creation test case
| Python | bsd-3-clause | andreagrandi/workshopvenues |
aeb68225cc9c999b51b1733bffaf684280044c97 | salt/utils/yamldumper.py | salt/utils/yamldumper.py | # -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import Dumper
from yaml import SafeDumper
from salt.utils.odict i... | # -*- coding: utf-8 -*-
'''
salt.utils.yamldumper
~~~~~~~~~~~~~~~~~~~~~
'''
# pylint: disable=W0232
# class has no __init__ method
from __future__ import absolute_import
try:
from yaml import CDumper as Dumper
from yaml import CSafeDumper as SafeDumper
except ImportError:
from yaml import ... | Disable W0232, no `__init__` method. | Disable W0232, no `__init__` method.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
3b4b108e6dc2dce46442d5f09fbfe59a61baa02a | api/admin/author.py | api/admin/author.py | from django.contrib.admin import ModelAdmin, BooleanFieldListFilter
class AuthorOptions(ModelAdmin):
list_display = ['id', 'user', 'github_username', 'host', 'bio', 'enabled','friends','following','requests','pending']
list_editable = ['user', 'github_username', 'host', 'bio', 'enabled']
list_filter = (
... | from django.contrib.admin import ModelAdmin, BooleanFieldListFilter
class AuthorOptions(ModelAdmin):
list_display = ['id', 'user', 'github_username', 'host', 'bio', 'enabled']
list_editable = ['user', 'github_username', 'host', 'bio', 'enabled']
list_filter = (
('enabled', BooleanFieldListFilter),... | Revert "Making more fields viewable" | Revert "Making more fields viewable"
| Python | apache-2.0 | CMPUT404/socialdistribution,CMPUT404/socialdistribution,CMPUT404/socialdistribution |
19c3375fe1da5e1a7335cd79374bac6fdf7befe6 | pande_gas/utils/parallel_utils.py | pande_gas/utils/parallel_utils.py | """
IPython.parallel utilities.
"""
import os
import subprocess
import time
import uuid
class LocalCluster(object):
"""
Start an IPython.parallel cluster on localhost.
Parameters
----------
n_engines : int
Number of engines to initialize.
"""
def __init__(self, n_engines):
... | """
IPython.parallel utilities.
"""
import os
import subprocess
import time
import uuid
class LocalCluster(object):
"""
Start an IPython.parallel cluster on localhost.
Parameters
----------
n_engines : int
Number of engines to initialize.
"""
def __init__(self, n_engines):
... | Remove --ip=* from ipcontroller command | Remove --ip=* from ipcontroller command
| Python | bsd-3-clause | rbharath/pande-gas,rbharath/pande-gas |
61a277bc61d0f646bd8d1285b3aa2025f6593953 | app/applications.py | app/applications.py | from . import data_structures
# 1. Stack application
def balanced_parentheses_checker(symbol_string):
"""Verify that a set of parentheses is balanced."""
opening_symbols = '{[('
closing_symbols = '}])'
opening_symbols_stack = data_structures.Stack()
symbol_count = len(symbol_string)
counter =... | from . import data_structures
# 1. Stack application
def balanced_parentheses_checker(symbol_string):
"""Verify that a set of parentheses is balanced."""
opening_symbols = '{[('
closing_symbols = '}])'
opening_symbols_stack = data_structures.Stack()
symbol_count = len(symbol_string)
counter ... | Apply stack in implementation of conversion from decimal to bin, oct & hex. | Apply stack in implementation of conversion from decimal to bin, oct & hex.
| Python | mit | andela-kerinoso/data_structures_algo |
8bca1bd18697821cbf5269e93f6569a02470c040 | attributes.py | attributes.py | #!/usr/bin/python
# Read doc comments and work out what fields to anonymize
import inspect
import re
from nova.db.sqlalchemy import models
ANON_CONFIG_RE = re.compile('^ *:anon ([^ ]+): ([^ ]+)$')
def load_configuration():
configs = {}
for name, obj in inspect.getmembers(models):
if not inspect... | #!/usr/bin/python
# Read doc comments and work out what fields to anonymize
import inspect
import re
from nova.db.sqlalchemy import models
ANON_CONFIG_RE = re.compile('^\s*:anon\s+(\S+):\s+(\S+)\s+(\S+)?\s*$')
def load_configuration():
configs = {}
for name, obj in inspect.getmembers(models):
i... | Fix regex to optionally match substitution type and better whitespace support | Fix regex to optionally match substitution type and better whitespace support
| Python | apache-2.0 | rcbau/fuzzy-happiness |
bb80ef40356be4384b0ddf0e4510865d4d33c654 | appengine_config.py | appengine_config.py | """
`appengine_config` gets loaded when starting a new application instance.
"""
import site
import os.path
# add `lib` subdirectory as a site packages directory, so our `main` module can load
# third-party libraries.
site.addsitedir(os.path.join(os.path.dirname(__file__), 'lib'))
| """
`appengine_config` gets loaded when starting a new application instance.
"""
from google.appengine.ext import vendor
vendor.add('lib')
| Use a newer method for specifying the vendored packages directory. | Use a newer method for specifying the vendored packages directory.
| Python | mit | boulder-python/boulderpython.org,boulder-python/boulderpython.org,boulder-python/boulderpython.org,boulder-python/boulderpython.org |
2c4823d7a1acbfc048e67a58c0cd581c5699129e | biwako/bin/fields/util.py | biwako/bin/fields/util.py | import sys
from .base import Field
class Reserved(Field):
def __init__(self, *args, **kwargs):
super(Reserved, self).__init__(*args, **kwargs)
# Hack to add the reserved field to the class without
# having to explicitly give it a (likely useless) name
frame = sys._getf... | import sys
from .base import Field
class Reserved(Field):
def __init__(self, *args, **kwargs):
super(Reserved, self).__init__(*args, **kwargs)
# Hack to add the reserved field to the class without
# having to explicitly give it a (likely useless) name
frame = sys._getf... | Fix reserved field name setting | Fix reserved field name setting
| Python | bsd-3-clause | gulopine/steel |
3e202c0dd4fa4c99ebee758a13ee5f6e205ef336 | tests/functional/test_front_page.py | tests/functional/test_front_page.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from webpages import *
@pytest.fixture
def page(browser, server_url, access_token):
return FrontPage(browser, server_url, access_token)
class TestFrontPage(object):
def test_should_find_page_div(self... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from webpages import *
@pytest.fixture
def page(browser, server_url, access_token):
return FrontPage(browser, server_url, access_token)
class TestFrontPage(object):
def test_should_find_page_div(self... | Change failed test case for front page to make build pass | Change failed test case for front page to make build pass
| Python | apache-2.0 | eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me,eavatar/eavatar-me |
9aacf80789d6d540fe9260ecf22d7d489cd330a0 | bills/urls.py | bills/urls.py | from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^by_topic/(?P<topic_selected>(.*))/$', views.bill_list_by_topic, name='by_topic_selected'),
url(r'^by_topic/', views.bill_list_by_topic, name='by_topic'),
url(r'^by_location/(?P<location_selected>(.*))/', views.bill_list_by_locatio... | from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^by_topic/', views.bill_list_by_topic, name='by_topic'),
url(r'^by_location/', views.bill_list_by_location, name='by_location'),
url(r'^by_legislator/', views.bill_list_by_legislator, name='by_legislator'),
url(r'^current_sessi... | Remove special topics and locations from URLs | Remove special topics and locations from URLs
| Python | mit | jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot,jamesturk/tot |
9fa95b373c2b43c6e0852aff82ec4c31821a7742 | scss/tests/test_files.py | scss/tests/test_files.py | """Evaluates all the tests that live in `scss/tests/files`.
A test is any file with a `.scss` extension. It'll be compiled, and the output
will be compared to the contents of a file named `foo.css`.
Currently, test files must be nested exactly one directory below `files/`.
This limitation is completely arbitrary.
""... | """Evaluates all the tests that live in `scss/tests/files`.
A test is any file with a `.scss` extension. It'll be compiled, and the output
will be compared to the contents of a file named `foo.css`.
Currently, test files must be nested exactly one directory below `files/`.
This limitation is completely arbitrary.
""... | Add static root path to tests | Add static root path to tests
| Python | mit | Kronuz/pyScss,hashamali/pyScss,cpfair/pyScss,cpfair/pyScss,cpfair/pyScss,Kronuz/pyScss,hashamali/pyScss,hashamali/pyScss,Kronuz/pyScss,Kronuz/pyScss |
de958b9fc68ad6209749edbfe2bdde0ef68cf3c8 | experiments/middleware.py | experiments/middleware.py | from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# We detect widgets by relying on the fact that they are flagged as being embedable, and don't include these in visit tracking
if getattr(response, 'xframe_options... | from experiments.utils import participant
class ExperimentsRetentionMiddleware(object):
def process_response(self, request, response):
# Don't track, failed pages, ajax requests, logged out users or widget impressions.
# We detect widgets by relying on the fact that they are flagged as being embeda... | Revert "tidy up ajax page loads so they count towards experiments" | Revert "tidy up ajax page loads so they count towards experiments"
This reverts commit a37cacb96c4021fcc2f9e23e024d8947bb4e644f.
| Python | mit | mixcloud/django-experiments,bjarnoldus/django-experiments,bjarnoldus/django-experiments,robertobarreda/django-experiments,mixcloud/django-experiments,robertobarreda/django-experiments,squamous/django-experiments,squamous/django-experiments,uhuramedia/django-experiments,mixcloud/django-experiments,bjarnoldus/django-expe... |
88fc0f980f0efa403ab5ce7d6775bce008b284fc | _setup_database.py | _setup_database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_p... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_p... | Add contract retrieval option to database setup script | Add contract retrieval option to database setup script
| Python | mit | leaffan/pynhldb |
0dd6ec1c66b0873cc8f508ad4dffc2aa8fa6ad0d | testing/test_need_update.py | testing/test_need_update.py | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
@needinternet
def test_check_vers_update(fixture_update_dir):
package=fixture_update_dir("0.0.1")
launch = Laun... | from __future__ import absolute_import, print_function
from ..pyautoupdate.launcher import Launcher
from .pytest_skipif import needinternet
from .pytest_makevers import fixture_update_dir
import os
@needinternet
def test_check_vers_update(fixture_update_dir):
package=fixture_update_dir("0.0.1")
launch = Laun... | Make sure .old in need_update is removed properly | Make sure .old in need_update is removed properly
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
ebd9842569201ce0e87827c2031c28c51159c472 | tests/test_pathutils.py | tests/test_pathutils.py | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
... | from os.path import join
import sublime
import sys
from unittest import TestCase
from unittest.mock import patch
version = sublime.version()
try:
from libsass import pathutils
except ImportError:
from sublime_libsass.libsass import pathutils
class TestPathutils(TestCase):
def test_subpaths(self):
... | Change mocking scope to take effect | Change mocking scope to take effect
| Python | mit | blitzrk/sublime_libsass,blitzrk/sublime_libsass |
b11ef81b180cc18acb44988f3e269af6b54f4c89 | timewreport/interval.py | timewreport/interval.py | import dateutil.parser
from datetime import datetime
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__tags = t... | import dateutil.parser
from datetime import datetime, date
from dateutil.tz import tz
class TimeWarriorInterval(object):
def __init__(self, start, end, tags):
self.__start = self.__get_local_datetime(start)
self.__end = self.__get_local_datetime(end) if end is not None else None
self.__ta... | Make get_date() return date object instead of datetime | Make get_date() return date object instead of datetime
| Python | mit | lauft/timew-report |
b400be73feba0b571ac6453841426db9a78dfa00 | flowerconfig.py | flowerconfig.py | import os
AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest')
AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest')
AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1')
AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672'))
DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \
... | import os
AMPQ_ADMIN_USERNAME = os.getenv('AMQP_ADMIN_USERNAME', 'guest')
AMPQ_ADMIN_PASSWORD = os.getenv('AMQP_ADMIN_PASSWORD', 'guest')
AMQP_ADMIN_HOST = os.getenv('AMQP_ADMIN_HOST', '172.17.42.1')
AMQP_ADMIN_PORT = int(os.getenv('AMQP_ADMIN_PORT', '15672'))
DEFAULT_BROKER_API = 'http://%s:%s@%s:%d/api/' \
... | Remove FLOWER_ prefix for non flower based vars | Remove FLOWER_ prefix for non flower based vars | Python | mit | totem/celery-flower-docker,totem/celery-flower-docker |
423dd5ea414fe1857b44eef00a94f4dbb6d0c798 | import_test_data.py | import_test_data.py | #!/usr/bin/env python
# Script to import some test data into the db. Usually we should get a warning
# due to the bad formatting of the date, which is missing the time zone flag.
# Copy and execute this directly into the django shell.
from sest.models import *
from datetime import datetime
u = User.objects.create(u... | #!/usr/bin/env python
# Script to import some test data into the db. Usually we should get a warning
# due to the bad formatting of the date, which is missing the time zone flag.
# Copy and execute this directly into the django shell.
from sest.models import *
# from datetime import datetime
u = User.objects.create... | Update test data importer script. | Update test data importer script.
| Python | mit | bebosudo/sest,bebosudo/sest,bebosudo/sest |
2eae88ca423a60579e9b8572b0d4bcecbe2d8631 | utils/HTTPResponseParser.py | utils/HTTPResponseParser.py |
# Utility to parse HTTP responses
# http://pythonwise.blogspot.com/2010/02/parse-http-response.html
from StringIO import StringIO
from httplib import HTTPResponse
class FakeSocket(StringIO):
def makefile(self, *args, **kw):
return self
def parse_http_response(sock):
try:
# H4ck to standardi... |
# Utility to parse HTTP responses
# http://pythonwise.blogspot.com/2010/02/parse-http-response.html
from StringIO import StringIO
from httplib import HTTPResponse
class FakeSocket(StringIO):
def makefile(self, *args, **kw):
return self
def parse_http_response(sock):
try:
# H4ck to standardi... | Tweak the hack to fix bug when scanning through a proxy | Tweak the hack to fix bug when scanning through a proxy
| Python | agpl-3.0 | nabla-c0d3/sslyze |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.