commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
fa78c5b5442c904ba3888b858eb2c284f16664ed | pages/urls/page.py | pages/urls/page.py | from django.conf.urls import include, patterns, url
from rest_framework.routers import SimpleRouter
from .. import views
router = SimpleRouter(trailing_slash=False)
router.register(r'pages', views.PageViewSet)
urlpatterns = patterns('',
url(r'', include(router.urls)),
)
| from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
from .. import views
router = SimpleRouter(trailing_slash=False)
router.register(r'pages', views.PageViewSet)
urlpatterns = [
url(r'', include(router.urls)),
]
| Purge unnecessary patterns function from urls | Purge unnecessary patterns function from urls
| Python | bsd-2-clause | incuna/feincms-pages-api | ---
+++
@@ -1,4 +1,4 @@
-from django.conf.urls import include, patterns, url
+from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
@@ -8,6 +8,6 @@
router = SimpleRouter(trailing_slash=False)
router.register(r'pages', views.PageViewSet)
-urlpatterns = patterns('',
+urlpatt... |
13f3d7d4a708cd05712b610d979dcf857ae85856 | Agents/SentinelDefense.py | Agents/SentinelDefense.py |
from pysc2.agents import base_agents
from pysc2.lib import actions
## SENTINEL FUNCTIONS
# Functions related with Hallucination
_HAL_ADEPT = actions.FUNCTIONS.Hallucination_Adept_quick.id
_HAL_ARCHON = actions.FUNCTIONS.Hallucination_Archon_quick.id
_HAL_COL = actions.FUNCTIONS.Hallucination_Colossus_quick.id
_HAL... |
from pysc2.agents import base_agents
from pysc2.lib import actions
Class Sentry():
'''Defines how the sentry SC2 unit works'''
def Force_Field():
'''Function related with Force Field creation'''
_FORCE_FIELD = actions.FUNCTIONS.Effect_ForceField_screen.id
def Guardian_Shield():
'''Function ... | Define class sentry with main actions | Define class sentry with main actions | Python | apache-2.0 | SoyGema/Startcraft_pysc2_minigames | ---
+++
@@ -2,24 +2,37 @@
from pysc2.agents import base_agents
from pysc2.lib import actions
+Class Sentry():
+ '''Defines how the sentry SC2 unit works'''
+
+ def Force_Field():
+ '''Function related with Force Field creation'''
+ _FORCE_FIELD = actions.FUNCTIONS.Effect_ForceField_screen.id
-## SENTI... |
1c01b9e794445242c450534d1615a9dc755b89da | randcat.py | randcat.py | import random
random.seed()
while True:
print(chr(random.getrandbits(8)), end='')
| #! /usr/bin/python3
import random
random.seed() # this initializes with the Date, which I think is a novel enough seed
while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed
print(chr(random.getrandbits(8)), end='')
| Add some comments and a shebang on top. | Add some comments and a shebang on top.
| Python | apache-2.0 | Tombert/RandCat | ---
+++
@@ -1,6 +1,7 @@
+#! /usr/bin/python3
import random
-random.seed()
+random.seed() # this initializes with the Date, which I think is a novel enough seed
-while True:
- print(chr(random.getrandbits(8)), end='')
+while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go u... |
f897c6e6e592990291983b29324a1e85fc636b2a | python/setup.py | python/setup.py | from setuptools import setup
import sys
sys.path += ['src']
setup(
name = "epidb-client",
version = '0.1.2',
url = 'http://www.epiwork.eu/',
description = 'EPIWork Database - Client Code',
author = 'Fajran Iman Rusadi',
package_dir = {'': 'src'},
packages = ['epidb_client'],
install_re... | from setuptools import setup
import sys
sys.path += ['src']
setup(
name = "epidb-client",
version = '0.1.2',
url = 'http://www.epiwork.eu/',
description = 'EPIWork Database - Client Code',
author = 'Fajran Iman Rusadi',
package_dir = {'': 'src'},
packages = ['epidb_client'],
requires =... | Move simplejson to requires, not install_requires. | Move simplejson to requires, not install_requires.
| Python | agpl-3.0 | ISIFoundation/influenzanet-epidb-client | ---
+++
@@ -11,7 +11,7 @@
author = 'Fajran Iman Rusadi',
package_dir = {'': 'src'},
packages = ['epidb_client'],
- install_requires = ['simplejson'],
+ requires = ['simplejson'],
test_suite = 'epidb_client.tests',
)
|
28940582fcff57b66e702dfecfd96e83725fbab0 | leisure/__init__.py | leisure/__init__.py | # -*- coding: utf-8 -*-
"""
leisure
~~~~~~~~
Leisure a local job runner for Disco based project.
It provides a useful method for running your disco project without
needing a full disco cluster. This makes it a snap to develop and
debug jobs on your development machine.
To use, simply ex... | # -*- coding: utf-8 -*-
"""
leisure
~~~~~~~~
Leisure a local job runner for Disco based project.
It provides a useful method for running your disco project without
needing a full disco cluster. This makes it a snap to develop and
debug jobs on your development machine.
To use, simply ex... | Add script's path to the python path | Add script's path to the python path | Python | mit | trivio/leisure | ---
+++
@@ -27,6 +27,7 @@
from __future__ import absolute_import
import sys
+import os
from .disco import run_script
from . import shuffle
@@ -35,6 +36,10 @@
def main():
script = sys.argv[1]
+ script_dir = os.path.abspath(os.path.dirname(script))
+ if script_dir not in [os.path.abspath(p) for p in sys... |
589bc468783e6c7620c3be21195fdbe88e796234 | linguist/helpers.py | linguist/helpers.py | # -*- coding: utf-8 -*-
import collections
import itertools
from . import utils
def prefetch_translations(instances, **kwargs):
"""
Prefetches translations for the given instances.
Can be useful for a list of instances.
"""
from .mixins import ModelMixin
populate_missing = kwargs.get('popula... | # -*- coding: utf-8 -*-
import collections
import itertools
from . import utils
def prefetch_translations(instances, **kwargs):
"""
Prefetches translations for the given instances.
Can be useful for a list of instances.
"""
from .mixins import ModelMixin
if not isinstance(instances, collecti... | Fix prefetch_translations() -- be sure we only deal with iteratables. | Fix prefetch_translations() -- be sure we only deal with iteratables.
| Python | mit | ulule/django-linguist | ---
+++
@@ -11,6 +11,9 @@
Can be useful for a list of instances.
"""
from .mixins import ModelMixin
+
+ if not isinstance(instances, collections.Iterable):
+ instances = [instances]
populate_missing = kwargs.get('populate_missing', True)
grouped_translations = utils.get_grouped_tr... |
2f8a2fdad8deb96b7b3c971baf866f248c23fdda | madam_rest/views.py | madam_rest/views.py | from flask import jsonify, url_for
from madam_rest import app, asset_storage
@app.route('/assets/')
def assets_retrieve():
assets = [asset_key for asset_key in asset_storage]
return jsonify({
"data": assets,
"meta": {
"count": len(assets)
}
})
@app.route('/assets/<as... | from datetime import datetime
from flask import jsonify, url_for
from fractions import Fraction
from frozendict import frozendict
from madam_rest import app, asset_storage
def _serializable(value):
"""
Utility function to convert data structures with immutable types to
mutable, serializable data structur... | Improve serialization of asset metadata. | Improve serialization of asset metadata.
| Python | agpl-3.0 | eseifert/madam-rest | ---
+++
@@ -1,6 +1,27 @@
+from datetime import datetime
from flask import jsonify, url_for
+from fractions import Fraction
+from frozendict import frozendict
from madam_rest import app, asset_storage
+
+
+def _serializable(value):
+ """
+ Utility function to convert data structures with immutable types to
+... |
bae4032cc686fbac906d19456ed744a97b0e1365 | characters/views.py | characters/views.py | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... | from django.shortcuts import get_object_or_404, redirect, render
from characters.forms import CharacterForm
from characters.models import Character, Class, Race
def index(request):
all_characters = Character.objects.all()
context = {'all_characters': all_characters}
return render(request, 'characters/ind... | Set default race and class without extra database queries | Set default race and class without extra database queries
| Python | mit | mpirnat/django-tutorial-v2 | ---
+++
@@ -21,14 +21,11 @@
if request.method == 'POST' and form.is_valid():
- race = Race.objects.get(id=1)
- cclass = Class.objects.get(id=1)
-
character = Character(
name=request.POST['name'],
background=request.POST['background'],
- ... |
1549aa29892ec30e0926b7a92d1c0d8857edc8d5 | shub/utils.py | shub/utils.py | import imp, os, netrc, ConfigParser
SCRAPY_CFG_FILE = os.path.expanduser("~/.scrapy.cfg")
NETRC_FILE = os.path.expanduser('~/.netrc')
def missing_modules(*modules):
"""Receives a list of module names and returns those which are missing"""
missing = []
for module_name in modules:
try:
i... | import imp, os, netrc, ConfigParser
SCRAPY_CFG_FILE = os.path.expanduser("~/.scrapy.cfg")
NETRC_FILE = os.path.expanduser('~/.netrc')
def missing_modules(*modules):
"""Receives a list of module names and returns those which are missing"""
missing = []
for module_name in modules:
try:
i... | Fix prefix in environment variable that contains SH's key | Fix prefix in environment variable that contains SH's key
| Python | bsd-3-clause | scrapinghub/shub | ---
+++
@@ -15,7 +15,7 @@
def find_api_key():
"""Finds and returns the Scrapy Cloud APIKEY"""
- key = os.getenv("SH_APIKEY")
+ key = os.getenv("SHUB_APIKEY")
if not key:
key = get_key_netrc()
return key |
6a4dd66035956037d660271f18592af04edab818 | read_images.py | read_images.py | import time
import cv2
import os
import glob
# path = 'by_class'
path = 'test'
t1 = time.time()
file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]'))
t2 = time.time()
print('Time to list files: ', t2-t1)
file_classes=[ele.split('/')[1] for ele in file_names]
t3 = time.time()
print('Time to list lab... | import time
import os
import glob
import tensorflow as tf
# path = 'by_class'
path = 'test'
t1 = time.time()
file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]'))
filename_queue = tf.train.string_input_producer(file_names)
t2 = time.time()
print('Time to list files: ', t2-t1)
file_classes=[int(ele.... | Read all images using tf itself | Read all images using tf itself
| Python | apache-2.0 | iitmcvg/OCR-Handwritten-Text,iitmcvg/OCR-Handwritten-Text,iitmcvg/OCR-Handwritten-Text | ---
+++
@@ -1,25 +1,45 @@
import time
-import cv2
import os
import glob
+import tensorflow as tf
# path = 'by_class'
path = 'test'
t1 = time.time()
file_names=glob.glob(os.path.join(path,'*','train_*','*.[pP][nN][gG]'))
+filename_queue = tf.train.string_input_producer(file_names)
t2 = time.time()
print('... |
169d32333aa3152dcec893f2ce58c46d614aaea4 | models/employees.py | models/employees.py | import datetime
from openedoo.core.libs.tools import hashing_werkzeug
from openedoo_project import db
from .users import User
class Employee(User):
@classmethod
def is_exist(self, username):
employee = self.query.get(username=username).first()
return employee
@classmethod
def get_pub... | import datetime
from openedoo.core.libs.tools import hashing_werkzeug
from openedoo_project import db
from .users import User
class Employee(User):
@classmethod
def is_exist(self, username):
employee = self.query.get(username=username).first()
return employee
@classmethod
def get_pub... | Fix Dangerous default value {} as argument, pylint. | Fix Dangerous default value {} as argument, pylint.
| Python | mit | openedoo/module_employee,openedoo/module_employee,openedoo/module_employee | ---
+++
@@ -24,10 +24,7 @@
return employees
@classmethod
- def add(self, form={}):
- if not form:
- raise ValueError('Form is supplied with wrong data.')
-
+ def add(self, form=None):
data = {
'username': form['username'],
'fullname': form['fu... |
30e261d895fd4260e3788398b8dd46a5e889815e | sandbox/urls.py | sandbox/urls.py | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from apps.app import application
from accoun... | from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
from django.views.generic import TemplateView
from apps.app import application
from accoun... | Include i18n URLs in sandbox | Include i18n URLs in sandbox
| Python | bsd-3-clause | Mariana-Tek/django-oscar-accounts,Jannes123/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,django-oscar/django-oscar-accounts,machtfit/django-oscar-accounts,machtfit/django-oscar-accounts,Jannes123/django-oscar-accounts,michaelkuty/django-oscar-accounts,django-oscar/django-osc... | ---
+++
@@ -13,6 +13,7 @@
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
+ url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^giftcard-balance/', AccountBalanceView.as_view(),
name="account-balance"),
(r'^dashboard/accounts/', include(accounts_app.urls)), |
0189eef29ce0054ef8747da317c0717bde196c17 | py2app/__init__.py | py2app/__init__.py | """
builds Mac OS X application bundles from Python scripts
New keywords for distutils' setup function specify what to build:
app
list of scripts to convert into gui app bundles
py2app options, to be specified in the options keyword to the setup function:
optimize - string or int (0, 1, or 2)
i... | """
builds Mac OS X application bundles from Python scripts
New keywords for distutils' setup function specify what to build:
app
list of scripts to convert into gui app bundles
py2app options, to be specified in the options keyword to the setup function:
optimize - string or int (0, 1, or 2)
i... | Set py2app.__version__ using pkg_resources, that ensures that the version stays in sync with the value in setup.py | Set py2app.__version__ using pkg_resources, that ensures that the version
stays in sync with the value in setup.py
| Python | mit | metachris/py2app,metachris/py2app,metachris/py2app,metachris/py2app | ---
+++
@@ -27,8 +27,8 @@
dest_base - directory and basename for the executable
if a directory is contained, must be the same for all targets
"""
-
-__version__ = "0.4.4"
+import pkg_resources
+__version__ = pkg_resources.require('py2app')[0].version
# This makes the py2app command work in t... |
84f913d928d28bc193d21eb223e7815f69c53a22 | plugins/jira.py | plugins/jira.py | from neb.engine import Plugin, Command
import requests
class JiraPlugin(Plugin):
def get_commands(self):
"""Return human readable commands with descriptions.
Returns:
list[Command]
"""
return [
Command("jira", self.jira, "Perform commands on Matrix... | from neb.engine import Plugin, Command, KeyValueStore
import json
import requests
class JiraPlugin(Plugin):
def __init__(self, config="jira.json"):
self.store = KeyValueStore(config)
if not self.store.has("url"):
url = raw_input("JIRA URL: ").strip()
self.store.set("url"... | Make the plugin request server info from JIRA. | Make the plugin request server info from JIRA.
| Python | apache-2.0 | Kegsay/Matrix-NEB,matrix-org/Matrix-NEB,illicitonion/Matrix-NEB | ---
+++
@@ -1,33 +1,54 @@
-from neb.engine import Plugin, Command
+from neb.engine import Plugin, Command, KeyValueStore
+import json
import requests
+
class JiraPlugin(Plugin):
+ def __init__(self, config="jira.json"):
+ self.store = KeyValueStore(config)
+
+ if not self.store.has("url"):
+ ... |
2171559a3cfcaeda2abe8a343c118769edad245f | src/keybar/conf/development.py | src/keybar/conf/development.py | import os
from keybar.conf.base import *
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CE... | import os
from keybar.conf.base import *
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.cert')
KEYBAR_SERVER_KEY = os.path.join(certificates_dir, 'KEYBAR-intermediate-SERVER.key')
KEYBAR_CLIENT_CE... | Update logging config to actually log exceptions to console. | Update logging config to actually log exceptions to console.
| Python | bsd-3-clause | keybar/keybar | ---
+++
@@ -17,3 +17,20 @@
KEYBAR_HOST = 'keybar.local:8443'
KEYBAR_VERIFY_CLIENT_CERTIFICATE = False
+
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'handlers': {
+ 'console': {
+ 'class': 'logging.StreamHandler',
+ },
+ },
+ 'loggers': {
+ 'dj... |
cb036a9725304f138b6da92bc0aae7f497cbafa5 | server.py | server.py | import argparse
from flask import Flask, request
parser = argparse.ArgumentParser(description="Start a Blindstore server.")
parser.add_argument('-d', '--debug', action='store_true',
help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()
app = Flask(__name__)
@app.r... | import argparse
import json
from flask import Flask, request
parser = argparse.ArgumentParser(description="Start a Blindstore server.")
parser.add_argument('-d', '--debug', action='store_true',
help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()
NUM_RECORDS = 5
R... | Add call to get the database size, as JSON | Add call to get the database size, as JSON
| Python | mit | blindstore/blindstore-old-scarab | ---
+++
@@ -1,4 +1,5 @@
import argparse
+import json
from flask import Flask, request
@@ -7,7 +8,14 @@
help="enable Flask debug mode. DO NOT use in production.")
args = parser.parse_args()
+NUM_RECORDS = 5
+RECORD_SIZE = 64
+
app = Flask(__name__)
+
+@app.route('/db_size')
+def get_db_s... |
4fd67e4e17f0813056493a635e8256a017d894e2 | src/tempel/models.py | src/tempel/models.py | from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now=True, auto_now_ad... | from django.db import models
from django.conf import settings
from tempel import utils
class Entry(models.Model):
content = models.TextField()
language = models.CharField(max_length=20,
choices=utils.get_languages())
created = models.DateTimeField(auto_now=True, auto_now_ad... | Add text representation for Entry object | Add text representation for Entry object
| Python | agpl-3.0 | fajran/tempel | ---
+++
@@ -26,4 +26,6 @@
def get_extension(self):
return utils.get_extension(self.language)
+ def __unicode__(self):
+ return '<Entry: id=%s lang=%s>' % (self.id, self.language)
|
d17a2308ff903b459b6c9310fd6d42eb0e051544 | statsSend/teamCity/teamCityStatisticsSender.py | statsSend/teamCity/teamCityStatisticsSender.py | #!/usr/bin/env python3
from dateutil import parser
from statsSend.teamCity.teamCityConnection import TeamCityConnection
from statsSend.teamCity.teamCityUrlBuilder import TeamCityUrlBuilder
from statsSend.teamCity.teamCityProject import TeamCityProject
class TeamCityStatisticsSender:
def __init__(self, settings, ... | #!/usr/bin/env python3
from dateutil import parser
from statsSend.teamCity.teamCityConnection import TeamCityConnection
from statsSend.teamCity.teamCityUrlBuilder import TeamCityUrlBuilder
from statsSend.teamCity.teamCityProject import TeamCityProject
class TeamCityStatisticsSender:
def __init__(self, settings, ... | Add error handling in statistics sender | Add error handling in statistics sender
| Python | mit | luigiberrettini/build-deploy-stats | ---
+++
@@ -17,10 +17,19 @@
async def send(self):
if ("report_categories" in dir(self.reporter)):
- categories = [build_configuration.toCategory() async for build_configuration in self.project.retrieve_build_configurations()]
- self.reporter.report_categories(categories)
+ ... |
00b134df7281c39595f9efcc1c1da047d1d10277 | src/encoded/authorization.py | src/encoded/authorization.py | from .contentbase import LOCATION_ROOT
CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a'
def groupfinder(login, request):
if ':' not in login:
return None
namespace, localname = login.split(':', 1)
user = None
# We may get called before the context is found and the root set
root = r... | from .contentbase import LOCATION_ROOT
CHERRY_LAB_UUID = 'cfb789b8-46f3-4d59-a2b3-adc39e7df93a'
def groupfinder(login, request):
if ':' not in login:
return None
namespace, localname = login.split(':', 1)
user = None
# We may get called before the context is found and the root set
root = r... | Update group finder to new schemas | Update group finder to new schemas
| Python | mit | kidaa/encoded,philiptzou/clincoded,4dn-dcic/fourfront,hms-dbmi/fourfront,4dn-dcic/fourfront,philiptzou/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,kidaa/encoded,ENCODE-DCC/snovault,ClinGen/clincoded,ENCODE-DCC/snovault,kidaa/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/encode... | ---
+++
@@ -34,8 +34,12 @@
return None
principals = ['userid:%s' % user.uuid]
- lab_uuids = user.properties.get('lab_uuids', [])
- principals.extend('lab:' + lab_uuid for lab_uuid in lab_uuids)
- if CHERRY_LAB_UUID in lab_uuids:
+ lab = user.properties.get('lab')
+ if lab:
+ prin... |
5cd9ac8d3079fca16828b25b40fed8358286708b | geotrek/outdoor/models.py | geotrek/outdoor/models.py | from django.conf import settings
from django.contrib.gis.db import models
from django.utils.translation import gettext_lazy as _
from geotrek.authent.models import StructureRelated
from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin
from mapentity.models import MapEntityMixin
clas... | from django.conf import settings
from django.contrib.gis.db import models
from django.utils.translation import gettext_lazy as _
from geotrek.authent.models import StructureRelated
from geotrek.common.mixins import NoDeleteMixin, TimeStampedModelMixin, AddPropertyMixin
from mapentity.models import MapEntityMixin
clas... | Add links to site detail in site list | Add links to site detail in site list
| Python | bsd-2-clause | makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek | ---
+++
@@ -20,3 +20,11 @@
def __str__(self):
return self.name
+
+ @property
+ def name_display(self):
+ return '<a data-pk="{pk}" href="{url}" title="{name}">{name}</a>'.format(
+ pk=self.pk,
+ url=self.get_detail_url(),
+ name=self.name
+ ) |
c8e11b602eb7525789ed1c5f4ea686f45b44f304 | src/diamond/handler/httpHandler.py | src/diamond/handler/httpHandler.py | #!/usr/bin/python2.7
from Handler import Handler
import urllib
import urllib2
class HttpPostHandler(Handler):
# Inititalize Handler with url and batch size
def __init__(self, config=None):
Handler.__init__(self, config)
self.metrics = []
self.batch_size = int(self.config.get('batch', 100... | #!/usr/bin/env python
# coding=utf-8
from Handler import Handler
import urllib2
class HttpPostHandler(Handler):
# Inititalize Handler with url and batch size
def __init__(self, config=None):
Handler.__init__(self, config)
self.metrics = []
self.batch_size = int(self.config.get('batch', 1... | Remove unneeded import, fix python path and add coding | Remove unneeded import, fix python path and add coding
| Python | mit | signalfx/Diamond,ramjothikumar/Diamond,jriguera/Diamond,anandbhoraskar/Diamond,jriguera/Diamond,Precis/Diamond,jriguera/Diamond,socialwareinc/Diamond,saucelabs/Diamond,acquia/Diamond,dcsquared13/Diamond,stuartbfox/Diamond,hvnsweeting/Diamond,h00dy/Diamond,cannium/Diamond,dcsquared13/Diamond,Ssawa/Diamond,bmhatfield/Dia... | ---
+++
@@ -1,7 +1,7 @@
-#!/usr/bin/python2.7
+#!/usr/bin/env python
+# coding=utf-8
from Handler import Handler
-import urllib
import urllib2
|
f076acb05840c361890fbb5ef0c8b43d0de7e2ed | opsdroid/message.py | opsdroid/message.py | """ Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
self.text = text
self.user = user
self.room = room
self.connector = connector
... | """ Class to encapsulate a message """
import logging
class Message:
""" A message object """
def __init__(self, text, user, room, connector):
""" Create object with minimum properties """
self.text = text
self.user = user
self.room = room
self.connector = connector
... | Make regex a None property | Make regex a None property
| Python | apache-2.0 | FabioRosado/opsdroid,jacobtomlinson/opsdroid,opsdroid/opsdroid | ---
+++
@@ -11,6 +11,7 @@
self.user = user
self.room = room
self.connector = connector
+ self.regex = None
def respond(self, text):
""" Respond to this message using the connector it was created by """ |
c197bf432655ca051ff4fb672cd41e876d539990 | pipeline/api/api.py | pipeline/api/api.py | import datetime
import json
import falcon
from pipeline.api import models, schemas
def json_serializer(obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError('{} is not JSON serializable'.format(type(obj)))
def json_dump(data):
return json.dumps(data, default=json_se... | import datetime
import json
import falcon
from pipeline.api import models, schemas
def json_serializer(obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError('{} is not JSON serializable'.format(type(obj)))
def json_dump(data):
return json.dumps(data, default=json_se... | Allow creating and viewing stories | Allow creating and viewing stories
Closes #1
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline | ---
+++
@@ -13,6 +13,12 @@
def json_dump(data):
return json.dumps(data, default=json_serializer)
+def json_load(data):
+ try:
+ return json.loads(data)
+ except json.decoder.JSONDecodeError:
+ raise falcon.HTTPBadRequest(None, 'invalid JSON')
+
stories_schema = schemas.StorySchema(many=Tr... |
220b6a9fee0f307d4de1e48b29093812f7dd10ec | var/spack/repos/builtin/packages/m4/package.py | var/spack/repos/builtin/packages/m4/package.py | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
depends_on('libsigseg... | from spack import *
class M4(Package):
"""GNU M4 is an implementation of the traditional Unix macro processor."""
homepage = "https://www.gnu.org/software/m4/m4.html"
url = "ftp://ftp.gnu.org/gnu/m4/m4-1.4.17.tar.gz"
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
variant('sigsegv', de... | Make libsigsegv an optional dependency | Make libsigsegv an optional dependency
| Python | lgpl-2.1 | lgarren/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,LLNL/spack,tmerrick1/spack,krafczyk/spack,TheTimmy/spack,TheTimmy/spack,lgarren/spack,skosukhin/spack,matthiasdiener/spack,TheTimmy/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,lgarren/spack,mfherbst/spack,matthiasdiener/spack,matthiasdiener/s... | ---
+++
@@ -7,7 +7,9 @@
version('1.4.17', 'a5e9954b1dae036762f7b13673a2cf76')
- depends_on('libsigsegv')
+ variant('sigsegv', default=True, description="Build the libsigsegv dependency")
+
+ depends_on('libsigsegv', when='+sigsegv')
def install(self, spec, prefix):
configure("--prefi... |
b38647ef390ed6c78c2d55d706bac2f6a396ad39 | errors.py | errors.py | #
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuin... | #
## PyMoira client library
##
## This file contains the Moira-related errors.
#
import moira_constants
class MoiraBaseError(Exception):
"""Any exception thrown by the library is inhereted from this"""
pass
class MoiraConnectionError(MoiraBaseError):
"""An error which prevents the client from having or continuin... | Introduce a new error class. | Introduce a new error class.
| Python | mit | vasilvv/pymoira | ---
+++
@@ -30,3 +30,8 @@
"""An error raised in case when Moira MOTD is not empty."""
pass
+
+class MoiraUserError(MoiraBaseError):
+ """An error related to Moira but not returned from the server."""
+
+ pass |
70b41bfdb2e1fa6daa78f5a484a2825a25e3811e | apps/__init__.py | apps/__init__.py | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py']))]
... | ## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
import os,importlib,logging
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__))
subdirs = [o for o in os.listdir(curdir) if os.path.exists(os.path.sep.join([curdir,o,'__init__.py... | Add logging to error output | Add logging to error output
| Python | agpl-3.0 | sociam/indx,sociam/indx,sociam/indx | ---
+++
@@ -1,7 +1,7 @@
## module loader, goes to see which submodules have 'html' directories
## and declares them at the toplevel
-import os,importlib
+import os,importlib,logging
def find_module_dirs():
curdir = os.path.dirname(os.path.abspath(__file__)) |
95e347ae4086d05aadf91a393b856961b34026a5 | website_field_autocomplete/controllers/main.py | website_field_autocomplete/controllers/main.py | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/fiel... | # -*- coding: utf-8 -*-
# Copyright 2016 LasLabs Inc.
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import json
from openerp import http
from openerp.http import request
from openerp.addons.website.controllers.main import Website
class Website(Website):
@http.route(
'/website/fiel... | Use search_read * Use search_read in controller data getter, instead of custom implementation | [FIX] website_field_autocomplete: Use search_read
* Use search_read in controller data getter, instead of custom implementation
| Python | agpl-3.0 | Tecnativa/website,nicolas-petit/website,khaeusler/website,JayVora-SerpentCS/website,RoelAdriaans-B-informed/website,JayVora-SerpentCS/website,khaeusler/website,nicolas-petit/website,Tecnativa/website,khaeusler/website,Tecnativa/website,RoelAdriaans-B-informed/website,nicolas-petit/website,JayVora-SerpentCS/website,Roel... | ---
+++
@@ -35,12 +35,9 @@
Returns:
Dict of record dicts, keyed by ID
"""
- res = {}
if limit:
limit = int(limit)
- self.record_ids = request.env[model].search(domain, limit=limit)
- for rec_id in self.record_ids:
- res[rec_id.id] = ... |
3ec71d3925a3551f6f25fc25e827c88caaff1fdd | tests/integration/test_redirection_external.py | tests/integration/test_redirection_external.py | """Check external REDIRECTIONS"""
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
test_in... | """Check external REDIRECTIONS"""
import os
import pytest
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test_check_files,
test_check_links,
... | Add test for external redirection. | Add test for external redirection.
| Python | mit | okin/nikola,okin/nikola,okin/nikola,getnikola/nikola,getnikola/nikola,getnikola/nikola,okin/nikola,getnikola/nikola | ---
+++
@@ -1,4 +1,6 @@
"""Check external REDIRECTIONS"""
+
+import os
import pytest
@@ -15,6 +17,17 @@
)
+def test_external_redirection(build, output_dir):
+ ext_link = os.path.join(output_dir, 'external.html')
+
+ assert os.path.exists(ext_link)
+ with open(ext_link) as ext_link_fd:
+ ext... |
ad4effbdf95b51f151d613f02f70b4501bbe453d | tests/unit/extensions/flask_babel_unit_test.py | tests/unit/extensions/flask_babel_unit_test.py | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['LANGUAGES'] = {
'de': 'Deu... | # -*- coding: utf-8 -*-
"""
Unit Test: orchard.extensions.babel
"""
import unittest
import orchard
import orchard.extensions.flask_babel
class BabelUnitTest(unittest.TestCase):
def setUp(self):
self.app = orchard.create_app('Testing')
self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'
... | Set default locale in test to avoid test failures when different default is used than expected. | Set default locale in test to avoid test failures when different default is used than expected.
| Python | mit | BMeu/Orchard,BMeu/Orchard | ---
+++
@@ -14,6 +14,7 @@
def setUp(self):
self.app = orchard.create_app('Testing')
+ self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'
self.app.config['LANGUAGES'] = {
'de': 'Deutsch',
'en': 'English' |
09851ff2903db29703616da0fbc9ec003955712a | zerver/lib/markdown/preprocessor_priorities.py | zerver/lib/markdown/preprocessor_priorities.py | # Note that in the Markdown preprocessor registry, the highest
# numeric value is considered the highest priority, so the dict
# below is ordered from highest-to-lowest priority.
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"generate_response_description": 531,
"generate_api_title": 531... | # Note that in the Markdown preprocessor registry, the highest
# numeric value is considered the highest priority, so the dict
# below is ordered from highest-to-lowest priority.
# Priorities for the built-in preprocessors are commented out.
PREPROCESSOR_PRIORITES = {
"generate_parameter_description": 535,
"gen... | Document built-in preprocessor priorities for convenience. | markdown: Document built-in preprocessor priorities for convenience.
Fixes #19810
| Python | apache-2.0 | eeshangarg/zulip,rht/zulip,rht/zulip,kou/zulip,eeshangarg/zulip,rht/zulip,eeshangarg/zulip,zulip/zulip,rht/zulip,andersk/zulip,kou/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip,andersk/zulip,kou/zulip,andersk/zulip,rht/zulip,rht/zulip,zulip/zulip,kou/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,andersk... | ---
+++
@@ -1,6 +1,7 @@
# Note that in the Markdown preprocessor registry, the highest
# numeric value is considered the highest priority, so the dict
# below is ordered from highest-to-lowest priority.
+# Priorities for the built-in preprocessors are commented out.
PREPROCESSOR_PRIORITES = {
"generate_param... |
6835fa9e8978a081186008785bd2e11522372aa9 | tests/utils.py | tests/utils.py | import os
import re
from lxml import etree
def validate_xml(xmlout):
with open(os.path.join(os.path.dirname(__file__), 'pain.008.001.02.xsd'), 'rb') as schema_file:
schema_xml = schema_file.read()
schema_root = etree.XML(schema_xml)
schema = etree.XMLSchema(schema_root)
parser = etree.XMLPars... | import os
import re
from lxml import etree
def validate_xml(xmlout):
with open(os.path.join(os.path.dirname(__file__), 'pain.008.001.02.xsd'), 'rb') as schema_file:
schema_xml = schema_file.read()
schema_root = etree.XML(schema_xml)
schema = etree.XMLSchema(schema_root)
parser = etree.XMLPars... | Fix dates in test output | Fix dates in test output
| Python | mit | raphaelm/python-sepadd,lutoma/python-sepadd | ---
+++
@@ -18,4 +18,5 @@
pat1 = re.compile(b'-[0-9a-f]{12}')
pat2 = re.compile(b'<MsgId>[^<]*</MsgId>')
pat3 = re.compile(b'\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d')
- return pat3.sub(b'0000-00-00T00:00:00', pat2.sub(b'<MsgId></MsgId>', pat1.sub(b'-000000000000', xmlout)))
+ pat4 = re.compile(b'\d\d\d... |
36bb5605b4ec7a062190e8f5ef755023c0b2f6e4 | rebulk/debug.py | rebulk/debug.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Debug tools.
Can be configured by changing values of those variable.
DEBUG = False
Enable this variable to activate debug features (like defined_at parameters). It can slow down Rebulk
LOG_LEVEL = 0
Default log level of generated rebulk logs.
"""
import inspect
impo... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Debug tools.
Can be configured by changing values of those variable.
DEBUG = False
Enable this variable to activate debug features (like defined_at parameters). It can slow down Rebulk
LOG_LEVEL = 0
Default log level of generated rebulk logs.
"""
import inspect
impo... | Set default LOG_LEVEL to logging.DEBUG | Set default LOG_LEVEL to logging.DEBUG
| Python | mit | Toilal/rebulk | ---
+++
@@ -13,12 +13,13 @@
"""
import inspect
+import logging
import os
from collections import namedtuple
DEBUG = False
-LOG_LEVEL = 0
+LOG_LEVEL = logging.DEBUG
class Frame(namedtuple('Frame', ['lineno', 'package', 'name', 'filename'])): |
d6b2dc137111e0a077625feefb0a2c70fc8e789b | Lib/__init__.py | Lib/__init__.py | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | """\
SciPy --- A scientific computing package for Python
===================================================
You can support the development of SciPy by purchasing documentation
at
http://www.trelgol.com
It is being distributed for a fee for a limited time to try and raise
money for development.
Documentation is ... | Remove auto include of numpy namespace. | Remove auto include of numpy namespace.
| Python | bsd-3-clause | mgaitan/scipy,rgommers/scipy,Srisai85/scipy,tylerjereddy/scipy,juliantaylor/scipy,sonnyhu/scipy,apbard/scipy,juliantaylor/scipy,zxsted/scipy,behzadnouri/scipy,mikebenfield/scipy,richardotis/scipy,nmayorov/scipy,pnedunuri/scipy,befelix/scipy,anntzer/scipy,mortada/scipy,chatcannon/scipy,WarrenWeckesser/scipy,mingwpy/scip... | ---
+++
@@ -28,12 +28,6 @@
pkgload = _ni.PackageLoader()
del _ni
-from numpy import *
-del fft, ifft, info
-import numpy
-__all__.extend(filter(lambda x: x not in ['fft','ifft','info'], numpy.__all__))
-del numpy
-
from numpy.testing import ScipyTest
test = ScipyTest('scipy').test
__all__.append('test') |
56c25218cb3c987201839917930fc1ae791b5601 | reg/__init__.py | reg/__init__.py | # flake8: noqa
from .dispatch import dispatch, Dispatch
from .context import (dispatch_method, DispatchMethod,
methodify, clean_dispatch_methods)
from .arginfo import arginfo
from .error import RegistrationError
from .predicate import (Predicate, KeyIndex, ClassIndex,
match... | # flake8: noqa
from .dispatch import dispatch, Dispatch, LookupEntry
from .context import (dispatch_method, DispatchMethod,
methodify, clean_dispatch_methods)
from .arginfo import arginfo
from .error import RegistrationError
from .predicate import (Predicate, KeyIndex, ClassIndex,
... | Add LookupEntry to the API. | Add LookupEntry to the API.
| Python | bsd-3-clause | morepath/reg,taschini/reg | ---
+++
@@ -1,5 +1,5 @@
# flake8: noqa
-from .dispatch import dispatch, Dispatch
+from .dispatch import dispatch, Dispatch, LookupEntry
from .context import (dispatch_method, DispatchMethod,
methodify, clean_dispatch_methods)
from .arginfo import arginfo |
00a5d82c99ce6fb7096d432f12959ab4d8218f4f | booster_bdd/features/src/importBooster.py | booster_bdd/features/src/importBooster.py | import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.... | import pytest
import time
import requests
import support.helpers as helpers
import sys
import re
import os
class ImportBooster(object):
def importGithubRepo(self, gitRepo):
###############################################
# Environment variables
#
# Note: Pipelines = https://forge.... | Replace hardcoded Forge API URL by variable. | booster-bdd: Replace hardcoded Forge API URL by variable.
| Python | apache-2.0 | ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test,ldimaggi/fabric8-test | ---
+++
@@ -16,12 +16,12 @@
# Note: Pipelines = https://forge.api.openshift.io/api/services/jenkins/pipelines
# Tokens are stored in a form of "<access_token>;<refresh_token>(;<username>)"
theToken = helpers.get_user_tokens().split(";")[0]
- projectName = os.environ.get('PROJECT_NAME... |
c9e4a05ed2677fd569642e0ef77dd9f63bf3e15f | vumi/persist/tests/test_redis_base.py | vumi/persist/tests/test_redis_base.py | """Tests for vumi.persist.redis_base."""
from twisted.trial.unittest import TestCase
from vumi.persist.redis_base import Manager
class ManagerTestCase(TestCase):
def mk_manager(self, client, key_prefix='test'):
return Manager(client, key_prefix)
def test_sub_manager(self):
dummy_client = ob... | """Tests for vumi.persist.redis_base."""
from twisted.trial.unittest import TestCase
from vumi.persist.redis_base import Manager
class ManagerTestCase(TestCase):
def mk_manager(self, client=None, key_prefix='test'):
if client is None:
client = object()
return Manager(client, key_pref... | Make sub_manager test neater and also check key_separator. | Make sub_manager test neater and also check key_separator.
| Python | bsd-3-clause | TouK/vumi,vishwaprakashmishra/xmatrix,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi | ---
+++
@@ -6,12 +6,14 @@
class ManagerTestCase(TestCase):
- def mk_manager(self, client, key_prefix='test'):
+ def mk_manager(self, client=None, key_prefix='test'):
+ if client is None:
+ client = object()
return Manager(client, key_prefix)
def test_sub_manager(self):
- ... |
1a5e55e1a0354182a2b23cd51292cb1cd3c3a88d | mrburns/main/context_processors.py | mrburns/main/context_processors.py | from django.conf import settings
def glow_variables(request):
return {
'MAP_DATA_URL': settings.MAP_DATA_URL,
'OG_ABS_URL': 'https://{}{}'.format(request.get_host(),
request.path)
}
| from django.conf import settings
def glow_variables(request):
return {
'MAP_DATA_URL': settings.MAP_DATA_URL,
'OG_ABS_URL': u'https://{}{}'.format(request.get_host(),
request.path)
}
| Handle unicode paths in glow_variables | Handle unicode paths in glow_variables
| Python | mpl-2.0 | mozilla/mrburns,mozilla/mrburns,mozilla/mrburns | ---
+++
@@ -4,6 +4,6 @@
def glow_variables(request):
return {
'MAP_DATA_URL': settings.MAP_DATA_URL,
- 'OG_ABS_URL': 'https://{}{}'.format(request.get_host(),
- request.path)
+ 'OG_ABS_URL': u'https://{}{}'.format(request.get_host(),
+ ... |
ce28d39244b75ee0dd865017b4cf1a0125bf4887 | ynr/apps/parties/serializers.py | ynr/apps/parties/serializers.py | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... | from rest_framework import serializers
from parties.models import Party, PartyDescription, PartyEmblem
class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = PartyEmblem
fields = (
"image",
"description",
"date_approved",
... | Add legacy slug to embedded Party on memberships | Add legacy slug to embedded Party on memberships
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | ---
+++
@@ -47,4 +47,4 @@
class MinimalPartySerializer(PartySerializer):
class Meta:
model = Party
- fields = ("ec_id", "name")
+ fields = ("ec_id", "name", "legacy_slug") |
c37abb2849dc3c4b885673220f9f9965109f0be6 | sieve/sieve.py | sieve/sieve.py | def sieve(n):
if n < 2:
return []
not_prime = set()
prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
prime.append(i)
not_prime.update(range(i*i, n+1, i))
return prime
| def sieve(n):
return list(primes(n))
def primes(n):
if n < 2:
raise StopIteration
yield 2
not_prime = set()
for i in range(3, n+1, 2):
if i not in not_prime:
not_prime.update(range(i*i, n+1, i))
yield i
| Revert back to a generator - it's actually slight faster | Revert back to a generator - it's actually slight faster
| Python | agpl-3.0 | CubicComet/exercism-python-solutions | ---
+++
@@ -1,10 +1,13 @@
def sieve(n):
+ return list(primes(n))
+
+
+def primes(n):
if n < 2:
- return []
+ raise StopIteration
+ yield 2
not_prime = set()
- prime = [2]
for i in range(3, n+1, 2):
if i not in not_prime:
- prime.append(i)
not_pri... |
2127e3adf190736e14f8500753ffc58126cb39f4 | ovp_search/tests/test_execution.py | ovp_search/tests/test_execution.py | import ovp_search.apps
| import ovp_search.apps
from django.test import TestCase
from django.core.management import call_command
class RebuildIndexTestCase(TestCase):
def test_rebuild_index_execution(self):
call_command('rebuild_index', '--noinput', verbosity=0)
| Add test case for index rebuilding | Add test case for index rebuilding
| Python | agpl-3.0 | OpenVolunteeringPlatform/django-ovp-search | ---
+++
@@ -1 +1,7 @@
import ovp_search.apps
+from django.test import TestCase
+from django.core.management import call_command
+
+class RebuildIndexTestCase(TestCase):
+ def test_rebuild_index_execution(self):
+ call_command('rebuild_index', '--noinput', verbosity=0) |
e23d5a64cfd5604f74cce583db3366f2cabb5e1f | tests/basics/builtin_minmax.py | tests/basics/builtin_minmax.py | # test builtin min and max functions
print(min(0,1))
print(min(1,0))
print(min(0,-1))
print(min(-1,0))
print(max(0,1))
print(max(1,0))
print(max(0,-1))
print(max(-1,0))
print(min([1,2,4,0,-1,2]))
print(max([1,2,4,0,-1,2]))
# test with key function
lst = [2, 1, 3, 4]
print(min(lst, key=lambda x:x))
print(min(lst, ke... | # test builtin min and max functions
print(min(0,1))
print(min(1,0))
print(min(0,-1))
print(min(-1,0))
print(max(0,1))
print(max(1,0))
print(max(0,-1))
print(max(-1,0))
print(min([1,2,4,0,-1,2]))
print(max([1,2,4,0,-1,2]))
# test with key function
lst = [2, 1, 3, 4]
print(min(lst, key=lambda x:x))
print(min(lst, ke... | Add min/max "default" agrument test | tests: Add min/max "default" agrument test
| Python | mit | mpalomer/micropython,dinau/micropython,henriknelson/micropython,deshipu/micropython,blazewicz/micropython,supergis/micropython,MrSurly/micropython-esp32,henriknelson/micropython,torwag/micropython,matthewelse/micropython,swegener/micropython,dmazzella/micropython,turbinenreiter/micropython,Timmenem/micropython,tralamaz... | ---
+++
@@ -29,3 +29,9 @@
min([])
except ValueError:
print("ValueError")
+
+# 'default' tests
+print(min([1, 2, 3, 4, 5], default=-1))
+print(min([], default=-1))
+print(max([1, 2, 3, 4, 5], default=-1))
+print(max([], default=-1)) |
d90d91906981a4393810069b494d68230f17439e | frameworks/Scala/spray/setup.py | frameworks/Scala/spray/setup.py |
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
if os.name == 'nt':
subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile)
else:
subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile... |
import subprocess
import sys
import time
import os
def start(args, logfile, errfile):
if os.name == 'nt':
subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile)
else:
subprocess.check_call("$FWROOT/sbt/sbt assembly", shell=True, cwd="spray", stderr=er... | Enable spray to find sbt | Enable spray to find sbt
| Python | bsd-3-clause | zane-techempower/FrameworkBenchmarks,denkab/FrameworkBenchmarks,Verber/FrameworkBenchmarks,mfirry/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,k-r-g/FrameworkBenchmarks,nkasvosve/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,waiteb3/FrameworkBenchmarks,stefanocasazza/FrameworkBenchmarks,ashawnbandy-te-tfb/Framewo... | ---
+++
@@ -8,10 +8,9 @@
if os.name == 'nt':
subprocess.check_call('"..\\sbt\\sbt.bat" assembly', shell=True, cwd="spray", stderr=errfile, stdout=logfile)
else:
- subprocess.check_call("../sbt/sbt assembly", shell=True, cwd="spray", stderr=errfile, stdout=logfile)
+ subprocess.check_call("$FWROOT/sbt... |
6551c882745b13d5b9be183e83f379e34b067921 | tests/test_emailharvesterws.py | tests/test_emailharvesterws.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_botanick
----------------------------------
Tests for `botanick` module.
"""
import pytest
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
print(emails_found)
| Revert "Fix a codacy issue" | Revert "Fix a codacy issue"
This reverts commit 0fe83f1bfa54eda16c42fb5d81b33215dc3ba562.
| Python | mit | avidot/Botanick | ---
+++
@@ -8,9 +8,12 @@
Tests for `botanick` module.
"""
+import pytest
+
from botanick import Botanick
def test_botanick():
emails_found = Botanick.search("squad.pro")
assert emails_found != ""
+ print(emails_found) |
2666eee0a59581c504b36acd618e256cf313c377 | start_server.py | start_server.py | import os
def start_server():
os.system('ssh pi@192.168.2.4 python python-libs/RaspberryDrive/driving_server.py &')
return
| import os
def start_server():
count = 0
while count < 2
send_ssh_server_start(count)
count +=1
exit()
def send_ssh_server_start(count):
try:
os.system('ssh pi@192.168.2.4 python python-libs/RaspberryDrive/driving_server.py &')
return
except:
sleep(count + 1)
| Add logic to try server 3 times, pausing a little more each time. | Add logic to try server 3 times, pausing a little more each time.
| Python | mit | jwarshaw/RaspberryDrive | ---
+++
@@ -1,6 +1,16 @@
import os
def start_server():
- os.system('ssh pi@192.168.2.4 python python-libs/RaspberryDrive/driving_server.py &')
- return
+ count = 0
+ while count < 2
+ send_ssh_server_start(count)
+ count +=1
+ exit()
+def send_ssh_server_start(count):
+ try:
+ os.system('ssh pi@1... |
2849499a076b6997f8e3c7b76103df94f50ac6c3 | python/src/setup.py | python/src/setup.py | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... | #!/usr/bin/env python
"""Setup specs for packaging, distributing, and installing MR lib."""
import distribute_setup
# User may not have setuptools installed on their machines.
# This script will automatically install the right version from PyPI.
distribute_setup.use_setuptools()
# pylint: disable=g-import-not-at-top... | Increment PyPi package to 1.9.16.1 | Increment PyPi package to 1.9.16.1
| Python | apache-2.0 | talele08/appengine-mapreduce,talele08/appengine-mapreduce,soundofjw/appengine-mapreduce,westerhofffl/appengine-mapreduce,westerhofffl/appengine-mapreduce,GoogleCloudPlatform/appengine-mapreduce,westerhofffl/appengine-mapreduce,soundofjw/appengine-mapreduce,soundofjw/appengine-mapreduce,VirusTotal/appengine-mapreduce,Ca... | ---
+++
@@ -14,7 +14,7 @@
# To debug, set DISTUTILS_DEBUG env var to anything.
setuptools.setup(
name="GoogleAppEngineMapReduce",
- version="1.9.15.0",
+ version="1.9.16.1",
packages=setuptools.find_packages(),
author="Google App Engine",
author_email="app-engine-pipeline-api@googlegroups.... |
72205981af062258c4cf75c4323aa3e4d2859bb8 | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Vitaly Potyarkin'
BIO = 'Unsorted ramblings, sometimes related to programming'
SITENAME = 'Randomize'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Moscow'
DEFAULT_LANG = 'EN'
# Feed generation is usually not desir... | #!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Vitaly Potyarkin'
BIO = 'Unsorted ramblings, sometimes related to programming'
SITENAME = 'Randomize'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'Europe/Moscow'
DEFAULT_LANG = 'EN'
# Feed generation is usually not desir... | Replace default links and values | Replace default links and values
| Python | apache-2.0 | sio/potyarkin.ml,sio/potyarkin.ml | ---
+++
@@ -21,16 +21,17 @@
AUTHOR_FEED_RSS = None
# Blogroll
-LINKS = (('Pelican', 'http://getpelican.com/'),
- ('Python.org', 'http://python.org/'),
- ('Jinja2', 'http://jinja.pocoo.org/'),
- ('You can modify those links in your config file', '#'),)
+LINKS = ()
# Social widget
-SOCIAL... |
857124a12f10e3954c114c2b6b688857b80a77a5 | Spectrum.py | Spectrum.py | #!/usr/bin/python
from __future__ import print_function, division
# Spectrum Class
# Begun August 2016
# Jason Neal
class Spectrum:
""" Spectrum class represents and manipulates astronomical spectra. """
def __init__(self, pixel=[], flux=[], wavelength=[]):
""" Create a empty spectra """
... | #!/usr/bin/python
from __future__ import print_function, division
# Spectrum Class
# Begun August 2016
# Jason Neal
class Spectrum:
""" Spectrum class represents and manipulates astronomical spectra. """
def __init__(self, pixel=[], flux=[], wavelength=[]):
""" Create a empty spectra """
... | Remove simple testing from inside class module | Remove simple testing from inside class module
| Python | mit | jason-neal/spectrum_overload,jason-neal/spectrum_overload,jason-neal/spectrum_overload | ---
+++
@@ -22,18 +22,3 @@
# Try using Spectrum
#if __name__ == __main__:
-x = [1,2,3,4,5,6]
-y = [1,1,0.9,0.95,1,1]
-
-test = Spectrum()
-print(test)
-print(test.pixel, test.flux)
-test.pixel = x
-test.flux = y
-print(test)
-print(test.pixel, test.flux, test.wavelength)
-
-test2 = Spectrum(x, flux=y)
-print(tes... |
530f67493ba0d044a0896aff39bdab2ea5f1cf15 | __init__.py | __init__.py | from openerp.osv import orm
from openerp.tools.translate import _
__all__ = ['OEMetaSL']
def get_overrides():
overrides = {}
def add_override(func):
overrides[func.func_name] = func
@add_override
def copy(cls, cr, uid, rec_id, default=None, context=None):
# Raise by default. This me... | from openerp.osv import orm
from openerp.osv import osv
from openerp.tools.translate import _
__all__ = ['OEMetaSL']
def get_overrides():
overrides = {}
def add_override(func):
overrides[func.func_name] = func
@add_override
def copy(cls, cr, uid, rec_id, default=None, context=None):
... | Add osv method from openerp | Add osv method from openerp
| Python | agpl-3.0 | xcgd/oemetasl | ---
+++
@@ -1,4 +1,5 @@
from openerp.osv import orm
+from openerp.osv import osv
from openerp.tools.translate import _
__all__ = ['OEMetaSL'] |
709017ea46cd3784983ef0ee64cfe608aa44cf0c | tests/integration/aiohttp_utils.py | tests/integration/aiohttp_utils.py | import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999
if output == ... | import asyncio
import aiohttp
@asyncio.coroutine
def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999
response = yield from response_ctx.__aenter__() # NOQA: E999... | Fix aiohttp utils to pass encondig to response.json | Fix aiohttp utils to pass encondig to response.json
| Python | mit | graingert/vcrpy,graingert/vcrpy,kevin1024/vcrpy,kevin1024/vcrpy | ---
+++
@@ -4,7 +4,7 @@
@asyncio.coroutine
-def aiohttp_request(loop, method, url, output='text', **kwargs):
+def aiohttp_request(loop, method, url, output='text', encoding='utf-8', **kwargs):
session = aiohttp.ClientSession(loop=loop)
response_ctx = session.request(method, url, **kwargs) # NOQA: E999... |
2a3fe3b5e08c91ab8d77569b02b36da63909f619 | pysnmp/hlapi/v1arch/asyncore/sync/__init__.py | pysnmp/hlapi/v1arch/asyncore/sync/__init__.py | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp.proto.rfc1902 import *
from pysnmp.smi.rfc1902 import *
from pysnmp.hlapi.v1arch.auth import *
from pysnmp.hlapi.v1arch.asyncore.transport import *
fro... | #
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp.proto.rfc1902 import *
from pysnmp.smi.rfc1902 import *
from pysnmp.hlapi.v1arch.auth import *
from pysnmp.hlapi.v1arch.asyncore.transport import *
fro... | Remove the remnants of hlapi.v1arch.asyncore.sync.compat | Remove the remnants of hlapi.v1arch.asyncore.sync.compat
| Python | bsd-2-clause | etingof/pysnmp,etingof/pysnmp | ---
+++
@@ -9,13 +9,7 @@
from pysnmp.hlapi.v1arch.auth import *
from pysnmp.hlapi.v1arch.asyncore.transport import *
from pysnmp.hlapi.v1arch.asyncore.cmdgen import *
+from pysnmp.hlapi.v1arch.asyncore.dispatch import *
from pysnmp.hlapi.v1arch.asyncore.ntforg import *
-from pysnmp.hlapi.v1arch.asyncore.dispatch ... |
674721b9b094fe7e63d3356cf76e7eec0cb9bb62 | employees/serializers.py | employees/serializers.py | from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last... | from .models import Employee
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
depth = 1
fields = ('pk',
'username',
'email',
'first_name',
'last... | Add current_month_score and last_month_score to EmployeeListSerializer | Add current_month_score and last_month_score to EmployeeListSerializer
| Python | apache-2.0 | belatrix/BackendAllStars | ---
+++
@@ -31,7 +31,9 @@
'last_name',
'level',
'avatar',
- 'score')
+ 'score',
+ 'last_month_score',
+ 'current_month_score')
class EmployeeAvatarSerializer(serializers.ModelSerializer): |
25e7b4a2e297e9944b5065851c6e65eb40b11bcd | scripts/examples/OpenMV/99-Tests/unittests.py | scripts/examples/OpenMV/99-Tests/unittests.py | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, passed):
s = ... | # OpenMV Unit Tests.
#
import os, sensor, gc
TEST_DIR = "unittest"
TEMP_DIR = "unittest/temp"
DATA_DIR = "unittest/data"
SCRIPT_DIR = "unittest/script"
if not (TEST_DIR in os.listdir("")):
raise Exception('Unittest dir not found!')
print("")
test_failed = False
def print_result(test, result):
s = ... | Update unittest to ignore disabled functions. | Update unittest to ignore disabled functions.
| Python | mit | kwagyeman/openmv,kwagyeman/openmv,iabdalkader/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,kwagyeman/openmv,iabdalkader/openmv,openmv/openmv,openmv/openmv,iabdalkader/openmv,openmv/openmv | ---
+++
@@ -13,14 +13,14 @@
print("")
test_failed = False
-def print_result(test, passed):
+def print_result(test, result):
s = "Unittest (%s)"%(test)
padding = "."*(60-len(s))
- print(s + padding + ("PASSED" if passed == True else "FAILED"))
+ print(s + padding + result)
for test in sorted(os.... |
de228621deb5637ab0698ca23cf63ece46c5ddee | task/views.py | task/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from models import *
from serializers import *
# Create your views here.
class TaskListViewSet(viewsets.ModelViewSet):
permission_classes = (IsAuthenticated,)
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
from django.db.models import Q
from rest_framework.permissions import IsAuthenticated
from models import *
from serializers import *
# Create your views here.
class TaskListViewSet(viewsets.ModelViewSet):
permission... | Adjust the APIView query_set to return tasks created or assigned to the currently logged user | Adjust the APIView query_set to return tasks created or assigned to the currently logged user
| Python | apache-2.0 | toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile,toladata/TolaProfile | ---
+++
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from rest_framework import viewsets
+from django.db.models import Q
from rest_framework.permissions import IsAuthenticated
from models import *
from serializers import *
@@ -8,5 +9,13 @@
# Create your views here.
class Tas... |
da91f170c106c46a0d858e887220bc691066cdaa | tests/dtypes_test.py | tests/dtypes_test.py | from common import *
def test_dtype(ds_local):
ds = ds_local
for name in ds.column_names:
assert ds[name].values.dtype == ds.dtype(ds[name])
def test_dtypes(ds_local):
ds = ds_local
all_dtypes = [np.float64, np.float64, np.float64, np.float64, np.int64, np.int64, 'S25', np.object]
np.testing.assert_... | from common import *
def test_dtype(ds_local):
ds = ds_local
for name in ds.column_names:
assert ds[name].values.dtype == ds.dtype(ds[name])
def test_dtypes(ds_local):
ds = ds_local
assert (ds.dtypes.values == [ds[name].dtype for name in ds.column_names]).all()
| Update of the dtypes unit-test. | Update of the dtypes unit-test.
| Python | mit | maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex,maartenbreddels/vaex | ---
+++
@@ -4,12 +4,9 @@
def test_dtype(ds_local):
ds = ds_local
for name in ds.column_names:
- assert ds[name].values.dtype == ds.dtype(ds[name])
+ assert ds[name].values.dtype == ds.dtype(ds[name])
def test_dtypes(ds_local):
ds = ds_local
- all_dtypes = [np.float64, np.float64, np.float64, n... |
be77248c56b71ca3c5240ec55676d08227a1f526 | api/settings.py | api/settings.py | # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
DEBUG = False
TESTING = False
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
# Local Settings
"""MONG... | # -*- coding: utf-8 -*-
"""Application configuration."""
import os
class Config(object):
"""Base configuration."""
DEBUG = False
TESTING = False
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
SECRET_KEY = str(os.environ.g... | Add placeholder for secret key | Add placeholder for secret key
| Python | mit | jaredmichaelsmith/grove,jaredmichaelsmith/grove | ---
+++
@@ -11,6 +11,7 @@
TESTING = False
APP_DIR = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.abspath(os.path.join(APP_DIR, os.pardir))
+ SECRET_KEY = str(os.environ.get('SECRET_KEY'))
# Local Settings
"""MONGODB_DB = os.environ.get('WHERENO_DB', 'whereno')
@@ -21... |
877d90ff064b70a7ce861ed66082c4d703170fed | scripts/python/cgi-bin/resource.py | scripts/python/cgi-bin/resource.py | #!/usr/bin/env python
import datetime
import random
timestamp = datetime.datetime.now()
humidity = random.random()
temperature = random.random() * 100
print "Content-Type: application/json"
print
print """\
{"resource": "polling-resource",
"streams":
{
"temperature": {"value": %f, "timestamp": %s},
"humidi... | #!/usr/bin/env python
import datetime
import random
timestamp = datetime.datetime.now()
humidity = random.random()
temperature = random.random() * 100
print "Content-Type: application/json"
print
print """\
{"resource": "polling-resource",
"streams":
{
"temperature": {"value": %f, "timestamp": "%s"},
"humi... | Update timestamp to be a string | Update timestamp to be a string
| Python | apache-2.0 | projectcs13/sensor-cloud,projectcs13/sensor-cloud,EricssonResearch/iot-framework-engine,EricssonResearch/iot-framework-engine,projectcs13/sensor-cloud,EricssonResearch/iot-framework-engine,EricssonResearch/iot-framework-engine | ---
+++
@@ -10,8 +10,8 @@
{"resource": "polling-resource",
"streams":
{
- "temperature": {"value": %f, "timestamp": %s},
- "humidity": {"value": %f, "timestamp": %s}
+ "temperature": {"value": %f, "timestamp": "%s"},
+ "humidity": {"value": %f, "timestamp": "%s"}
}
}
""" % (temperature, time... |
e55ccadb0954eaa66526dc6f112b5eac54a51ab3 | calc/__init__.py | calc/__init__.py | """
_
___ __ _ | | ___
/ __|/ _` || | / __|
| (__| (_| || || (__
\___|\__,_||_| \___|
Note:
The relative imports here (noted by the . prefix) are done as a convenience
so that the consumers of the ``calc`` package can directly use objects
belonging to the ``calc.calc`` module. Essential... | """
_
___ __ _ | | ___
/ __|/ _` || | / __|
| (__| (_| || || (__
\___|\__,_||_| \___|
Rabbit hole:
The relative imports here (noted by the . prefix) are done as a convenience
so that the consumers of the ``calc`` package can directly use objects
belonging to the ``calc.calc`` module. Es... | Mark relative imports as a rabbit hole discussion | Mark relative imports as a rabbit hole discussion
| Python | isc | bike-barn/red-green-refactor | ---
+++
@@ -6,7 +6,7 @@
\___|\__,_||_| \___|
-Note:
+Rabbit hole:
The relative imports here (noted by the . prefix) are done as a convenience
so that the consumers of the ``calc`` package can directly use objects
belonging to the ``calc.calc`` module. Essentially this enables the consumer |
db2d8da9109ab4a8aa51acbd80abb2088a7fd299 | campus02/urls.py | campus02/urls.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='we... | #!/usr/bin/python
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns(
'',
url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^web/', include('campus02.web.urls', namespace='we... | Rearrange admin URL mount point. | Rearrange admin URL mount point.
| Python | mit | fladi/django-campus02,fladi/django-campus02 | ---
+++
@@ -6,8 +6,8 @@
urlpatterns = patterns(
'',
+ url(r'^', include('django.contrib.auth.urls')),
url(r'^admin/', include(admin.site.urls)),
- url(r'^', include('django.contrib.auth.urls')),
url(r'^web/', include('campus02.web.urls', namespace='web')),
url(r'^', include('campus02.base... |
e112fedcc11ec12d1a669b47a223b4363eeb27e0 | virustotal/server.py | virustotal/server.py | #!/usr/bin/env python
from contextlib import closing
from sqlite3 import connect
from os.path import isfile
from bottle import request, template, route, run
@route('/virustotal/<db>')
def virus(db):
if not isfile(db):
return 'The database does not exist: "%s"' % db
with connect(db, timeout=10) as conn... | #!/usr/bin/env python
from contextlib import closing
from sqlite3 import connect
from os.path import isfile
from bottle import request, template, route, run
@route('/virustotal/<db>')
def virus(db):
if not isfile(db):
return 'The database does not exist: "%s"' % db
with connect(db, timeout=10) as conn... | Fix typo in previous commit | Fix typo in previous commit
| Python | mit | enricobacis/playscraper | ---
+++
@@ -11,8 +11,8 @@
return 'The database does not exist: "%s"' % db
with connect(db, timeout=10) as connection:
with closing(connection.cursor()) as cursor:
- cursor.execute('SELECT count(*), CAST(0.999 + detected * 10 AS INT) || '0%' AS score'
- 'FROM... |
8226571dc97230a486a3b59c8752411e038f04ee | openprescribing/matrixstore/tests/matrixstore_factory.py | openprescribing/matrixstore/tests/matrixstore_factory.py | import mock
import sqlite3
from matrixstore.connection import MatrixStore
from matrixstore import db
from matrixstore.tests.import_test_data_fast import import_test_data_fast
def matrixstore_from_data_factory(data_factory, end_date=None, months=None):
"""
Returns a new in-memory MatrixStore instance using th... | import mock
import sqlite3
from matrixstore.connection import MatrixStore
from matrixstore import db
from matrixstore.tests.import_test_data_fast import import_test_data_fast
def matrixstore_from_data_factory(data_factory, end_date=None, months=None):
"""
Returns a new in-memory MatrixStore instance using th... | Fix MatrixStore test patching to work with LiveServerTestCase | Fix MatrixStore test patching to work with LiveServerTestCase
| Python | mit | annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing | ---
+++
@@ -11,7 +11,9 @@
Returns a new in-memory MatrixStore instance using the data from the
supplied DataFactory
"""
- connection = sqlite3.connect(":memory:")
+ # We need this connection to be sharable across threads because
+ # LiveServerTestCase runs in a separate thread from the main te... |
31ce7c5c264e7648427f73b51cd966165e63ec23 | beaver/redis_transport.py | beaver/redis_transport.py | import datetime
import redis
import urlparse
import beaver.transport
class RedisTransport(beaver.transport.Transport):
def __init__(self, file_config, beaver_config):
super(RedisTransport, self).__init__(file_config, beaver_config)
redis_url = beaver_config.get('redis_url')
_url = urlpa... | import datetime
import redis
import time
import urlparse
import beaver.transport
class RedisTransport(beaver.transport.Transport):
def __init__(self, file_config, beaver_config):
super(RedisTransport, self).__init__(file_config, beaver_config)
redis_url = beaver_config.get('redis_url')
... | Allow for initial connection lag. Helpful when waiting for an SSH proxy to connect | Allow for initial connection lag. Helpful when waiting for an SSH proxy to connect
| Python | mit | doghrim/python-beaver,Appdynamics/beaver,josegonzalez/python-beaver,doghrim/python-beaver,jlambert121/beaver,davidmoravek/python-beaver,josegonzalez/python-beaver,imacube/python-beaver,PierreF/beaver,zuazo-forks/beaver,zuazo-forks/beaver,thomasalrin/beaver,python-beaver/python-beaver,PierreF/beaver,rajmarndi/python-bea... | ---
+++
@@ -1,5 +1,6 @@
import datetime
import redis
+import time
import urlparse
import beaver.transport
@@ -17,6 +18,19 @@
self.redis = redis.StrictRedis(host=_url.hostname, port=_url.port, db=int(_db), socket_timeout=10)
self.redis_namespace = beaver_config.get('redis_namespace')
+ ... |
597a2ec7a6ff0bae0b43a67e8be675017fd1d7f1 | falafel/mappers/tests/test_current_clocksource.py | falafel/mappers/tests/test_current_clocksource.py | from falafel.mappers.current_clocksource import CurrentClockSource
from falafel.tests import context_wrap
CLKSRC = """
tsc
"""
def test_get_current_clksr():
clksrc = CurrentClockSource(context_wrap(CLKSRC))
assert clksrc.data == "tsc"
| from falafel.mappers.current_clocksource import CurrentClockSource
from falafel.tests import context_wrap
CLKSRC = """
tsc
"""
def test_get_current_clksr():
clksrc = CurrentClockSource(context_wrap(CLKSRC))
assert clksrc.data == "tsc"
assert clksrc.is_kvm is False
assert clksrc.is_vmi_timer != clksrc... | Enhance coverage of current_closcksource to 100% | Enhance coverage of current_closcksource to 100%
| Python | apache-2.0 | RedHatInsights/insights-core,RedHatInsights/insights-core | ---
+++
@@ -9,3 +9,5 @@
def test_get_current_clksr():
clksrc = CurrentClockSource(context_wrap(CLKSRC))
assert clksrc.data == "tsc"
+ assert clksrc.is_kvm is False
+ assert clksrc.is_vmi_timer != clksrc.is_tsc |
196fe935afd6adfec5d205e88472d7ef607b4743 | checkout.py | checkout.py | __author__ = 'RMGiroux'
import asyncio
from asyncio import subprocess
import sys
class OutputCollector:
def __init__(self, name):
self.name = name
@asyncio.coroutine
def process_line(self, stream):
while not stream.at_eof():
line = yield from stream.readline()
prin... | __author__ = 'RMGiroux'
import asyncio
from asyncio import subprocess
import sys
class OutputCollector:
def __init__(self, name):
self.name = name
@asyncio.coroutine
def process_line(self, stream):
while not stream.at_eof():
line = yield from stream.readline()
prin... | Add comment showing parallel waf invocation | Add comment showing parallel waf invocation
| Python | apache-2.0 | RMGiroux/python_experiments | ---
+++
@@ -26,9 +26,9 @@
callback(line)
@asyncio.coroutine
-def async_exec(repo, stdoutCallback):
+def async_exec(command, stdoutCallback):
fork = yield from asyncio.create_subprocess_shell(
- ("git clone %s"%repo),stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
+ (command),stdout... |
603ad671c1f6976f75065a4365589a75e1e384ee | service_and_process/serializers.py | service_and_process/serializers.py | from .models import *
from rest_framework import serializers
class MasterWorkableSerializer(serializers.ModelSerializer):
class Meta:
model = MasterWorkable
| from .models import *
from rest_framework import serializers
class MasterWorkableSerializer(serializers.ModelSerializer):
class Meta:
model = MasterWorkable
fields = '__all__'
| Add explicit fields in serializer | Add explicit fields in serializer
| Python | apache-2.0 | rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory,rameshgopalakrishnan/v_excel_inventory | ---
+++
@@ -5,3 +5,4 @@
class MasterWorkableSerializer(serializers.ModelSerializer):
class Meta:
model = MasterWorkable
+ fields = '__all__' |
910c21778751e2814e649adf6f4db99378891ab1 | _lib/wordpress_post_processor.py | _lib/wordpress_post_processor.py | import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content) ... | import sys
import json
import requests
from string import Template
import dateutil.parser
def posts_at_url(url):
current_page = 1
max_page = sys.maxint
while current_page <= max_page:
resp = requests.get(url, params={'json':1,'page':current_page})
results = json.loads(resp.content) ... | Update to new multiauthor taxonomy name | Update to new multiauthor taxonomy name
| Python | cc0-1.0 | kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh,kave/cfgov-refresh | ---
+++
@@ -33,7 +33,7 @@
post['category'] = [cat['title'] for cat in post['taxonomy_fj_category']]
post['tags'] = [tag['title'] for tag in post['taxonomy_fj_tag']]
author_template = Template("$first_name $last_name")
- post['author'] = [author['title'] for author in post['taxonomy_author']]
+ po... |
f243d309e5168b5855045227c9c0a6b082bedc69 | luigi/tasks/gtrnadb/__init__.py | luigi/tasks/gtrnadb/__init__.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | Check that there are data files to import | Check that there are data files to import
It is possible for the pattern to match nothing leading to no files
being imported. This is an error case so we raise an exception if it
happens.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | ---
+++
@@ -13,7 +13,7 @@
limitations under the License.
"""
-from glob import iglob
+from glob import glob
import luigi
@@ -24,12 +24,16 @@
class GtRNAdb(luigi.WrapperTask): # pylint: disable=R0904
"""
- Imports all GtRNAdb data. This will generate a task for each separate file to
- create th... |
9c7090215ecda3fd4d173c8c5f2d3e1462fbbeee | takePicture.py | takePicture.py | import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 50:
#os.unlink('greg.jpg')
img = cam.capture('gregTest.jpg')
time.sleep(.25)
#oc.rename('gregTemp.jpg', 'greg.jpg')
x +=1
exit()
| import picamera as p
import os
import time
os.chdir('/home/pi/Desktop')
cam = p.PiCamera()
cam.resolution = (320,240)
cam.hflip = True
cam.vflip = True
x = 0
while x < 50:
os.unlink('gregTest.jpg')
img = cam.capture('tempGregTest.jpg')
oc.rename('gregTempTest.jpg', 'gregTest.jpg')
time.sleep(.25)
x +=1
exit()
| Add temp file sequence to take picture file | Add temp file sequence to take picture file
| Python | mit | jwarshaw/RaspberryDrive | ---
+++
@@ -12,9 +12,9 @@
x = 0
while x < 50:
- #os.unlink('greg.jpg')
- img = cam.capture('gregTest.jpg')
+ os.unlink('gregTest.jpg')
+ img = cam.capture('tempGregTest.jpg')
+ oc.rename('gregTempTest.jpg', 'gregTest.jpg')
time.sleep(.25)
- #oc.rename('gregTemp.jpg', 'greg.jpg')
x +=1
exit() |
9f05a8917ee6fd01a334ef2e1e57062be8ef13af | byceps/config_defaults.py | byceps/config_defaults.py | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Disable Flask-SQLAlchemy's tracking... | """
byceps.config_defaults
~~~~~~~~~~~~~~~~~~~~~~
Default configuration values
:Copyright: 2006-2020 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import timedelta
from pathlib import Path
# database connection
SQLALCHEMY_ECHO = False
# Avoid connection errors after datab... | Enable DBMS pool pre-pinging to avoid connection errors | Enable DBMS pool pre-pinging to avoid connection errors
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | ---
+++
@@ -14,6 +14,10 @@
# database connection
SQLALCHEMY_ECHO = False
+
+# Avoid connection errors after database becomes temporarily
+# unreachable, then becomes reachable again.
+SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping': True}
# Disable Flask-SQLAlchemy's tracking of object modifications.
SQLALCHEMY_... |
968b862f6e437b627776b9b8ccf6204434493101 | tests/test_rover_instance.py | tests/test_rover_instance.py |
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
|
from unittest import TestCase
from rover import Rover
class TestRover(TestCase):
def setUp(self):
self.rover = Rover()
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
def test_rover_position(self):
assert self.rover.position == (self.rover.x, self... | Add failing rover position reporting test | Add failing rover position reporting test
| Python | mit | authentik8/rover | ---
+++
@@ -9,3 +9,6 @@
def test_rover_compass(self):
assert self.rover.compass == ['N', 'E', 'S', 'W']
+
+ def test_rover_position(self):
+ assert self.rover.position == (self.rover.x, self.rover.y, self.rover.direction) |
4d6c580f5dcf246bd75b499ee7a630eaf024b4d0 | harvester/sns_message.py | harvester/sns_message.py | import os
import boto3
import botocore.exceptions
import logging
import requests
logger = logging.getLogger(__name__)
def format_results_subject(cid, registry_action):
'''Format the "subject" part of the harvesting message for
results from the various processes.
Results: [Action from Registry] on [Work... | import os
import boto3
import botocore.exceptions
import logging
import requests
logger = logging.getLogger(__name__)
def format_results_subject(cid, registry_action):
'''Format the "subject" part of the harvesting message for
results from the various processes.
Results: [Action from Registry] on [Work... | Add worker emoji to subject | Add worker emoji to subject
| Python | bsd-3-clause | barbarahui/harvester,mredar/harvester,ucldc/harvester,barbarahui/harvester,mredar/harvester,ucldc/harvester | ---
+++
@@ -20,7 +20,7 @@
resp = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4')
worker_ip = resp.text
worker_id = worker_ip.replace('.', '-')
- return 'Results: {} on {} for CID: {}'.format(
+ return 'Results: {} on :worker: {} for CID: {}'.format(
registry_action,
... |
5c442db8a6352c21325f372486409d44ad3f5b76 | ServerBackup.py | ServerBackup.py | #!/usr/bin/python2
import LogUncaught, ConfigParser, logging, os
sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')
# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)
# Logger Formatter
sbLFORMAT = logging.Formatter('[%(as... | #!/usr/bin/python2
import LogUncaught, ConfigParser, logging, PushBullet, os
from time import localtime, strftime
sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')
# Logger File Handler
sbLFH = logging.FileHandler(sbConfig.get('ServerBackup', 'log_location'))
sbLFH.setLevel(logging.DEBUG)
# Logg... | Backup directory is made, and a notification is sent and logged if the directory doesn't exist | Backup directory is made, and a notification is sent and logged if the directory doesn't exist
| Python | mit | dwieeb/usr-local-bin | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/python2
-import LogUncaught, ConfigParser, logging, os
+import LogUncaught, ConfigParser, logging, PushBullet, os
+from time import localtime, strftime
sbConfig = ConfigParser.RawConfigParser()
sbConfig.read('scripts.cfg')
@@ -9,7 +10,7 @@
sbLFH.setLevel(logging.DEBUG)
# Lo... |
f4444f390ed2d16fab40e098d743870420da3bad | blockbuster/bb_logging.py | blockbuster/bb_logging.py | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.... | import config
import logging
import logging.handlers
# ######### Set up logging ##########
# log.basicConfig(format="%(asctime)s - %(levelname)s: %(message)s", level=log.DEBUG)
logger = logging.getLogger("blockbuster")
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
tfh = logging.... | Change log level for file handler | Change log level for file handler
| Python | mit | mattstibbs/blockbuster-server,mattstibbs/blockbuster-server | ---
+++
@@ -11,7 +11,7 @@
# create file handler which logs even debug messages
tfh = logging.handlers.TimedRotatingFileHandler(str.format('{0}/app.log', config.log_directory),
when='midnight', delay=False, encoding=None, backupCount=7)
-tfh.setLevel(logging.DEBUG)
+t... |
21835415f0224e08c7328151d4319ec73d67cbe1 | station.py | station.py | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = eval(input("Enter the max capacity of... | """Creates the station class"""
class Station:
"""
Each train station is an instance of the Station class.
Methods:
__init__: creates a new stations
total_station_pop: calculates total station population
"""
def __init__(self):
self.capacity = int(eval(input("Enter the max capacit... | Add int to input statements | Add int to input statements
Ref #23 #10
| Python | mit | ForestPride/rail-problem | ---
+++
@@ -10,13 +10,13 @@
"""
def __init__(self):
- self.capacity = eval(input("Enter the max capacity of the station: "))
+ self.capacity = int(eval(input("Enter the max capacity of the station: ")))
#testfuntion()
- self.escalators = eval(input("Enter the number of escala... |
be6fb5a1ec264f2f3f5dd57c84b90a9c2c686fe3 | mltsp/ext/celeryconfig.py | mltsp/ext/celeryconfig.py | #CELERY_RESULT_BACKEND = 'mltsp.ext.rethinkdb_backend:RethinkBackend'
CELERY_RESULT_BACKEND = "amqp"
#CELERY_RETHINKDB_BACKEND_SETTINGS = {
# 'host': '127.0.0.1',
# 'port': 28015,
# 'db': 'celery_test',
# 'auth_key': '',
# 'timeout': 20,
# 'table': 'celery_taskmeta',
# 'options': {}
#}
CE... | #CELERY_RESULT_BACKEND = 'mltsp.ext.rethinkdb_backend:RethinkBackend'
CELERY_RESULT_BACKEND = "amqp"
CELERY_RETHINKDB_BACKEND_SETTINGS = {
'host': '127.0.0.1',
'port': 28015,
'db': 'celery_test',
# 'auth_key': '',
'timeout': 20,
'table': 'celery_taskmeta',
'options': {}
}
CELERY_RESULT_SE... | Change Celery RethinkDB backend config | Change Celery RethinkDB backend config
| Python | bsd-3-clause | bnaul/mltsp,bnaul/mltsp,bnaul/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,mltsp/mltsp,bnaul/mltsp,bnaul/mltsp,acrellin/mltsp,mltsp/mltsp,acrellin/mltsp,mltsp/mltsp,mltsp/mltsp,mltsp/mltsp,acrellin/mltsp,acrellin/mltsp,bnaul/mltsp | ---
+++
@@ -2,15 +2,15 @@
CELERY_RESULT_BACKEND = "amqp"
-#CELERY_RETHINKDB_BACKEND_SETTINGS = {
- # 'host': '127.0.0.1',
- # 'port': 28015,
- # 'db': 'celery_test',
+CELERY_RETHINKDB_BACKEND_SETTINGS = {
+ 'host': '127.0.0.1',
+ 'port': 28015,
+ 'db': 'celery_test',
# 'auth_key': '',
- ... |
42d64b71db7a21355132d1c1573e12798e377b4c | incomplete/pythagoras.py | incomplete/pythagoras.py | import sys
def gather_squares_triangles(p1,p2,depth)
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...... | import sys
def gather_squares_triangles(p1,p2,depth)
""" Draw Square and Right Triangle given 2 points,
Recurse on new points
args:
p1,p2 (float,float) : absolute position on base vertices
depth (int) : decrementing counter that terminates recursion
return:
squares [(float,float,float,float)...... | Gather Squares & Triangles Implemented | PythagTree: Gather Squares & Triangles Implemented
| Python | mit | kpatel20538/Rosetta-Code-Python-Tasks | ---
+++
@@ -13,8 +13,20 @@
triangles [(float,float,float)...] : absolute positions of
vertices of right triangles
"""
- pass
+ if depth == 0:
+ return [],[]
+ pd = (p2[0] - p1[0]),(p1[1] - p2[1])
+ p3 = (p2[0] - pd[1]),(p2[1] - pd[0])
+ p4 = (p1[0] - pd[1]),(p1[1] - pd[0])
+ p5 = (p4[0] ... |
3609df9044fd72008234bae9145487f315096fcd | hcalendar/__init__.py | hcalendar/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
"""
python-hcalendar is a basic hCalendar parser
"""
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
python-hcalendar is a basic hCalendar parser
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__version_info__ = {
'major': 0,
'minor': 2,
'micro': 0,
... | Fix hcalendar module __doc__ missing | Fix hcalendar module __doc__ missing
| Python | mit | mback2k/python-hcalendar | ---
+++
@@ -1,13 +1,12 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
+"""
+python-hcalendar is a basic hCalendar parser
+"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
-
-"""
-python-hcalendar is a basic... |
5688ca60985db606a3d42078a017bd851c1f01f6 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | Cut fbcode_builder dep for thrift on krb5 | Cut fbcode_builder dep for thrift on krb5
Summary: [Thrift] Cut `fbcode_builder` dep for `thrift` on `krb5`. In the past, Thrift depended on Kerberos and the `krb5` implementation for its transport-layer security. However, Thrift has since migrated fully to Transport Layer Security for its transport-layer security and... | Python | apache-2.0 | facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift,facebook/fbthrift | ---
+++
@@ -21,15 +21,12 @@
'no1msd/mstch:git_hash',
ShellQuoted('$(git describe --abbrev=0 --tags)')
)
- builder.add_option('krb5/krb5:git_hash', 'krb5-1.16.1-final')
return {
'depends_on': [folly, fizz, sodium, rsocket, wangle, zstd],
'steps': [
# This i... |
65e041bd03863563b52496c1cec81a0c9425f4ee | geonamescache/mappers.py | geonamescache/mappers.py | # -*- coding: utf-8 -*-
from geonamescache import GeonamesCache
from . import mappings
def country(from_key='name', to_key='iso'):
gc = GeonamesCache()
dataset = gc.get_dataset_by_key(gc.get_countries(), from_key)
def mapper(key):
if 'name' == from_key and key in mappings.country_names:
... | # -*- coding: utf-8 -*-
from geonamescache import GeonamesCache
from . import mappings
def country(from_key='name', to_key='iso'):
"""Creates and returns a mapper function to access country data.
The mapper function that is returned must be called with one argument. In
the default case you call it with a... | Add documentation for country mapper | Add documentation for country mapper
| Python | mit | yaph/geonamescache,yaph/geonamescache | ---
+++
@@ -4,13 +4,29 @@
def country(from_key='name', to_key='iso'):
+ """Creates and returns a mapper function to access country data.
+
+ The mapper function that is returned must be called with one argument. In
+ the default case you call it with a name and it returns a 3-letter
+ ISO_3166-1 code... |
b34eaedad04c32252f8f2972c335635c6783ae79 | evelink/__init__.py | evelink/__init__.py | """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.5.0"
# Implement NullHandler... | """EVELink - Python bindings for the EVE API."""
import logging
from evelink import account
from evelink import api
from evelink import char
from evelink import constants
from evelink import corp
from evelink import eve
from evelink import map
from evelink import server
__version__ = "0.5.1"
# Implement NullHandler... | Update version to 0.5.1 for Hyperion release | Update version to 0.5.1 for Hyperion release
| Python | mit | bastianh/evelink,FashtimeDotCom/evelink,ayust/evelink,Morloth1274/EVE-Online-POCO-manager,zigdon/evelink | ---
+++
@@ -11,7 +11,7 @@
from evelink import map
from evelink import server
-__version__ = "0.5.0"
+__version__ = "0.5.1"
# Implement NullHandler because it was only added in Python 2.7+.
class NullHandler(logging.Handler): |
2814f5b2bbd2c53c165f13009eb85cb2c5030b57 | chicago/search_indexes.py | chicago/search_indexes.py | from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics... | from datetime import datetime
from councilmatic_core.haystack_indexes import BillIndex
from django.conf import settings
from haystack import indexes
import pytz
from chicago.models import ChicagoBill
app_timezone = pytz.timezone(settings.TIME_ZONE)
class ChicagoBillIndex(BillIndex, indexes.Indexable):
topics... | Use prepared data, rather than the object last action date, to determine boost | Use prepared data, rather than the object last action date, to determine boost
| Python | mit | datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic,datamade/chi-councilmatic | ---
+++
@@ -22,11 +22,13 @@
data = super(ChicagoBillIndex, self).prepare(obj)
boost = 0
- if obj.last_action_date:
- now = app_timezone.localize(datetime.now())
- # obj.last_action_date can be in the future
- weeks_passed = (now - obj.last_action_date).day... |
91a551c0bc29d09cd2f034741c1291bfad7346db | tensorflow/tools/docker/jupyter_notebook_config.py | tensorflow/tools/docker/jupyter_notebook_config.py | # Copyright 2015 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 applicable law or a... | # Copyright 2015 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 applicable law or a... | Move imports to beginning of code | Move imports to beginning of code
| Python | apache-2.0 | AnishShah/tensorflow,dhalleine/tensorflow,LUTAN/tensorflow,chemelnucfin/tensorflow,brchiu/tensorflow,jalexvig/tensorflow,Intel-tensorflow/tensorflow,benoitsteiner/tensorflow-xsmm,alistairlow/tensorflow,ageron/tensorflow,sandeepdsouza93/TensorFlow-15712,RapidApplicationDevelopment/tensorflow,ravindrapanda/tensorflow,rdi... | ---
+++
@@ -12,6 +12,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
+import os
+from IPython.lib import passwd
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
@@ -20,7 ... |
dd51e13a2a7b4e4005127ca0e409d0882179b39f | bluebottle/mail/__init__.py | bluebottle/mail/__init__.py | from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
def send_mail(template_name, subject, to, **kwargs):
if hasattr(to, 'pr... | from django.contrib.sites.models import Site
from django.template.loader import get_template
from django.utils import translation
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
from bluebottle.clients import properties
def send_mail(template_name, subj... | Use CONTACT_EMAIL als default from address | Use CONTACT_EMAIL als default from address
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle | ---
+++
@@ -4,6 +4,7 @@
from bluebottle.clients.context import ClientContext
from bluebottle.clients.mail import EmailMultiAlternatives
+from bluebottle.clients import properties
def send_mail(template_name, subject, to, **kwargs):
@@ -24,7 +25,9 @@
if hasattr(to, 'primary_language') and to.primary_lang... |
606e9731bdcaf61f1358a5fc5341c85c83d18370 | IPython/config/profile/sympy/ipython_config.py | IPython/config/profile/sympy/ipython_config.py | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
lines = """
from __future__ import division
from sympy import *
x, y, z = symbols('xyz')
k, m, n = symbols('kmn... | c = get_config()
app = c.InteractiveShellApp
# This can be used at any point in a config file to load a sub config
# and merge it into the current one.
load_subconfig('ipython_config.py', profile='default')
lines = """
from __future__ import division
from sympy import *
x, y, z = symbols('x,y,z')
k, m, n = symbols('k... | Fix sympy profile to work with sympy 0.7. | Fix sympy profile to work with sympy 0.7.
Sympy 0.7 no longer supports x,y,z = symbols('xyz').
symbols ('xyz') is now a single symbol 'xyz'.
Change the sympy profile to symbols(x,y,z).
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -8,8 +8,8 @@
lines = """
from __future__ import division
from sympy import *
-x, y, z = symbols('xyz')
-k, m, n = symbols('kmn', integer=True)
+x, y, z = symbols('x,y,z')
+k, m, n = symbols('k,m,n', integer=True)
f, g, h = map(Function, 'fgh')
"""
|
ab0f6115c50bea63856c1e880249ad4bdca3ce42 | src/web/urls.py | src/web/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
url(r'^logout/', auth_views.logout, {'next_page': '/login'}, nam... | from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/', auth_views.login, name='login',
kwargs={'redirect_authenticated_user': True}),
url(r'^logout/', auth_views.logout, {'next_page': '/login'}, nam... | Add ansible namespace in root URLconf | Add ansible namespace in root URLconf
| Python | bsd-3-clause | lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin | ---
+++
@@ -8,5 +8,5 @@
kwargs={'redirect_authenticated_user': True}),
url(r'^logout/', auth_views.logout, {'next_page': '/login'}, name='logout'),
url(r'^admin/', admin.site.urls),
- url(r'^playbooks/', include('ansible.urls')),
+ url(r'^playbooks/', include('ansible.urls', namespace='ansibl... |
5bf24464b00257a9fa5f66047a2f7815c1e4f8fb | tweepy/utils.py | tweepy/utils.py | # Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
import datetime
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
def parse_datetime(datetime_string):
return datetime.datetime.strptime(
datetime_string, "%Y-%m-%dT%H:%M:%S.%f%z"
)
| # Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
import datetime
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
def parse_datetime(datetime_string):
return datetime.datetime.strptime(
datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ"
).re... | Fix parse_datetime to parse API datetime string format with Python 3.6 | Fix parse_datetime to parse API datetime string format with Python 3.6
The '%z' directive didn't accept 'Z' until Python 3.7
| Python | mit | svven/tweepy,tweepy/tweepy | ---
+++
@@ -12,5 +12,6 @@
def parse_datetime(datetime_string):
return datetime.datetime.strptime(
- datetime_string, "%Y-%m-%dT%H:%M:%S.%f%z"
- )
+ datetime_string, "%Y-%m-%dT%H:%M:%S.%fZ"
+ ).replace(tzinfo=datetime.timezone.utc)
+ # Use %z when support for Python 3.6 is dropped |
a0740ec8373a3a178e3e83b4ec2768621c697181 | versions/rattoolsversions.py | versions/rattoolsversions.py | #!/usr/bin/env python
#
# RatToolsDev
#
# The development versions of rattools
#
# Author P G Jones - 15/10/2012 <p.g.jones@qmul.ac.uk> : First revision
####################################################################################################
import rattools
class RatToolsDev(rattools.RatToolsDevelopment):... | #!/usr/bin/env python
#
# RatToolsDev
#
# The development versions of rattools
#
# Author P G Jones - 15/10/2012 <p.g.jones@qmul.ac.uk> : First revision
####################################################################################################
import rattools
class RatToolsDev(rattools.RatToolsDevelopment):... | Add fixed release rat-tools versions 4, 4.1, 4.2 | Add fixed release rat-tools versions 4, 4.1, 4.2
| Python | mit | mjmottram/snoing,mjmottram/snoing | ---
+++
@@ -13,6 +13,23 @@
""" Initialise dev version."""
super(RatToolsDev, self).__init__("rattools-dev", system, "root-5.34.02")
+class RatTools42(rattools.RatToolsRelease):
+ def __init__(self, system):
+ """ Initialise an arbitrary snaphot version."""
+ super(RatTools42, self... |
988f4aec1588f409f296e89acb47040cb2606cf8 | ocradmin/plugins/numpy_nodes.py | ocradmin/plugins/numpy_nodes.py |
import node
import manager
import stages
import numpy
class Rotate90Node(node.Node):
"""
Rotate a Numpy image by num*90 degrees.
"""
arity = 1
stage = stages.FILTER_BINARY
name = "Numpy::Rotate90"
_parameters = [{
"name": "num",
"value": 1,
}]
... |
import node
import manager
import stages
import numpy
class Rotate90Node(node.Node):
"""
Rotate a Numpy image by num*90 degrees.
"""
arity = 1
stage = stages.FILTER_BINARY
name = "Numpy::Rotate90"
_parameters = [{
"name": "num",
"value": 1,
}]
... | Add a grayscale rotation node (for testing) | Add a grayscale rotation node (for testing)
| Python | apache-2.0 | vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium | ---
+++
@@ -31,6 +31,14 @@
return numpy.rot90(image, int(self._params.get("num", 1)))
+class Rotate90GrayNode(Rotate90Node):
+ """
+ Grayscale version of above.
+ """
+ stage = stages.FILTER_GRAY
+ name = "Numpy::Rotate90Gray"
+
+
class Manager(manager.StandardManager):
"""
Hand... |
dd237d82426ebbc3d2854641e8e73e2001857b67 | damn/templatetags/damn.py | damn/templatetags/damn.py |
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] ... |
from django import template
from django.utils.safestring import mark_safe
from ..processors import AssetRegistry
register = template.Library()
class AssetsNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
context.render_context['AMN'] ... | Rename 'name' argument to 'filename' | Rename 'name' argument to 'filename'
| Python | bsd-2-clause | funkybob/django-amn | ---
+++
@@ -31,7 +31,7 @@
@register.simple_tag(takes_context=True)
-def asset(context, name=None, alias=None, mode=None, *args):
+def asset(context, filename=None, alias=None, mode=None, *args):
'''
{% asset alias mode=? ... %}
{% asset file.js ... %}
@@ -42,14 +42,14 @@
mode = asset mode [i... |
7769e5ddd5784b7e56b75fc33f25b0f40ecaa99e | cryptex/exchange/__init__.py | cryptex/exchange/__init__.py | from cryptex.exchange.exchange import Exchange
from cryptex.exchange.cryptsy import Cryptsy
from cryptex.exchange.btce import BTCE
| from cryptex.exchange.exchange import Exchange
from cryptex.exchange.cryptsy import Cryptsy, CryptsyPublic
from cryptex.exchange.btce import BTCE, BTCEPublic
| Add public imports to exchange module | Add public imports to exchange module
| Python | mit | coink/cryptex | ---
+++
@@ -1,3 +1,3 @@
from cryptex.exchange.exchange import Exchange
-from cryptex.exchange.cryptsy import Cryptsy
-from cryptex.exchange.btce import BTCE
+from cryptex.exchange.cryptsy import Cryptsy, CryptsyPublic
+from cryptex.exchange.btce import BTCE, BTCEPublic |
88f341c6a9d079c89537feb1fb0aa8908732421a | evennia/server/migrations/0002_auto_20190128_1820.py | evennia/server/migrations/0002_auto_20190128_1820.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a PickleO... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-01-28 18:20
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
from evennia.utils.utils import to_bytes, to_str
def migrate_serverconf(apps, schema_editor):
"""
Move server conf from a custom binary field into a... | Fix migration for various situations | Fix migration for various situations
| Python | bsd-3-clause | jamesbeebop/evennia,jamesbeebop/evennia,jamesbeebop/evennia | ---
+++
@@ -4,7 +4,7 @@
import pickle
from django.db import migrations, models
import evennia.utils.picklefield
-from evennia.utils.utils import to_bytes
+from evennia.utils.utils import to_bytes, to_str
def migrate_serverconf(apps, schema_editor):
"""
@@ -13,8 +13,8 @@
ServerConfig = apps.get_model("... |
deb91e9f1e3c7332c005ca498f1c6bc79cf59b34 | ansible-tests/validations-api.py | ansible-tests/validations-api.py | #!/usr/bin/env python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Hello World!"
app.run(debug=True)
| #!/usr/bin/env python
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return jsonify({"msg": "Hello World!"})
@app.route('/v1/validations/')
def list_validations():
return jsonify({"TODO": "List existing validations"})
@app.route('/v1/validations/<uuid>/')
def show_v... | Add the basic validation routes | Add the basic validation routes
| Python | apache-2.0 | coolsvap/clapper,coolsvap/clapper,rthallisey/clapper,coolsvap/clapper,rthallisey/clapper | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-from flask import Flask
+from flask import Flask, jsonify
app = Flask(__name__)
@@ -8,7 +8,27 @@
@app.route('/')
def index():
- return "Hello World!"
+ return jsonify({"msg": "Hello World!"})
+
+
+@app.route('/v1/validations/')
+def list_validations():
... |
f3dd0c94c0c7be2a5ebc2c0df59dd9fb15969eb9 | ghpythonremote/_configure_ironpython_installation.py | ghpythonremote/_configure_ironpython_installation.py | import sys
import pip
from .helpers import get_rhino_ironpython_path
if __name__ == '__main__':
location = None
if len(sys.argv) > 1:
location = sys.argv[1]
rhino_ironpython_path = get_rhino_ironpython_path(location=location)
package_name = __package__.split('.')[0]
pip_cmd = ['install', pa... | import sys
import pip
import logging
from .helpers import get_rhino_ironpython_path
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
if __name__ == '__main__':
location = None
if len(sys.argv) > 1:
location = sys.argv[1]
rhino_ironpython_path = get_rhino_ironpython_path(... | Correct --no-binary option, incorrect formatting in pypi doc | Correct --no-binary option, incorrect formatting in pypi doc
| Python | mit | Digital-Structures/ghpythonremote,pilcru/ghpythonremote | ---
+++
@@ -1,6 +1,9 @@
import sys
import pip
+import logging
from .helpers import get_rhino_ironpython_path
+
+logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
if __name__ == '__main__':
location = None
@@ -9,7 +12,7 @@
rhino_ironpython_path = get_rhino_ironpython_path(loca... |
e821236194b7e6f132c9fd08758b751edd8f0fc8 | Python/ProcBridge/example/client.py | Python/ProcBridge/example/client.py | import procbridge
# from procbridge import procbridge
host = '127.0.0.1'
port = 8077
client = procbridge.ProcBridge(host, port)
print(client.request('echo', {}))
print(client.request('add', {
'elements': [1, 2, 3, 4, 5]
}))
| import procbridge
# from procbridge import procbridge
host = '127.0.0.1'
port = 8877
client = procbridge.ProcBridge(host, port)
print(client.request('echo', {}))
print(client.request('add', {
'elements': [1, 2, 3, 4, 5]
}))
| Make port number the same in both Java and Python examples | Make port number the same in both Java and Python examples
| Python | mit | gongzhang/proc-bridge,gongzhang/proc-bridge | ---
+++
@@ -3,7 +3,7 @@
host = '127.0.0.1'
-port = 8077
+port = 8877
client = procbridge.ProcBridge(host, port)
|
b9dd3a5d2f52f6cebb55b322cf4ddb2b9e1d8ccc | arches/db/install/truncate_db.py | arches/db/install/truncate_db.py | import os
import inspect
import subprocess
from django.template import Template
from django.template import Context
from django.conf import settings
from arches.management.commands import utils
def create_sqlfile(database_settings, path_to_file):
context = Context(database_settings)
postgres_version = s... | import os
import inspect
import subprocess
from django.template import Template
from django.template import Context
from django.conf import settings
from arches.management.commands import utils
def create_sqlfile(database_settings, path_to_file):
context = Context(database_settings)
postgres_version = s... | Remove reference to postgis template. Django now installs postgis when database is created. | Remove reference to postgis template. Django now installs postgis when database is created.
| Python | agpl-3.0 | archesproject/arches,cvast/arches,cvast/arches,archesproject/arches,cvast/arches,cvast/arches,archesproject/arches,archesproject/arches | ---
+++
@@ -17,7 +17,6 @@
t = Template(
"SELECT pg_terminate_backend({{ PID }}) from pg_stat_activity where datname='{{ NAME }}';\n"
- "SELECT pg_terminate_backend({{ PID }}) from pg_stat_activity where datname='{{ POSTGIS_TEMPLATE }}';\n"
"\n"
"DROP DATABASE IF EXISTS {{ NAME }};\n"
@@ -26,7 +25,6 @@
"... |
48a92a395967aa6a0171495e80566910f76fd06c | kino/functions/github.py | kino/functions/github.py | import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password =... | import datetime
from github import Github
from slack.slackbot import SlackerAdapter
from utils.config import Config
from utils.resource import MessageResource
class GithubManager(object):
def __init__(self):
self.config = Config().github
self.username = self.config["USERNAME"]
password =... | Modify commit count str format | Modify commit count str format
| Python | mit | DongjunLee/kino-bot | ---
+++
@@ -30,4 +30,4 @@
if len(commit_events) == 0:
self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EMPTY)
else:
- self.slackbot.send_message(channel=channel, text=MessageResource.GITHUB_COMMIT_EXIST + len(commit_events))
+ self.sla... |
859c67eff781285473b92f6e363c9c3a3aaed33e | ExplorerTest.py | ExplorerTest.py | import time
import spi_serial
if __name__ == "__main__":
ss = spi_serial.SpiSerial()
time.sleep(3)
cmd = [1]
ss.write(cmd)
if ss.inWaiting() > 0:
print(''.join(chr(k) for k in ss.read(0)))
cmd = [2]
ss.write(cmd)
if ss.inWaiting() > 0:
print(''.join(chr(k) for k in ss.read(... | import time
import spi_serial
if __name__ == "__main__":
ss = spi_serial.SpiSerial()
time.sleep(3)
cmd = [1]
ss.write(cmd)
if ss.inWaiting() > 0:
print(''.join(chr(k) for k in ss.read(0)))
cmd = [2]
ss.write(cmd)
if ss.inWaiting() > 0:
print(''.join(chr(k) for k in ss.rea... | Fix tab (change to spaces) | Fix tab (change to spaces)
Fixes:
$ python ExplorerTest.py
File "ExplorerTest.py", line 6
time.sleep(3)
^
IndentationError: unexpected indent | Python | mit | EnhancedRadioDevices/915MHzEdisonExplorer_SW | ---
+++
@@ -3,8 +3,8 @@
if __name__ == "__main__":
ss = spi_serial.SpiSerial()
- time.sleep(3)
-
+ time.sleep(3)
+
cmd = [1]
ss.write(cmd)
if ss.inWaiting() > 0: |
7a308233707e7e024311a3767367875921c6217b | graphiter/models.py | graphiter/models.py | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)... | Add blank=True for Page.time_until field | Add blank=True for Page.time_until field | Python | bsd-2-clause | jwineinger/django-graphiter | ---
+++
@@ -15,7 +15,7 @@
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
- time_until = models.CharField(max_length=50, default=u"")
+ time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=... |
e8dae2888576fa2305cddda0e48f332276b176b5 | app/__init__.py | app/__init__.py | #!flask/bin/python
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
| #!flask/bin/python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
from app import views, models
| Update to flask_sqlalchemy to use python 3 import | Update to flask_sqlalchemy to use python 3 import | Python | agpl-3.0 | lasa/website,lasa/website,lasa/website | ---
+++
@@ -1,6 +1,6 @@
#!flask/bin/python
from flask import Flask
-from flask.ext.sqlalchemy import SQLAlchemy
+from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config.from_object('config') |
fd697a0a4a4aeb3455ec7b7e8b3ed38ce0eb4502 | test/sockettest.py | test/sockettest.py | import kaa
@kaa.coroutine()
def new_client(client):
ip, port = client.address
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port %d\n' % (ip, port))
remote = tls.TLSSocket()
#remote = kaa.Socket()
yield remote.connect... | import logging
import kaa
from kaa.net.tls import TLSSocket
log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield client.starttls_server()
client.write('Hello %s, connecting from port... | Fix TLS support in socket test | Fix TLS support in socket test
| Python | lgpl-2.1 | freevo/kaa-base,freevo/kaa-base | ---
+++
@@ -1,31 +1,26 @@
+import logging
import kaa
+from kaa.net.tls import TLSSocket
+
+log = logging.getLogger('tls').ensureRootHandler()
@kaa.coroutine()
def new_client(client):
- ip, port = client.address
+ ip, port = client.peer[:2]
print 'New connection from %s:%s' % (ip, port)
#yield cli... |
91c620e228ad73e2e34efbd60813ed35b3f9ef46 | tests/test_dtool_dataset_freeze.py | tests/test_dtool_dataset_freeze.py | """Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_create.dataset im... | """Test the ``dtool dataset create`` command."""
import os
import shutil
from click.testing import CliRunner
from dtoolcore import DataSet, ProtoDataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
from dtool_cre... | Fix the freeze functional test | Fix the freeze functional test
| Python | mit | jic-dtool/dtool-create | ---
+++
@@ -5,30 +5,36 @@
from click.testing import CliRunner
-from dtoolcore import DataSet
+from dtoolcore import DataSet, ProtoDataSet
from . import chdir_fixture, tmp_dir_fixture # NOQA
from . import SAMPLE_FILES_DIR
def test_dataset_freeze_functional(chdir_fixture): # NOQA
- from dtool_create.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.