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
7201a7f6c87efa74165ca22c4a2db9ce292bae62
baseline.py
baseline.py
#/usr/bin/python """ Baseline example that needs to be beaten """ import numpy as np import matplotlib.pyplot as plt x, y, yerr = np.loadtxt("data/data.txt", unpack=True) A = np.vstack((np.ones_like(x), x)).T C = np.diag(yerr * yerr) cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A))) b_ls, m_ls = np.dot(cov, n...
#/usr/bin/python """ Baseline example that needs to be beaten """ import os import numpy as np import matplotlib.pyplot as plt x, y, yerr = np.loadtxt("data/data.txt", unpack=True) A = np.vstack((np.ones_like(x), x)).T C = np.diag(yerr * yerr) cov = np.linalg.inv(np.dot(A.T, np.linalg.solve(C, A))) b_ls, m_ls = np....
Add RESULT_M and RESULT_B to environment varaible
Add RESULT_M and RESULT_B to environment varaible [ci skip]
Python
mit
arfon/dottravis,arfon/dottravis
dde82212ddf255ffb15b2b083352d7cf5b4b5b34
tutorials/urls.py
tutorials/urls.py
from django.conf.urls import include, url from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view()), url(r'add/', views.NewTutorial.as_view(), name='add_tutorial'), url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tutorial'), # This must be ...
from django.conf.urls import include, url from tutorials import views urlpatterns = [ url(r'^$', views.ListTutorials.as_view(), name='list_tutorials'), url(r'add/', views.CreateNewTutorial.as_view(), name='add_tutorial'), url(r'(?P<tutorial_id>[\w\-]+)/edit/', views.EditTutorials.as_view(), name='edit_tut...
Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials
Add url name to ListView, New url for delete view, Refactor ViewClass name for NewTutorials to CreateNewTutorials
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
bc2b8d04398f9df9985452b2b8a016208cf216cd
salesforce/__init__.py
salesforce/__init__.py
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # """ A database backend for the Django ORM. Allows access to all Salesforce objects accessible via the SOQL API. """ import logging import warnings import django DJANGO_18_PLU...
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # """ A database backend for the Django ORM. Allows access to all Salesforce objects accessible via the SOQL API. """ import logging import warnings import django DJANGO_18_PLU...
Remove Django 1.8/1.9 warnings; much better supported now.
Remove Django 1.8/1.9 warnings; much better supported now.
Python
mit
chromakey/django-salesforce,django-salesforce/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,hynekcer/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce
c5158020475e62d7e8b86a613a02c0a659038f88
formish/tests/testish/testish/lib/xformish.py
formish/tests/testish/testish/lib/xformish.py
""" General purpose formish extensions. """ from formish import validation, widgets, Form class DateParts(widgets.DateParts): def __init__(self, **k): k['day_first'] = k.pop('l10n').is_day_first() super(DateParts, self).__init__(**k) class ApproximateDateParts(widgets.DateParts): _templat...
""" General purpose formish extensions. """ from formish import validation, widgets, Form from convertish.convert import ConvertError class DateParts(widgets.DateParts): def __init__(self, **k): k['day_first'] = k.pop('l10n').is_day_first() super(DateParts, self).__init__(**k) class Approximat...
Fix custom widget to raise correct exception type.
Fix custom widget to raise correct exception type.
Python
bsd-3-clause
ish/formish,ish/formish,ish/formish
750dc7d4eddf691117cebf815e163a4d10af39cb
src/TulsiGenerator/Scripts/bazel_options.py
src/TulsiGenerator/Scripts/bazel_options.py
# Copyright 2017 The Tulsi Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
# Copyright 2017 The Tulsi Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
Support enabling tsan and ubsan from Xcode UI
Support enabling tsan and ubsan from Xcode UI Xcode won't let you enable ubsan from the UI as it requires a 'Compile Sources' phase with (Objective-)C(++) sources, but if you manually edit the scheme and enable it or equivalently add the phase with a dummy file, enable it from the UI, and then remove the phase, ubsan ...
Python
apache-2.0
pinterest/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,pinterest/tulsi,bazelbuild/tulsi,bazelbuild/tulsi,pinterest/tulsi,pinterest/tulsi,pinterest/tulsi,pinterest/tulsi
1e90db8de39bd8c4b1a4d58148b991af8b5c32dd
storage/models/fighter.py
storage/models/fighter.py
from storage.models.base import * class Fighter(Base): __tablename__ = 'fighters' id = Column(Integer, primary_key=True) ref = Column(String(STR_SIZE), unique=True, nullable=False) name = Column(String(STR_SIZE), nullable=False) country = Column(String(STR_SIZE)) city = Column(String(STR_SIZE...
from storage.models.base import * class Fighter(Base): __tablename__ = 'fighters' id = Column(Integer, primary_key=True) ref = Column(String(STR_SIZE), unique=True, nullable=False) name = Column(String(STR_SIZE), nullable=False) country = Column(String(STR_SIZE)) city = Column(String(STR_SIZE...
Add restriction for specialization string in db
Add restriction for specialization string in db
Python
apache-2.0
Some1Nebo/ufcpy
146463512e17a6bae0dfc0e8f3aa8d99200a5e9c
transfers/examples/pre-transfer/archivesspace_ids.py
transfers/examples/pre-transfer/archivesspace_ids.py
#!/usr/bin/env python from __future__ import print_function import csv import errno import os import sys def main(transfer_path): """ Generate archivesspaceids.csv with reference IDs based on filenames. """ as_ids = [] for dirpath, _, filenames in os.walk(transfer_path): for filename in ...
#!/usr/bin/env python from __future__ import print_function import csv import errno import os import sys def main(transfer_path): """ Generate archivesspaceids.csv with reference IDs based on filenames. """ archivesspaceids_path = os.path.join(transfer_path, 'metadata', 'archivesspaceids.csv') if...
Automate transfers: archivesspace example checks if output file already exists
Automate transfers: archivesspace example checks if output file already exists Check if archivesspaceids.csv already exists (presumably user provided). Do not generate one automatically in that case.
Python
agpl-3.0
artefactual/automation-tools,artefactual/automation-tools
1c19d7fb5914554b470a6d067902a9c61882ff4a
packs/softlayer/actions/destroy_instance.py
packs/softlayer/actions/destroy_instance.py
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] # destroy the node self...
from lib.softlayer import SoftlayerBaseAction class SoftlayerDeleteInstance(SoftlayerBaseAction): def run(self, name): driver = self._get_driver() # go from name to Node Object try: node = [n for n in driver.list_nodes() if n.extra['hostname'] == name][0] except IndexEr...
Return a sane error if there is no Nodes with that name instead of IndexError
Return a sane error if there is no Nodes with that name instead of IndexError
Python
apache-2.0
tonybaloney/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pearsontechnology/st2contrib,meirwah/st2contrib,psychopenguin/st2contrib,pidah/st2contrib,digideskio/st2contrib,digideskio/st2contrib,psychopenguin/st2contrib,meirwah/st2contrib,lmEshoo/st2contrib,pinterb/st2contrib,tonybaloney/st2contrib,pidah/st2cont...
0219907b3351fea2467ad961fef750481b62e205
dask_ndmeasure/_test_utils.py
dask_ndmeasure/_test_utils.py
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*- from __future__ import absolute_import import dask.array.utils def _assert_eq_nan(a, b, **kwargs): a = a.copy() b = b.copy() a_nan = (a != a) b_nan = (b != b) a[a_nan] = 0 b[b_nan] = 0 dask.array.utils.assert_eq(a_nan, b_nan, **kwargs) dask.array.utils.asse...
Add _assert_eq_nan to compare arrays that have NaN
Add _assert_eq_nan to compare arrays that have NaN As comparisons with NaN are false even if both values are NaN, using the `assert_eq` does not work correctly in this case. To fix it, we add this shim function around `assert_eq`. First we verify that they have the same NaN values using a duck type friendly strategy (...
Python
bsd-3-clause
dask-image/dask-ndmeasure
1c494f21cde384b611998d237baa430384dcefbc
Challenges/chall_22.py
Challenges/chall_22.py
#!/usr/local/bin/python3 # Python Challenge - 22 # http://www.pythonchallenge.com/pc/hex/copper.html # http://www.pythonchallenge.com/pc/hex/white.gif # Username: butter; Password: fly # Keyword: ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source ...
#!/usr/local/bin/python3 # Python Challenge - 22 # http://www.pythonchallenge.com/pc/hex/copper.html # http://www.pythonchallenge.com/pc/hex/white.gif # Username: butter; Password: fly # Keyword: ''' Uses Anaconda environment with Pillow for image processing - Python 3.7, numpy, and Pillow (PIL) - Run `source ...
Refactor image open to with block
Refactor image open to with block
Python
mit
HKuz/PythonChallenge
f7a8f66047e2277cd95b553cd7aadfa24fbaad95
scuole/stats/models.py
scuole/stats/models.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return sel...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class SchoolYear(models.Model): name = models.CharField(max_length=9) def __str__(self): return sel...
Add two more fields to StatsBase
Add two more fields to StatsBase
Python
mit
texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole
06f045d51b24ee834f7bbb572ccce304431fc602
merlin/engine/battle.py
merlin/engine/battle.py
class Prepare(object): """ Prepare the champions for the battle! Usage: hero = Prepare(name="Aragorn", base_attack=100, base_hp=100) or like this: aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100} hero = Prepare(**aragorn) """ def __init__(self, name, b...
class Prepare(object): """ Prepare the champions for the battle! Usage: hero = Prepare(name="Aragorn", base_attack=100, base_hp=100) or like this: aragorn = {"name": "Aragorn", "base_attack": 100, "base_hp": 100} hero = Prepare(**aragorn) """ def __init__(self, name, b...
Add property status in Prepare
Add property status in Prepare
Python
mit
lerrua/merlin-engine
c201fc0feef5f7eeede327d6239fc3082ae24180
server/worker/queue.py
server/worker/queue.py
"""Process queues.""" from datetime import datetime from server.extensions import db from server.models import QueueEntry def finished_entries(): """Process finished entries.""" queue_entries = db.session.query(QueueEntry) \ .filter(QueueEntry.finishes_at <= datetime.now()) \ .all() for ...
"""Process queues.""" from datetime import datetime from server.extensions import db from server.models import QueueEntry def finished_entries(): """Process finished entries.""" queue_entries = db.session.query(QueueEntry) \ .filter(QueueEntry.finishes_at <= datetime.now()) \ .all() for ...
Set research level in ticker
Set research level in ticker
Python
mit
Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival,Nukesor/spacesurvival
738d080512f36939ce4a23f3d3db0b378550564a
tests/test_build_chess.py
tests/test_build_chess.py
# -*- coding: utf-8 -*- from app.chess.chess import Chess import unittest class TestBuildChess(unittest.TestCase): """ `TestBuildChess()` class is unit-testing the class Chess(). """ # /////////////////////////////////////////////////// def setUp(self): params = [4, 4] piece...
# -*- coding: utf-8 -*- from app.chess.chess import Chess import unittest class TestBuildChess(unittest.TestCase): """ `TestBuildChess()` class is unit-testing the class Chess(). """ # /////////////////////////////////////////////////// def setUp(self): params = [4, 4] piece...
Add a TDD funct to test the solution (only kings)
Add a TDD funct to test the solution (only kings)
Python
mit
aymguesmi/ChessChallenge
baca7b88893f175a222d7130ef1889893ed6b970
iterm2_tools/images.py
iterm2_tools/images.py
""" Functions for displaying images inline in iTerm2. See https://iterm2.com/images.html. """ from __future__ import print_function, division, absolute_import import sys import os import base64 IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a' def display_image_bytes(b, filename=None, ...
""" Functions for displaying images inline in iTerm2. See https://iterm2.com/images.html. """ from __future__ import print_function, division, absolute_import import sys import os import base64 IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a' def display_image_bytes(b, filename=None, ...
Add a deprecation message to the docstring of image_bytes()
Add a deprecation message to the docstring of image_bytes()
Python
mit
asmeurer/iterm2-tools
a2f1cdc05e63b7b68c16f3fd1e5203608888b059
traits/util/deprecated.py
traits/util/deprecated.py
""" A decorator for marking methods/functions as deprecated. """ # Standard library imports. import logging # We only warn about each function or method once! _cache = {} def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorator(fn): ...
# Test the 'trait_set', 'trait_get' interface to # the HasTraits class. # # Copyright (c) 2014, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # License included in /LICENSE.txt and may be redistributed only under the # conditions described in the...
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
3900c8173bff6c3b1175ff9d6cffec1b98db7c74
address_book/address_book.py
address_book/address_book.py
__all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] def add_person(self, person): self.persons.append(person)
from person import Person __all__ = ['AddressBook'] class AddressBook(object): def __init__(self): self.persons = [] def add_person(self, person): self.persons.append(person) def __contains__(self, item): if isinstance(item, Person): return item in self.persons ...
Add ability to check is the Person in AddressBook or not
Add ability to check is the Person in AddressBook or not
Python
mit
dizpers/python-address-book-assignment
d08e8144b90d3fe89fd449d31bdb655d62f3a749
serfclient/connection.py
serfclient/connection.py
import socket import sys class SerfConnectionError(Exception): pass class SerfConnection(object): """ Manages RPC communication to and from a Serf agent. """ def __init__(self, host='localhost', port=7373): self.host, self.port = host, port self._socket = None def __repr__(...
import socket import sys class SerfConnectionError(Exception): pass class SerfConnection(object): """ Manages RPC communication to and from a Serf agent. """ def __init__(self, host='localhost', port=7373): self.host, self.port = host, port self._socket = None def __repr__(...
Move all 'connect' logic into a private method
Move all 'connect' logic into a private method
Python
mit
charleswhchan/serfclient-py,KushalP/serfclient-py
14c41706d6437247bbe69e0e574c03863fbe5bda
api/v2/views/maintenance_record.py
api/v2/views/maintenance_record.py
from rest_framework.serializers import ValidationError from core.models import MaintenanceRecord from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerializer from api.v2.views.base import AuthOptionalViewSet class MaintenanceRecordViewSet(AuthOptionalViewSet): ...
import django_filters from rest_framework import filters from rest_framework.serializers import ValidationError from core.models import AtmosphereUser, MaintenanceRecord from core.query import only_current from api.permissions import CanEditOrReadOnly from api.v2.serializers.details import MaintenanceRecordSerialize...
Add '?active=' filter for Maintenance Record
[ATMO-1200] Add '?active=' filter for Maintenance Record
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
611c34eee4b5aa263669f1b7321b97fab9a98b5e
dask/distributed/tests/test_ipython_utils.py
dask/distributed/tests/test_ipython_utils.py
from dask.distributed import dask_client_from_ipclient def test_dask_client_from_ipclient(): from IPython.parallel import Client c = Client() dc = dask_client_from_ipclient(c) assert 2 == dc.get({'a': 1, 'b': (lambda x: x + 1, 'a')}, 'b') dc.close(close_workers=True, close_scheduler=True)
from dask.distributed import dask_client_from_ipclient import numpy as np from numpy.testing import assert_array_almost_equal import dask.array as da def test_dask_client_from_ipclient(): from IPython.parallel import Client c = Client() dask_client = dask_client_from_ipclient(c) # data a = np.ara...
Remove lambda test. Add dask array tests.
Remove lambda test. Add dask array tests.
Python
bsd-3-clause
PhE/dask,clarkfitzg/dask,jayhetee/dask,simudream/dask,mikegraham/dask,vikhyat/dask,PhE/dask,wiso/dask,jcrist/dask,esc/dask,mraspaud/dask,esc/dask,marianotepper/dask,vikhyat/dask,pombredanne/dask,simudream/dask,freeman-lab/dask,cpcloud/dask,blaze/dask,marianotepper/dask,jcrist/dask,hainm/dask,ContinuumIO/dask,blaze/dask...
6fbf3edb489059f93cee6684bf5046386f538391
src/attendance/wsgi.py
src/attendance/wsgi.py
""" WSGI config for openservices project. It exposes the WSGI callable as a module-level variable named ``application``. """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "attendance.settings") application = get_wsgi_application()
""" WSGI config for openservices project. It exposes the WSGI callable as a module-level variable named ``application``. """ import os import sys sys.path.append(os.path.abspath(os.path.join(__file__, '../..'))) from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "atte...
Append source path in WSGI mode.
Append source path in WSGI mode.
Python
bsd-2-clause
OpenServicesEU/python-attendance
1629d6d369bce079c33986aa62a12a1ad3a8a47d
test/test_grequest.py
test/test_grequest.py
from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def canc...
from mpi4py import MPI import mpiunittest as unittest class GReqCtx(object): source = 1 tag = 7 completed = False free_called = False def query(self, status): status.Set_source(self.source) status.Set_tag(self.tag) def free(self): self.free_called = True def canc...
Remove commented-out line in testcase
Remove commented-out line in testcase
Python
bsd-2-clause
pressel/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,mpi4py/mpi4py,pressel/mpi4py,pressel/mpi4py,pressel/mpi4py
8c2a52ce4eb47e89450677d0beed9c3d45b417e0
tests/test_default.py
tests/test_default.py
import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( '.molecule/ansible_inventory').get_hosts('all') def test_hosts_file(File): f = File('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root'
import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( '.molecule/ansible_inventory').get_hosts('all') def test_service_running_and_enabled(Service): collectd = Service("collectd") collectd.is_running collectd.is_enabled
Write a sensible (if post hoc) test.
Write a sensible (if post hoc) test. I had a hard time getting this test to fail so I could prove it works, but it's a simple test and its main purpose is to provide an example for later tests, so I'm calling it Good Enough.
Python
mit
idi-ops/ansible-collectd
a72b20a7c614c86a196585a6703b218613f6d74b
modules/githubsearch.py
modules/githubsearch.py
import requests import simplejson as json class GithubSearch(object): def __init__(self): self.api_url = "https://api.github.com/search/code?q=" self.repo = "OpenTreeOfLife/treenexus" def search(self,term): search_url = "%s+repo:%s" % (self.api_url, self.repo) r = requests.ge...
import requests import simplejson as json class GithubSearch(object): def __init__(self): self.api_url = "https://api.github.com/search/code?q=" self.repo = "OpenTreeOfLife/treenexus" def search(self,term): search_url = "%s%s+repo:%s" % (self.api_url, term, self.repo) print "...
Add a simple search controller which wraps around the Github code search API
Add a simple search controller which wraps around the Github code search API
Python
bsd-2-clause
OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api,OpenTreeOfLife/phylesystem-api
41ad0f842320161c45079f7a75d64df6c8716e5d
london_commute_alert.py
london_commute_alert.py
import datetime import os import requests def update(): requests.packages.urllib3.disable_warnings() resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json() return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp} def email(lines): with open('curl_raw_c...
import datetime import os import requests def update(): requests.packages.urllib3.disable_warnings() resp = requests.get('http://api.tfl.gov.uk/Line/Mode/tube/Status').json() return {el['id']: el['lineStatuses'][0]['statusSeverityDescription'] for el in resp} def email(lines): with open('curl_raw_c...
Move from python anywhere to webfaction
Move from python anywhere to webfaction
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
3eb57619a4e8a669cf879b67d96377ccb21de204
babel_util/scripts/wos_to_pajek.py
babel_util/scripts/wos_to_pajek.py
#!/usr/bin/env python3 from parsers.wos import WOSStream from util.PajekFactory import PajekFactory from util.misc import open_file, Checkpoint if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML") parser.add_argument('outfile') ...
#!/usr/bin/env python3 from parsers.wos import WOSStream from util.PajekFactory import PajekFactory from util.misc import open_file, Checkpoint if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Creates Pajek (.net) files from WOS XML") parser.add_argument('outfile') ...
Add wos-only option to script
Add wos-only option to script
Python
agpl-3.0
jevinw/rec_utilities,jevinw/rec_utilities
557e634a3b68c13b1a19151ec3b96f456e17d347
penelophant/database.py
penelophant/database.py
""" Database Module """ from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy()
""" Database Module """ from flask_sqlalchemy import SQLAlchemy from penelophant import app db = SQLAlchemy(app)
Attach app to SQLAlchemy properly
Attach app to SQLAlchemy properly
Python
apache-2.0
kevinoconnor7/penelophant,kevinoconnor7/penelophant
f76a2070d91d60a261e8f6120a01075491eb785f
conftest.py
conftest.py
# -*- coding: utf-8 -*- pytest_plugins = [ u'ckan.tests.pytest_ckan.ckan_setup', u'ckan.tests.pytest_ckan.fixtures', ]
# -*- coding: utf-8 -*- pytest_plugins = [ ]
Remove pytest plugins from archiver
Remove pytest plugins from archiver
Python
mit
ckan/ckanext-archiver,ckan/ckanext-archiver,ckan/ckanext-archiver
67d08aff211ae1edbae202819f39be7c34812137
hggithub.py
hggithub.py
# Mimic the hggit extension. try: from hggit import * hggit_reposetup = reposetup except ImportError: # Allow this module to be imported without # hg-git installed, eg for setup.py pass __version__ = "0.1.0" def reposetup(ui, repo, **kwargs): """ Automatically adds Bitbucket->GitHub mir...
# Mimic the hggit extension. try: from hggit import * hggit_reposetup = reposetup except ImportError: # Allow this module to be imported without # hg-git installed, eg for setup.py pass __version__ = "0.1.0" def reposetup(ui, repo, **kwargs): """ Automatically adds Bitbucket->GitHub mir...
Allow for extra slashes in project paths, such as mq patch queues.
Allow for extra slashes in project paths, such as mq patch queues.
Python
bsd-2-clause
stephenmcd/hg-github
0d3740cef051ed08a307dc2b42fe022ce2f1ba28
bot/utils/attributeobject.py
bot/utils/attributeobject.py
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, v...
class AttributeObject: def __init__(self, *excluded_keys): self._excluded_keys = excluded_keys def __getattr__(self, item): return self._getattr(item) def __setattr__(self, key, value): if key == "_excluded_keys" or key in self._excluded_keys: super().__setattr__(key, v...
Allow to specify initial items on DictionaryObject constructor
Allow to specify initial items on DictionaryObject constructor
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
7bbec0e5306766741b22341a100db046d76b82a8
apps/books/models.py
apps/books/models.py
from django.db import models from apps.categories.models import Category from apps.users.models import UserProfile from apps.reviews.models import Review class Book(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=500) author = models.CharField(max_length=255) ...
from django.db import models from apps.categories.models import Category from apps.users.models import UserProfile from apps.reviews.models import Review class Book(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=500) author = models.CharField(max_length=255) ...
Fix get_rating in Book model
Fix get_rating in Book model
Python
mit
vuonghv/brs,vuonghv/brs,vuonghv/brs,vuonghv/brs
d6b3c47169082eeee6f1f01458b8791de2573849
kolibri/plugins/management/kolibri_plugin.py
kolibri/plugins/management/kolibri_plugin.py
from __future__ import absolute_import, print_function, unicode_literals from kolibri.plugins.base import KolibriFrontEndPluginBase class ManagementModule(KolibriFrontEndPluginBase): """ The Management module. """ entry_file = "assets/src/management.js" base_url = "management" template = "...
from __future__ import absolute_import, print_function, unicode_literals from kolibri.core.webpack import hooks as webpack_hooks from kolibri.plugins.base import KolibriPluginBase class ManagementPlugin(KolibriPluginBase): """ Required boilerplate so that the module is recognized as a plugin """ pass class...
Use new plugin classes for management
Use new plugin classes for management
Python
mit
66eli77/kolibri,learningequality/kolibri,indirectlylit/kolibri,lyw07/kolibri,jtamiace/kolibri,learningequality/kolibri,aronasorman/kolibri,jamalex/kolibri,christianmemije/kolibri,rtibbles/kolibri,benjaoming/kolibri,jtamiace/kolibri,jayoshih/kolibri,MingDai/kolibri,DXCanas/kolibri,jamalex/kolibri,rtibbles/kolibri,mrpau/...
7b73d73b7b61830b955f7ec686570c7371bb16d1
comics/crawler/utils/lxmlparser.py
comics/crawler/utils/lxmlparser.py
#encoding: utf-8 from lxml.html import parse, fromstring class LxmlParser(object): def __init__(self, url=None, string=None): if url: self.root = parse(url).getroot() self.root.make_links_absolute(url) elif string: self.root = fromstring(string) def text(se...
#encoding: utf-8 from lxml.html import parse, fromstring class LxmlParser(object): def __init__(self, url=None, string=None): if url is not None: self.root = parse(url).getroot() self.root.make_links_absolute(url) elif string is not None: self.root = fromstring(...
Update exception handling in LxmlParser
Update exception handling in LxmlParser Signed-off-by: Stein Magnus Jodal <e14d2e665cf0bcfd7f54daa10a36c228abaf843a@jodal.no>
Python
agpl-3.0
datagutten/comics,jodal/comics,datagutten/comics,klette/comics,jodal/comics,jodal/comics,klette/comics,datagutten/comics,jodal/comics,datagutten/comics,klette/comics
072d5bf150ff3f8d743a84c636929e7a326bf8ea
src/python/tensorflow_cloud/tuner/constants.py
src/python/tensorflow_cloud/tuner/constants.py
# Lint as: python3 # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
# Lint as: python3 # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
Fix path to API doc
Fix path to API doc
Python
apache-2.0
tensorflow/cloud,tensorflow/cloud
5a6ff9a69a2d769f6ac363f20afb89a23dd2290d
homeassistant/components/device_tracker/mqtt.py
homeassistant/components/device_tracker/mqtt.py
""" homeassistant.components.device_tracker.mqtt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MQTT platform for the device tracker. device_tracker: platform: mqtt qos: 1 devices: paulus_oneplus: /location/paulus annetherese_n4: /location/annetherese """ import logging from homeassistant import util impo...
""" homeassistant.components.device_tracker.mqtt ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MQTT platform for the device tracker. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.mqtt.html """ import logging from homeassistant import util ...
Move configuration details to docs
Move configuration details to docs
Python
mit
emilhetty/home-assistant,mikaelboman/home-assistant,alexmogavero/home-assistant,devdelay/home-assistant,nevercast/home-assistant,shaftoe/home-assistant,srcLurker/home-assistant,tboyce021/home-assistant,instantchow/home-assistant,DavidLP/home-assistant,Julian/home-assistant,jnewland/home-assistant,florianholzapfel/home-...
6a07b94f9c84741fcc399f9dee3945d0339b19e0
download.py
download.py
import youtube_dl, os from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = "" done = False error = False started = None uuid = "" total = 0 finished = 0 title = "" def __i...
import youtube_dl, os from multiprocessing.pool import ThreadPool from youtube_dl.utils import DownloadError from datetime import datetime from uuid import uuid4 class Download: link = "" done = False error = False started = None uuid = "" total = 0 finished = 0 title = "" def __i...
Add function to get files for playlist
Add function to get files for playlist
Python
mit
pielambr/PLDownload,pielambr/PLDownload
4eeec96f3c79b9584278639293631ab787132f67
custom/ewsghana/reminders/third_soh_reminder.py
custom/ewsghana/reminders/third_soh_reminder.py
from corehq.apps.locations.models import SQLLocation from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondSOHReminder class ThirdSOHReminder(SecondSOHReminder): def get_users_messages(self): for sql_location in SQLLocation.objects.filter(domain...
from corehq.apps.locations.dbaccessors import get_web_users_by_location from corehq.apps.locations.models import SQLLocation from corehq.apps.reminders.util import get_preferred_phone_number_for_recipient from corehq.apps.users.models import CommCareUser from custom.ewsghana.reminders.second_soh_reminder import SecondS...
Send third soh also to web users
Send third soh also to web users
Python
bsd-3-clause
qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
172372000f121b31daa0965dca3bf28976b6cba9
aiodocker/exceptions.py
aiodocker/exceptions.py
class DockerError(Exception): def __init__(self, status, data, *args): super().__init__(*args) self.status = status self.message = data['message'] def __repr__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) def __str__(self): return ...
class DockerError(Exception): def __init__(self, status, data, *args): super().__init__(*args) self.status = status self.message = data['message'] def __repr__(self): return 'DockerError({self.status}, {self.message!r})'.format(self=self) def __str__(self): return ...
Fix flake8 error (too long line)
Fix flake8 error (too long line)
Python
mit
barrachri/aiodocker,gaopeiliang/aiodocker,paultag/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker,barrachri/aiodocker,gaopeiliang/aiodocker
540273ac75880925934e69275c9da1de61fbd699
PyBingWallpaper.py
PyBingWallpaper.py
#! /usr/bin/python3 import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os #Variables: saveDir = 'C:\BingWallPaper\\' i = 0 while i<1: try: usock = urlopen('http://www.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=zh-CN') ex...
#! /usr/bin/python3 import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os if __name__=="__main__": #Variables: saveDir = "C:\\BingWallPaper\\" if (not os.path.exists(saveDir)): os.mkdir(saveDir) i = 0 while i<1...
Create directory in case not exist
Create directory in case not exist
Python
mit
adamadanandy/PyBingWallpaper
e752a0ab47da9d9b34b5ce6f5cd40ac98977ec6e
symUtil.py
symUtil.py
import os import re def mkdir_p(path): if not os.path.exists(path): os.makedirs(path) def GetSymbolFileName(libName): # Guess the name of the .sym file on disk if libName[-4:] == ".pdb": return re.sub(r"\.[^\.]+$", ".sym", libName) return libName + ".sym"
import os def mkdir_p(path): if not os.path.exists(path): os.makedirs(path) def GetSymbolFileName(libName): # Guess the name of the .sym file on disk if libName[-4:] == ".pdb": return libName[:-4] + ".sym" return libName + ".sym"
Refactor out the re. It's not necessary to regex the replacement of an explicitly checked string in an explicit location. This should be simpler.
Refactor out the re. It's not necessary to regex the replacement of an explicitly checked string in an explicit location. This should be simpler.
Python
mpl-2.0
bytesized/Snappy-Symbolication-Server
2b1cd9a58aa51ef53996dc1897a7a0e50f29d7ca
isitopenaccess/plugins/bmc.py
isitopenaccess/plugins/bmc.py
import requests from copy import deepcopy from datetime import datetime from isitopenaccess.plugins import string_matcher def page_license(record): """ To respond to the provider identifier: http://www.biomedcentral.com This should determine the licence conditions of the BMC article and populate ...
import requests from copy import deepcopy from datetime import datetime from isitopenaccess.plugins import string_matcher def page_license(record): """ To respond to the provider identifier: http://www.biomedcentral.com This should determine the licence conditions of the BMC article and populate ...
ADD MISSING FILE TO PREV COMMIT "modify BMC plugin: overwrite URL for CC-BY license. We have a MORE specific URL (from the license statement on the BMC pages) than the Open Definition one"
ADD MISSING FILE TO PREV COMMIT "modify BMC plugin: overwrite URL for CC-BY license. We have a MORE specific URL (from the license statement on the BMC pages) than the Open Definition one"
Python
bsd-3-clause
CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge,CottageLabs/OpenArticleGauge
a3dc06b0389eccd9a97270399c9878968c2d910c
shopify_auth/__init__.py
shopify_auth/__init__.py
VERSION = (0, 1, 0) __version__ = '.'.join(map(str, VERSION)) __author__ = 'Gavin Ballard'
import shopify from django.conf import settings from django.core.exceptions import ImproperlyConfigured VERSION = (0, 1, 1) __version__ = '.'.join(map(str, VERSION)) __author__ = 'Gavin Ballard' def initialize(): if not settings.SHOPIFY_APP_API_KEY or not settings.SHOPIFY_APP_API_SECRET: raise Imp...
Add initialize() method to ShopifyAuth, which sets up the API key and secret of the app.
Add initialize() method to ShopifyAuth, which sets up the API key and secret of the app.
Python
mit
funkybob/django-shopify-auth,discolabs/django-shopify-auth,funkybob/django-shopify-auth,discolabs/django-shopify-auth,RafaAguilar/django-shopify-auth,RafaAguilar/django-shopify-auth
f003fd0099b1817e965483e94a51745834a802de
simple_neural_network.py
simple_neural_network.py
# This code is inspired from this post: # http://www.kdnuggets.com/2015/10/neural-network-python-tutorial.html?utm_content=buffer2cfea&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer import numpy as np # Feature matrix and targets X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]]) print X.shape y = np.array...
# This code is inspired from this post: # http://www.kdnuggets.com/2015/10/neural-network-python-tutorial.html?utm_content=buffer2cfea&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer import numpy as np np.random.seed(314) # Feature matrix and targets X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]]) print...
Set a seed for the simple neural network
Set a seed for the simple neural network
Python
mit
yassineAlouini/ml-experiments,yassineAlouini/ml-experiments
0688d285494e9c2ddb5b6ab35f2c0bd1dac02a54
basecampx/client.py
basecampx/client.py
import json import requests class Client(object): LAUNCHPAD_URL = 'https://launchpad.37signals.com' BASE_URL = 'https://basecamp.com/%s/api/v1' def __init__(self, access_token, user_agent, account_id=None): """Initialize client for making requests. user_agent -- string identifying the ap...
import json import urlparse import requests class Client(object): LAUNCHPAD_URL = 'https://launchpad.37signals.com/' BASE_URL = 'https://basecamp.com/%s/api/v1/' def __init__(self, access_token, user_agent, account_id=None): """Initialize client for making requests. user_agent -- string ...
Use urljoin to form urls.
Use urljoin to form urls.
Python
mit
nous-consulting/basecamp-next
2cc9de18bf20753907c2c0e591b58ccefe1578e0
erudite/components/commands/find_owner.py
erudite/components/commands/find_owner.py
""" Command that will allow for a user to inject triples into a database. """ from rhobot.components.commands.base_command import BaseCommand from rdflib.namespace import FOAF from rhobot.namespace import RHO import logging logger = logging.getLogger(__name__) class FindOwner(BaseCommand): def initialize_command...
""" Command that will allow for a user to inject triples into a database. """ from rhobot.components.commands.base_command import BaseCommand from rdflib.namespace import FOAF from rhobot.namespace import RHO from rhobot.components.storage import StoragePayload import logging logger = logging.getLogger(__name__) clas...
Update find owner to work with promises.
Update find owner to work with promises.
Python
bsd-3-clause
rerobins/rho_erudite
144f14bc292e9621508ac755c70d679affddfb90
corehq/apps/couch_sql_migration/management/commands/show_started_migrations.py
corehq/apps/couch_sql_migration/management/commands/show_started_migrations.py
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from operator import attrgetter import six from django.core.management.base import BaseCommand from corehq.apps.domain_migration_flags.api import get_uncompleted_migrations from ...progress import CO...
from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals from operator import attrgetter from django.core.management.base import BaseCommand import six from corehq.apps.domain_migration_flags.api import get_uncompleted_migrations from ...progress import C...
Print diff stats for each domain
Print diff stats for each domain
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
5950f14ab025999b8161204595a7c35554fe46a0
celery/decorators.py
celery/decorators.py
from celery.task.base import Task from celery.registry import tasks from inspect import getargspec def task(**options): """Make a task out of any callable. Examples: >>> @task() ... def refresh_feed(url): ... return Feed.objects.get(url=url).refresh() ...
from celery.task.base import Task from inspect import getargspec def task(**options): """Make a task out of any callable. Examples: >>> @task() ... def refresh_feed(url): ... return Feed.objects.get(url=url).refresh() >>> refresh_feed("http://example...
Allow base=PeriodicTask argument to task decorator
Allow base=PeriodicTask argument to task decorator
Python
bsd-3-clause
WoLpH/celery,cbrepo/celery,ask/celery,cbrepo/celery,frac/celery,mitsuhiko/celery,WoLpH/celery,ask/celery,frac/celery,mitsuhiko/celery
e88899fe11f1216e25e6f42f4af2acf003b22071
documentation/doxygen/makeimage.py
documentation/doxygen/makeimage.py
#! /usr/bin/env python import ROOT import shutil import os def makeimage(MacroName, ImageName, OutDir, cp, py, batch): '''Generates the ImageName output of the macro MacroName''' if batch: ROOT.gROOT.SetBatch(1) if py: execfile(MacroName) else: ROOT.gInterpreter.ProcessLine(".x " + MacroName...
#! /usr/bin/env python import ROOT import shutil import os def makeimage(MacroName, ImageName, OutDir, cp, py, batch): '''Generates the ImageName output of the macro MacroName''' ROOT.gStyle.SetImageScaling(3.) if batch: ROOT.gROOT.SetBatch(1) if py: execfile(MacroName) else: ROOT.gInte...
Implement high def pictures for python tutorials.
Implement high def pictures for python tutorials.
Python
lgpl-2.1
olifre/root,olifre/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,olifre/root,olifre/root,olifre/root,karies/root,root-mirror/root,karies/root,root-mirror/root,karies/root,karies/root,karies/root,olifre/root,root-mirror/root,karies/root,olifre/root,olifre/root,karies/root,root-mirror/root,ol...
1cc15cbe37e1118f102f05d9530d6f0a6055d638
handler/base_handler.py
handler/base_handler.py
import os from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): @truncated_stdout @with_payload def where(self, role=None): my_role = os.environ.get('ROLE', 'no_role') if my_role == role: print(self.my_info()) ...
import os from serf_master import SerfHandler from utils import with_payload, truncated_stdout class BaseHandler(SerfHandler): def __init__(self, *args, **kwargs): super(BaseHandler, self).__init__(*args, **kwargs) self.setup() def setup(self): pass @truncated_stdout @with_...
Add setup method to base serf handler
Add setup method to base serf handler
Python
mit
waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode
fa73ac1d9451cbef8be65cfcd2f03762831f4212
website_snippet_data_slider/__openerp__.py
website_snippet_data_slider/__openerp__.py
# -*- coding: utf-8 -*- # © 2016-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Snippet - Data Slider", "summary": "Abstract data slider for use on website. Primary use is product slider.", "version": "9.0.1.0.0", "category": "Website", "w...
# -*- coding: utf-8 -*- # © 2016-TODAY LasLabs Inc. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Website Snippet - Data Slider", "summary": "Abstract data slider for use on website." " Primary use (and default implementation) is product slider.", "version...
Update summary to fix flake in website_snippet_data_slider
Update summary to fix flake in website_snippet_data_slider
Python
agpl-3.0
laslabs/odoo-website,laslabs/odoo-website,laslabs/odoo-website
813b81293cd2bd69982aef36ad09fc52f7bea1f6
relaygram/http_server.py
relaygram/http_server.py
import http.server from threading import Thread import os.path class HTTPHandler: def __init__(self, config): self.config = config handler = HTTPHandler.make_http_handler('C:/tmp/test/') self.httpd = http.server.HTTPServer(('', 8000), handler) self.thread = Thread(target=self.mai...
import http.server from threading import Thread import os.path class HTTPHandler: def __init__(self, config): self.config = config handler = HTTPHandler.make_http_handler(self.config['media_dir']) self.httpd = http.server.HTTPServer(('', self.config['media']['port']), handler) se...
Use proper settings for httpd server.
Use proper settings for httpd server.
Python
mit
Surye/relaygram
103f232f6b4c12e1d1c643c48c5055d66d7a126d
workshopvenues/venues/tests/test_models.py
workshopvenues/venues/tests/test_models.py
""" This file demonstrates writing tests using the unittest module. These will pass when you run "./manage.py test --settings=workshopvenues.settings_test venues" Replace this with more appropriate tests for your application. """ from django.test import TestCase from .factories import FacilityFactory, CountryFactory,...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "./manage.py test --settings=workshopvenues.settings_test venues" Replace this with more appropriate tests for your application. """ from django.test import TestCase from .factories import FacilityFactory, CountryFactory,...
Add an additional test for Venue model to cover all the factory cases.
Add an additional test for Venue model to cover all the factory cases.
Python
bsd-3-clause
andreagrandi/workshopvenues
b977de3af3ae93a57f36e1d6eea234f01cbc7a61
py/selenium/__init__.py
py/selenium/__init__.py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
Remove import of Selenium RC
Remove import of Selenium RC
Python
apache-2.0
bayandin/selenium,carlosroh/selenium,asolntsev/selenium,Herst/selenium,alb-i986/selenium,joshuaduffy/selenium,oddui/selenium,TikhomirovSergey/selenium,sankha93/selenium,mojwang/selenium,lmtierney/selenium,carlosroh/selenium,jsakamoto/selenium,mach6/selenium,Herst/selenium,krmahadevan/selenium,DrMarcII/selenium,tbeadle/...
e0b2ce4b0287e8321cddde6c658a833dcf147974
features.py
features.py
import numpy as np def mean_energy(x_blocks): return np.sqrt(np.mean(x_blocks**2, axis=1)) if __name__ == '__main__': import matplotlib.pyplot as plt from files import load_wav from analysis import split_to_blocks def analyze_mean_energy(file, block_size=1024): x, fs = load_wav(file) ...
import numpy as np from numpy.linalg import norm def mean_power(x_blocks): return np.sqrt(np.mean(x_blocks**2, axis=-1)) def power(x_blocks): return np.sqrt(np.sum(x_blocks**2, axis=-1)) def mean_energy(x_blocks): return np.mean(x_blocks**2, axis=-1) def energy(x_blocks): return np.sum(x_blocks**2, ...
Add computation on energy and power (mean and total).
Add computation on energy and power (mean and total).
Python
mit
bzamecnik/tfr,bzamecnik/tfr
fc6aae454464aa31f1be401148645310ea9ee2b9
cloud4rpi/errors.py
cloud4rpi/errors.py
# -*- coding: utf-8 -*- import subprocess TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \ 'Change the variable type or the passed value.' \ class InvalidTokenError(Exception): pass class InvalidConfigError(TypeError): pass class UnexpectedVariableTypeError(Type...
# -*- coding: utf-8 -*- import subprocess TYPE_WARN_MSG = 'WARNING! A string "%s" passed to a numeric variable. ' \ 'Change the variable type or the passed value.' \ class InvalidTokenError(Exception): pass class InvalidConfigError(TypeError): pass class UnexpectedVariableTypeError(Type...
Fix receiving an error message for python2 & 3
Fix receiving an error message for python2 & 3
Python
mit
cloud4rpi/cloud4rpi
c17fed815cd062b37ebe5e6118da43afcf89db1f
relay_api/core/relay.py
relay_api/core/relay.py
import RPi.GPIO as GPIO class relay(): def __init__(self, gpio_num, NC=False): self.gpio_num = gpio_num GPIO.setmode(GPIO.BCM) try: GPIO.input(self.gpio_num) raise LookupError("Relay is already in use!") except RuntimeError: GPIO.setup(self.gpio_...
import RPi.GPIO as GPIO class relay(): def __init__(self, gpio_num, NC=False): self.gpio = gpio_num self.nc = NC GPIO.setmode(GPIO.BCM) try: GPIO.input(self.gpio) raise LookupError("Relay is already in use!") except RuntimeError: GPIO.set...
Add nc and state as attributes. Change name of gpio_num to gpio
Add nc and state as attributes. Change name of gpio_num to gpio
Python
mit
pahumadad/raspi-relay-api
abff14b5804bf43bc2bffeac6418259580bdbae5
makecard.py
makecard.py
#!/usr/bin/env python import svgwrite def main(): print 'test' if __name__ == '__main__': main()
#!/usr/bin/env python import sys import svgwrite def main(): drawing = svgwrite.Drawing(size=('1000', '1400')) img = svgwrite.image.Image('bullets/NYCS-bull-trans-1.svg',insert=(100, 100), size=(100,100)) drawing.add(img) sys.stdout.write(drawing.tostring()) if __name__ == '__main__': main()
Include the first bullet svg
Include the first bullet svg
Python
apache-2.0
nanaze/xmascard
b29e607d56ab07d07f4e33e2229a728cf0be1585
usability/python-markdown/pymdpreprocessor.py
usability/python-markdown/pymdpreprocessor.py
"""This preprocessor replaces Python code in markdowncell with the result stored in cell metadata """ #----------------------------------------------------------------------------- # Copyright (c) 2014, Juergen Hasch # # Distributed under the terms of the Modified BSD License. # #--------------------------------------...
# -*- coding: utf-8 -*- """This preprocessor replaces Python code in markdowncell with the result stored in cell metadata """ from nbconvert.preprocessors import * import re def get_variable( match, variables): try: x = variables[match] return x except KeyError: return "" class PyMar...
Update preprocessor for 4.x: New imports and make it more robust
Update preprocessor for 4.x: New imports and make it more robust
Python
bsd-3-clause
jbn/IPython-notebook-extensions,juhasch/IPython-notebook-extensions,ipython-contrib/IPython-notebook-extensions,Konubinix/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,andyneff/IPython-notebook-extensions,jcb91/IPython-notebook-extensions,andyneff/IPython-notebook-extensions,ipython-contrib/IPython-note...
dbe7c01ed649abb1cbd8efe07a6633951cb1943e
tests/integration/states/test_handle_error.py
tests/integration/states/test_handle_error.py
# -*- coding: utf-8 -*- ''' tests for host state ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.case import ModuleCase class HandleErrorTest(ModuleCase): ''' Validate that ordering works correctly ''' def test_handle_error(self): ...
# -*- coding: utf-8 -*- ''' tests for host state ''' # Import Python libs from __future__ import absolute_import, unicode_literals # Import Salt Testing libs from tests.support.case import ModuleCase class HandleErrorTest(ModuleCase): ''' Validate that ordering works correctly ''' def test_function_...
Update integration test: docs, add more checks, rename
Update integration test: docs, add more checks, rename
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
14414263ef7578ec0c710e99de0f62c49319c6be
saw-remote-api/python/tests/saw/test_provers.py
saw-remote-api/python/tests/saw/test_provers.py
from cryptol import cryptoltypes from cryptol.bitvector import BV import saw from saw.proofscript import * import unittest from pathlib import Path def cry(exp): return cryptoltypes.CryptolLiteral(exp) class ProverTest(unittest.TestCase): @classmethod def setUpClass(self): saw.connect(reset_ser...
from cryptol import cryptoltypes from cryptol.bitvector import BV import saw from saw.proofscript import * import unittest from pathlib import Path def cry(exp): return cryptoltypes.CryptolLiteral(exp) class ProverTest(unittest.TestCase): @classmethod def setUpClass(self): saw.connect(reset_ser...
Remove Yices test from RPC prover test
Remove Yices test from RPC prover test
Python
bsd-3-clause
GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script,GaloisInc/saw-script
61b9a0e69b2db362e526bd3312e0e47609a42fad
scenarios/UAC/bob_cfg.py
scenarios/UAC/bob_cfg.py
from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig allargs = (('SHA-512-256', 'SHA-256', 'MD5', 'MD5-sess'), \ ('SHA-512-256', 'SHA-256', 'SHA-256-sess', 'MD5'), \ ('SHA-512-256', 'SHA-512-256-sess', 'SHA-256', 'MD5')) \ class AUTH_CREDS(AUTH_CREDS_orig): enalgs = None realm = 'VoIPTests.NET' ...
from random import shuffle from lib.test_config import AUTH_CREDS as AUTH_CREDS_orig allalgs = (('SHA-512-256', 'SHA-256', 'MD5', 'MD5-sess'), \ ('SHA-512-256', 'SHA-256', 'SHA-256-sess', 'MD5'), \ ('SHA-512-256', 'SHA-512-256-sess', 'SHA-256', 'MD5')) \ class AUTH_CREDS(AUTH_CREDS_orig): enalgs = None re...
Fix typo: allargs -> allalgs. Add missing import of shuffle().
Fix typo: allargs -> allalgs. Add missing import of shuffle().
Python
bsd-2-clause
sippy/voiptests,sippy/voiptests
56471d264671b652b4b40619f709dc6b8e02eac1
dragonflow/db/models/host_route.py
dragonflow/db/models/host_route.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 # d...
# 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 # d...
Change HostRoute to a plain model
Change HostRoute to a plain model Since HostRoute doesn't have id, store it as a plain db model. Change-Id: I3dbb9e5ffa42bf48f47b7010ee6baf470b55e85e Partially-Implements: bp refactor-nb-api
Python
apache-2.0
openstack/dragonflow,openstack/dragonflow,openstack/dragonflow
2e1f4ffa667bcff2c10caf64be345f3e8619232f
python/simple_types.py
python/simple_types.py
# Many built-in types have built-in names assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == ra...
# Many built-in types have built-in names assert(type(5) == int) assert(type(True) == bool) assert(type(5.7) == float) assert(type(9 + 5j) == complex) assert(type((8, 'dog', False)) == tuple) assert(type('hello') == str) assert(type(b'hello') == bytes) assert(type([1, '', False]) == list) assert(type(range(1,10)) == ra...
Add example of date type in Python
Add example of date type in Python
Python
mit
rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal/polyglot,rtoal/ple,rtoal/ple,rtoal...
517a65e5fba0ec302a05ad550f473bd72a719398
test/test_recipes.py
test/test_recipes.py
from __future__ import print_function, absolute_import import json import os import sys from imp import reload from io import StringIO import pytest import yaml from adr import query from adr.main import run_recipe class new_run_query(object): def __init__(self, test): self.test = test def __call_...
from __future__ import print_function, absolute_import import json import os import sys from imp import reload from io import BytesIO, StringIO import pytest import yaml from adr import query from adr.main import run_recipe class new_run_query(object): def __init__(self, test): self.test = test de...
Fix python 2 error when dumping expected test results
Fix python 2 error when dumping expected test results
Python
mpl-2.0
ahal/active-data-recipes,ahal/active-data-recipes
5d21ad5ae63addac0892242fe774250a2934fc87
awx/lib/metrics.py
awx/lib/metrics.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging from functools import wraps from django_statsd.clients import statsd logger = logging.getLogger(__name__) def task_timer(fn): @wraps(fn) def __wrapped__(self, *args, **kwargs): statsd.incr('tasks.{}.{}.count'.format( ...
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging from functools import wraps from django_statsd.clients import statsd logger = logging.getLogger(__name__) def task_timer(fn): @wraps(fn) def __wrapped__(self, *args, **kwargs): statsd.incr('tasks.{0}.{1}.count'.format( ...
Fix up statsd work to support python 2.6
Fix up statsd work to support python 2.6 Format specifiers must include field specifier
Python
apache-2.0
snahelou/awx,wwitzel3/awx,wwitzel3/awx,wwitzel3/awx,snahelou/awx,snahelou/awx,snahelou/awx,wwitzel3/awx
432323eaf442db41d6486841168c159732d8dfe0
bhgcal/__init__.py
bhgcal/__init__.py
from __future__ import unicode_literals import os from datetime import datetime from dateutil.relativedelta import relativedelta import requests login_url = 'http://bukkesprangetnatur.barnehage.no/LogOn' ics_url = ('http://bukkesprangetnatur.barnehage.no/Ukeplan/' 'PlanMonthAsICalendar/61?year={year}&mont...
from __future__ import unicode_literals from datetime import datetime import os import sys from dateutil.relativedelta import relativedelta import requests bases = {'r\xf8sslyngen': 59, 'myrulla': 61} login_url = 'http://bukkesprangetnatur.barnehage.no/LogOn' ics_url = ('http://bukkesprangetnatur.barnehage...
Support iterating over the different bases
Support iterating over the different bases And fix the encoding issue that suddenly became obvious.
Python
mit
asmundg/bhgcal
eb1568e9baf3d60a8d1e3ea59c49d54dc7b34437
tests/test_pgbackup.py
tests/test_pgbackup.py
# coding: utf-8 """ Unit tests for essential functions in postgresql backup. """ from unittest.mock import MagicMock, mock_open, patch import pytest import smdba.postgresqlgate class TestPgBackup: """ Test suite for postgresql backup. """ @patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_...
# coding: utf-8 """ Unit tests for essential functions in postgresql backup. """ from unittest.mock import MagicMock, mock_open, patch import pytest import smdba.postgresqlgate class TestPgBackup: """ Test suite for postgresql backup. """ @patch("smdba.postgresqlgate.os.path.exists", MagicMock(return_...
Add test for constructor of pgbackup for pg_data is set correctly.
Add test for constructor of pgbackup for pg_data is set correctly.
Python
mit
SUSE/smdba,SUSE/smdba
643c60364266c9015b919a39ff8f0807e6138efc
fileupload/views.py
fileupload/views.py
from fileupload.models import Picture from django.views.generic import CreateView, DeleteView from django.http import HttpResponse from django.utils import simplejson from django.core.urlresolvers import reverse from django.conf import settings class PictureCreateView(CreateView): model = Picture def form_v...
from fileupload.models import Picture from django.views.generic import CreateView, DeleteView from django.http import HttpResponse from django.utils import simplejson from django.core.urlresolvers import reverse from django.conf import settings class PictureCreateView(CreateView): model = Picture def form_v...
Add comment about browsers not liking application/json.
Add comment about browsers not liking application/json.
Python
mit
Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,minhlongdo/django-jquery-file-upload,extremoburo/django-jquery-file-upload,Imaginashion/cloud-vision,Imaginashion/cloud-vision,extremoburo/django-jquery-file-upload,vaniakov/django-jquery-file-upload,vaniakov/django-jquery-file-upload,madteckhead/django-jq...
6672a0634265e09366a9274d3c2a04afca49cf02
dirtree_filter.py
dirtree_filter.py
class DirTreeFilter(object): def __init__(self, show_hidden=False, show_files=True, show_dirs=True): self.show_hidden = show_hidden self.show_files = show_files self.show_dirs = show_dirs self.hidden_exts = [".pyc", ".pyo", ".o", ".a", ".obj", ".lib", ".swp", "~"] self.hidden...
import re def compile_file_patterns(patterns): return re.compile("$%s^" % "|".join("(%s)" % re.escape(p).replace("\\*", ".*") for p in patterns)) hidden_files = [".*", "*~", "*.swp", "*.pyc", "*.pyo", "*.o", "*.a", "*.obj", "*.lib", "*.class"] hidden_dirs = ["CVS", "__pycache__"] class DirTreeFilter(object): ...
Use file patterns compiled to regular expressions to match hidden files.
Use file patterns compiled to regular expressions to match hidden files.
Python
mit
shaurz/devo
5b215758adab39923399db98b5975fc76d389472
__init__.py
__init__.py
# -*- coding: utf-8 -*- import configparser import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [option] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify con...
# -*- coding: utf-8 -*- import optparse from blo import Blo if __name__ == '__main__': parser = optparse.OptionParser("usage: %prog [options] markdown_file.md") parser.add_option("-c", "--config", dest="config_file", default="./blo.cfg", type="string", help="specify configuration file pat...
Implement main section of blo package.
Implement main section of blo package.
Python
mit
10nin/blo,10nin/blo
357fc83908fe09da2c69be78afdae9f1cf5c4b0d
hjlog/forms/post.py
hjlog/forms/post.py
from flask_wtf import Form from wtforms import TextAreaField, StringField, SelectField, BooleanField from wtforms.validators import InputRequired, Optional, Length class PostForm(Form): title = StringField('제목', validators=[InputRequired(), Length(max=120)]) body = TextAreaField('내용', validators=[InputRequired...
from flask_wtf import Form from wtforms import TextAreaField, StringField, SelectField, BooleanField from wtforms.validators import InputRequired, Optional, Length class PostForm(Form): title = StringField('제목', validators=[InputRequired(), Length(max=120)]) body = TextAreaField('내용', validators=[InputRequired...
Change label text of 'private' Field
Change label text of 'private' Field
Python
mit
heejongahn/hjlog,heejongahn/hjlog,heejongahn/hjlog,heejongahn/hjlog
b3839c72a831589dd707b38ae2088fd4b304faa1
django_filters/rest_framework/filterset.py
django_filters/rest_framework/filterset.py
from __future__ import absolute_import from copy import deepcopy from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from django_filters import filterset from .filters import BooleanFilter, IsoDateTimeFilter from .. import compat, utils FILTER_FOR_DBFIELD_D...
from __future__ import absolute_import from copy import deepcopy from django.db import models from django import forms from django.utils.translation import ugettext_lazy as _ from django_filters import filterset from .filters import BooleanFilter, IsoDateTimeFilter from .. import compat, utils FILTER_FOR_DBFIELD_D...
Move crispy helper to '.form' property
Move crispy helper to '.form' property
Python
bsd-3-clause
alex/django-filter,alex/django-filter
550106fbff26c16cdf2269dc0778814c05ed1e3b
nap/apps.py
nap/apps.py
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
from django.apps import AppConfig from django.utils.module_loading import autodiscover_modules class NapConfig(AppConfig): '''App Config that performs auto-discover on ready.''' name = 'nap' def ready(self): super(NapConfig, self).ready() autodiscover_modules('publishers')
Fix to include mandatory name attribute
Fix to include mandatory name attribute
Python
bsd-3-clause
MarkusH/django-nap,limbera/django-nap
14398ec42c0d31d577278d8748b0617650f91775
porick/controllers/create.py
porick/controllers/create.py
import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log...
import logging from pylons import request, response, session, tmpl_context as c, url from pylons.controllers.util import abort, redirect import porick.lib.helpers as h from porick.lib.auth import authorize from porick.lib.base import BaseController, render from porick.lib.create import create_quote, create_user log...
Deal with comma-separated tags lists HNGH
Deal with comma-separated tags lists HNGH
Python
apache-2.0
kopf/porick,kopf/porick,kopf/porick
99bd91cac200f9e83ee710ac8758fd20ac1febfa
examples/find_facial_features_in_picture.py
examples/find_facial_features_in_picture.py
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("biden.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph.".fo...
from PIL import Image, ImageDraw import face_recognition # Load the jpg file into a numpy array image = face_recognition.load_image_file("two_people.jpg") # Find all facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) print("I found {} face(s) in this photograph...
Tweak demo to show multiple faces in one window instead of separate windows
Tweak demo to show multiple faces in one window instead of separate windows
Python
mit
ageitgey/face_recognition
5b2e154fe28a32eb128c9c1060c1954eb1664c3f
child_sync_typo3/wizard/child_depart_wizard.py
child_sync_typo3/wizard/child_depart_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __open...
# -*- encoding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __open...
Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
Correct wrong inheritance on sponsorship_typo3 child_depart wizard.
Python
agpl-3.0
eicher31/compassion-switzerland,ecino/compassion-switzerland,Secheron/compassion-switzerland,ecino/compassion-switzerland,eicher31/compassion-switzerland,ndtran/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,Secheron/compassion-switzerland,eicher31/compassion-switzerland,...
5293a24bc2ab6a3aa1c9fc98d857c79548509356
explanatory_style.py
explanatory_style.py
import gate class EventAttributionUnit: """event, attribution must be gate.Annotation objects """ def __init__(self, event, attribution): self._event = event self._attribution = attribution for annotation in [self._event, self._attribution]: # if type(anntotation) != "A...
import gate class EventAttributionUnit: def __init__(self, event, attribution): """event, attribution must be gate.Annotation objects """ self._event = event self._attribution = attribution for annotation in [self._event, self._attribution]: if not isinstance(an...
Add __main__ program for running on files
Add __main__ program for running on files
Python
mit
nickwbarber/HILT-annotations
b1196e347129e79bd616cc572714982be6739d3c
indra/pipeline/decorators.py
indra/pipeline/decorators.py
pipeline_functions = {} def register_pipeline(function): if function.__name__ in pipeline_functions: raise ExistingFunctionError( '%s is already registered with %s.%s' % ( function.__name__, function.__module__, function.__name__)) pipeline_functions[function.__name__] = fu...
pipeline_functions = {} def register_pipeline(function): """Decorator to register a function for the assembly pipeline.""" if function.__name__ in pipeline_functions: raise ExistingFunctionError( '%s is already registered with %s.%s' % ( function.__name__, function.__module...
Add minimal docstring for decorator
Add minimal docstring for decorator
Python
bsd-2-clause
johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,bgyori/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra
b69bf4dd6e9c1d8b9133c2a8f2b18ac8d41f3145
src/streaming-programs/car-average-speeds.py
src/streaming-programs/car-average-speeds.py
#!/usr/bin/python import sys import json # Count average speeds for links def main(locationdata_dictionary_file): locationdata = {} with open(locationdata_dictionary_file, "r") as dictionary_file: locationdata = json.load(dictionary_file) for input_line in sys.stdin: data = json.loads(in...
#!/usr/bin/python import sys import json # Count average speeds for links def main(locationdata_dictionary_file): locationdata = {} with open(locationdata_dictionary_file, "r") as dictionary_file: locationdata = json.load(dictionary_file) for input_line in sys.stdin: data = json.loads(in...
Use default dictionary when no arg passed
Use default dictionary when no arg passed
Python
mit
gofore/aws-emr,gofore/aws-emr,gofore/aws-emr,gofore/aws-emr
6ee4cd2ace969365a4898e3f89944e8ddbdca1c8
wolme/wallet/models.py
wolme/wallet/models.py
from __future__ import unicode_literals from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext as _ @python_2_unicode_compatible class Tag(models.Model): slug = models.SlugField(unique=True) des...
from __future__ import unicode_literals from django.conf import settings from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext as _ @python_2_unicode_compatible class Tag(models.Model): slug = mod...
Add default to movement date
Add default to movement date
Python
bsd-2-clause
synasius/wolme
cbc60512f0f29ba3444573b6fd835e1505e5e35c
radar/radar/validation/fetal_anomaly_scans.py
radar/radar/validation/fetal_anomaly_scans.py
from radar.validation.data_sources import DataSourceValidationMixin from radar.validation.core import Field, Validation from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, optional, min_, max_, none_if_blank...
from radar.validation.data_sources import DataSourceValidationMixin from radar.validation.core import Field, Validation from radar.validation.meta import MetaValidationMixin from radar.validation.patients import PatientValidationMixin from radar.validation.validators import required, optional, min_, max_, none_if_blank...
Check date of scan is not in future
Check date of scan is not in future
Python
agpl-3.0
renalreg/radar,renalreg/radar,renalreg/radar,renalreg/radar
6ef190887b38df4f5212a8a7017e002051734c9f
lokar/bib.py
lokar/bib.py
# coding=utf-8 from __future__ import unicode_literals from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') self.init(xml) def in...
# coding=utf-8 from __future__ import unicode_literals from io import BytesIO from .marc import Record from .util import etree, parse_xml, show_diff class Bib(object): """ An Alma Bib record """ def __init__(self, alma, xml): self.alma = alma self.orig_xml = xml.encode('utf-8') sel...
Add xml header and post data as stream-like object just to be sure
Add xml header and post data as stream-like object just to be sure
Python
agpl-3.0
scriptotek/almar,scriptotek/lokar
e9f2a3c29185466f1c92121e9f4e4b727fb20fd0
scripts/rename_tutorial_src_files.py
scripts/rename_tutorial_src_files.py
#%% from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") dirs = sorted([Path(f) for f in directory.iterdir()]) d: PurePath sufix = "__out__" for d in dirs: if d.name.endswith(sufix): continue output_dir_name = d.name + "__out__" output_directory = dir...
#%% from pathlib import Path, PurePath from string import digits directory = Path("./docs/tutorial/src") skip_names = {"bigger_applications"} skip_dirs = {directory / name for name in skip_names} dirs = sorted([Path(f) for f in directory.iterdir() if f not in skip_dirs]) d: PurePath sufix = "__out__" for d in dirs: ...
Update tutorial renamer to exclude files
:sparkles: Update tutorial renamer to exclude files
Python
mit
tiangolo/fastapi,tiangolo/fastapi,tiangolo/fastapi
0998953838a36cec14ab356d13e84732fb02167a
examples/tf/demo.py
examples/tf/demo.py
# python3 # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
# python3 # Copyright 2020 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
Add online prediction example for TF
Add online prediction example for TF Change-Id: I508aaca04576b3bda500fae3350351ef7b251747
Python
apache-2.0
GoogleCloudPlatform/ml-pipeline-generator-python,GoogleCloudPlatform/ml-pipeline-generator-python
4563ad431102bd578582dfd6af41fe68ac7c6c26
examples/basic.py
examples/basic.py
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 # A simpleflow activity can b...
import time from simpleflow import ( activity, Workflow, futures, ) @activity.with_attributes(task_list='quickstart', version='example') def increment(x): return x + 1 @activity.with_attributes(task_list='quickstart', version='example') def double(x): return x * 2 @activity.with_attributes(ta...
Revert "Update example workflow to show you can use classes"
Revert "Update example workflow to show you can use classes" This reverts commit dbce79102efa8fee233af95939f1ff0b9d060b00.
Python
mit
botify-labs/simpleflow,botify-labs/simpleflow
bd0a572faf851ee01177c44fc2fe64770ab4f38a
app/main/views/index.py
app/main/views/index.py
import markdown import os from flask import render_template, url_for, redirect, Markup from app.main import main from flask_login import login_required from flask.ext.login import current_user from mdx_gfm import GithubFlavoredMarkdownExtension @main.route('/') def index(): if current_user and current_user.is_au...
import markdown import os from flask import render_template, url_for, redirect, Markup from app.main import main from flask_login import login_required from flask.ext.login import current_user from mdx_gfm import GithubFlavoredMarkdownExtension @main.route('/') def index(): if current_user and current_user.is_au...
Add encoding to the documentation file.
Add encoding to the documentation file.
Python
mit
alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin
b235ae762adb76fe9835d98f7e2a4fc3d92db251
src/util/sortLargeFIs.py
src/util/sortLargeFIs.py
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): ...
import os, sys from operator import itemgetter def errorExit(msg): sys.stderr.write(msg) sys.exit(1) def main(): # Verify arguments if len(sys.argv) != 2: errorExit("Usage: {} FILE\n".format(os.path.basename(sys.argv[0]))) fileName = sys.argv[1] if not os.path.isfile(fileName): ...
Modify to handle ARtool output
Modify to handle ARtool output
Python
apache-2.0
jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules,jdebrabant/parallel_arules
f22fa6d0c1b7e3bde95554f87af7254c2c381c41
django_app_lti/urls.py
django_app_lti/urls.py
from django.urls import path from .views import LTILaunchView, LTIToolConfigView, logout_view, logged_out_view urlpatterns = [ path('', LTILaunchView.as_view(), name='index'), path('launch', LTILaunchView.as_view(), name='launch'), path('config', LTIToolConfigView.as_view(), name='config'), path('logou...
from django.urls import path from .views import LTILaunchView, LTIToolConfigView, logout_view, logged_out_view app_name = 'lti' urlpatterns = [ path('', LTILaunchView.as_view(), name='index'), path('launch', LTILaunchView.as_view(), name='launch'), path('config', LTIToolConfigView.as_view(), name='config')...
Add app_name to url module
Add app_name to url module
Python
bsd-3-clause
Harvard-ATG/django-app-lti
1f8cc2ffe1f4c9b390a5dc19a2bd9eb4601f0055
ledger/migrations/0002_auto_20170717_2255.py
ledger/migrations/0002_auto_20170717_2255.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 03:55 from __future__ import unicode_literals from django.db import migrations, connection def load_data(apps, schema_editor): Account = apps.get_model("ledger", "Account") Account(name="Cash", type="asset").save() Account(name="Bank", t...
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-18 03:55 from __future__ import unicode_literals from django.db import migrations, connection def load_data(apps, schema_editor): Account = apps.get_model("ledger", "Account") Account(name="Cash", type="asset").save() Account(name="Bank", t...
Add a balance (equity) account
Add a balance (equity) account
Python
mpl-2.0
jackbravo/condorest-django,jackbravo/condorest-django,jackbravo/condorest-django
6908fb4f5796e0b2f44ce93f54227f3873bb9a9b
masters/master.client.dart.packages/packages.py
masters/master.client.dart.packages/packages.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. PACKAGES = [ { 'name' : 'core-elements', 'package_dependencies' : [], }, { 'name' : 'paper-elements', 'package_dependencies' : ['core-e...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. PACKAGES = [ { 'name' : 'core-elements', 'package_dependencies' : [], }, { 'name' : 'paper-elements', 'package_dependencies' : ['core-e...
Add googleapis_auth to dart package waterfall
Add googleapis_auth to dart package waterfall Review URL: https://codereview.chromium.org/574283003 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291992 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
924bee7b0a8b11aa0f1506584966533924d29478
django_hash_filter/templatetags/hash_filter.py
django_hash_filter/templatetags/hash_filter.py
from django import template from django.template.defaultfilters import stringfilter from django.template.base import TemplateSyntaxError import hashlib from django_hash_filter.templatetags import get_available_hashes register = template.Library() @register.filter @stringfilter def hash(value, arg): """ Return...
from django import template from django.template.defaultfilters import stringfilter from django.template.base import TemplateSyntaxError import hashlib from django_hash_filter.templatetags import get_available_hashes register = template.Library() @register.filter @stringfilter def hash(value, arg): """ Return...
Add helpful text to template error
Add helpful text to template error
Python
mit
andrewjsledge/django-hash-filter
aa10d2c0d49fd28afcda2b67f969fdb4a1d3072b
backend/breach/views.py
backend/breach/views.py
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt def get_work(request): return HttpResponse('Not implemented') @csrf_exempt def work_completed(request): return HttpResponse('Not implemented')
import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt def create_new_work(): return {'url': 'https://www.dimkarakostas.com/?breach-test', 'amount': 10, 'timeout': 0} def get_work(request): new_work = create_new_work() return HttpRes...
Change get_work to response with work JSON
Change get_work to response with work JSON
Python
mit
dimkarakostas/rupture,esarafianou/rupture,dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,dimriou/rupture,dimk...
804edb8d7423ee882e483bec8ffe551a168602b4
contentstore/models.py
contentstore/models.py
from django.db import models from django.utils.translation import ugettext_lazy as _ class Schedule(models.Model): minute = models.CharField(_('minute'), max_length=64, default='*') hour = models.CharField(_('hour'), max_length=64, default='*') day_of_week = models.CharField( _('day of week'), max...
from django.db import models from django.utils.translation import ugettext_lazy as _ class Schedule(models.Model): """ Schdules (sometimes referred to as Protocols) are the method used to define the rate and frequency at which the messages are sent to the recipient """ minute = models.CharFie...
Add docstring to Schedule model
Add docstring to Schedule model
Python
bsd-3-clause
praekelt/django-messaging-contentstore,praekelt/django-messaging-contentstore
0f7853c3568791f0e93ece57d2fc750dbc93b963
starlette/concurrency.py
starlette/concurrency.py
import asyncio import functools import typing from typing import Any, AsyncGenerator, Iterator try: import contextvars # Python 3.7+ only. except ImportError: # pragma: no cover contextvars = None # type: ignore async def run_in_threadpool( func: typing.Callable, *args: typing.Any, **kwargs: typing.An...
import asyncio import functools import typing from typing import Any, AsyncGenerator, Iterator try: import contextvars # Python 3.7+ only. except ImportError: # pragma: no cover contextvars = None # type: ignore T = typing.TypeVar("T") async def run_in_threadpool( func: typing.Callable[..., T], *args...
Add type hint for run_in_threadpool return type
Add type hint for run_in_threadpool return type
Python
bsd-3-clause
encode/starlette,encode/starlette
52c7efbe7f9a24f568768fb926f487a276a47f51
numba/typesystem/exttypes/attributestype.py
numba/typesystem/exttypes/attributestype.py
# -*- coding: utf-8 -*- """ Extension attribute table type. Supports ordered (struct) fields, or unordered (hash-based) fields. """ from numba.typesystem import * from numba.typesystem.exttypes import ordering #------------------------------------------------------------------------ # Extension Attributes Type #----...
# -*- coding: utf-8 -*- """ Extension attribute table type. Supports ordered (struct) fields, or unordered (hash-based) fields. """ import numba from numba.typesystem import NumbaType, is_obj from numba.typesystem.exttypes import ordering #------------------------------------------------------------------------ # Ex...
Add to_struct to attribute table
Add to_struct to attribute table
Python
bsd-2-clause
gmarkall/numba,sklam/numba,GaZ3ll3/numba,stonebig/numba,IntelLabs/numba,IntelLabs/numba,GaZ3ll3/numba,cpcloud/numba,GaZ3ll3/numba,seibert/numba,GaZ3ll3/numba,gdementen/numba,gdementen/numba,sklam/numba,cpcloud/numba,stuartarchibald/numba,stuartarchibald/numba,shiquanwang/numba,stefanseefeld/numba,shiquanwang/numba,Inte...
3075a10c56fb38611134aa15c06b6da8cc777868
enthought/pyface/tasks/task_window_layout.py
enthought/pyface/tasks/task_window_layout.py
# Enthought library imports. from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \ Tuple # Local imports. from task_layout import TaskLayout class TaskWindowLayout(HasStrictTraits): """ A picklable object that describes the layout and state of a TaskWindow. """ # The ID of ...
# Enthought library imports. from enthought.traits.api import Dict, HasStrictTraits, Instance, List, Str, \ Tuple # Local imports. from task_layout import TaskLayout class TaskWindowLayout(HasStrictTraits): """ A picklable object that describes the layout and state of a TaskWindow. """ # The ID of ...
Add a few useful utility methods to TaskWindowLayout.
Add a few useful utility methods to TaskWindowLayout.
Python
bsd-3-clause
brett-patterson/pyface,pankajp/pyface,geggo/pyface,geggo/pyface,enthought/traitsgui
663f44e94c22f8ac889a1d7608e6ab0e3cbf9ad3
checkeol.py
checkeol.py
# Check files for incorrect newlines import fnmatch, os def check_file(fname): for n, line in enumerate(open(fname, "rb")): if "\r" in line: print "%s@%d: CR found" % (fname, n) return def check_files(root, patterns): for root, dirs, files in os.walk(root): for f in fi...
# Check files for incorrect newlines import fnmatch, os def check_file(fname): for n, line in enumerate(open(fname, "rb")): if "\r" in line: print "%s@%d: CR found" % (fname, n) return def check_files(root, patterns): for root, dirs, files in os.walk(root): for f in fi...
Check on the EOL chars in ,cover gold files.
Check on the EOL chars in ,cover gold files.
Python
apache-2.0
larsbutler/coveragepy,jayhetee/coveragepy,nedbat/coveragepy,blueyed/coveragepy,hugovk/coveragepy,7WebPages/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,larsbutler/coveragepy,hugovk/coveragepy,nedbat/coveragepy,jayhetee/coveragepy,hug...
251e13b96ed10e48b69ccf5d625d673a5507f222
requests_kerberos/__init__.py
requests_kerberos/__init__.py
""" requests Kerberos/GSSAPI authentication library ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. This library adds optional Kerberos/GSSAPI authentication support and supports mutual authentication. Basic GET usage: >>> import requests >>> f...
""" requests Kerberos/GSSAPI authentication library ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Requests is an HTTP library, written in Python, for human beings. This library adds optional Kerberos/GSSAPI authentication support and supports mutual authentication. Basic GET usage: >>> import requests >>> f...
Remove REQUIRED, OPTIONAL, DISABLED from default exports
Remove REQUIRED, OPTIONAL, DISABLED from default exports Prevent polluting the callers namespace with generically named constants.
Python
isc
requests/requests-kerberos,AbsoluteMSTR/requests-kerberos,rbcarson/requests-kerberos,requests/requests-kerberos,danc86/requests-kerberos
bcc3a4e4c8b3117deea4c7621653f65b588537f9
keystone/common/policies/token_revocation.py
keystone/common/policies/token_revocation.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...
Add scope_types to token revocation policies
Add scope_types to token revocation policies This doesn't seem useful since the API will return an empty list regardless because PKI support has been removed. More or less doing this for consistency. Change-Id: Iaa2925119fa6c9e2324546ed44aa54bac51dba05
Python
apache-2.0
mahak/keystone,openstack/keystone,openstack/keystone,mahak/keystone,openstack/keystone,mahak/keystone
c7ed2e94f10b680eef9942f2bda1d246f11595c5
src/foremast/consts.py
src/foremast/consts.py
"""Load base config and export package constants.""" import logging from configparser import ConfigParser from os.path import expanduser LOG = logging.getLogger(__name__) def find_config(): """Look for config in config_locations. If not found, give a fatal error. Returns: ConfigParser: found configu...
"""Load base config and export package constants.""" import logging from configparser import ConfigParser from os.path import expanduser LOG = logging.getLogger(__name__) def find_config(): """Look for **foremast.cfg** in config_locations. If not found, give a fatal error. Returns: ConfigParser...
Update docstring to include config file name
docs: Update docstring to include config file name
Python
apache-2.0
gogoair/foremast,gogoair/foremast