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
07a1a4bf4dc9ed6173c19e3409b11a311e029d7a
sim.py
sim.py
from gensim import models import time start_time = time.perf_counter() print('\nLoading vectors...\n') w = models.KeyedVectors.load_word2vec_format('/home/ubuntu/sim/CBOW|skipgram.bin', binary=True) relations = {'': [''], '': [''], '': ['']} original_verbs = list(relations.keys()) for ve...
from gensim import models import time start_time = time.perf_counter() print('\nLoading vectors...\n') w = models.KeyedVectors.load_word2vec_format('/home/ubuntu/sim/CBOW|skipgram.bin', binary=True) relations = {'': [''], '': [''], '': ['']} original_verbs = list(relations.keys()) for ve...
Print data for each paraverb.
Print data for each paraverb.
Python
mit
albertomh/ug-dissertation
48edfcddca89c506107035bd804fa536d3dec84d
geotrek/signage/migrations/0013_auto_20200423_1255.py
geotrek/signage/migrations/0013_auto_20200423_1255.py
# Generated by Django 2.0.13 on 2020-04-23 12:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.RemoveField( model_name='bla...
# Generated by Django 2.0.13 on 2020-04-23 12:55 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('signage', '0012_auto_20200406_1411'), ] operations = [ migrations.RunSQL(sql=[("DELETE FROM geotrek.signag...
Remove element with deleted=true before removefield
Remove element with deleted=true before removefield
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
84f6cc46e7ba7e2e3c046e957545687ce6802278
cegui/src/ScriptingModules/PythonScriptModule/bindings/distutils/PyCEGUI/__init__.py
cegui/src/ScriptingModules/PythonScriptModule/bindings/distutils/PyCEGUI/__init__.py
import os import os.path # atrocious and unholy! def get_my_path(): import fake return os.path.dirname(str(fake).split()[3][1:]) libpath = os.path.abspath(get_my_path()) #print "libpath =", libpath os.environ['PATH'] = libpath + ";" + os.environ['PATH'] from PyCEGUI import *
import os import os.path # atrocious and unholy! def get_my_path(): import fake return os.path.dirname(os.path.abspath(fake.__file__)) libpath = get_my_path() #print "libpath =", libpath os.environ['PATH'] = libpath + ";" + os.environ['PATH'] from PyCEGUI import *
Use a less pathetic method to retrieve the PyCEGUI dirname
MOD: Use a less pathetic method to retrieve the PyCEGUI dirname
Python
mit
cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two,cbeck88/cegui-mirror-two
e9b7c19a7080bd9e9a88f0e2eb53a662ee5b154b
tests/python/verify_image.py
tests/python/verify_image.py
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get(...
import unittest import os from selenium import webdriver from time import sleep class TestClaimsLogin(unittest.TestCase): def setUp(self): self.driver = webdriver.PhantomJS() self.ip = os.environ.get('DOCKER_IP', '172.17.0.1') def test_verify_main_screen_loaded(self): self.driver.get(...
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Change self.assertIn to self.assertTrue('Hello Implementer' in greeting.txt)
Python
mit
censof/ansible-deployment,censof/ansible-deployment,censof/ansible-deployment
dce91e460421ef9416f5ca98a5850c23a0cbf7c0
akaudit/userinput.py
akaudit/userinput.py
def yesno(prompt='? '): # raw_input returns the empty string for "enter" yes = set(['yes','y', 'ye', '']) no = set(['no','n']) choice = input(prompt).lower() if choice in yes: return True elif choice in no: return False else: sys.stdout.write("Please respond with 'yes' or 'no'")
from six.moves import input def yesno(prompt='? '): # raw_input returns the empty string for "enter" yes = set(['yes','y', 'ye', '']) no = set(['no','n']) choice = input(prompt).lower() if choice in yes: return True elif choice in no: return False else: sys.stdout.write("Please respond with 'yes' or 'no'...
Support input() on python 2.
Support input() on python 2.
Python
apache-2.0
flaccid/akaudit
372edf44efd7e028890e4623a950052a606bb123
shade/tests/functional/util.py
shade/tests/functional/util.py
# -*- coding: utf-8 -*- # 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, softw...
# -*- coding: utf-8 -*- # 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, softw...
Enable running tests against RAX and IBM
Enable running tests against RAX and IBM Rackspace requires performance flavors be used for boot from volume. IBM does not have Ubuntu or Cirros images in the cloud. Change-Id: I95c15d92072311eb4aa0a4b7f551a95c4dc6e082
Python
apache-2.0
dtroyer/python-openstacksdk,openstack/python-openstacksdk,stackforge/python-openstacksdk,openstack-infra/shade,dtroyer/python-openstacksdk,openstack-infra/shade,stackforge/python-openstacksdk,openstack/python-openstacksdk
aeb9b1abb8b3bf4ebcd2e019b724446bad72190d
dbsettings/management.py
dbsettings/management.py
from django.db.models.signals import post_migrate def mk_permissions(permissions, appname, verbosity): """ Make permission at app level - hack with empty ContentType. Adapted code from http://djangosnippets.org/snippets/334/ """ from django.contrib.auth.models import Permission from django.co...
from django.db.models.signals import post_migrate def mk_permissions(permissions, appname, verbosity): """ Make permission at app level - hack with empty ContentType. Adapted code from http://djangosnippets.org/snippets/334/ """ from django.contrib.auth.models import Permission from django.co...
Change __name__ for label (Django 1.9)
Change __name__ for label (Django 1.9)
Python
bsd-3-clause
zlorf/django-dbsettings,helber/django-dbsettings,DjangoAdminHackers/django-dbsettings,zlorf/django-dbsettings,sciyoshi/django-dbsettings,helber/django-dbsettings,DjangoAdminHackers/django-dbsettings,sciyoshi/django-dbsettings
e03aae99999f48a8d7ef8012f5b3718d1523224e
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
cla_backend/apps/cla_eventlog/management/commands/find_and_delete_old_cases.py
import sys from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): two_years = self.now - relati...
import sys from django.core.management.base import BaseCommand from dateutil.relativedelta import relativedelta from legalaid.models import Case from cla_butler.tasks import DeleteOldData class FindAndDeleteCasesUsingCreationTime(DeleteOldData): def get_eligible_cases(self): two_years = self.now - relati...
Refactor command to accept input or no input on delete
Refactor command to accept input or no input on delete
Python
mit
ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend
8bf1e479f1dd8423613d6eb0f5c78dd78fdc9c67
troposphere/sns.py
troposphere/sns.py
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class TopicPolicy(AWSObject): ...
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject, AWSProperty class Subscription(AWSProperty): props = { 'Endpoint': (basestring, True), 'Protocol': (basestring, True), } class TopicPolicy(AWSObject): ...
Validate the Subscription policy is made up of Subscription objects
Validate the Subscription policy is made up of Subscription objects
Python
bsd-2-clause
wangqiang8511/troposphere,7digital/troposphere,pas256/troposphere,Hons/troposphere,WeAreCloudar/troposphere,johnctitus/troposphere,nicolaka/troposphere,LouTheBrew/troposphere,yxd-hde/troposphere,jantman/troposphere,alonsodomin/troposphere,micahhausler/troposphere,inetCatapult/troposphere,garnaat/troposphere,cloudtools/...
ceed67d1e3dbe831d5301406d15eec583d85825f
blueplayer/__main__.py
blueplayer/__main__.py
import sys import serial from blueplayer import blueplayer def main(args): # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port: try: player = bl...
import sys import serial from blueplayer import blueplayer def main(): args = sys.argv[1:] # first argument should be a serial terminal to open if not len(args): port = "/dev/ttyAMA0" else: port = args[0] player = None with serial.Serial(port) as serial_port: try: ...
Fix args in entry point
Fix args in entry point
Python
mit
dylwhich/rpi-ipod-emulator
67ebd0a80ec51e29dd176c8375c92e7cebf9b686
dmoj/executors/KOTLIN.py
dmoj/executors/KOTLIN.py
import os.path from dmoj.executors.java_executor import JavaExecutor with open(os.path.join(os.path.dirname(__file__), 'java-security.policy')) as policy_file: policy = policy_file.read() class Executor(JavaExecutor): name = 'KOTLIN' ext = '.kt' compiler = 'kotlinc' vm = 'kotlin_vm' securit...
import os.path from dmoj.executors.java_executor import JavaExecutor with open(os.path.join(os.path.dirname(__file__), 'java-security.policy')) as policy_file: policy = policy_file.read() class Executor(JavaExecutor): name = 'KOTLIN' ext = '.kt' compiler = 'kotlinc' compiler_time_limit = 20 ...
Raise Kotlin compiler time limit to 20s
Raise Kotlin compiler time limit to 20s
Python
agpl-3.0
DMOJ/judge,DMOJ/judge,DMOJ/judge
e582a8632409cdf5625b51978e742ca9282c3d6f
show_vmbstereocamera.py
show_vmbstereocamera.py
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Show the images from two Allied Vision cameras # # # External dependencies # import sys from PySide import QtGui import VisionToolkit as vt # # Main application # if __name__ == '__main__' : application = QtGui.QApplication( sys.argv ) widget = vt.VmbStereoCame...
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Show the images from two Allied Vision cameras # # # External dependencies # import sys import cv2 import numpy as np #from PySide import QtGui import VisionToolkit as vt # # Image callback function # def Callback( frame_left, frame_right ) : # Put images side by...
Add OpenCV display for debug.
Add OpenCV display for debug.
Python
mit
microy/PyStereoVisionToolkit,microy/VisionToolkit,microy/StereoVision,microy/VisionToolkit,microy/StereoVision,microy/PyStereoVisionToolkit
aa19102b6679a19adb8eb7146742aaf357ad28ef
stagecraft/tools/txex-migration.py
stagecraft/tools/txex-migration.py
#!/usr/bin/env python import os import sys try: username = os.environ['GOOGLE_USERNAME'] password = os.environ['GOOGLE_PASSWORD'] except KeyError: print("Please supply username (GOOGLE_USERNAME)" "and password (GOOGLE_PASSWORD) as environment variables") sys.exit(1) from spreadsheets import...
#!/usr/bin/env python import os import sys try: username = os.environ['GOOGLE_USERNAME'] password = os.environ['GOOGLE_PASSWORD'] except KeyError: print("Please supply username (GOOGLE_USERNAME)" "and password (GOOGLE_PASSWORD) as environment variables") sys.exit(1) column_positions = { ...
Use new configureable spreadsheet loader in script.
Use new configureable spreadsheet loader in script. These are the correct positions currently.
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
5ebcb9a666f03439bb075ac5961d2230ea649371
dockci/api/exceptions.py
dockci/api/exceptions.py
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionException(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionException, self).__init__() if...
""" Exceptions relating to API issues """ from werkzeug.exceptions import HTTPException class BaseActionExceptionMixin(HTTPException): """ An HTTP exception for when an action can't be performed """ response = None def __init__(self, action=None): super(BaseActionExceptionMixin, self).__init__() ...
Make BaseActionException mixin for pylint
Make BaseActionException mixin for pylint
Python
isc
RickyCook/DockCI,sprucedev/DockCI,sprucedev/DockCI-Agent,sprucedev/DockCI,sprucedev/DockCI,sprucedev/DockCI,RickyCook/DockCI,RickyCook/DockCI,RickyCook/DockCI,sprucedev/DockCI-Agent
c5eb64cda6972df0e96a9f3dc9e776386ef50a78
examples/hello_world.py
examples/hello_world.py
#!/usr/bin/env python3 from __future__ import print_function import os from binascii import hexlify import cantools SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) MOTOHAWK_PATH = os.path.join(SCRIPT_DIR, '..', 'tests', '...
#!/usr/bin/env python3 # # > python3 hello_world.py # Message: {'Temperature': 250.1, 'AverageRadius': 3.2, 'Enable': 'Enabled'} # Encoded: c001400000000000 # Decoded: {'Enable': 'Enabled', 'AverageRadius': 3.2, 'Temperature': 250.1} # from __future__ import print_function import os from binascii import hexlify import...
Correct DBC file path in hello world example.
Correct DBC file path in hello world example.
Python
mit
cantools/cantools,eerimoq/cantools
8f14e64701fb26da8e4a614da6129964f29be16d
testapp/testapp/testmain/models.py
testapp/testapp/testmain/models.py
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.M...
from django.db import models class ClassRoom(models.Model): number = models.CharField(max_length=4) def __unicode__(self): return unicode(self.number) class Lab(models.Model): name = models.CharField(max_length=10) def __unicode__(self): return unicode(self.name) class Dept(models.M...
Add new testing model `School`
Add new testing model `School` Issue #43
Python
mit
applegrew/django-select2,dulaccc/django-select2,strongriley/django-select2,Feria/https-github.com-applegrew-django-select2,hobarrera/django-select2,hisie/django-select2,Feria/https-github.com-applegrew-django-select2,hisie/django-select2,bubenkoff/django-select2,pbs/django-select2,dantagg/django-select2,hobarrera/djang...
7733eef2eb6674ce800126e5abf4d98c0434b224
16B/16B-242/imaging/concat_and_split.py
16B/16B-242/imaging/concat_and_split.py
''' Combine the tracks, then split out the science fields ''' import os from glob import glob from tasks import virtualconcat, split # Grab all of the MS tracks in the folder (should be 12) myvis = glob("*.speclines.ms") assert len(myvis) == 12 default('virtualconcat') virtualconcat(vis=myvis, concatvis='16B-242_...
''' Combine the tracks, then split out the science fields ''' import os from glob import glob from tasks import virtualconcat, split # Grab all of the MS tracks in the folder (should be 12) myvis = glob("16B-242.*.ms") assert len(myvis) == 12 default('virtualconcat') virtualconcat(vis=myvis, concatvis='16B-242_li...
Change glob for 242 tracks
Change glob for 242 tracks
Python
mit
e-koch/VLA_Lband,e-koch/VLA_Lband
4246ec034ed52fa0dc7aa947b4f560f95f082538
Lib/unittest/test/__init__.py
Lib/unittest/test/__init__.py
"""Test suite for distutils. This test suite consists of a collection of test modules in the distutils.tests package. Each test module has a name starting with 'test' and contains a function test_suite(). The function is expected to return an initialized unittest.TestSuite instance. Tests for the command classes in...
import os import sys import unittest here = os.path.dirname(__file__) loader = unittest.defaultTestLoader def test_suite(): suite = unittest.TestSuite() for fn in os.listdir(here): if fn.startswith("test") and fn.endswith(".py"): modname = "unittest.test." + fn[:-3] __import__...
Remove incorrect docstring in unittest.test
Remove incorrect docstring in unittest.test
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
60eb4891013dfc5a00fbecd98a79999a365c0839
example/article/admin.py
example/article/admin.py
from django.contrib import admin from django.forms import ModelForm from article.models import Article # The timezone support was introduced in Django 1.4, fallback to standard library for 1.3. try: from django.utils.timezone import now except ImportError: from datetime import datetime now = datetime.now ...
from django.contrib import admin from django.forms import ModelForm from django.utils.timezone import now from article.models import Article class ArticleAdminForm(ModelForm): def __init__(self, *args, **kwargs): super(ArticleAdminForm, self).__init__(*args, **kwargs) self.fields['publication_dat...
Remove old Django compatibility code
Remove old Django compatibility code
Python
apache-2.0
django-fluent/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,edoburu/django-fluent-comments,edoburu/django-fluent-comments,django-fluent/django-fluent-comments,django-fluent/django-fluent-comments
685ae9d284a9df71563c05773e4110e5ddc16b38
backend/breach/forms.py
backend/breach/forms.py
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', ...
from django.forms import ModelForm from breach.models import Target, Victim class TargetForm(ModelForm): class Meta: model = Target fields = ( 'name', 'endpoint', 'prefix', 'alphabet', 'secretlength', 'alignmentalphabet', ...
Add sourceip and target parameters to AttackForm
Add sourceip and target parameters to AttackForm
Python
mit
dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimkarakostas/rupture,esara...
09a54e7a09b362b48bde21dad25b14e73cf72c98
main.py
main.py
import re class dna(): """Instantiate a DNA object""" def __init__(self): self.sequence = "" def genSequence(self, N): """Generate a DNA sequence of length N in the subset [G-A-T-C]""" import random self.sequence = "" for i in range(N): ...
import re class dna(): """Instantiate a DNA object""" def __init__(self): self.sequence = "" def genSequence(self, N): """Generate a DNA sequence of length N in the subset [G-A-T-C]""" import random self.sequence = "" for i in range(N): ...
Return all most frequent subsequences
Return all most frequent subsequences
Python
mit
kir0ul/dna
c7a67d4a69e1fe2ecb7f6c1a56202c6153e9766c
frigg/builds/filters.py
frigg/builds/filters.py
from rest_framework import filters from frigg.builds.models import Build, Project class ProjectPermissionFilter(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(Project.objects.permitted_query(request.user)) class BuildPermissionFilter(filters.BaseF...
from rest_framework import filters from frigg.builds.models import Build, Project class ProjectPermissionFilter(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(Project.objects.permitted_query(request.user)).distinct() class BuildPermissionFilter(fi...
Fix multiple instance bug in api
Fix multiple instance bug in api
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
e3f8fa13758ebed06abc1369d8c85474f7346d29
api/nodes/urls.py
api/nodes/urls.py
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^(?P<node_id>\w+)/$', views.NodeDetail.as_view(), name='node-d...
from django.conf.urls import url from api.nodes import views urlpatterns = [ # Examples: # url(r'^$', 'api.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', views.NodeList.as_view(), name='node-list'), url(r'^bulk_delete/(?P<confirmation_token>\w+)/$', views.NodeBulkDel...
Add second delete url where users will send request to confirm they want to bulk delete.
Add second delete url where users will send request to confirm they want to bulk delete.
Python
apache-2.0
GageGaskins/osf.io,adlius/osf.io,brandonPurvis/osf.io,cwisecarver/osf.io,chrisseto/osf.io,abought/osf.io,GageGaskins/osf.io,binoculars/osf.io,RomanZWang/osf.io,danielneis/osf.io,Nesiehr/osf.io,KAsante95/osf.io,baylee-d/osf.io,billyhunt/osf.io,adlius/osf.io,HalcyonChimera/osf.io,wearpants/osf.io,erinspace/osf.io,crcrese...
ed98c6fc0c8872263a696d4d403eba773c759233
tests/httplib_adapter_test.py
tests/httplib_adapter_test.py
import sys import unittest import ocookie.httplib_adapter from tests import app py3 = sys.version_info[0] == 3 if py3: import http.client as httplib else: import httplib port = 5040 app.run(port) class HttplibAdapterTest(unittest.TestCase): def test_cookies(self): conn = httplib.HTTPConnection('l...
import sys import unittest import ocookie.httplib_adapter from tests import app py3 = sys.version_info[0] == 3 if py3: import http.client as httplib def to_bytes(text): return text.encode('utf8') else: import httplib def to_bytes(text): return text port = 5040 app.run(port) class Http...
Deal with str/bytes mismatch in python 3
Deal with str/bytes mismatch in python 3
Python
bsd-2-clause
p/ocookie
94245d7a52a274c6763382a10e3a1dbe0b2cbf18
cea/interfaces/dashboard/api/dashboard.py
cea/interfaces/dashboard/api/dashboard.py
from flask_restplus import Namespace, Resource, fields, abort import cea.config import cea.plots.cache api = Namespace('Dashboard', description='Dashboard plots') LAYOUTS = ['row', 'grid', 'map'] CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]} for c...
from flask_restplus import Namespace, Resource, fields, abort import cea.config import cea.plots.cache api = Namespace('Dashboard', description='Dashboard plots') LAYOUTS = ['row', 'grid', 'map'] CATEGORIES = {c.name: {'label': c.label, 'plots': [{'id': p.id(), 'name': p.name} for p in c.plots]} for c...
Allow 'scenario-name' to be null if it does not exist
Allow 'scenario-name' to be null if it does not exist
Python
mit
architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst
e8fc301de8fab1d9dfcb99aa94e7c4467dab689a
amy/workshops/migrations/0223_membership_agreement_link.py
amy/workshops/migrations/0223_membership_agreement_link.py
# Generated by Django 2.2.13 on 2020-11-18 20:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0222_workshoprequest_workshop_listed'), ] operations = [ migrations.AddField( model_name='membership', ...
# Generated by Django 2.2.17 on 2020-11-29 10:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workshops', '0222_workshoprequest_workshop_listed'), ] operations = [ migrations.AddField( model_name='membership', ...
Update help text in migration
Update help text in migration
Python
mit
swcarpentry/amy,pbanaszkiewicz/amy,swcarpentry/amy,pbanaszkiewicz/amy,swcarpentry/amy,pbanaszkiewicz/amy
96780184daeb63ea5eb5fa3229e32bc6b4968ba6
meterbus/telegram_ack.py
meterbus/telegram_ack.py
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch class TelegramACK(object): @staticmethod def parse(data): if data is None: raise MBusFrameDecodeError("Data is None") if data is not None and len(data) < 1: raise MBusFrameDecodeError("Inval...
from .exceptions import MBusFrameDecodeError, MBusFrameCRCError, FrameMismatch class TelegramACK(object): @staticmethod def parse(data): if data is None: raise MBusFrameDecodeError("Data is None") if data is not None and len(data) < 1: raise MBusFrameDecodeError("Inval...
Support for writing this frame to serial port
Support for writing this frame to serial port
Python
bsd-3-clause
ganehag/pyMeterBus
8255449613cb721ece23b822b8ef380a31f9b0bc
flattening_ocds/tests/test_input.py
flattening_ocds/tests/test_input.py
from flattening_ocds.input import unflatten_line, SpreadsheetInput, unflatten def test_unflatten_line(): # Check flat fields remain flat assert unflatten_line({'a': 1, 'b': 2}) == {'a': 1, 'b': 2} assert unflatten_line({'a/b': 1, 'a/c': 2, 'd/e': 3}) == {'a': {'b': 1, 'c': 2}, 'd': {'e': 3}} # Check m...
from flattening_ocds.input import unflatten_line, SpreadsheetInput, unflatten class ListInput(SpreadsheetInput): def __init__(self, sheets, **kwargs): self.sheets = sheets super(ListInput, self).__init__(**kwargs) def get_sheet_lines(self, sheet_name): print(sheet_name) return...
Add some unit tests of the unflatten function
Add some unit tests of the unflatten function
Python
mit
OpenDataServices/flatten-tool
aeac44b782397e78925fa74d2e87aa73c88b8162
core/polyaxon/utils/np_utils.py
core/polyaxon/utils/np_utils.py
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
#!/usr/bin/python # # Copyright 2018-2020 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
Add check for nan values
Add check for nan values
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
066a7dacf20ed3dd123790dc78e99317856ea731
tutorial/polls/admin.py
tutorial/polls/admin.py
from django.contrib import admin # Register your models here. from .models import Question class QuestionAdmin(admin.ModelAdmin): fields = ['pub_date', 'question_text'] admin.site.register(Question, QuestionAdmin)
from django.contrib import admin # Register your models here. from .models import Question class QuestionAdmin(admin.ModelAdmin): #fields = ['pub_date', 'question_text'] fieldsets = [ (None, {'fields' : ['question_text']}), ('Date Information', { 'fields' : ['pub_date'], 'classes': ['collap...
Put Question Admin fields in a fieldset and added a collapse class to the date field
Put Question Admin fields in a fieldset and added a collapse class to the date field
Python
mit
ikosenn/django_reignited,ikosenn/django_reignited
180e6bc667f033cb87730b738d3f4602c16bbae9
website/notifications/views.py
website/notifications/views.py
from framework.auth.decorators import must_be_logged_in from model import Subscription from flask import request from modularodm import Q from modularodm.exceptions import NoResultsFound from modularodm.storage.mongostorage import KeyExistsException @must_be_logged_in def subscribe(auth, **kwargs): user = auth.us...
from framework.auth.decorators import must_be_logged_in from model import Subscription from flask import request from modularodm import Q from modularodm.exceptions import NoResultsFound from modularodm.storage.mongostorage import KeyExistsException @must_be_logged_in def subscribe(auth, **kwargs): user = auth.us...
Use node id (not project id) to create component Subscriptions
Use node id (not project id) to create component Subscriptions
Python
apache-2.0
billyhunt/osf.io,TomBaxter/osf.io,aaxelb/osf.io,lamdnhan/osf.io,binoculars/osf.io,pattisdr/osf.io,erinspace/osf.io,GageGaskins/osf.io,asanfilippo7/osf.io,GageGaskins/osf.io,brianjgeiger/osf.io,saradbowman/osf.io,rdhyee/osf.io,hmoco/osf.io,barbour-em/osf.io,kwierman/osf.io,alexschiller/osf.io,caseyrollins/osf.io,jnayak1...
5b283e1dd48b811b54345de53c177d78e4eb084a
fancypages/__init__.py
fancypages/__init__.py
import os __version__ = (0, 0, 1, 'alpha', 1) FP_MAIN_TEMPLATE_DIR = os.path.join( os.path.dirname(os.path.abspath(__file__)) )
import os __version__ = (0, 0, 1, 'alpha', 1) def get_fancypages_paths(path): return [os.path.join(os.path.dirname(os.path.abspath(__file__)), path)]
Bring path function in line with oscar fancypages
Bring path function in line with oscar fancypages
Python
bsd-3-clause
socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages
bc6c6098505a90e3fb1180bd28d9c650c6d1e51d
heltour/tournament/tasks.py
heltour/tournament/tasks.py
from heltour.tournament.models import * from heltour.tournament import lichessapi from heltour.celery import app from celery.utils.log import get_task_logger logger = get_task_logger(__name__) # Disabled for now because of rate-limiting lichess_teams = [] # ['lichess4545-league'] @app.task(bind=True) def update_play...
from heltour.tournament.models import * from heltour.tournament import lichessapi from heltour.celery import app from celery.utils.log import get_task_logger logger = get_task_logger(__name__) # Disabled for now because of rate-limiting lichess_teams = [] # ['lichess4545-league'] @app.task(bind=True) def update_play...
Add completion log message to the background task
Add completion log message to the background task
Python
mit
cyanfish/heltour,cyanfish/heltour,cyanfish/heltour,cyanfish/heltour
b9701cfb65c4c641231bef385dde74b8d940f901
gimlet/backends/sql.py
gimlet/backends/sql.py
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels', **engine_kwargs): meta = MetaData(bind=create_engine(url, **engine_kwargs)) self.table = Table(table_nam...
from sqlalchemy import MetaData, Table, Column, types, create_engine, select from .base import BaseBackend class SQLBackend(BaseBackend): def __init__(self, url, table_name='gimlet_channels', **engine_kwargs): meta = MetaData(bind=create_engine(url, **engine_kwargs)) self.table = Table(table_nam...
Use count/scalar to test if key is present in SQL back end
Use count/scalar to test if key is present in SQL back end This is simpler than using select/execute/fetchone. Also, scalar automatically closes the result set whereas fetchone does not. This may fix some performance issues.
Python
mit
storborg/gimlet
5cb6e90714ffe91377e01743451ed4aefe4a1e24
greencard/greencard.py
greencard/greencard.py
"""Greencard implementation.""" from functools import wraps TESTS = [] def greencard(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparen...
"""Greencard implementation.""" from functools import wraps TESTS = [] def greencard(func): """ A decorator for providing a unittesting function/method with every card in a librarian card library database when it is called. """ @wraps(func) def wrapped(*args, **kwargs): """Transparen...
Fix test descovery to correctly add test dir to path and import modules rather then files
Fix test descovery to correctly add test dir to path and import modules rather then files
Python
mit
Nekroze/greencard,Nekroze/greencard
8e3445e0ddedd5611be1f35166a9f37ae018e232
client/initialize.py
client/initialize.py
#!/usr/bin/env python import os from tempfile import NamedTemporaryFile from textwrap import dedent import shutil from qlmdm import top_dir from qlmdm.prompts import get_bool os.chdir(top_dir) cron_file = '/etc/cron.d/qlmdm' cron_exists = os.path.exists(cron_file) if cron_exists: prompt = 'Do you want to repla...
#!/usr/bin/env python import os from tempfile import NamedTemporaryFile from textwrap import dedent import shutil from qlmdm import top_dir from qlmdm.prompts import get_bool os.chdir(top_dir) cron_file = '/etc/cron.d/qlmdm' cron_exists = os.path.exists(cron_file) if cron_exists: prompt = 'Do you want to repla...
Set client crontab file permissions before copying it into place
Set client crontab file permissions before copying it into place Set the permissions on the client crontab file before copying it rather than after, so the time during which the file is inconsistent is reduced.
Python
apache-2.0
quantopian/PenguinDome,quantopian/PenguinDome
c454e2ccafe0c8981ca0789edd2850cbde15c6a3
wallace/environments.py
wallace/environments.py
from sqlalchemy import ForeignKey, Column, String, desc from .models import Node, Info from information import State class Environment(Node): """Defines an environment node. Environments are nodes that have a state and that receive a transmission from anyone that observes them. """ __tablename_...
from sqlalchemy import ForeignKey, Column, String, desc from .models import Node, Info from information import State class Environment(Node): """Defines an environment node. Environments are nodes that have a state and that receive a transmission from anyone that observes them. """ __tablename_...
Remove side effect where observing connects
Remove side effect where observing connects
Python
mit
Dallinger/Dallinger,suchow/Wallace,berkeley-cocosci/Wallace,jcpeterson/Dallinger,Dallinger/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,suchow/Wallace,jcpeterson/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,berkeley-cocosci/Wallace,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,suchow/Wal...
2d13b639f17fd7430191c45ee14f6d200228fd5a
geoportal/geoportailv3_geoportal/views/luxthemes.py
geoportal/geoportailv3_geoportal/views/luxthemes.py
from pyramid.view import view_config from c2cgeoportal_commons.models import DBSession from c2cgeoportal_commons.models.main import Theme import logging log = logging.getLogger(__name__) class LuxThemes(object): def __init__(self, request): self.request = request @view_config(route_name='isthemepri...
import logging import re from c2cgeoportal_commons.models import DBSession, main from c2cgeoportal_geoportal.lib.caching import get_region from c2cgeoportal_geoportal.lib.wmstparsing import TimeInformation from c2cgeoportal_geoportal.views.theme import Theme from pyramid.view import view_config from geoportailv3_geop...
Fix themes.json with internal WMS
Fix themes.json with internal WMS
Python
mit
Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3
5d2858d740eebfe180ceef22ae5cc80b902a5ccf
books/views.py
books/views.py
from django.core.urlresolvers import reverse from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.utils.translation import ugettext as _ from books.forms import BookForm from shared.models import BookType def index(request): book_list = BookType.obje...
from django.core.urlresolvers import reverse from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.utils.translation import ugettext as _ from books.forms import BookForm from shared.models import BookType def index(request): book_list = BookType.obje...
Fix KeyError in alerts implementation
Fix KeyError in alerts implementation - Fix for alert that wasn't dismissing after refreshing the page
Python
agpl-3.0
m4tx/egielda,m4tx/egielda,m4tx/egielda
643b47b2b805a045d9344e11e85ae4334ea79056
casia/conf/global_settings.py
casia/conf/global_settings.py
# -*- coding: utf-8 -*- # This file is part of Casia - CAS server based on Django # Copyright (C) 2013 Mateusz Małek # Casia 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 # L...
# -*- coding: utf-8 -*- # This file is part of Casia - CAS server based on Django # Copyright (C) 2013 Mateusz Małek # Casia 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 # L...
Remove middleware classes which are currently unnecessary
Remove middleware classes which are currently unnecessary
Python
agpl-3.0
mkwm/casia,mkwm/casia
df37b65872bc1b5a21a1e74934b834472fc6ca7b
buffer/managers/updates.py
buffer/managers/updates.py
from buffer.models.update import Update PATHS = { 'GET_PENDING': 'profiles/%s/updates/pending.json', } class Updates(list): def __init__(self, api, profile_id): self.api = api self.profile_id = profile_id @property def pending(self): url = PATHS['GET_PENDING'] % self.profile_id response = s...
from buffer.models.update import Update PATHS = { 'GET_PENDING': 'profiles/%s/updates/pending.json', 'GET_SENT': 'profiles/%s/updates/sent.json', } class Updates(list): def __init__(self, api, profile_id): self.api = api self.profile_id = profile_id self.__pending = [] self.__sent = [] @pro...
Improve proper using of property decorator and logic
Improve proper using of property decorator and logic
Python
mit
vtemian/buffpy,bufferapp/buffer-python
a4375a6ec5ca54b887527885235317986011801c
guesser.py
guesser.py
from synt.utils.redis_manager import RedisManager from synt.utils.extractors import best_word_feats from synt.utils.text import sanitize_text MANAGER = RedisManager() DEFAULT_CLASSIFIER = MANAGER.load_classifier() def guess(text, classifier=DEFAULT_CLASSIFIER): """Takes a blob of text and returns the sentiment an...
from synt.utils.redis_manager import RedisManager from synt.utils.extractors import best_word_feats from synt.utils.text import sanitize_text MANAGER = RedisManager() DEFAULT_CLASSIFIER = MANAGER.load_classifier() def guess(text, classifier=DEFAULT_CLASSIFIER): """Takes a blob of text and returns the sentiment an...
Return a -1 .. 1 sentiment score.
Return a -1 .. 1 sentiment score.
Python
agpl-3.0
lrvick/synt
e01e0d7b1f3bb5d54d428c8f237b72a3c5170b7d
number_to_words_test.py
number_to_words_test.py
import unittest from number_to_words import NumberToWords class TestNumberToWords(unittest.TestCase): def setUp(self): self.n2w = NumberToWords() def tearDown(self): self.n2w = None if __name__ == '__main__': unittest.main()
import unittest from number_to_words import NumberToWords class TestNumberToWords(unittest.TestCase): def setUp(self): self.n2w = NumberToWords() def tearDown(self): self.n2w = None def test_zero_and_single_digits(self): NUMBERS = { 0: 'zero', 1: 'one', 2: 'two', 3: '...
Add tests for number 0 to 9
Add tests for number 0 to 9
Python
mit
ianfieldhouse/number_to_words
3b768fdc642471446092a08446ec8f2ab08281c3
clean.py
clean.py
import GutterColor.settings as settings class Clean: """Clean up the cache and generated icons""" def __init__(self, view): pass
import GutterColor.settings as settings from os import walk, remove, path, listdir from shutil import rmtree from threading import Thread class Clean(Thread): """Clean up the cache and generated icons""" def __init__(self, files): Thread.__init__(self) self.files = files def run(self): self.remove_...
Add Clean class to remove files/folders.
Add Clean class to remove files/folders.
Python
mit
ggordan/GutterColor,ggordan/GutterColor
88995b5e2bcd6f3e21d8810a97f3c38cc84e8189
pulldb/subscriptions.py
pulldb/subscriptions.py
# Copyright 2013 Russell Heilling from google.appengine.ext import ndb class Subscription(ndb.Model): '''Subscription object in datastore. Holds subscription data. Parent should be User. ''' start_date = ndb.DateProperty() volume = ndb.KeyProperty(kind='Volume')
# Copyright 2013 Russell Heilling from google.appengine.ext import ndb from pulldb.users import user_key class Subscription(ndb.Model): '''Subscription object in datastore. Holds subscription data. Parent should be User. ''' start_date = ndb.DateProperty() volume = ndb.KeyProperty(kind='Volume') def subs...
Add basic subscription fetcher / creator
Add basic subscription fetcher / creator
Python
mit
xchewtoyx/pulldb
6424d1998d10d4d5e1165e7c530d414e86e1067b
tests/example_project/tests/test_newman/helpers.py
tests/example_project/tests/test_newman/helpers.py
from djangosanetesting import SeleniumTestCase class NewmanTestCase(SeleniumTestCase): fixtures = ['newman_admin_user'] SUPERUSER_USERNAME = u"superman" SUPERUSER_PASSWORD = u"xxx" NEWMAN_URI = "/newman/" def __init__(self): super(NewmanTestCase, self).__init__() self.elements = ...
from djangosanetesting import SeleniumTestCase class NewmanTestCase(SeleniumTestCase): fixtures = ['newman_admin_user'] SUPERUSER_USERNAME = u"superman" SUPERUSER_PASSWORD = u"xxx" NEWMAN_URI = "/newman/" def __init__(self): super(NewmanTestCase, self).__init__() self.elements = ...
Use class for logout instead of href, to please IE8
Use class for logout instead of href, to please IE8
Python
bsd-3-clause
WhiskeyMedia/ella,MichalMaM/ella,petrlosa/ella,petrlosa/ella,WhiskeyMedia/ella,ella/ella,whalerock/ella,MichalMaM/ella,whalerock/ella,whalerock/ella
d5be5401a1666f6a4caa2604c9918345f6202b70
tests/testapp/models.py
tests/testapp/models.py
from django.db import models from django.utils.timezone import now from towel import deletion from towel.managers import SearchManager from towel.modelview import ModelViewURLs class PersonManager(SearchManager): search_fields = ('family_name', 'given_name') class Person(models.Model): created = models.Dat...
from django.db import models from django.utils.timezone import now from towel import deletion from towel.managers import SearchManager from towel.modelview import ModelViewURLs class PersonManager(SearchManager): search_fields = ('family_name', 'given_name') class Person(models.Model): created = models.Dat...
Use the item access variant instead
Use the item access variant instead
Python
bsd-3-clause
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
115bb7cf36bad5d38ac3b0be9a0bab7823c3b003
IATISimpleTester/lib/helpers.py
IATISimpleTester/lib/helpers.py
from collections import defaultdict import re from lxml import etree from IATISimpleTester import app # given an expression list and the name of an expression, # select it, def select_expression(expression_list, expression_name, default_expression_name=None): expression_dicts = {x["id"]: x for x in expression_l...
from collections import defaultdict import re from lxml import etree from IATISimpleTester import app # given an expression list and the name of an expression, # select it, def select_expression(expression_list, expression_name, default_expression_name=None): expression_dicts = {x["id"]: x for x in expression_l...
Remove this emboldening thing again
Remove this emboldening thing again
Python
mit
pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester,pwyf/data-quality-tester
a9d3f47098bc7499d62d4866883fa45622f01b74
app/main/errors.py
app/main/errors.py
# coding=utf-8 from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data @main.app_errorhandler(404) def page_not_found(e): template_data = get_template_data(main, {}) return render_template("errors/404.html", **template_data), 404 @ma...
# coding=utf-8 from flask import render_template, current_app, request from . import main from ..helpers.search_helpers import get_template_data from dmutils.apiclient import APIError @main.app_errorhandler(APIError) def api_error_handler(e): return _render_error_page(e.status_code) @main.app_errorhandler(404)...
Add API error handling similar to supplier app
Add API error handling similar to supplier app Currently 404s returned by the API are resulting in 500s on the buyer app for invalid supplier requests. This change takes the model used in the supplier frontend to automatically handle uncaught APIErrors. It is not identical to the supplier app version because the defau...
Python
mit
alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-di...
e66e2f19611e4f7bca9be400b13238e249b1b3d2
cadorsfeed/fetch.py
cadorsfeed/fetch.py
import mechanize import re def fetchLatest(): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") latestDate = br["txt_ReportDate"] return latestDate def fetchReport(reportDate): br = mechanize.Browser() ...
from werkzeug.exceptions import NotFound, InternalServerError import mechanize import re def fetchLatest(): br = mechanize.Browser() br.open("http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/cadors-screaq/nrpt.aspx?lang=eng") br.select_form(name="pageForm") latestDate = br["txt_ReportDate"] return latestDate...
Raise exceptions for common errors rather than returning invalid data.
Raise exceptions for common errors rather than returning invalid data.
Python
mit
kurtraschke/cadors-parse,kurtraschke/cadors-parse
91d7e27882c4317199f2de99964da4ef3a2e3950
edx_data_research/web_app/__init__.py
edx_data_research/web_app/__init__.py
from flask import Flask from flask.ext.mail import Mail from flask.ext.mongoengine import MongoEngine from flask.ext.security import MongoEngineUserDatastore, Security # Create app app = Flask(__name__) app.config.from_object('config') # Create mail object mail = Mail(app)
from flask import Flask from flask.ext.mail import Mail from flask.ext.mongoengine import MongoEngine from flask.ext.security import MongoEngineUserDatastore, Security # Create app app = Flask(__name__) app.config.from_object('config') # Create mail object mail = Mail(app) # Create database connection object db = Mo...
Define flask security object for login stuff
Define flask security object for login stuff
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
e6e525746613505e5f6be49a92901bb95a4e2199
k8s/models/pod_disruption_budget.py
k8s/models/pod_disruption_budget.py
#!/usr/bin/env python # -*- coding: utf-8 from __future__ import absolute_import import six from .common import ObjectMeta from ..base import Model from ..fields import Field, ListField class PodDisruptionBudgetMatchExpressions(Model): key = Field(six.text_type) operator = Field(six.text_type) values = ...
#!/usr/bin/env python # -*- coding: utf-8 from __future__ import absolute_import import six from .common import ObjectMeta from ..base import Model from ..fields import Field, ListField class LabelSelectorRequirement(Model): key = Field(six.text_type) operator = Field(six.text_type) values = ListField(s...
Fix issues with class naming
Fix issues with class naming
Python
apache-2.0
fiaas/k8s
027f016c6168325cb0e8b66adb1c10461399e0e1
katagawa/sql/__init__.py
katagawa/sql/__init__.py
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ __slots__ = () def __init__(self, subtokens: typing.List['Token']): """ :param subtokens: Any subtokens this token has. """ self.subtokens = subtoke...
""" SQL generators for Katagawa. """ import abc import typing class Token(abc.ABC): """ Base class for a token. """ __slots__ = () def __init__(self, subtokens: typing.List['Token']=None): """ :param subtokens: Any subtokens this token has. """ if subtokens is Non...
Add consume_tokens function to Token.
Add consume_tokens function to Token.
Python
mit
SunDwarf/asyncqlio
9c16b71ecbb38115f107c7baba56304fb9630ec5
ocds/export/__init__.py
ocds/export/__init__.py
from .models import ( Release, ReleasePackage, Record, RecordPackage ) from .schema import Tender from .helpers import ( mode_test, get_ocid ) def release_tender(tender, prefix): """ returns Release object created from `tender` with ocid `prefix` """ date = tender.get('dateModified', '...
from .models import ( Release, ReleasePackage, Record, RecordPackage ) from .schema import Tender from .helpers import ( mode_test, get_ocid ) def release_tender(tender, prefix): """ returns Release object created from `tender` with ocid `prefix` """ date = tender.get('dateModified', '...
Update helpers for generating releases
Update helpers for generating releases
Python
apache-2.0
yshalenyk/openprocurement.ocds.export,yshalenyk/openprocurement.ocds.export,yshalenyk/ocds.export
fb3abf0d1cf27d23c78dd8101dd0c54cf589c2ef
corehq/apps/locations/resources/v0_6.py
corehq/apps/locations/resources/v0_6.py
from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class ...
from corehq.apps.api.resources.auth import RequirePermissionAuthentication from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import HqPermissions from corehq.apps.locations.resources import v0_5 class LocationResource(v0_5.LocationResource): resource_name = 'location' class ...
Use objects manager that automatically filters out archived forms
Use objects manager that automatically filters out archived forms Co-authored-by: Ethan Soergel <c1732a0c832c5c8cbfae77286e6475129315f488@users.noreply.github.com>
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
577e2a03c15e4e489d0df4c3c2a2bea8b9aa54b6
fluent_utils/softdeps/any_urlfield.py
fluent_utils/softdeps/any_urlfield.py
""" Optional integration with django-any-urlfield """ from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # s...
""" Optional integration with django-any-urlfield """ from __future__ import absolute_import from django.db import models from fluent_utils.django_compat import is_installed if is_installed('any_urlfield'): from any_urlfield.models import AnyUrlField as BaseUrlField else: BaseUrlField = models.URLField # s...
Fix AnyUrlField migration issue on Django 1.11.
Fix AnyUrlField migration issue on Django 1.11.
Python
apache-2.0
edoburu/django-fluent-utils
d981b34dc18236cf857d1249629b6437005e073f
openmc/capi/__init__.py
openmc/capi/__init__.py
""" This module provides bindings to C functions defined by OpenMC shared library. When the :mod:`openmc` package is imported, the OpenMC shared library is automatically loaded. Calls to the OpenMC library can then be via functions or objects in the :mod:`openmc.capi` subpackage, for example: .. code-block:: python ...
""" This module provides bindings to C functions defined by OpenMC shared library. When the :mod:`openmc` package is imported, the OpenMC shared library is automatically loaded. Calls to the OpenMC library can then be via functions or objects in the :mod:`openmc.capi` subpackage, for example: .. code-block:: python ...
Remove FutureWarning for capi import
Remove FutureWarning for capi import
Python
mit
mit-crpg/openmc,shikhar413/openmc,smharper/openmc,amandalund/openmc,amandalund/openmc,wbinventor/openmc,walshjon/openmc,amandalund/openmc,paulromano/openmc,mit-crpg/openmc,walshjon/openmc,paulromano/openmc,liangjg/openmc,mit-crpg/openmc,johnnyliu27/openmc,amandalund/openmc,walshjon/openmc,shikhar413/openmc,shikhar413/o...
56f27099a8f7be39a6d8848a9378af6ed48f528f
bongo/apps/frontend/tests/templatetags_tests.py
bongo/apps/frontend/tests/templatetags_tests.py
from django.test import TestCase from django.conf import settings from django.template import Context, Template from bongo.apps.bongo.tests import factories def render_template(string, context=None): context = Context(context) if context else None return Template(string).render(context) class TemplateTagsTe...
from django.test import TestCase from django.conf import settings from django.utils.html import escape from django.template import Context, Template from bongo.apps.bongo.tests import factories def render_template(string, context=None): context = Context(context) if context else None return Template(string).r...
Fix broken test (not the intermittent one, this was just a dumb thing)
Fix broken test (not the intermittent one, this was just a dumb thing)
Python
mit
BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo
347f4440deb7b0cce9fd0dcb6e26dbda340f437c
planetstack/openstack_observer/steps/sync_images.py
planetstack/openstack_observer/steps/sync_images.py
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
import os import base64 from django.db.models import F, Q from xos.config import Config from observer.openstacksyncstep import OpenStackSyncStep from core.models.image import Image class SyncImages(OpenStackSyncStep): provides=[Image] requested_interval=0 observes=Image def fetch_pending(self, deleted...
Check the existence of the images_path
Check the existence of the images_path ERROR:planetstack.log:[Errno 2] No such file or directory: '/opt/xos/images' BEG TRACEBACK Traceback (most recent call last): File "/opt/xos/observer/event_loop.py", line 349, in sync failed_objects = sync_step(failed=list(self.failed_step_objects), deletion=deletion) Fil...
Python
apache-2.0
jermowery/xos,cboling/xos,cboling/xos,xmaruto/mcord,jermowery/xos,cboling/xos,xmaruto/mcord,xmaruto/mcord,xmaruto/mcord,jermowery/xos,cboling/xos,jermowery/xos,cboling/xos
7805f06446f31ac483ba219147f4053661e86647
penchy/jobs/__init__.py
penchy/jobs/__init__.py
from job import * from jvms import * from tools import * from filters import * from workloads import * # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # jvm 'JVM', 'ValgrindJVM', # filters # workloads ...
from job import * import jvms import tools import filters import workloads from dependency import Edge JVM = jvms.JVM # all job elements that are interesting for the user have to be enumerated here __all__ = [ # job 'Job', 'JVMNodeConfiguration', # dependencies 'Edge', # jvms 'JVM', #...
Restructure jobs interface to match job description docs.
Restructure jobs interface to match job description docs. Signed-off-by: Michael Markert <5eb998b7ac86da375651a4cd767b88c9dad25896@googlemail.com>
Python
mit
fhirschmann/penchy,fhirschmann/penchy
e95d3b9a9075481f22938dd0c577606947900568
jumpgate/common/aes.py
jumpgate/common/aes.py
import base64 from Crypto import Cipher from jumpgate import config BLOCK_SIZE = 32 PADDING = '#' def pad(string): return string + (BLOCK_SIZE - len(string) % BLOCK_SIZE) * PADDING def create_cypher(): return Cipher.AES.new(pad(config.CONF['secret_key'])) def encode_aes(string): cipher = create_cy...
import base64 from Crypto.Cipher import AES from jumpgate import config BLOCK_SIZE = 32 PADDING = '#' def pad(string): return string + (BLOCK_SIZE - len(string) % BLOCK_SIZE) * PADDING def create_cypher(): return AES.new(pad(config.CONF['secret_key'])) def encode_aes(string): cipher = create_cypher...
Adjust AES import a bit
Adjust AES import a bit
Python
mit
softlayer/jumpgate,myxemhoho/mutil-cloud-manage-paltform,HOQTEC/MCP,wpf710/app-proxy,HOQTEC/MCP,softlayer/jumpgate,myxemhoho/mutil-cloud-manage-paltform,wpf710/app-proxy
4d2d940d672c6af14916cf4c4cecf2a5bb6de4ef
libqtile/layout/hybridlayoutdemo.py
libqtile/layout/hybridlayoutdemo.py
from base import SubLayout, Rect from sublayouts import VerticalStack, Floating from subtile import SubTile class HybridLayoutDemo(SubLayout): def _init_sublayouts(self): class TopWindow(VerticalStack): def filter_windows(self, windows): windows = [w for w in windows if w.name ...
from base import SubLayout, Rect from sublayouts import VerticalStack, Floating from subtile import SubTile class HybridLayoutDemo(SubLayout): def _init_sublayouts(self): class TopWindow(VerticalStack): def filter_windows(self, windows): windows = [w for w in windows if w.name ...
Add request_rectange to HybridLayoutDemo - no clue why this never was here, but it stops it actually working
Add request_rectange to HybridLayoutDemo - no clue why this never was here, but it stops it actually working
Python
mit
dequis/qtile,farebord/qtile,de-vri-es/qtile,StephenBarnes/qtile,ramnes/qtile,ramnes/qtile,flacjacket/qtile,tych0/qtile,farebord/qtile,kseistrup/qtile,kopchik/qtile,aniruddhkanojia/qtile,kiniou/qtile,jdowner/qtile,kynikos/qtile,soulchainer/qtile,soulchainer/qtile,kynikos/qtile,andrewyoung1991/qtile,jdowner/qtile,apinsar...
521ebf29990de4d997c90f4168ea300d75776cfc
components/utilities.py
components/utilities.py
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True
"""Utilities for general operations.""" def IsNumeric(num_str): try: val = int(num_str) except ValueError: return False else: return True def GuaranteeUnicode(obj): if type(obj) == unicode: return obj elif type(obj) == str: return unicode(obj, "utf-8") ...
Add GuranteeUnicode function which always returns a unicode object
Add GuranteeUnicode function which always returns a unicode object
Python
mit
lnishan/SQLGitHub
fce5152e8d902821c9b521402667ac87f9e9a17b
checks.d/system_core.py
checks.d/system_core.py
import psutil from checks import AgentCheck class SystemCore(AgentCheck): def check(self, instance): cpu_times = psutil.cpu_times(percpu=True) for i, cpu in enumerate(cpu_times): for key, value in cpu._asdict().iteritems(): self.rate( "system.core.{...
import psutil from checks import AgentCheck class SystemCore(AgentCheck): def check(self, instance): cpu_times = psutil.cpu_times(percpu=True) self.gauge("system.core.count", len(cpu_times)) for i, cpu in enumerate(cpu_times): for key, value in cpu._asdict().iteritems(): ...
Send the core count as a metric
Send the core count as a metric
Python
bsd-3-clause
truthbk/dd-agent,tebriel/dd-agent,indeedops/dd-agent,mderomph-coolblue/dd-agent,packetloop/dd-agent,PagerDuty/dd-agent,joelvanvelden/dd-agent,indeedops/dd-agent,jyogi/purvar-agent,manolama/dd-agent,tebriel/dd-agent,packetloop/dd-agent,amalakar/dd-agent,a20012251/dd-agent,jraede/dd-agent,AniruddhaSAtre/dd-agent,brettlan...
f7d792d684e6c74f4a3e508bc29bbe2bacc458f0
cms/templatetags/cms.py
cms/templatetags/cms.py
from django import template from django.utils.dateformat import format from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def iso_time_tag(date): """ Returns an ISO date, with the year tagged in a say-no-more span. This allows the date representation t...
from django import template from django.utils.dateformat import format from django.utils.safestring import mark_safe register = template.Library() @register.filter(is_safe=True) def iso_time_tag(date): """ Returns an ISO date, with the year tagged in a say-no-more span. This allows the date representation t...
Fix order of date parts
Fix order of date parts
Python
apache-2.0
willingc/pythondotorg,lebronhkh/pythondotorg,malemburg/pythondotorg,SujaySKumar/pythondotorg,python/pythondotorg,python/pythondotorg,willingc/pythondotorg,demvher/pythondotorg,SujaySKumar/pythondotorg,lsk112233/Clone-test-repo,Mariatta/pythondotorg,ahua/pythondotorg,malemburg/pythondotorg,lepture/pythondotorg,Mariatta/...
0b37e71972d067bd06bfab1d7a0c0f47badefb17
scout/markers/models.py
scout/markers/models.py
from django.db import models from model_utils import Choices MARKER_COLOURS = Choices( ('blue', 'Blue'), ('red', 'Red') ) class Marker(models.Model): name = models.CharField(max_length=255) address = models.TextField(blank=True) lat = models.CharField(max_length=255, blank=True) long = model...
from django.db import models from model_utils import Choices MARKER_COLOURS = Choices( ('blue', 'Blue'), ('red', 'Red') ) class Marker(models.Model): name = models.CharField(max_length=255) address = models.TextField(blank=True) lat = models.CharField(max_length=255, blank=True) long = model...
Return the address from the marker.
Return the address from the marker.
Python
mit
meizon/scout,meizon/scout,meizon/scout,meizon/scout
ce77cbeb6fcb71b49c669188b38e43fb75e4d729
pyinfra_cli/__main__.py
pyinfra_cli/__main__.py
# pyinfra # File: pyinfra_cli/__main__.py # Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point import signal import sys import click from colorama import init as colorama_init from .legacy import run_main_with_legacy_arguments from .main import cli, main # Init colorama for Windows ANSI color ...
# pyinfra # File: pyinfra_cli/__main__.py # Desc: bootstrap stuff for the pyinfra CLI and provide it's entry point import signal import sys import click import gevent from colorama import init as colorama_init from .legacy import run_main_with_legacy_arguments from .main import cli, main # Init colorama for Windo...
Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2).
Kill all running greenlets when ctrl+c (works a charm in Python 3, not so much in 2).
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
299aa432b3183e9db418f0735511330763c8141b
botbot/fileinfo.py
botbot/fileinfo.py
"""File information""" import os import time import pwd import stat import hashlib from .config import CONFIG def get_file_hash(path): """Get md5 hash of a file""" def reader(fo): """Generator which feeds bytes to the md5 hasher""" while True: b = fo.read(128) if len(b)...
"""File information""" import os import pwd import hashlib from .config import CONFIG def reader(fo): """Generator which feeds bytes to the md5 hasher""" while True: b = fo.read(128) if len(b) > 0: yield b else: raise StopIteration() def get_file_hash(path): ...
Move reader() generator out of file hasher
Move reader() generator out of file hasher
Python
mit
jackstanek/BotBot,jackstanek/BotBot
405e34b7573e3af78051741feb32e7589e49dfb9
controllers/main.py
controllers/main.py
# -*- coding: utf-8 -*- import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): ...
# -*- coding: utf-8 -*- import logging import simplejson import os import base64 import openerp from ..helpers.zebra import zebra class PrintController(openerp.addons.web.http.Controller): _cp_path = '/printer_proxy' @openerp.addons.web.http.jsonrequest def output(self, request, format="epl2", **kwargs): ...
Remove line that causes a form feed upon every call to PrintController.output_epl.
Remove line that causes a form feed upon every call to PrintController.output_epl.
Python
agpl-3.0
ryepdx/printer_proxy,ryepdx/printer_proxy
465b34b2252a4a516aba8f8ea6adac13980ba39c
config/test/__init__.py
config/test/__init__.py
from SCons.Script import * def run_tests(env): import shlex import subprocess import sys subprocess.call(shlex.split(env.get('TEST_COMMAND'))) sys.exit(0) def generate(env): import os cmd = 'python tests/testHarness -C tests --diff-failed --view-failed ' \ '--view-unfiltered --...
from SCons.Script import * def run_tests(env): import shlex import subprocess import sys sys.exit(subprocess.call(shlex.split(env.get('TEST_COMMAND')))) def generate(env): import os cmd = 'python tests/testHarness -C tests --diff-failed --view-failed ' \ '--view-unfiltered --save-f...
Return exit code when running tests
Return exit code when running tests
Python
lgpl-2.1
CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang,CauldronDevelopmentLLC/cbang
1b066f793c6c3f8f8b1e9df2659922e2a5dbaf3a
challenge_5/python/alexbotello/FindTheDifference.py
challenge_5/python/alexbotello/FindTheDifference.py
from collections import Counter class Solution: def findTheDifference(self, s, t): s = dict(Counter(s)) t = dict(Counter(t)) for key in t.keys(): if key not in s.keys(): s[key] = 0 if s[key] - t[key] <= -1: return key if __name__ ...
from collections import Counter class Solution: def findTheDifference(self, s, t): s = Counter(s) t = Counter(t) for key in t.keys(): if s[key] != t[key]: return key if __name__ == '__main__': test_case = Solution() s, t = [input() for _ in range(2)] pr...
Refactor to remove nested for loop
Refactor to remove nested for loop
Python
mit
mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges
2b8869bb508f4fb67867385f3058372bde664ca5
CheckProxy/CheckProxy.py
CheckProxy/CheckProxy.py
import discord import requests from discord.ext import commands class checkproxy: """Cog for proxy checking""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def checkproxy(self, ctx, proxy): """Checks the provided proxy.""" p = proxy ...
import discord import requests from discord.ext import commands class checkproxy: """Cog for proxy checking""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def checkproxy(self, ctx, proxy): """Checks the provided proxy.""" p = proxy ...
Add 5s timeout to checkproxy (in an effort to prevent bot hanging
Add 5s timeout to checkproxy (in an effort to prevent bot hanging
Python
agpl-3.0
FrostTheFox/RocketMap-cogs
85fd83e57173aaf00e61169812e3929d5d946896
health_check/contrib/celery/backends.py
health_check/contrib/celery/backends.py
from datetime import datetime, timedelta from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_st...
from datetime import timedelta from django.conf import settings from django.utils import timezone from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBa...
Send timezone-aware datetime for task expiry
Send timezone-aware datetime for task expiry Needed because this task would consistantly fail if django is set to a later-than-UTC timezone, due to celery thinking the task expired the instant it's sent.
Python
mit
KristianOellegaard/django-health-check,KristianOellegaard/django-health-check
6bc4f24c8bdd2be0875fba7cb98a81ff86caa5c3
tests/behave/environment.py
tests/behave/environment.py
# -*- coding: utf-8 -*- u""" Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. This file is part of Toolium. 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/lic...
# -*- coding: utf-8 -*- u""" Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U. This file is part of Toolium. 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/lic...
Add before_all method to set configuration files
Add before_all method to set configuration files
Python
apache-2.0
Telefonica/toolium-examples
3d04ab5df773be611bbbf790196e587d0da3c5e4
colored_logging.py
colored_logging.py
""" Formatter for the logging module, coloring terminal output according to error criticity. """ import enum import logging import sys Colors = enum.Enum("Colors", ("RED", "GREEN", "YELLOW", "BLUE")) LEVEL_COLOR_MAPPING = {logging.WARNING: Colors.YELLOW, logging.ERROR: Colors.RED, ...
""" Formatter for the logging module, coloring terminal output according to error criticity. """ import enum import logging import sys Colors = enum.Enum("Colors", ("RED", "GREEN", "YELLOW", "BLUE")) LEVEL_COLOR_MAPPING = {logging.WARNING: Colors.YELLOW, logging.ERROR: Colors.RED, ...
Disable colored logging for Windows
Disable colored logging for Windows
Python
mpl-2.0
desbma/sacad,desbma/sacad
d0f022f393152a6850f6f33f3b1ad88cc2492b24
dockwidgets.py
dockwidgets.py
from PyQt5.QtWidgets import QDockWidget, QTreeView class WorkerDockWidget(QDockWidget): def __init__(self, title="Dock Widget", parent=None, flags=None): super().__init__(title) self.workerTree = QTreeView(self)
from PyQt5.QtWidgets import QDockWidget, QTreeWidget, QWidget, QGridLayout, QFormLayout, QPushButton, QComboBox, QSizePolicy, QFrame from PyQt5.QtCore import Qt class WorkerDockWidget(QDockWidget): def __init__(self): super().__init__("Workers") #self.setSizePolicy(QSizePolicy.Preferred, QSizePol...
Add some UI and logic for handling workers
Add some UI and logic for handling workers
Python
mit
DrLuke/gpnshader
29110323469d20ff1e481ab2267812afd8e0a3a4
more/chameleon/main.py
more/chameleon/main.py
import morepath import chameleon class ChameleonApp(morepath.App): pass @ChameleonApp.setting_section(section='chameleon') def get_setting_section(): return {'auto_reload': False} @ChameleonApp.template_engine(extension='.pt') def get_chameleon_render(path, original_render, settings): config = setting...
import os import morepath import chameleon class ChameleonApp(morepath.App): pass @ChameleonApp.setting_section(section='chameleon') def get_setting_section(): return {'auto_reload': False} @ChameleonApp.template_engine(extension='.pt') def get_chameleon_render(name, original_render, registry, search_path...
Adjust to modifications in Morepath. But now to enable real explicit file support.
Adjust to modifications in Morepath. But now to enable real explicit file support.
Python
bsd-3-clause
morepath/more.chameleon
1cf5660d9661646b3d8731986d7581ad27582d77
djclick/params.py
djclick/params.py
import click from django.core.exceptions import ObjectDoesNotExist class ModelInstance(click.ParamType): def __init__(self, qs): from django.db import models if isinstance(qs, type) and issubclass(qs, models.Model): qs = qs.objects.all() self.qs = qs self.name = '{}.{...
import click from django.core.exceptions import ObjectDoesNotExist class ModelInstance(click.ParamType): def __init__(self, qs): from django.db import models if isinstance(qs, type) and issubclass(qs, models.Model): qs = qs.objects.all() self.qs = qs self.name = '{}.{...
Fix failing test on Python 3
Fix failing test on Python 3
Python
mit
GaretJax/django-click
20279983ce2817bf7e75490d85823126ca2c1aed
pande_gas/features/basic.py
pande_gas/features/basic.py
""" Basic molecular features. """ __author__ = "Steven Kearnes" __copyright__ = "Copyright 2014, Stanford University" __license__ = "BSD 3-clause" from rdkit.Chem import Descriptors from pande_gas.features import Featurizer class MolecularWeight(Featurizer): """ Molecular weight. """ name = ['mw', ...
""" Basic molecular features. """ __author__ = "Steven Kearnes" __copyright__ = "Copyright 2014, Stanford University" __license__ = "BSD 3-clause" from rdkit.Chem import Descriptors from pande_gas.features import Featurizer class MolecularWeight(Featurizer): """ Molecular weight. """ name = ['mw', ...
Rename descriptors -> rval to avoid confusion
Rename descriptors -> rval to avoid confusion
Python
bsd-3-clause
rbharath/pande-gas,rbharath/pande-gas
04efe96b9ee16b650970d7ddf0ce3a3dd82d55ea
forms.py
forms.py
from flask_wtf import Form from wtforms.fields import StringField, HiddenField, BooleanField, DecimalField from wtforms import validators from flask import request class DonateForm(Form): first_name = StringField(u'First', [validators.required(message="Your first name is required.")]) last_name = Str...
from flask_wtf import Form from wtforms.fields import StringField, HiddenField, BooleanField, DecimalField from wtforms import validators from flask import request class DonateForm(Form): first_name = StringField(u'First', [validators.required(message="Your first name is required.")]) last_name = Str...
Add minimal amount of 1 to form validation
Add minimal amount of 1 to form validation
Python
mit
MinnPost/salesforce-stripe,texastribune/salesforce-stripe,MinnPost/salesforce-stripe,texastribune/salesforce-stripe,MinnPost/salesforce-stripe,texastribune/salesforce-stripe
4d0b5d54ecfde43dc898da03d5481f19943a65e1
renzongxian/0000/0000.py
renzongxian/0000/0000.py
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果 """ from PIL import Image, ImageDraw, ImageFont import sys def add_num_to_img(file_path): im = Image.open(file_path) im_draw = ImageD...
# Source:https://github.com/Show-Me-the-Code/show-me-the-code # Author:renzongxian # Date:2014-11-30 # Python 3.4 """ 第 0000 题:将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果 """ from PIL import Image, ImageDraw, ImageFont import sys def add_num_to_img(file_path): im = Image.open(file_path) im_draw = ImageD...
Rename the result image to avoid overwriting the original image
Rename the result image to avoid overwriting the original image
Python
mit
starlightme/python,haiyangd/python-show-me-the-code-,EricSekyere/python,ZSeaPeng/python,wangjun/python,yangzilong1986/python,ZuoGuocai/python,luoxufeiyan/python,agogear/python-1,sravaniaitha/python,dominjune/python,ZuoGuocai/python,luoxufeiyan/python,xchaoinfo/python,Ph0enixxx/python,sravaniaitha/python,karnikamit/pyth...
b82d85114c13f945cc1976606d4d36d5b4b2885a
phonenumber_field/formfields.py
phonenumber_field/formfields.py
#-*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.forms.fields import CharField from django.core.exceptions import ValidationError from phonenumber_field.validators import validate_international_phonenumber from phonenumber_field.phonenumber import to_python class PhoneNumberF...
#-*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from django.forms.fields import CharField from django.core.exceptions import ValidationError from phonenumber_field.validators import validate_international_phonenumber from phonenumber_field.phonenumber import to_python class PhoneNumberF...
Fix formfield to return an empty string if an empty value is given. This allows empty input for not null model fields with blank=True.
Fix formfield to return an empty string if an empty value is given. This allows empty input for not null model fields with blank=True.
Python
mit
bramd/django-phonenumber-field,bramd/django-phonenumber-field
3480330cb042b08ff85bfa988a130c7fa391a0ee
flask_restler/__init__.py
flask_restler/__init__.py
import logging __license__ = "MIT" __project__ = "Flask-Restler" __version__ = "1.6.2" logger = logging.getLogger('flask-restler') logger.addHandler(logging.NullHandler()) class APIError(Exception): """Store API exception's information.""" status_code = 400 def __init__(self, message, status_code=N...
import logging __license__ = "MIT" __project__ = "Flask-Restler" __version__ = "1.6.2" logger = logging.getLogger('flask-restler') logger.addHandler(logging.NullHandler()) class APIError(Exception): """Store API exception's information.""" status_code = 400 def __init__(self, message, status_code=N...
Support endpoint name in route.
Support endpoint name in route.
Python
mit
klen/flask-restler,klen/flask-restler
373a172535db60e0b428500b1036decd97cf9504
bookstore_app/urls.py
bookstore_app/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/', views.register, name='register'), url(r'^login/', views.login, name='login') ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^register/$', views.register, name='register'), url(r'^login/$', views.login, name='login'), url(r'^books/([a-zA-Z0-9]+)/$', views.book, name='book') ]
Add book url route matcher
Add book url route matcher
Python
mit
siawyoung/bookstore,siawyoung/bookstore,siawyoung/bookstore
5442d45689a567528753a0e705733f86eac37220
buckets/test/views.py
buckets/test/views.py
from django.core.files.storage import default_storage from django.views.decorators.http import require_POST from django.http import HttpResponse @require_POST def fake_s3_upload(request): key = request.POST.get('key') file = request.FILES.get('file') default_storage.save(key, file.read()) return Htt...
from django.core.files.storage import default_storage from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from django.http import HttpResponse @csrf_exempt @require_POST def fake_s3_upload(request): key = request.POST.get('key') file = request.FILES.get(...
Set fake_s3_upload view to be CSRF exempt
Set fake_s3_upload view to be CSRF exempt
Python
agpl-3.0
Cadasta/django-buckets,Cadasta/django-buckets,Cadasta/django-buckets
bcc44a366ab7afbdc448e038e7804cd6719590cc
NeuralNet/activations.py
NeuralNet/activations.py
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: ...
import numpy as np class Activator: @staticmethod def sigmoid(signal, deriv=False): if deriv: return np.multiply(signal, 1 - signal) activation = 1 / (1 + np.exp(-signal)) return activation @staticmethod def tanh(signal, deriv=False): if deriv: ...
Implement correct derivation of SoftMax
Implement correct derivation of SoftMax
Python
mit
ZahidDev/NeuralNet
572d924de7025eb6a41734e7f8df039210c930c1
eventlet/__init__.py
eventlet/__init__.py
__version__ = '1.0.2' try: from eventlet import greenthread from eventlet import greenpool from eventlet import queue from eventlet import timeout from eventlet import patcher from eventlet import convenience import greenlet sleep = greenthread.sleep spawn = greenthread.spawn s...
version_info = (1, 0, 3) __version__ = ".".join(map(str, version_info)) try: from eventlet import greenthread from eventlet import greenpool from eventlet import queue from eventlet import timeout from eventlet import patcher from eventlet import convenience import greenlet sleep = gre...
Fix version info, and bump to 1.0.3
Fix version info, and bump to 1.0.3
Python
mit
Cue/eventlet,Cue/eventlet
146832fe1eba0bc22125ade183f34621de5625fa
apps/bluebottle_utils/fields.py
apps/bluebottle_utils/fields.py
from decimal import Decimal from django.db import models class MoneyField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_digits', 9) kwargs.setdefault('decimal_places', 2) super(MoneyField, self).__init__(*args, default=Decimal('0.00'), **kwargs)
from decimal import Decimal from django.db import models class MoneyField(models.DecimalField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_digits', 9) kwargs.setdefault('decimal_places', 2) kwargs.setdefault('default', Decimal('0.00')) super(MoneyField, self).__ini...
Add south introspection rule for MoneyField.
Add south introspection rule for MoneyField.
Python
bsd-3-clause
onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site
1ef71bd1b1eabcbe3d2148d8eb5e3f5a890450d7
idiokit/dns/_hostlookup.py
idiokit/dns/_hostlookup.py
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: ...
from .. import idiokit from ._iputils import parse_ip from ._conf import hosts from ._dns import DNSError, a, aaaa def _filter_ips(potential_ips): results = [] for ip in potential_ips: try: family, ip = parse_ip(ip) except ValueError: continue else: ...
Add configurable path to hosts file for HostLookup()
Add configurable path to hosts file for HostLookup() Required for unit testing so that tests don't have to rely on /etc/hosts file.
Python
mit
abusesa/idiokit
476b66510cd7b84233ad02ccfcde3ecd33604c57
simple_es/event/domain_event.py
simple_es/event/domain_event.py
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier must be an instance o...
from simple_es.identifier.identifies import Identifies class DomainEvent(): """ Base class for all domain driven events """ identifier = None _recorded = False def __init__(self, identifier=None): if not isinstance(identifier, Identifies): raise TypeError('Event identifier...
Add a _recorded bool to events
Add a _recorded bool to events
Python
apache-2.0
OnShift/simple-es
70049aa7b2f8dcede7d562def03b262f4c39816a
indra/sources/lincs/api.py
indra/sources/lincs/api.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str __all__ = [] import requests DATASET_URL = 'http://lincs.hms.harvard.edu/db/datasets/20000/results' def _get_lincs_drug_target_data(): resp = requests.get(DATASET_URL, params={'output_type': '.csv'}) ass...
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str __all__ = [] import csv import requests from indra.sources.lincs.processor import LincsProcessor DATASET_URL = 'http://lincs.hms.harvard.edu/db/datasets/20000/results' def process_from_web(): lincs_data = _...
Return a list of dicts for data.
Return a list of dicts for data.
Python
bsd-2-clause
pvtodorov/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,pvtodorov/indra,bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/indra,pvtodorov/indra,johnbachman/indra
581bc613ed00b99fc252e52953a9757ff580a510
generateConfig.py
generateConfig.py
#!/bin/python3.5 import os config = """ .VSBasePath = 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community' .WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10' .WindowsSDKSubVersion = '10.0.15063.0' #if __WINDOWS__ .FazEPath = 'CURRENT_DIRECTORY' .FBuildCache = 'C:/temp/fazecache' .VulkanSDK...
#!/bin/python3.5 import os config = """ .WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10' .WindowsSDKSubVersion = '10.0.15063.0' #if __WINDOWS__ .FazEPath = 'CURRENT_DIRECTORY' .FBuildCache = 'C:/temp/fazecache' .VulkanSDKBasePath = 'C:/VulkanSDK/1.0.54.0' #endif #if __LINUX__ .FazEPath = 'CURRENT_DIREC...
Use professional vs instead of community if found
Use professional vs instead of community if found
Python
mit
jgavert/Faze,jgavert/Faze,jgavert/Faze,jgavert/Faze
da510e3156b1a92bc9139263f9e27e793dd6316c
importlib_metadata/abc.py
importlib_metadata/abc.py
from __future__ import absolute_import import abc import sys if sys.version_info >= (3,): # pragma: nocover from importlib.abc import MetaPathFinder else: # pragma: nocover from abc import ABCMeta as MetaPathFinder class DistributionFinder(MetaPathFinder): """ A MetaPathFinder capable of discover...
from __future__ import absolute_import import abc import sys if sys.version_info >= (3,): # pragma: nocover from importlib.abc import MetaPathFinder else: # pragma: nocover class MetaPathFinder(object): __metaclass__ = abc.ABCMeta class DistributionFinder(MetaPathFinder): """ A MetaPathFi...
Fix MetaPathFinder compatibility stub on Python 2.7
Fix MetaPathFinder compatibility stub on Python 2.7
Python
apache-2.0
python/importlib_metadata
c3cb6a294fe83557d86d9415f8cdf8efb4f7e59f
elevator/message.py
elevator/message.py
import msgpack import logging class MessageFormatError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Request(object): """Handler objects for frontend->backend objects messages""" def __init__(self, raw_message, compressed=...
import msgpack import logging class MessageFormatError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Request(object): """Handler objects for frontend->backend objects messages""" def __init__(self, raw_message, compressed=...
Fix : response datas list should not be unicoded
Fix : response datas list should not be unicoded
Python
mit
oleiade/Elevator
51a9fe51f170132ab9da09fbf3aa73c59678aa03
start.py
start.py
#!/usr/bin/env python2.7 """ Run a local instance of Boulder for testing purposes. This runs in non-monolithic mode and requires RabbitMQ on localhost. Keeps servers alive until ^C or 100K seconds elapse. Exits non-zero if any servers fail to start, or die before timer/^C. """ import os import signal import sys impo...
#!/usr/bin/env python2.7 """ Run a local instance of Boulder for testing purposes. This runs in non-monolithic mode and requires RabbitMQ on localhost. Keeps servers alive until ^C. Exit non-zero if any servers fail to start, or die before ^C. """ import os import sys import time sys.path.append('./test') import st...
Remove 100K-second max runtime, just run until ^C or server crash.
Remove 100K-second max runtime, just run until ^C or server crash.
Python
mpl-2.0
letsencrypt/boulder,patf/boulder,lmcro/boulder,deserted/boulder,jgillula/boulder,mozmark/boulder,ZCloud-Firstserver/boulder,postfix/boulder,KyleChamberlin/boulder,kuba/boulder,modulexcite/boulder,ibukanov/boulder,hlandauf/boulder,mehmooda/boulder,julienschmidt/boulder,tomclegg/boulder,mommel/boulder,mozmark/boulder,jcj...
3a0d81e62d8a6cd6807d0447b72cc35206e2c8fd
ecs-cleaner.py
ecs-cleaner.py
import boto3 def main(event, context): client = boto3.client(u'ecs') inspect_clusters = [u'staging1'] for cluster in inspect_clusters: resp = client.list_container_instances( cluster=cluster ) instances = resp[u'containerInstanceArns'] try: nxt_tok = resp[u'nextToken'] whil...
import boto3 def main(event, context): ecs_client = boto3.client(u'ecs') inspect_clusters = [u'staging1'] for cluster in inspect_clusters: resp = ecs_client.list_container_instances( cluster=cluster ) instances = resp[u'containerInstanceArns'] try: nxt_tok = resp[u'nextToken'] ...
Add instance detach and terminate
Add instance detach and terminate
Python
mit
silinternational/ecs-agent-monitor
4b30b6dd4eb24c36cd32d37bf6555be79cdc80a8
scripts/maf_split_by_src.py
scripts/maf_split_by_src.py
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
#!/usr/bin/env python2.3 """ Read a MAF from stdin and break into a set of mafs containing no more than a certain number of columns """ usage = "usage: %prog" import sys, string import bx.align.maf from optparse import OptionParser import psyco_full INF="inf" def __main__(): # Parse command line arguments ...
Allow splitting by a particular component (by index)
Allow splitting by a particular component (by index)
Python
mit
uhjish/bx-python,uhjish/bx-python,uhjish/bx-python
c02900e7fb8657316fa647f92c4f9ddbcedb2b7c
rma/helpers/formating.py
rma/helpers/formating.py
from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)...
from math import floor from collections import Counter def floored_percentage(val, digits): """ Return string of floored value with given digits after period :param val: :param digits: :return: """ val *= 10 ** (digits + 2) return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)...
Add transforming function to pref_encodings
Add transforming function to pref_encodings
Python
mit
gamenet/redis-memory-analyzer
c0882e8096d1fecd5785a85e43a472d2e6d184db
error_proxy.py
error_proxy.py
#!/usr/bin/env python import sys import json from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class ErrorHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(420) if sys.argv[1:]: config_file = sys.argv[1:] else: config_file = "Proxyfile" with open(config_...
#!/usr/bin/env python import sys import json from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class ErrorHTTPRequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(self.config['get_response']) if sys.argv[1:]: config_file = sys.argv[1:] else: config_file = "Prox...
Configure GET response via Proxyfile
Configure GET response via Proxyfile
Python
mit
pozorvlak/error_proxy
cfe4148feac51a9be6ff74e978a22f1493adff8b
doajtest/unit/test_tasks_sitemap.py
doajtest/unit/test_tasks_sitemap.py
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import os, shutil, time from portality.lib import paths from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @clas...
from doajtest.helpers import DoajTestCase from portality.core import app from portality.tasks import sitemap from portality.background import BackgroundApi import time from portality.store import StoreFactory class TestSitemap(DoajTestCase): store_impl = None @classmethod def setUpClass(cls) -> None: ...
Increase timeout for slow test
Increase timeout for slow test
Python
apache-2.0
DOAJ/doaj,DOAJ/doaj,DOAJ/doaj,DOAJ/doaj