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 |
|---|---|---|---|---|---|---|---|---|---|
cfa77bed245d80d453f7b463ea35473bbc29cc50 | toolkits/rdk.py | toolkits/rdk.py | import numpy as np
from cinfony import rdk
from cinfony.rdk import *
class Fingerprint(rdk.Fingerprint):
@property
def raw(self):
return np.array(self.fp, dtype=bool)
rdk.Fingerprint = Fingerprint
| import numpy as np
from cinfony import rdk
from cinfony.rdk import *
class Fingerprint(rdk.Fingerprint):
@property
def raw(self):
return np.array(self.fp, dtype=bool)
rdk.Fingerprint = Fingerprint
# Patch reader not to return None as molecules
def _readfile(format, filename):
for mol in r... | Patch readfile not to return mols | Patch readfile not to return mols
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery |
e6c774c13a01f2cbe09947c39c1dac7b4989bebc | jason2/project.py | jason2/project.py | class Project(object):
"""Holds project configuration parameters, such as data directory."""
def __init__(self, data_directory):
self.data_directory = data_directory
| import ConfigParser
class Project(object):
"""Holds project configuration parameters, such as data directory."""
@classmethod
def from_config(cls, filename):
config = ConfigParser.RawConfigParser()
config.read(filename)
return cls(config.get("data", "directory"))
def __init__... | Add from_configfile method to Project | Add from_configfile method to Project
| Python | mit | gadomski/jason2 |
686406781af00d93e4d70049499068037d72be74 | geotrek/core/tests/test_forms.py | geotrek/core/tests/test_forms.py | from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with dynamic segmentation onl... | from django.conf import settings
from django.test import TestCase
from unittest import skipIf
from geotrek.core.factories import TrailFactory, PathFactory
from geotrek.authent.factories import UserFactory
from geotrek.core.forms import TrailForm, PathForm
@skipIf(not settings.TREKKING_TOPOLOGY_ENABLED, 'Test with d... | Add tests for path overlapping check | Add tests for path overlapping check
| Python | bsd-2-clause | GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek |
4b26066a6f3b666ec107621334ddbcceec6a819a | micro/read_code.py | micro/read_code.py | import fileinput
def read_code():
return ''.join([line for line in fileinput.input()])
if __name__ == '__main__':
code = read_code()
print(code)
| import fileinput
def read_code(filename='-'):
return ''.join([line for line in fileinput.input(filename)])
if __name__ == '__main__':
import sys
filename = sys.argv[1] if len(sys.argv) > 1 else '-'
code = read_code(filename)
print(code)
| Correct a reading of a code | Correct a reading of a code
| Python | mit | thewizardplusplus/micro,thewizardplusplus/micro,thewizardplusplus/micro |
9be37b96450780b41f5a5443568ca41a18e06d22 | lcapy/sequence.py | lcapy/sequence.py | """This module handles sequences.
Copyright 2020 Michael Hayes, UCECE
"""
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n ... | """This module handles sequences.
Copyright 2020 Michael Hayes, UCECE
"""
from .expr import ExprList
class Sequence(ExprList):
def __init__(self, seq, n=None):
super (Sequence, self).__init__(seq)
# Save the indexes. Ideally, should annotate which item
# in sequence corresponds to n ... | Add pretty and latex for Sequence | Add pretty and latex for Sequence
| Python | lgpl-2.1 | mph-/lcapy |
4559e01646010e1ed260d77e612774778a0c1359 | lib/rfk/site/forms/login.py | lib/rfk/site/forms/login.py | from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \
PasswordField, IntegerField, FieldList, FormField, validators
class LoginForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required()])
remember = Boolean... | from wtforms import Form, SubmitField, BooleanField, TextField, SelectField, \
PasswordField, IntegerField, FieldList, FormField, validators
class LoginForm(Form):
username = TextField('Username', [validators.Required()])
password = PasswordField('Password', [validators.Required()])
remember = Boolean... | Make it clear that the E-Mail address is optional. | Make it clear that the E-Mail address is optional.
| Python | bsd-3-clause | buckket/weltklang,buckket/weltklang,krautradio/PyRfK,krautradio/PyRfK,krautradio/PyRfK,buckket/weltklang,buckket/weltklang,krautradio/PyRfK |
3d9bf8afd912ccb0d1df72353a9c306c59773007 | swf/exceptions.py | swf/exceptions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.spli... | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.spli... | Update SWFError with a formatted type | Update SWFError with a formatted type
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow |
5a9f027bb3e660cd0146c4483c70e54a76332048 | makerscience_profile/api.py | makerscience_profile/api.py | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileRe... | from .models import MakerScienceProfile
from tastypie.resources import ModelResource
from tastypie.authorization import DjangoAuthorization
from tastypie import fields
from tastypie.constants import ALL_WITH_RELATIONS
from dataserver.authentication import AnonymousApiKeyAuthentication
from accounts.api import ProfileRe... | Enable full location for profile | Enable full location for profile
| Python | agpl-3.0 | atiberghien/makerscience-server,atiberghien/makerscience-server |
58f982d01a7c47a12a7ae600c2ca17cb6c5c7ed9 | monitor/runner.py | monitor/runner.py | from time import sleep
from monitor.camera import Camera
from monitor.plotter_pygame import PyGamePlotter
def run(plotter, camera):
while True:
plotter.show(camera.get_image_data())
sleep(1.0)
if __name__ == "main":
cam_ioc = "X1-CAM"
plo = PyGamePlotter()
cam = Camera(cam_ioc)
... | import sys
from time import sleep
from camera import Camera
from plotter_pygame import PyGamePlotter
def run(plotter, camera):
old_timestamp = -1
while True:
data, timestamp = camera.get_image_data()
if timestamp != old_timestamp:
plotter.show(data)
old_timestamp = time... | Update to set screensize and take camera IOC as arg | Update to set screensize and take camera IOC as arg
| Python | apache-2.0 | nickbattam/picamon,nickbattam/picamon,nickbattam/picamon,nickbattam/picamon |
2917f396f52eb042f2354f0a7e1d05dd59b819e3 | aids/strings/reverse_string.py | aids/strings/reverse_string.py | '''
Reverse a string
'''
def reverse_string_iterative(string):
pass
def reverse_string_recursive(string):
pass
def reverse_string_pythonic(string):
return string[::-1] | '''
Reverse a string
'''
def reverse_string_iterative(string):
result = ''
for char in range(len(string) - 1, -1 , -1):
result += char
return result
def reverse_string_recursive(string):
if string:
return reverse_string_recursive(string[1:]) + string[0]
return ''
def reverse_string_pythonic(string... | Add iterative and recursive solutions to reverse strings | Add iterative and recursive solutions to reverse strings
| Python | mit | ueg1990/aids |
8af5aaee0aad575c9f1039a2943aff986a501747 | tests/manage.py | tests/manage.py | #!/usr/bin/env python
import channels.log
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
def get_channels_logger(*args, **kwargs):
"""Return logger for channels."""
return logging.getLogger("django.channels")
#... | #!/usr/bin/env python
import logging
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, PROJECT_ROOT)
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings")
from django.core.management import execute_from_c... | Fix logging compatibility with the latest Channels | Fix logging compatibility with the latest Channels
| Python | apache-2.0 | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio |
f4695f43e9eae5740efc303374c892850dfea1a2 | trade_server.py | trade_server.py | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
res... | import json
import threading
import socket
import SocketServer
from orderbook import asks, bids
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
response = ''
if... | Fix bugs occuring when no response is given. | Fix bugs occuring when no response is given.
| Python | mit | Tribler/decentral-market |
e98eeadb9d5906bf65efc7a17658ae498cfcf27d | chainer/utils/__init__.py | chainer/utils/__init__.py | import contextlib
import shutil
import tempfile
import numpy
from chainer.utils import walker_alias # NOQA
# import class and function
from chainer.utils.conv import get_conv_outsize # NOQA
from chainer.utils.conv import get_deconv_outsize # NOQA
from chainer.utils.experimental import experimental # NOQA
from c... | import contextlib
import shutil
import tempfile
import numpy
from chainer.utils import walker_alias # NOQA
# import class and function
from chainer.utils.conv import get_conv_outsize # NOQA
from chainer.utils.conv import get_deconv_outsize # NOQA
from chainer.utils.experimental import experimental # NOQA
from c... | Make ignore_errors False by default | Make ignore_errors False by default
| Python | mit | ronekko/chainer,chainer/chainer,okuta/chainer,wkentaro/chainer,ktnyt/chainer,chainer/chainer,okuta/chainer,niboshi/chainer,chainer/chainer,hvy/chainer,chainer/chainer,rezoo/chainer,keisuke-umezawa/chainer,anaruse/chainer,okuta/chainer,hvy/chainer,keisuke-umezawa/chainer,ktnyt/chainer,jnishi/chainer,niboshi/chainer,keis... |
b423e73ec440d10ff80110c998d13ea8c2b5a764 | stock_request_picking_type/models/stock_request_order.py | stock_request_picking_type/models/stock_request_order.py | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | # Copyright 2019 Open Source Integrators
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import api, fields, models
class StockRequestOrder(models.Model):
_inherit = 'stock.request.order'
@api.model
def _get_default_picking_type(self):
return self.env['stock.picki... | Synchronize Picking Type and Warehouse | [IMP] Synchronize Picking Type and Warehouse
[IMP] User write()
| Python | agpl-3.0 | OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse,OCA/stock-logistics-warehouse |
8fd395e1085f0508da401186b09f7487b3f9ae64 | odbc2csv.py | odbc2csv.py | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=")
cur = conn.cursor()
tables = []
cur.tables("%", "", "")
for row in cur.fetchall():
tables.append(row[2])
for table in tables:
cur.execute("select * from %s" % table)
column_names = []
for d in cur.description:
column_names.append(d... | import pypyodbc
import csv
conn = pypyodbc.connect("DSN=")
cur = conn.cursor()
tables = []
cur.execute("select * from sys.tables")
for row in cur.fetchall():
tables.append(row[0])
for table in tables:
cur.execute("select * from %s" % table)
column_names = []
for d in cur.description:
colu... | Fix to fetching tables from MS SQL Server. | Fix to fetching tables from MS SQL Server. | Python | isc | wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts,wablair/misc_scripts |
6a8fadc2d607adaf89e6ea15fca65136fac651c6 | src/auspex/instruments/utils.py | src/auspex/instruments/utils.py | from . import bbn
import auspex.config
from auspex.log import logger
from QGL import *
ChannelLibrary()
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined i... | from . import bbn
import auspex.config
from auspex.log import logger
def pulse_marker(marker_name, length = 100e-9):
""" Utility to generate a square pulse on a APS2 marker. Used for instance to switch a signal between spectrum analyzer and input line
marker_name as defined in measure.yaml """
from QGL im... | Move QGL import inside function | Move QGL import inside function
A channel library is not always available
| Python | apache-2.0 | BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex,BBN-Q/Auspex |
89ee95bf33ce504377087de383f56e8582623738 | pylab/website/tests/test_comments.py | pylab/website/tests/test_comments.py | import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from django_comments.models import Comment
from pylab.core.models import Project
class CommentsTests(WebTest):
def setUp(self):
self.user = User.objects.create_user('u1')
self.project = Project.obje... | from django_webtest import WebTest
from django.contrib.auth.models import User
from django_comments.models import Comment
from pylab.core.models import Project
class CommentsTests(WebTest):
def setUp(self):
self.user = User.objects.create_user('u1', email='test@example.com')
self.project = Pro... | Add email parameter for creating test user | Add email parameter for creating test user
| Python | agpl-3.0 | python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website |
11d9225871fa4980c7782a849c3ecd425edbe806 | git_helper.py | git_helper.py | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.... | import os
def git_file_path(view, git_path):
if not git_path:
return False
full_file_path = view.file_name()
git_path_to_file = full_file_path.replace(git_path,'')
if git_path_to_file[0] == "/":
git_path_to_file = git_path_to_file[1:]
return git_path_to_file
def git_root(directory):
if os.... | Fix error when there is no git | Fix error when there is no git
| Python | mit | bradsokol/VcsGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,bradsokol/VcsGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,akpersad/GitGutter,biodamasceno/GitGutter,natecavanaugh/GitGu... |
d7a77380ad95e316efb73a7be485d9b882fd64e9 | Core/models.py | Core/models.py | from django.db import models
##
# Location Types
##
class World(models.Model):
name = models.CharField(max_length=30)
homes = models.ManyToManyField(Home)
class Home(models.Model):
name = models.CharField(max_length=30)
rooms = models.ManyToManyField(Room)
class Room(models.Model):
name = models.CharField(max_... | from django.db import models
##
# Location Types
##
class World(models.Model):
name = models.CharField(max_length=30)
homes = models.ManyToManyField(Home)
class Meta:
db_table = u'Worlds'
class Home(models.Model):
name = models.CharField(max_length=30)
rooms = models.ManyToManyField(Room)
class Meta:
db_ta... | Add table names to core model items | Add table names to core model items
| Python | mit | Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation,Tomcuzz/OctaHomeAutomation |
6a856e613248e32bd7fc8027adfb9df4d74b2357 | candidates/management/commands/candidates_make_party_sets_lookup.py | candidates/management/commands/candidates_make_party_sets_lookup.py | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_ro... | import json
from os.path import dirname, join, realpath
from django.conf import settings
from django.core.management.base import BaseCommand
from candidates.election_specific import AREA_POST_DATA
from candidates.popit import get_all_posts
class Command(BaseCommand):
def handle(self, **options):
repo_ro... | Make the party set JS generator output keys in a predictable order | Make the party set JS generator output keys in a predictable order
This makes it easier to check with "git diff" if there have been any
changes.
| Python | agpl-3.0 | neavouli/yournextrepresentative,neavouli/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,mysociety/yournextrepresentative,mysociety/yournextmp-popit,datamade/yournextmp-popit,neavouli/yourn... |
c126b7a6b060a30e5d5c698dfa3210786f169b92 | camoco/cli/commands/remove.py | camoco/cli/commands/remove.py | import camoco as co
def remove(args):
print(co.del_dataset(args.type,args.name,safe=args.force))
| import camoco as co
def remove(args):
co.del_dataset(args.type,args.name,safe=args.force)
print('Done')
| Make stderr messages more interpretable | Make stderr messages more interpretable
| Python | mit | schae234/Camoco,schae234/Camoco |
fab561da9c54e278e7762380bf043a2fe03e39da | xerox/darwin.py | xerox/darwin.py | # -*- coding: utf-8 -*-
""" Copy + Paste in OS X
"""
import subprocess
import commands
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
... | # -*- coding: utf-8 -*-
""" Copy + Paste in OS X
"""
import subprocess
from .base import *
def copy(string):
"""Copy given string into system clipboard."""
try:
subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE).communicate(str(unicode(string)))
except OSError as why:
raise XcodeNotFo... | Use `subprocess.check_output` rather than `commands.getoutput`. | Use `subprocess.check_output` rather than `commands.getoutput`.
`commands` is deprecated.
| Python | mit | solarce/xerox,kennethreitz/xerox |
7816cf0562435176a33add229942ac3ee8e7b94c | yolodex/urls.py | yolodex/urls.py | from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from .views import (
RealmView,
RealmCorrectionsView,
EntitySearchView,
EntityListView,
EntityDetailView,
EntityDetailNetworkEmbedView,
)
from .api_views import (
YolodexRouter,
EntityView... | from django.conf.urls import url
from django.utils.translation import ugettext_lazy as _
from .views import (
RealmView,
RealmCorrectionsView,
EntitySearchView,
EntityListView,
EntityDetailView,
EntityDetailNetworkEmbedView,
)
from .api_views import (
YolodexRouter,
EntityViewSet,
E... | Update urlpatterns and remove old patterns pattern | Update urlpatterns and remove old patterns pattern | Python | mit | correctiv/django-yolodex,correctiv/django-yolodex,correctiv/django-yolodex |
57810d41ac50284341c42217cfa6ea0917d10f21 | zephyr/forms.py | zephyr/forms.py | from django import forms
class RegistrationForm(forms.Form):
full_name = forms.CharField(max_length=100)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput, max_length=100)
| from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
def is_unique(value):
try:
print "foo + " + value
User.objects.get(email=value)
raise ValidationError(u'%s is already registered' % valu... | Add a custom validator to ensure email uniqueness, include ommitted fields. | Add a custom validator to ensure email uniqueness, include ommitted fields.
Previously no check was performed to ensure that the same email wasn't used
to register twice. Here we add a validator to perform that check.
We also noted that the domain field was omitted, but checked by a client of
this class. Therefore, w... | Python | apache-2.0 | umkay/zulip,jeffcao/zulip,hafeez3000/zulip,dawran6/zulip,RobotCaleb/zulip,bastianh/zulip,brockwhittaker/zulip,hustlzp/zulip,littledogboy/zulip,aliceriot/zulip,MariaFaBella85/zulip,m1ssou/zulip,Gabriel0402/zulip,JanzTam/zulip,bitemyapp/zulip,amyliu345/zulip,alliejones/zulip,hayderimran7/zulip,dwrpayne/zulip,bastianh/zul... |
325fed2ef774e708e96d1b123672e1be238d7d21 | nailgun/nailgun/models.py | nailgun/nailgun/models.py | from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, pr... | from django.db import models
from django.contrib.auth.models import User
from jsonfield import JSONField
class Environment(models.Model):
#user = models.ForeignKey(User, related_name='environments')
name = models.CharField(max_length=100)
class Role(models.Model):
id = models.CharField(max_length=30, pr... | Allow nodes not to have related environment | Allow nodes not to have related environment
| Python | apache-2.0 | SmartInfrastructures/fuel-main-dev,nebril/fuel-web,dancn/fuel-main-dev,SergK/fuel-main,zhaochao/fuel-main,nebril/fuel-web,prmtl/fuel-web,zhaochao/fuel-main,eayunstack/fuel-web,nebril/fuel-web,SmartInfrastructures/fuel-main-dev,SmartInfrastructures/fuel-main-dev,teselkin/fuel-main,Fiware/ops.Fuel-main-dev,teselkin/fuel-... |
23456a32038f13c6219b6af5ff9fff7e1daae242 | abusehelper/core/tests/test_utils.py | abusehelper/core/tests/test_utils.py | import pickle
import unittest
from .. import utils
class TestCompressedCollection(unittest.TestCase):
def test_collection_can_be_pickled_and_unpickled(self):
original = utils.CompressedCollection()
original.append("ab")
original.append("cd")
unpickled = pickle.loads(pickle.dumps(... | import socket
import pickle
import urllib2
import unittest
import idiokit
from .. import utils
class TestFetchUrl(unittest.TestCase):
def test_should_raise_TypeError_when_passing_in_an_opener(self):
sock = socket.socket()
try:
sock.bind(("localhost", 0))
sock.listen(1)
... | Add a test for utils.fetch_url(..., opener=...) | Add a test for utils.fetch_url(..., opener=...)
Signed-off-by: Ossi Herrala <37524b811d80bbe1732e3577b04d7a5fd222cfc5@gmail.com>
| Python | mit | abusesa/abusehelper |
567925c770f965c7440b13b63b11b5615bf3c141 | src/connection.py | src/connection.py | from . import output
import json
import sys
import urllib.parse
import http.client
def getRequest(id, conf):
db = conf['db']
headers = conf['headers']
test = db[id]
method = test['method'].upper()
fullpath = conf['path'] + test['path']
desc = test['desc']
params = ''
server = conf['dom... | from . import output
import json
import sys
import urllib.parse
import http.client
def getRequest(id, conf):
db = conf['db']
headers = conf['headers']
test = db[id]
method = test['method'].upper()
fullpath = conf['path'] + test['path']
desc = test['desc']
params = ''
server = conf['dom... | Add a properly string for outputing | Add a properly string for outputing
| Python | mit | manoelhc/restafari,manoelhc/restafari |
a81f78385f8ec9a94d0d511805801d1f0a6f17ed | drogher/shippers/fedex.py | drogher/shippers/fedex.py | from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = self.tracking_number... | import itertools
from .base import Shipper
class FedEx(Shipper):
shipper = 'FedEx'
class FedExExpress(FedEx):
barcode_pattern = r'^\d{34}$'
@property
def tracking_number(self):
return self.barcode[20:].lstrip('0')
@property
def valid_checksum(self):
chars, check_digit = se... | Use itertools.cycle for repeating digits | Use itertools.cycle for repeating digits
| Python | bsd-3-clause | jbittel/drogher |
b7fcbc3a2117f00177ddd7a353eb6a4dee5bc777 | stat_retriever.py | stat_retriever.py | """
stat-retriever by Team-95
stat_retriever.py
"""
import requests
def main():
url = "http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference="
"&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment="
"&Height=&LastNGames=0&LeagueID=00&Location=&Month=... | """
stat-retriever by Team-95
stat_retriever.py
"""
import requests
import json
def main():
season = "2014-15"
url = ("http://stats.nba.com/stats/leaguedashplayerbiostats?College=&Conference="
"&Country=&DateFrom=&DateTo=&Division=&DraftPick=&DraftYear=&GameScope=&GameSegment="
"&Height=&LastNGames=0&... | Fix formatting once more, added response parsing | Fix formatting once more, added response parsing
| Python | mit | Team-95/stat-retriever |
ce3249dea725d40d5e0916b344cdde53ab6d53dc | src/satosa/micro_services/processors/scope_extractor_processor.py | src/satosa/micro_services/processors/scope_extractor_processor.py | from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning
from .base_processor import BaseProcessor
CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute'
CONFIG_DEFAULT_MAPPEDATTRIBUTE = ''
class ScopeExtractorProcessor(BaseProcessor):
"""
Extracts the scope from a scoped attribute and ... | from ..attribute_processor import AttributeProcessorError, AttributeProcessorWarning
from .base_processor import BaseProcessor
CONFIG_KEY_MAPPEDATTRIBUTE = 'mapped_attribute'
CONFIG_DEFAULT_MAPPEDATTRIBUTE = ''
class ScopeExtractorProcessor(BaseProcessor):
"""
Extracts the scope from a scoped attribute and ... | Make the ScopeExtractorProcessor usable for the Primary Identifier | Make the ScopeExtractorProcessor usable for the Primary Identifier
This patch adds support to use the ScopeExtractorProcessor on the Primary
Identifiert which is, in contrast to the other values, a string.
Closes #348
| Python | apache-2.0 | SUNET/SATOSA,SUNET/SATOSA,its-dirg/SATOSA |
8445d491030be7fb2fa1175140a4b022b2690425 | conman/cms/tests/test_urls.py | conman/cms/tests/test_urls.py | from incuna_test_utils.testcases.urls import URLTestCase
from .. import views
class TestCMSIndexURL(URLTestCase):
"""Make sure that the CMSIndex view has a URL"""
def test_url(self):
self.assert_url_matches_view(
views.CMSIndex,
'/cms/',
'cms:index',
)
| from unittest import mock
from django.test import TestCase
from incuna_test_utils.testcases.urls import URLTestCase
from .. import urls, views
class TestCMSIndexURL(URLTestCase):
"""Make sure that the CMSIndex view has a URL"""
def test_url(self):
self.assert_url_matches_view(
views.CMSI... | Add further tests of the cms urls | Add further tests of the cms urls
| Python | bsd-2-clause | meshy/django-conman,Ian-Foote/django-conman,meshy/django-conman |
748c9728b4de0d19b4e18e3c0e0763dc8d20ba37 | queue_job/tests/__init__.py | queue_job/tests/__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Guewen Baconnier
# Copyright 2012 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pu... | Remove deprecated fast_suite and check list for unit tests | Remove deprecated fast_suite and check list for unit tests
| Python | agpl-3.0 | leorochael/queue |
23fa1c55ec9fcbc595260be1039a4b8481cb4f13 | api/comments/views.py | api/comments/views.py | from rest_framework import generics
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
from api.base.utils import get_object_or_error
class CommentMixin(object):
"""Mixin with convenience methods for retrieving the current comment based on th... | from modularodm import Q
from modularodm.exceptions import NoResultsFound
from rest_framework import generics
from rest_framework.exceptions import NotFound
from api.comments.serializers import CommentSerializer, CommentDetailSerializer
from website.project.model import Comment
class CommentMixin(object):
"""Mixi... | Return deleted comments instead of throwing error | Return deleted comments instead of throwing error
| Python | apache-2.0 | kch8qx/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,kch8qx/osf.io,ZobairAlijan/osf.io,acshi/osf.io,DanielSBrown/osf.io,GageGaskins/osf.io,icereval/osf.io,wearpants/osf.io,mfraezz/osf.io,acshi/osf.io,jnayak1/osf.io,crcresearch/osf.io,danielneis/osf.io,brandonPurvis/osf.io,samanehsan/osf.io,samanehsan/osf.io,SS... |
10aab1c427a82b4cfef6b07ae1103260e14ca322 | geotrek/feedback/admin.py | geotrek/feedback/admin.py | from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
cla... | from django.conf import settings
from django.contrib import admin
from geotrek.feedback import models as feedback_models
if 'modeltranslation' in settings.INSTALLED_APPS:
from modeltranslation.admin import TabbedTranslationAdmin
else:
from django.contrib.admin import ModelAdmin as TabbedTranslationAdmin
cla... | Fix deleted line during merge | Fix deleted line during merge
| Python | bsd-2-clause | makinacorpus/Geotrek,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek |
d7c4f0471271d104c0ff3500033e425547ca6c27 | notification/context_processors.py | notification/context_processors.py | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
}
else:
return {} | from notification.models import Notice
def notification(request):
if request.user.is_authenticated():
return {
"notice_unseen_count": Notice.objects.unseen_count_for(request.user, on_site=True),
"notifications": Notice.objects.filter(user=request.user.id)
}
else:
... | Add user notifications to context processor | Add user notifications to context processor
| Python | mit | affan2/django-notification,affan2/django-notification |
7b681bfd34a24dc15b219dd355db2557914b7b49 | tests/conftest.py | tests/conftest.py | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
de... | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
de... | Revert previous commit due to arrayfire-python bug. | Revert previous commit due to arrayfire-python bug.
| Python | bsd-2-clause | daurer/afnumpy,FilipeMaia/afnumpy |
a94a8f0e5c773995da710bb8e90839c7b697db96 | cobe/tokenizer.py | cobe/tokenizer.py | # Copyright (C) 2010 Peter Teichman
import re
class MegaHALTokenizer:
def split(self, phrase):
if len(phrase) == 0:
return []
# add ending punctuation if it is missing
if phrase[-1] not in ".!?":
phrase = phrase + "."
# megahal traditionally considers [a-z... | # Copyright (C) 2010 Peter Teichman
import re
class MegaHALTokenizer:
def split(self, phrase):
if len(phrase) == 0:
return []
# add ending punctuation if it is missing
if phrase[-1] not in ".!?":
phrase = phrase + "."
# megahal traditionally considers [a-z... | Use the re.UNICODE flag (i.e., Python character tables) in findall() | Use the re.UNICODE flag (i.e., Python character tables) in findall()
| Python | mit | LeMagnesium/cobe,meska/cobe,wodim/cobe-ng,wodim/cobe-ng,LeMagnesium/cobe,pteichman/cobe,tiagochiavericosta/cobe,pteichman/cobe,meska/cobe,DarkMio/cobe,tiagochiavericosta/cobe,DarkMio/cobe |
b7c95f6eed786000278f5719fbf4ac037af20e50 | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/users/tests/factories.py | from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
... | from typing import Any, Sequence
from django.contrib.auth import get_user_model
from factory import Faker, post_generation
from factory.django import DjangoModelFactory
class UserFactory(DjangoModelFactory):
username = Faker("user_name")
email = Faker("email")
name = Faker("name")
@post_generation
... | Update factory-boy's .generate to evaluate | Update factory-boy's .generate to evaluate
Co-Authored-By: Timo Halbesma <98c2d5a1e48c998bd9ba9dbc53d6857beae1c9bd@halbesma.com>
| Python | bsd-3-clause | pydanny/cookiecutter-django,pydanny/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,ryankanno/cookiecutter-django,ryankanno/cookiecutter-django,trungdong/cookiecutter-django,pydanny/cookiecutter-django,trungdong/cookiecutter-dja... |
32b35f49c525d6b527de325ecc4837ab7c18b5ad | apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py | apiserver/alembic/versions/201711101357_451d4bb125cb_add_ranking_data_to_participants_table.py | """Add ranking data to participants table
Revision ID: 451d4bb125cb
Revises: 49be2190c22d
Create Date: 2017-11-10 13:57:37.807238+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '451d4bb125cb'
down_revision = '49be219... | """Add ranking data to participants table
Revision ID: 451d4bb125cb
Revises: 49be2190c22d
Create Date: 2017-11-10 13:57:37.807238+00:00
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '451d4bb125cb'
down_revision = '49be219... | Rename rank field to avoid column name clash | Rename rank field to avoid column name clash
| Python | mit | HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteChallenge/Halite-II,HaliteCh... |
e9709abadb2daa1a0752fa12b8e017074f0fb098 | classes/person.py | classes/person.py | class Person(object):
def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"):
self.person_name = person_name
self.person_surname = person_surname
self.person_type = person_type
self.wants_accommodation = wants_accommodation
def full_name(self):
... | class Person(object):
def __init__(self, person_type, person_name, person_surname="", wants_accommodation="N"):
self.person_name = person_name
self.person_surname = person_surname
self.person_type = person_type
self.wants_accommodation = wants_accommodation
def full_name(self):
... | Change full name method to stop validating for str type which is repetitive and has been tested elsewhere | Change full name method to stop validating for str type which is repetitive and has been tested elsewhere
| Python | mit | peterpaints/room-allocator |
8d43061490c32b204505382ec7b77c18ddc32d9d | conf_site/apps.py | conf_site/apps.py | from django.apps import AppConfig as BaseAppConfig
from django.utils.importlib import import_module
class AppConfig(BaseAppConfig):
name = "conf_site"
def ready(self):
import_module("conf_site.receivers")
| from importlib import import_module
from django.apps import AppConfig as BaseAppConfig
class AppConfig(BaseAppConfig):
name = "conf_site"
def ready(self):
import_module("conf_site.receivers")
| Remove Django importlib in favor of stdlib. | Remove Django importlib in favor of stdlib.
Django's copy of importlib was deprecated in 1.7 and therefore removed
in Django 1.9:
https://docs.djangoproject.com/en/1.10/releases/1.7/#django-utils-dictconfig-django-utils-importlib
This is okay, since we are using Python 2.7 and can rely on the copy in
the standard lib... | Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
858f993ceffb497bee12457d1d4102339af410a4 | typer/__init__.py | typer/__init__.py | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
BadArgumentUsage,
BadOptionUsage,
BadParameter,
ClickException,
FileError,
MissingParameter,
NoSuchOption,
UsageError,
)
from click.termui im... | """Typer, build great CLIs. Easy to code. Based on Python type hints."""
__version__ = "0.0.4"
from click.exceptions import ( # noqa
Abort,
Exit,
)
from click.termui import ( # noqa
clear,
confirm,
echo_via_pager,
edit,
get_terminal_size,
getchar,
launch,
pause,
progressb... | Clean exports from typer, remove unneeded Click components | :fire: Clean exports from typer, remove unneeded Click components
and add Exit exception
| Python | mit | tiangolo/typer,tiangolo/typer |
2833e2296cff6a52ab75c2c88563e81372902035 | src/heartbeat/checkers/build.py | src/heartbeat/checkers/build.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from pkg_resources import get_distribution, DistributionNotFound
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing pack... | from pkg_resources import Requirement, WorkingSet
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def check(request):
package_name = settings.HEARTBEAT.get('package_name')
if not package_name:
raise ImproperlyConfigured(
'Missing package_name key f... | Package name should be searched through the same distros list we use for listing installed packages. get_distribution is using the global working_set which may not contain the requested package if the initialization(pkg_resources import time) happened before the project name to appear in the sys.path. | Package name should be searched through the same distros list
we use for listing installed packages. get_distribution is using
the global working_set which may not contain the requested package
if the initialization(pkg_resources import time) happened before
the project name to appear in the sys.path.
| Python | mit | pbs/django-heartbeat |
fa776fc0d3c568bda7d84ccd9b345e34c3fcf312 | ideascube/mediacenter/tests/factories.py | ideascube/mediacenter/tests/factories.py | from django.conf import settings
import factory
from ..models import Document
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summary"
lang = settings.LANGUAGE_CODE
original = factory.django.FileFie... | from django.conf import settings
import factory
from ..models import Document
class EmptyFileField(factory.django.FileField):
DEFAULT_FILENAME = None
class DocumentFactory(factory.django.DjangoModelFactory):
title = factory.Sequence(lambda n: "Test document {0}".format(n))
summary = "This is a test summ... | Allow DocumentFactory to handle preview field. | Allow DocumentFactory to handle preview field.
The factory.django.FileField.DEFAULT_FILENAME == 'example.dat'.
It means that by default a FileField created by factoryboy is considered as a
True value.
Before this commit, we were not defining a Document.preview field in the
factory so factoryboy created a empty FileFie... | Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
e0607c27cf990f893d837af5717de684bb62aa63 | plugins/spark/__init__.py | plugins/spark/__init__.py | import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.... | import os
import romanesco
from . import pyspark_executor, spark
SC_KEY = '_romanesco_spark_context'
def setup_pyspark_task(event):
"""
This is executed before a task execution. If it is a pyspark task, we
create the spark context here so it can be used for any input conversion.
"""
info = event.... | Fix spark mode (faulty shutdown conditional logic) | Fix spark mode (faulty shutdown conditional logic)
| Python | apache-2.0 | Kitware/romanesco,girder/girder_worker,girder/girder_worker,Kitware/romanesco,girder/girder_worker,Kitware/romanesco,Kitware/romanesco |
e771eeb4595197ae4c147f617c4cf7e5825f279c | object_extractor/named_object.py | object_extractor/named_object.py | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... | from collections import defaultdict
class EntityForm:
def __init__(self):
self._score = 0.
self.forms = defaultdict(float)
def add_form(self, score, normal_form):
self._score += score
self.forms[normal_form] += score
def normal_form(self):
return max(self.forms.it... | Remove `objects' group as useless | Remove `objects' group as useless
| Python | mit | Lol4t0/named-objects-extractor |
c6427c035b9d1d38618ebfed33f729e3d10f270d | config.py | config.py | from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bo... | from katagawa.kg import Katagawa
from schema.config import Guild
class Config:
def __init__(self, bot):
dsn = f'postgresql://beattie:passwd@localhost/config'
self.db = Katagawa(dsn)
self.bot = bot
self.bot.loop.create_task(self.db.connect())
def __del__(self):
self.bo... | Change set to merge correctly | Change set to merge correctly
| Python | mit | BeatButton/beattie,BeatButton/beattie-bot |
dbda7d542c2f9353a57b63b7508afbf9bc2397cd | examples/address_validation.py | examples/address_validation.py | #!/usr/bin/env python
"""
This example shows how to validate addresses. Note that the validation
class can handle up to 100 addresses for validation.
"""
import logging
import binascii
from example_config import CONFIG_OBJ
from fedex.services.address_validation_service import FedexAddressValidationRequest
# Set this t... | #!/usr/bin/env python
"""
This example shows how to validate addresses. Note that the validation
class can handle up to 100 addresses for validation.
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.address_validation_service import FedexAddressValidationRequest
# Set this to the INFO level... | Remove un-necessary binascii module import. | Remove un-necessary binascii module import.
| Python | bsd-3-clause | gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex,obr/python-fedex,python-fedex-devs/python-fedex,python-fedex-devs/python-fedex,obr/python-fedex,gtaylor/python-fedex,gtaylor/python-fedex,python-fedex-devs/python-fedex,AxiaCore/python-fedex |
0fe2cf6b03c6eb11a7cabed9302a1aa312a33b31 | django/projects/mysite/run-gevent.py | django/projects/mysite/run-gevent.py | #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings... | #!/usr/bin/env python
# Import gevent monkey and patch everything
from gevent import monkey
monkey.patch_all(httplib=True)
# Import the rest
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIApp
from django.core.management import setup_environ
from gevent.wsgi import WSGIServer
import sys
import settings... | Allow host/port config in settings file for gevent run script | Allow host/port config in settings file for gevent run script
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID |
b1bb08a8ee246774b43e521e8f754cdcc88c418b | gasistafelice/gas/management.py | gasistafelice/gas/management.py | from django.db.models.signals import post_syncdb
from gasistafelice.gas.workflow_data import workflow_dict
def init_workflows(app, created_models, verbosity, **kwargs):
app_label = app.__name__.split('.')[-2]
if app_label == 'workflows' and created_models: # `worklows` app was syncronized for the first time
... | from django.db.models.signals import post_syncdb
from gasistafelice.gas.workflow_data import workflow_dict
def init_workflows(app, created_models, verbosity, **kwargs):
app_label = app.__name__.split('.')[-2]
if app_label == 'workflows' and "Workflow" in created_models: # `worklows` app was syncronized for th... | Fix in post_syncdb workflow registration | Fix in post_syncdb workflow registration
| Python | agpl-3.0 | michelesr/gasistafelice,befair/gasistafelice,matteo88/gasistafelice,matteo88/gasistafelice,OrlyMar/gasistafelice,kobe25/gasistafelice,michelesr/gasistafelice,kobe25/gasistafelice,befair/gasistafelice,michelesr/gasistafelice,matteo88/gasistafelice,kobe25/gasistafelice,feroda/gasistafelice,OrlyMar/gasistafelice,michelesr... |
7080057c9abc6e455222e057315055b3e9965cc9 | runtests.py | runtests.py | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
ALLOWED_HOSTS=[
'testserver',
],
INSTALLED_APPS=[
... | #!/usr/bin/env python
import django
from django.conf import settings
from django.core.management import call_command
TEST_SETTINGS = {
'DATABASES': {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
},
'ALLOWED_HOSTS': [
'testserver',
],
'INSTALLED_APPS': [... | Set middleware setting according to Django version in test settings | Set middleware setting according to Django version in test settings
Django 1.10 introduced new-style middleware and the corresponding
MIDDLEWARE setting and deprecated MIDDLEWARE_CLASSES. The latter is
ignored on Django 2.
| Python | mit | wylee/django-perms |
4dbc42b0516578d59b315b1ac1fa6ccf3e262f1e | seo/escaped_fragment/app.py | seo/escaped_fragment/app.py | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... | # Copyright (C) Ivan Kravets <me@ikravets.com>
# See LICENSE for details.
from subprocess import check_output, CalledProcessError
from urllib import unquote
def application(env, start_response):
status = "200 OK"
response = ""
qs = env.get("QUERY_STRING", None)
if not qs or not qs.startswith("_escap... | Fix broken content from PhJS | Fix broken content from PhJS | Python | apache-2.0 | platformio/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,orgkhnargh/platformio-web,platformio/platformio-web |
fd061738d025b5371c1415a1f5466bcf5f6476b7 | py2deb/config/__init__.py | py2deb/config/__init__.py | import os
config_dir = os.path.dirname(os.path.abspath(__file__))
# Destination of built packages.
PKG_REPO = '/tmp/'
| import os
config_dir = os.path.dirname(os.path.abspath(__file__))
# Destination of built packages.
if os.getuid() == 0:
PKG_REPO = '/var/repos/deb-repo/repository/pl-py2deb'
else:
PKG_REPO = '/tmp'
| Make it work out of the box on the build-server and locally | Make it work out of the box on the build-server and locally
| Python | mit | paylogic/py2deb,paylogic/py2deb |
8d9b50b2cd8b0235863c48a84ba5f23af4531765 | ynr/apps/parties/tests/test_models.py | ynr/apps/parties/tests/test_models.py | """
Test some of the basic model use cases
"""
from django.test import TestCase
from .factories import PartyFactory, PartyEmblemFactory
class TestPartyModels(TestCase):
def setUp(self):
PartyFactory.reset_sequence()
def test_party_str(self):
party = PartyFactory()
self.assertEqual(s... | """
Test some of the basic model use cases
"""
from django.test import TestCase
from django.core.files.storage import DefaultStorage
from candidates.tests.helpers import TmpMediaRootMixin
from .factories import PartyFactory, PartyEmblemFactory
class TestPartyModels(TmpMediaRootMixin, TestCase):
def setUp(self):... | Test using tmp media root | Test using tmp media root
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative |
b6a2ba81c9ddd642cfa271cab809a5c2511f7204 | app/auth/forms.py | app/auth/forms.py | from flask_wtf import Form
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(Form):
email = StringField('Email', validators=[
... | from flask_wtf import FlaskForm
from wtforms import (
StringField, PasswordField, BooleanField, SubmitField,
ValidationError,
)
from wtforms.validators import (
InputRequired, Length, Email, Regexp, EqualTo,
)
from app.models import User
class LoginForm(FlaskForm):
email = StringField('Email', valida... | Change Form to FlaskForm (previous is deprecated) | :art: Change Form to FlaskForm (previous is deprecated)
| Python | mit | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys |
58544043b8dee4e55bad0be5d889a40c0ae88960 | tests/__init__.py | tests/__init__.py | import logging
import os
import re
import unittest.mock
# Default to turning off all but critical logging messages
logging.basicConfig(level=logging.CRITICAL)
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a local file ... | import logging
import os
import re
import io
import unittest.mock
# Default to turning off all but critical logging messages
logging.basicConfig(level=logging.CRITICAL)
def mock_open_url(url, allow_local=False, timeout=None, verify_ssl=True, http_headers=None):
"""Open local files instead of URLs.
If it's a l... | Fix intermittent errors during test runs. | Fix intermittent errors during test runs.
| Python | unlicense | HXLStandard/libhxl-python,HXLStandard/libhxl-python |
2f2b64321a54c93a109c0b65866d724227db9399 | tests/conftest.py | tests/conftest.py | from unittest.mock import MagicMock
import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="em... | import pytest
from rocketchat_API.rocketchat import RocketChat
@pytest.fixture(scope="session")
def rocket():
_rocket = RocketChat()
return _rocket
@pytest.fixture(scope="session")
def create_user(rocket):
def _create_user(name="user1", password="password", email="email@domain.com"):
# create e... | Remove Mock and create "empty" object on the fly | Remove Mock and create "empty" object on the fly
| Python | mit | jadolg/rocketchat_API |
00f1ff26fcd7d0398d057eee2c7c6f6b2002e959 | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def event_loop():
print("in event_loop")
try:
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
loop = asyncio.new_event_loop()
yield loop
loop.close()
| import pytest
@pytest.fixture
def event_loop():
try:
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
except ImportError:
pass
loop = asyncio.new_event_loop()
yield loop
loop.close()
| Remove accidentally left in print statement | Remove accidentally left in print statement
| Python | mit | kura/blackhole,kura/blackhole |
dcebceec83c31fc9b99cb5e232ae066ee229c3bf | tests/conftest.py | tests/conftest.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Shared fixture functions."""
import pathlib
import pytest # pylint: disable=E0401
import spacy # pylint: disable=E0401
from spacy.language import Language # pylint: disable=E0401
from spacy.tokens import Doc # pylint: disable=E0401
@pytest.fixture(s... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Shared fixture functions."""
import pathlib
import pytest # pylint: disable=E0401
import spacy # pylint: disable=E0401
from spacy.language import Language # pylint: disable=E0401
from spacy.tokens import Doc # pylint: disable=E0401
@pytest.fixture(s... | Set fixture scope to module, so that pipes from one file dont influence tests from another | Set fixture scope to module, so that pipes from one file dont influence tests from another
| Python | apache-2.0 | ceteri/pytextrank,ceteri/pytextrank |
6b148e4c98628e9ef60cc3ce70c7cdeb8a215c49 | scarplet/datasets/base.py | scarplet/datasets/base.py | """ Convenience functions to load example datasets """
import os
import scarplet as sl
EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'data/')
def load_carrizo():
path = os.path.join(EXAMPLE_DIRECTORY, 'carrizo.tif')
data = sl.load(path)
re... | """ Convenience functions to load example datasets """
import os
import scarplet as sl
EXAMPLE_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'data/')
def load_carrizo():
"""
Load sample dataset containing fault scarps along the San Andreas Fault
f... | Add docstrings for load functions | Add docstrings for load functions
| Python | mit | rmsare/scarplet,stgl/scarplet |
39acab842be6a82d687d4edf6c1d29e7bf293fae | udp_logger.py | udp_logger.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import socket, AF_INET, SOCK_DGRAM
def create_udp_server_socket(endpoint):
skt = socket(AF_INET, SOCK_DGRAM)
skt.bind(endpoint)
return skt
if __name__ == '__main__':
ENDPOINT = ("", 3000) # empty string == INADDR_ANY
skt = create_udp_ser... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from socket import socket, AF_INET, SOCK_DGRAM
from optparse import OptionParser
def create_udp_server_socket(endpoint):
skt = socket(AF_INET, SOCK_DGRAM)
skt.bind(endpoint)
return skt
def MakeOptionParser():
parser = OptionParser()
parser.add_option('-a'... | Support for appending to a file | Support for appending to a file
| Python | mit | tmacam/remote_logging_cpp,tmacam/remote_logging_cpp |
3a74774a42521f4b68e484855d103495438095c3 | examples/schema/targetinfo.py | examples/schema/targetinfo.py | import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField(jsl.StringField(), max_items=2)
rsync = jsl.ArrayField(jsl.StringField(), max_items=2)
containers = jsl.ArrayField([
jsl.StringField(),
jsl.ArrayField(jsl.StringField())
])
| import jsl
class TargetInfo(jsl.Document):
docker = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
rsync = jsl.ArrayField([
jsl.StringField(),
jsl.OneOfField([jsl.StringField(), jsl.NullField()])
])
containers = jsl.Array... | Correct the target info schema: docker and rsync messages are Null in case of success. Suggested by @vinzenz and corrected by @artmello. | Correct the target info schema: docker and rsync messages are Null in case of
success. Suggested by @vinzenz and corrected by @artmello.
| Python | apache-2.0 | leapp-to/snactor |
74260bc1b401d9ec500fba1eae72b99c2a2db147 | github.py | github.py | import requests
GITHUB_API_URL = "https://api.github.com/graphql"
QUERY = """
query($repository_owner:String!, $repository_name: String!, $count: Int!) {
repository(
owner: $repository_owner,
name: $repository_name) {
refs(last: $count,refPrefix:"refs/tags/") {
edges {
node{
... | import requests
GITHUB_API_URL = "https://api.github.com/graphql"
QUERY = """
query($repository_owner:String!,
$repository_name: String!,
$count: Int!) {
repository(owner: $repository_owner,
name: $repository_name) {
refs(last: $count,refPrefix:"refs/tags/") {
nodes {
... | Update query to use nodes | Update query to use nodes
| Python | mit | ayushgoel/LongShot |
05e62b96cfa50934d98d78a86307d94239dd7a4b | Orange/__init__.py | Orange/__init__.py | from .misc.lazy_module import LazyModule
from .version import \
short_version as __version__, git_revision as __git_version__
ADDONS_ENTRY_POINT = 'orange.addons'
from Orange import data
for mod_name in ['classification', 'clustering', 'distance', 'evaluation',
'feature', 'misc', 'regression', '... | from .misc.lazy_module import LazyModule
from .version import \
short_version as __version__, git_revision as __git_version__
ADDONS_ENTRY_POINT = 'orange.addons'
from Orange import data
for mod_name in ['classification', 'clustering', 'distance', 'evaluation',
'feature', 'misc', 'regression', '... | Add preprocess to the list of modules lazy-imported in Orange | Add preprocess to the list of modules lazy-imported in Orange
| Python | bsd-2-clause | cheral/orange3,qPCR4vir/orange3,kwikadi/orange3,qusp/orange3,cheral/orange3,cheral/orange3,marinkaz/orange3,kwikadi/orange3,kwikadi/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,qusp/orange3,kwikadi/orange3,marinkaz/orange3,marinkaz/orange3,kwikadi/orange3,qusp/orange3,marinkaz/orange3,qusp/orange3,qPCR4vir/... |
896a9b3d116a6ac2d313c5ea8dbc16345a097138 | linguine/ops/StanfordCoreNLP.py | linguine/ops/StanfordCoreNLP.py | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
def __init__(self):
# I don't see anywhere to put properties like this path...
# For now it's hardcoded and would ... | #!/usr/bin/env python
import os
"""
Performs some core NLP operations as a proof of concept for the library.
"""
from stanford_corenlp_pywrapper import CoreNLP
class StanfordCoreNLP:
"""
When the JSON segments return from the CoreNLP library, they
separate the data acquired from each word into their... | Format JSON to be collections of tokens | Format JSON to be collections of tokens
When coreNLP returns the JSON payload, it is in an unmanageable format
where multiple arrays are made for all parts of speech, tokens, and
lemmas. It's much easier to manage when the response is formatted as a
list of objects:
{
"token": "Pineapple",
"lemma": "Pineapple",
... | Python | mit | rigatoni/linguine-python,Pastafarians/linguine-python |
f473cc24e0f2a41699ed9e684b400cb5cb562ce6 | go_contacts/backends/utils.py | go_contacts/backends/utils.py | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... | from vumi.persist.model import VumiRiakError
from go_api.collections.errors import CollectionUsageError
from go_api.queue import PausingQueueCloseMarker
from twisted.internet.defer import inlineCallbacks, returnValue
@inlineCallbacks
def _get_page_of_keys(model_proxy, user_account_key, max_results, cursor):
try:
... | Change to more generic variable names in _fill_queue | Change to more generic variable names in _fill_queue
| Python | bsd-3-clause | praekelt/go-contacts-api,praekelt/go-contacts-api |
b7b41a160294edd987f73be7817c8b08aa8ed70e | herders/templatetags/utils.py | herders/templatetags/utils.py | from django import template
register = template.Library()
@register.filter
def get_range(value):
return range(value)
@register.filter
def absolute(value):
return abs(value)
@register.filter
def subtract(value, arg):
return value - arg
@register.filter
def multiply(value, arg):
return value * ar... | from django import template
register = template.Library()
@register.filter
def get_range(value):
if value:
return range(value)
else:
return 0
@register.filter
def absolute(value):
return abs(value)
@register.filter
def subtract(value, arg):
return value - arg
@register.filter
de... | Return 0 with the get_range filter if value is invalid instead of raise exception | Return 0 with the get_range filter if value is invalid instead of raise exception
| Python | apache-2.0 | porksmash/swarfarm,PeteAndersen/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm,porksmash/swarfarm,porksmash/swarfarm,PeteAndersen/swarfarm |
6d018ef0ac8bc020b38dab1dd29dd6e383be2e8e | src/sentry_heroku/plugin.py | src/sentry_heroku/plugin.py | """
sentry_heroku.plugin
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Sentry Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
"""
import sentry_heroku
from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin
class HerokuReleaseHook(ReleaseHook):
def handle(self, reque... | """
sentry_heroku.plugin
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2015 by Sentry Team, see AUTHORS for more details.
:license: Apache 2.0, see LICENSE for more details.
"""
import sentry_heroku
from sentry.plugins import ReleaseHook, ReleaseTrackingPlugin
class HerokuReleaseHook(ReleaseHook):
def handle(self, reque... | Add url and environment to payload | Add url and environment to payload
| Python | apache-2.0 | getsentry/sentry-heroku |
400289449e164ff168372d9df286acba35926e61 | map_points/oauth2/decorators.py | map_points/oauth2/decorators.py | import httplib2
from decorator import decorator
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials
@decorator
def auth_required(f, request, *args, **kwargs):
if 'credentials' not in request.ses... | import httplib2
from decorator import decorator
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from googleapiclient import discovery
from oauth2client.client import OAuth2Credentials
@decorator
def auth_required(f, request, *args, **kwargs):
"""
Verify if request is author... | Add docstr to auth_required decorator. | Add docstr to auth_required decorator.
| Python | mit | nihn/map-points,nihn/map-points,nihn/map-points,nihn/map-points |
2d0b44d65a8167a105cbc63e704735b1c360e0c4 | api/core/urls.py | api/core/urls.py | from django.urls import path, re_path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [
path('go/<path:path>', views.redirector, name='redirector'),
re_path('^', views.index, name='index'),... | from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.views import logout
from django.urls import path, re_path
from . import views
urlpatterns = static('/compiled/', document_root=settings.BUILD_ROOT) + [
path('go/<path:path>', views.redirector, name='redirector'),... | Handle logout on the backend | Handle logout on the backend
| Python | mit | citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement,citizenlabsgr/voter-engagement |
e6ae7fc2c30aa8af087b803408359189ece58f30 | keystone/common/policies/revoke_event.py | keystone/common/policies/revoke_event.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... | Move revoke events to DocumentedRuleDefault | Move revoke events to DocumentedRuleDefault
The overall goal is to define a richer policy for deployers
and operators[0]. To achieve that goal a new policy
class was introduce that requires additional parameters
when defining policy objects.
This patch switches our revoke events policy object to
the policy.Documented... | Python | apache-2.0 | rajalokan/keystone,mahak/keystone,rajalokan/keystone,ilay09/keystone,openstack/keystone,rajalokan/keystone,openstack/keystone,openstack/keystone,mahak/keystone,ilay09/keystone,mahak/keystone,ilay09/keystone |
5cb8d2a4187d867111b32491df6e53983f124d73 | rawkit/raw.py | rawkit/raw.py | from rawkit.libraw import libraw
class Raw(object):
def __init__(self, filename=None):
self.data = libraw.libraw_init(0)
libraw.libraw_open_file(self.data, bytes(filename, 'utf-8'))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
libr... | from rawkit.libraw import libraw
class Raw(object):
def __init__(self, filename=None):
self.data = libraw.libraw_init(0)
libraw.libraw_open_file(self.data, bytes(filename, 'utf-8'))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
"""C... | Add close method to Raw class | Add close method to Raw class
Fixes #10
| Python | mit | nagyistoce/rawkit,SamWhited/rawkit,photoshell/rawkit |
abd5fcac1fa585daa73910273adf429baf671de3 | contrib/runners/windows_runner/windows_runner/__init__.py | contrib/runners/windows_runner/windows_runner/__init__.py | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | # -*- coding: utf-8 -*-
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | Remove code we dont need anymore. | Remove code we dont need anymore.
| Python | apache-2.0 | nzlosh/st2,StackStorm/st2,StackStorm/st2,StackStorm/st2,Plexxi/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2,Plexxi/st2 |
6e874375ee1d371a3e6ecb786ade4e1b16d84da5 | wafer/kv/views.py | wafer/kv/views.py | from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs to be viewed or edited."""
queryset = ... | from rest_framework import viewsets
from wafer.kv.models import KeyValue
from wafer.kv.serializers import KeyValueSerializer
from wafer.kv.permissions import KeyValueGroupPermission
from wafer.utils import order_results_by
class KeyValueViewSet(viewsets.ModelViewSet):
"""API endpoint that allows key-value pairs ... | Order paginated KV API results. | Order paginated KV API results.
| Python | isc | CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer |
d8872865cc7159ffeeae45a860b97cd241f95c6e | vispy/visuals/tests/test_arrows.py | vispy/visuals/tests/test_arrows.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... | # -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
import numpy as np
from vispy.visuals.line.arrow import ARROW_TYPES
from vispy.scene import visuals, transforms
from vispy.testing import (requires_application, TestingCanvas... | Disable antialias for GL drawing lines | Disable antialias for GL drawing lines
| Python | bsd-3-clause | inclement/vispy,michaelaye/vispy,srinathv/vispy,jay3sh/vispy,julienr/vispy,QuLogic/vispy,jay3sh/vispy,julienr/vispy,ghisvail/vispy,drufat/vispy,Eric89GXL/vispy,inclement/vispy,RebeccaWPerry/vispy,michaelaye/vispy,kkuunnddaannkk/vispy,Eric89GXL/vispy,jdreaver/vispy,sbtlaarzc/vispy,srinathv/vispy,Eric89GXL/vispy,drufat/v... |
a1be6021c4d13b1212dff74dc981a602951994fb | erpnext/patches/v4_0/customer_discount_to_pricing_rule.py | erpnext/patches/v4_0/customer_discount_to_pricing_rule.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.au... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils.nestedset import get_root_of
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
frappe.db.au... | Fix in pricing rule patch | Fix in pricing rule patch
| Python | agpl-3.0 | mbauskar/omnitech-erpnext,indictranstech/internal-erpnext,pawaranand/phrerp,SPKian/Testing,indictranstech/reciphergroup-erpnext,Drooids/erpnext,suyashphadtare/gd-erp,shft117/SteckerApp,hernad/erpnext,pawaranand/phrerp,pombredanne/erpnext,rohitwaghchaure/digitales_erpnext,Tejal011089/trufil-erpnext,suyashphadtare/sajil-... |
701d312815fe6f193e1e555abe9fc65f9cee0567 | core/management/commands/send_tweets.py | core/management/commands/send_tweets.py | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
... | import twitter
from django.core.management.base import BaseCommand
from django.conf import settings
from core.models import Tweet
class Command(BaseCommand):
help = "Send out tweets."
def handle(self, *args, **options):
for tweet in Tweet.objects.filter(was_sent=False, failed_trials__lte=5):
... | Use ENJAZACESSS when is access is provided | Use ENJAZACESSS when is access is provided
| Python | agpl-3.0 | enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,enjaz/enjaz,enjaz/enjaz,enjaz/enjaz,osamak/student-portal,osamak/student-portal,osamak/student-portal |
d324b27e41aee52b044e5647a4a13aecc9130c3e | tests/conftest.py | tests/conftest.py | import pytest
from utils import *
from pgcli.pgexecute import PGExecute
@pytest.yield_fixture(scope="function")
def connection():
create_db('_test_db')
connection = db_connection('_test_db')
yield connection
drop_tables(connection)
connection.close()
@pytest.fixture
def cursor(connection):
... | import pytest
from utils import (POSTGRES_HOST, POSTGRES_USER, create_db, db_connection,
drop_tables)
import pgcli.pgexecute
@pytest.yield_fixture(scope="function")
def connection():
create_db('_test_db')
connection = db_connection('_test_db')
yield connection
drop_tables(connection)
connection.c... | Replace splat import in tests. | Replace splat import in tests.
| Python | bsd-3-clause | koljonen/pgcli,darikg/pgcli,n-someya/pgcli,thedrow/pgcli,dbcli/vcli,joewalnes/pgcli,zhiyuanshi/pgcli,thedrow/pgcli,darikg/pgcli,janusnic/pgcli,bitemyapp/pgcli,dbcli/pgcli,MattOates/pgcli,suzukaze/pgcli,bitmonk/pgcli,bitmonk/pgcli,johshoff/pgcli,nosun/pgcli,d33tah/pgcli,johshoff/pgcli,koljonen/pgcli,lk1ngaa7/pgcli,zhiyu... |
e5beaabc66cbb87f63e2648b277bada72ddec7dc | tests/conftest.py | tests/conftest.py | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
de... | import arrayfire
import pytest
backends = arrayfire.library.get_available_backends()
# do not use opencl backend, it's kinda broken
#backends = [x for x in backends if x != 'opencl']
# This will set the different backends before each test is executed
@pytest.fixture(scope="function", params=backends, autouse=True)
de... | Allow unsafe change of backend for testing | Allow unsafe change of backend for testing
| Python | bsd-2-clause | FilipeMaia/afnumpy,daurer/afnumpy |
c5a617db987fda0302cf5963bbc41e8d0887347d | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture
def observe(monkeypatch):
def patch(module, func):
original_func = getattr(module, func)
def wrapper(*args, **kwargs):
result = original_func(*args, **kwargs)
self.calls[self.last_call] = (args, kwargs, result)
self.last_call += 1
... | import pytest
@pytest.fixture
def observe(monkeypatch):
"""
Wrap a function so its call history can be inspected.
Example:
# foo.py
def func(bar):
return 2 * bar
# test.py
import pytest
import foo
def test_func(observe):
observer = observe(foo, "func")
a... | Clean up test helper, add example | Clean up test helper, add example
| Python | mit | numberoverzero/pyservice |
dec3ec25739e78c465fd5e31a161a674331edbed | serpent/cv.py | serpent/cv.py | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = N... | import numpy as np
import skimage.io
import skimage.util
import os
def extract_region_from_image(image, region_bounding_box):
return image[region_bounding_box[0]:region_bounding_box[2], region_bounding_box[1]:region_bounding_box[3]]
def isolate_sprite(image_region_path, output_file_path):
result_image = N... | Change scale range to normalization with source and target min max | Change scale range to normalization with source and target min max
| Python | mit | SerpentAI/SerpentAI |
7157843c2469fd837cb30df182ad69583790b9eb | makeaface/makeaface/urls.py | makeaface/makeaface/urls.py | from django.conf.urls.defaults import *
from motion.feeds import PublicEventsFeed
urlpatterns = patterns('',
url(r'^$', 'makeaface.views.home', name='home'),
url(r'^$', 'makeaface.views.home', name='group_events'),
url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'),
url(r'^entry/(... | from django.conf.urls.defaults import *
from motion.feeds import PublicEventsFeed
urlpatterns = patterns('',
url(r'^$', 'makeaface.views.home', name='home'),
url(r'^$', 'makeaface.views.home', name='group_events'),
url(r'^authorize/?$', 'makeaface.views.authorize', name='authorize'),
url(r'^entry/(... | Handle when /grid ends with a period, since Twitter let apgwoz link to it that way | Handle when /grid ends with a period, since Twitter let apgwoz link to it that way
| Python | mit | markpasc/make-a-face,markpasc/make-a-face |
fedf1df20418169a377012c22bf81f758e2978e8 | tests/test_dbg.py | tests/test_dbg.py | import pytest
from boink.dbg_tests import (_test_add_single_kmer,
_test_add_two_kmers,
_test_kmer_degree,
_test_kmer_in_degree,
_test_kmer_out_degree)
def test_add_single_kmer():
_test_add_single_km... | import pytest
from utils import *
from boink.dbg_tests import (_test_add_single_kmer,
_test_add_two_kmers,
_test_kmer_degree,
_test_kmer_in_degree,
_test_kmer_out_degree,
_te... | Add right tip structure tests | Add right tip structure tests
| Python | mit | camillescott/boink,camillescott/boink,camillescott/boink,camillescott/boink |
568c3466844ec9b27fbe7e3a4e1bae772203923d | touch/__init__.py | touch/__init__.py | from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get(... | from pelican import signals
import logging
import os
import time
logger = logging.getLogger(__name__)
def set_file_utime(path, datetime):
mtime = time.mktime(datetime.timetuple())
logger.info('touching %s', path)
os.utime(path, (mtime, mtime))
def touch_file(path, context):
content = context.get(... | Update timestamps of generated feeds as well | Update timestamps of generated feeds as well
| Python | agpl-3.0 | frickp/pelican-plugins,UHBiocomputation/pelican-plugins,xsteadfastx/pelican-plugins,mikitex70/pelican-plugins,jantman/pelican-plugins,proteansec/pelican-plugins,lindzey/pelican-plugins,farseerfc/pelican-plugins,davidmarquis/pelican-plugins,UHBiocomputation/pelican-plugins,makefu/pelican-plugins,mwcz/pelican-plugins,goe... |
394262effa690eda51ba9ee29aa86d98c683e17d | foundry/tests.py | foundry/tests.py | from django.core import management
from django.test import TestCase
from django.contrib.contenttypes.models import ContentType
from post.models import Post
from foundry.models import Member, Listing
class TestCase(TestCase):
def setUp(self):
# Post-syncdb steps
management.call_command('migrate'... | from django.core import management
from django.utils import unittest
from django.contrib.contenttypes.models import ContentType
from django.test.client import Client
from post.models import Post
from foundry.models import Member, Listing
class TestCase(unittest.TestCase):
def setUp(self):
self.client =... | Add test to show login form is broken | Add test to show login form is broken
| Python | bsd-3-clause | praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry |
332452cf7ccd6d3ee583be9a6aac27b14771263f | source/services/omdb_service.py | source/services/omdb_service.py | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoe... | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoe... | Add url to RTRating object | Add url to RTRating object
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu |
a27d3f76f194a9767022e37c83d5d18861552cfd | all-domains/tutorials/cracking-the-coding-interview/linked-lists-detect-a-cycle/solution.py | all-domains/tutorials/cracking-the-coding-interview/linked-lists-detect-a-cycle/solution.py | # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
... | # https://www.hackerrank.com/challenges/ctci-linked-list-cycle
# Python 3
"""
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty.
A Node is defined as:
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
... | Solve problem to detect linked list cycle | Solve problem to detect linked list cycle
https://www.hackerrank.com/challenges/ctci-linked-list-cycle
| Python | mit | arvinsim/hackerrank-solutions |
0be3b5bf33a3e0254297eda664c85fd249bce2fe | amostra/tests/test_jsonschema.py | amostra/tests/test_jsonschema.py | import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'].pop('uuid')
sample_dict['proper... | from operator import itemgetter
import hypothesis_jsonschema
from hypothesis import HealthCheck, given, settings
from hypothesis import strategies as st
from amostra.utils import load_schema
sample_dict = load_schema("sample.json")
# Pop uuid and revision cause they are created automatically
sample_dict['properties'... | Use itemgetter instead of lambda | TST: Use itemgetter instead of lambda
| Python | bsd-3-clause | NSLS-II/amostra |
d0ac312de9b48a78f92f9eb09e048131578483f5 | giles/utils.py | giles/utils.py | # Giles: utils.py
# Copyright 2012 Phil Bordelon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progra... | # Giles: utils.py
# Copyright 2012 Phil Bordelon
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progra... | Add my classic Struct "class." | Add my classic Struct "class."
That's right, I embrace the lazy.
| Python | agpl-3.0 | sunfall/giles |
b26ce5b5ff778208314bfd21014f88ee24917d7a | ideas/views.py | ideas/views.py | from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serialize... | from .models import Idea
from .serializers import IdeaSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET',])
def idea_list(request):
if request.method == 'GET':
ideas = Idea.objects.all()
serialize... | Add GET for idea and refactor vote | Add GET for idea and refactor vote
| Python | mit | neosergio/vote_hackatrix_backend |
6464c3ed7481e347dc6ca93ccfcad6964456e769 | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "capomastro.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| #!/usr/bin/env python
import os
import sys
# This bootstraps the virtualenv so that the system Python can use it
app_root = os.path.dirname(os.path.realpath(__file__))
activate_this = os.path.join(app_root, 'bin', 'activate_this.py')
execfile(activate_this, dict(__file__=activate_this))
if __name__ == "__main__":
... | Add temporary bootstrapping to get the service working with how the charm presently expects to run the app. | Add temporary bootstrapping to get the service working with how the charm presently expects to run the app.
| Python | mit | timrchavez/capomastro,timrchavez/capomastro |
8318bae21bd5cb716a4cbf2cd2dfe46ea8cadbcf | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
import dotenv
dotenv.read_dotenv('.env')
from configurations.management import execute_from_command_... | #!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development')
if os.environ['DJANGO_CONFIGURATION'] == 'Development':
import dotenv
dotenv.read_dotenv('.en... | Hide .env behind a development environment. | Hide .env behind a development environment.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
e9c7b17ccd9709eb90f38bec9d59c48dc6f793b2 | calico_containers/tests/st/utils.py | calico_containers/tests/st/utils.py | import sh
from sh import docker
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
intf = sh.ifconfig.eth0()
return sh.perl(intf, "-ne", 's/dr:(\S+)/print $1/e')
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.... | import sh
from sh import docker
import socket
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def cleanup_inside(name):
"""
Clean the... | Use socket connection to get own IP. | Use socket connection to get own IP.
Former-commit-id: ebec31105582235c8aa74e9bbfd608b9bf103ad1 | Python | apache-2.0 | robbrockbank/libcalico,tomdee/libnetwork-plugin,TrimBiggs/libcalico,plwhite/libcalico,tomdee/libcalico,projectcalico/libnetwork-plugin,L-MA/libcalico,projectcalico/libcalico,djosborne/libcalico,Symmetric/libcalico,TrimBiggs/libnetwork-plugin,alexhersh/libcalico,insequent/libcalico,caseydavenport/libcalico,TrimBiggs/lib... |
4a827bfff24758677e9c1d9d3b186fc14f23e0bb | lib/oeqa/runtime/cases/parselogs_rpi.py | lib/oeqa/runtime/cases/parselogs_rpi.py | from oeqa.runtime.cases.parselogs import *
rpi_errors = [
'bcmgenet fd580000.genet: failed to get enet-eee clock',
'bcmgenet fd580000.genet: failed to get enet-wol clock',
'bcmgenet fd580000.genet: failed to get enet clock',
'bcmgenet fd580000.ethernet: failed to get enet-eee clock',
'bcmgenet fd58... | from oeqa.runtime.cases.parselogs import *
rpi_errors = [
]
ignore_errors['raspberrypi4'] = rpi_errors + common_errors
ignore_errors['raspberrypi4-64'] = rpi_errors + common_errors
ignore_errors['raspberrypi3'] = rpi_errors + common_errors
ignore_errors['raspberrypi3-64'] = rpi_errors + common_errors
class ParseLogs... | Update the error regexps to 5.10 kernel | parselogs: Update the error regexps to 5.10 kernel
The old messages are no longer necessary
Signed-off-by: Khem Raj <729d64b6f67515e258459a5f6d20ec88b2caf8df@gmail.com>
| Python | mit | agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi,agherzan/meta-raspberrypi |
b1781b8c82979ee3765197084a9c8e372cb68cf8 | jazzband/hooks.py | jazzband/hooks.py | import json
import uuid
from flask_hookserver import Hooks
from .db import redis
from .members.models import User
from .projects.tasks import update_project_by_hook
from .tasks import spinach
hooks = Hooks()
@hooks.hook("ping")
def ping(data, guid):
return "pong"
@hooks.hook("membership")
def membership(dat... | import json
import uuid
from flask_hookserver import Hooks
from .db import redis
from .members.models import User
from .projects.tasks import update_project_by_hook
from .tasks import spinach
hooks = Hooks()
@hooks.hook("ping")
def ping(data, guid):
return "pong"
@hooks.hook("membership")
def membership(dat... | Use new (?) repository transferred hook. | Use new (?) repository transferred hook.
| Python | mit | jazzband/jazzband-site,jazzband/website,jazzband/website,jazzband/website,jazzband/website,jazzband/site,jazzband/jazzband-site,jazzband/site |
6e6c60613180bb3d7e2d019129e57d1a2c33286d | backend/backend/models.py | backend/backend/models.py | from django.db import models
class Animal(models.Model):
MALE = 'male'
FEMALE = 'female'
GENDER_CHOICES = ((MALE, 'Male'), (FEMALE, 'Female'))
father = models.ForeignKey("self", null = True, on_delete = models.SET_NULL, related_name = "child_father")
mother = models.ForeignKey("self", null = True... | from django.db import models
from django.core.validators import MaxValueValidator, MaxLengthValidator
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
from datetime import datetime
def current_year():
return datetime.now().year
class Animal(models.Model):
... | Add length validator to name. Add dob validator can't be higher than current year. | Add length validator to name.
Add dob validator can't be higher than current year.
| Python | apache-2.0 | mmlado/animal_pairing,mmlado/animal_pairing |
a1897464b7974589723790f946fed0c1a5bdb475 | chef/fabric.py | chef/fabric.py | from chef import Search
from chef.api import ChefAPI, autoconfigure
from chef.exceptions import ChefError
class Roledef(object):
def __init__(self, name, api, hostname_attr):
self.name = name
self.api = api
self.hostname_attr = hostname_attr
def __call__(self):
for row in Searc... | from chef import Search
from chef.api import ChefAPI, autoconfigure
from chef.exceptions import ChefError
class Roledef(object):
def __init__(self, name, api, hostname_attr):
self.name = name
self.api = api
self.hostname_attr = hostname_attr
def __call__(self):
for row in Searc... | Work around when fqdn is not defined for a node. | Work around when fqdn is not defined for a node.
| Python | apache-2.0 | Scalr/pychef,jarosser06/pychef,cread/pychef,coderanger/pychef,Scalr/pychef,jarosser06/pychef,dipakvwarade/pychef,dipakvwarade/pychef,coderanger/pychef,cread/pychef |
1ce39741886cdce69e3801a1d0afb25c39a8b844 | fitbit/models.py | fitbit/models.py | from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
| from django.contrib.auth.models import User
from django.db import models
class Token(models.Model):
fitbit_id = models.CharField(max_length=50)
refresh_token = models.CharField(max_length=120)
def __repr__(self):
return '<Token %s>' % self.fitbit_id
def __str__(self):
return self.fit... | Add repr and str to our token model | Add repr and str to our token model
| Python | apache-2.0 | Bachmann1234/fitbitSlackBot,Bachmann1234/fitbitSlackBot |
0420ed666f8a2cd5cd6c2055b13a5d26cc5d3792 | output.py | output.py | def summarizeECG(instHR, avgHR, brady, tachy):
"""Create txt file summarizing ECG analysis
:param instHR: (int)
:param avgHR: (int)
:param brady: (int)
:param tachy: (int)
"""
#Calls hrdetector() to get instantaneous heart rate
#instHR = findInstHR()
#Calls findAvgHR() to get averag... | def summarizeECG(instHR, avgHR, brady, tachy):
"""Create txt file summarizing ECG analysis
:param instHR: (int)
:param avgHR: (int)
:param brady: (int)
:param tachy: (int)
"""
#Calls hrdetector() to get instantaneous heart rate
#instHR = findInstHR()
#Calls findAvgHR() to get averag... | Add units to brady and tachy strings. | Add units to brady and tachy strings.
| Python | mit | raspearsy/bme590hrm |
93f9bb4115c4259dd38962229947b87e952a25a7 | completion/levenshtein.py | completion/levenshtein.py | def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = pr... | def levenshtein(top_string, bot_string):
if len(top_string) < len(bot_string):
return levenshtein(bot_string, top_string)
# len(s1) >= len(s2)
if len(bot_string) == 0:
return len(top_string)
previous_row = range(len(bot_string) + 1)
for i, top_char in enumerate(top_string):
... | Use better variable names for algorithmic determination | Use better variable names for algorithmic determination
| Python | mit | thatsIch/sublime-rainmeter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.