commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
ae2a3716556b6c689d46e52544f7c98f2dfa0a69 | Remove language property from Context resource template | chop-dbhi/serrano,rv816/serrano_night,chop-dbhi/serrano,rv816/serrano_night | serrano/resources/templates.py | serrano/resources/templates.py | Category = {
'fields': [':pk', 'name', 'order', 'parent_id'],
'allow_missing': True,
}
BriefField = {
'fields': [':pk', 'name', 'description'],
'allow_missing': True,
}
Field = {
'fields': [
':pk', 'name', 'plural_name', 'description', 'keywords',
'app_name', 'model_name', 'field_name',
'modified', 'published', 'archived', 'operators',
'simple_type', 'internal_type', 'data_modified', 'enumerable',
'searchable', 'unit', 'plural_unit', 'nullable'
],
'aliases': {
'plural_name': 'get_plural_name',
'plural_unit': 'get_plural_unit',
},
'allow_missing': True,
}
BriefConcept = {
'fields': [':pk', 'name', 'description'],
'allow_missing': True,
}
Concept = {
'fields': [
':pk', 'name', 'plural_name', 'description', 'keywords',
'category_id', 'order', 'modified', 'published', 'archived',
'formatter_name', 'queryview', 'sortable'
],
'aliases': {
'plural_name': 'get_plural_name',
},
'allow_missing': True,
}
ConceptField = {
'fields': ['alt_name', 'alt_plural_name'],
'aliases': {
'alt_name': 'name',
'alt_plural_name': 'get_plural_name',
},
'allow_missing': True,
}
Context = {
'exclude': ['user', 'session_key'],
'allow_missing': True,
}
View = {
'exclude': ['user', 'session_key'],
'allow_missing': True,
}
| Category = {
'fields': [':pk', 'name', 'order', 'parent_id'],
'allow_missing': True,
}
BriefField = {
'fields': [':pk', 'name', 'description'],
'allow_missing': True,
}
Field = {
'fields': [
':pk', 'name', 'plural_name', 'description', 'keywords',
'app_name', 'model_name', 'field_name',
'modified', 'published', 'archived', 'operators',
'simple_type', 'internal_type', 'data_modified', 'enumerable',
'searchable', 'unit', 'plural_unit', 'nullable'
],
'aliases': {
'plural_name': 'get_plural_name',
'plural_unit': 'get_plural_unit',
},
'allow_missing': True,
}
BriefConcept = {
'fields': [':pk', 'name', 'description'],
'allow_missing': True,
}
Concept = {
'fields': [
':pk', 'name', 'plural_name', 'description', 'keywords',
'category_id', 'order', 'modified', 'published', 'archived',
'formatter_name', 'queryview', 'sortable'
],
'aliases': {
'plural_name': 'get_plural_name',
},
'allow_missing': True,
}
ConceptField = {
'fields': ['alt_name', 'alt_plural_name'],
'aliases': {
'alt_name': 'name',
'alt_plural_name': 'get_plural_name',
},
'allow_missing': True,
}
Context = {
'fields': [':pk', ':local', 'language'],
'exclude': ['user', 'session_key'],
'allow_missing': True,
}
View = {
'exclude': ['user', 'session_key'],
'allow_missing': True,
}
| bsd-2-clause | Python |
d13353eac11e03aa3d3d83d49058b05ceb64e626 | Update version.py | mir-dataset-loaders/mirdata | mirdata/version.py | mirdata/version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Version info"""
# version = '0.1.0'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Version info"""
# version = '0.1.0'
` | bsd-3-clause | Python |
42b6e51df4377e933e6ee24b12a5d83d42a655da | Add missing packages to backend | picsadotcom/maguire | backend/setup.py | backend/setup.py | from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='admin@picsa.com',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'djangorestframework==3.6.4',
'django-rest-auth',
'dj-database-url',
'psycopg2',
'raven',
'gunicorn',
'django-filter',
'whitenoise',
'celery',
'redis',
'pytz',
'python-dateutil',
'django-cors-middleware',
'django-reversion',
'graphene<2.0',
'graphene-django<2.0.0',
'graphql-core<2.0',
'pendulum',
'django-role-permissions==1.2.1',
'django-celery-beat',
'boto3',
'django-storages',
'opbeat',
'postmarker',
'django-extensions',
],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from setuptools import setup, find_packages
setup(
name="maguire",
version="0.1",
url='https://github.com/picsadotcom/maguire',
license='BSD',
author='Picsa',
author_email='admin@picsa.com',
packages=find_packages(),
include_package_data=True,
install_requires=[
'Django',
'djangorestframework==3.6.4',
'django-rest-auth',
'dj-database-url',
'psycopg2',
'raven',
'gunicorn',
'django-filter',
'whitenoise',
'celery',
'redis',
'pytz',
'python-dateutil',
'django-cors-middleware',
'django-reversion',
'graphene<2.0',
'graphene-django<2.0.0',
'graphql-core<2.0',
'pendulum',
'django-role-permissions==1.2.1',
'django-celery-beat',
'boto3',
'django-storages',
'opbeat',
],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| bsd-3-clause | Python |
43b0bd441f4b91357cb4895eb59a394eaf2feef0 | Add __version__ | JaviMerino/bart,ARM-software/bart | bart/__init__.py | bart/__init__.py | # Copyright 2015-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Initialization for bart"""
import bart.sched
import bart.common
import bart.thermal
import pkg_resources
try:
__version__ = pkg_resources.get_distribution("trappy").version
except pkg_resources.DistributionNotFound:
__version__ = "local"
| # Copyright 2015-2015 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Initialization for bart"""
import bart.sched
import bart.common
import bart.thermal
| apache-2.0 | Python |
98f7b5df3286503ab082f85b242f8282f9783b66 | Add refresh token for Strava | python-social-auth/social-core,python-social-auth/social-core | social_core/backends/strava.py | social_core/backends/strava.py | """
Strava OAuth2 backend, docs at:
https://python-social-auth.readthedocs.io/en/latest/backends/strava.html
"""
from .oauth import BaseOAuth2
class StravaOAuth(BaseOAuth2):
name = 'strava'
AUTHORIZATION_URL = 'https://www.strava.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://www.strava.com/oauth/token'
ACCESS_TOKEN_METHOD = 'POST'
# Strava doesn't check for parameters in redirect_uri and directly appends
# the auth parameters to it, ending with an URL like:
# http://example.com/complete/strava?redirect_state=xxx?code=xxx&state=xxx
# Check issue #259 for details.
REDIRECT_STATE = False
REVOKE_TOKEN_URL = 'https://www.strava.com/oauth/deauthorize'
SCOPE_SEPARATOR = ','
EXTRA_DATA = [
('refresh_token'),
('expires_in', 'expires'),
]
def get_user_id(self, details, response):
return response['athlete']['id']
def get_user_details(self, response):
"""Return user details from Strava account"""
# because there is no usernames on strava
username = response['athlete']['id']
email = response['athlete'].get('email', '')
fullname, first_name, last_name = self.get_user_names(
first_name=response['athlete'].get('firstname', ''),
last_name=response['athlete'].get('lastname', ''),
)
return {'username': str(username),
'fullname': fullname,
'first_name': first_name,
'last_name': last_name,
'email': email}
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json('https://www.strava.com/api/v3/athlete',
params={'access_token': access_token})
def revoke_token_params(self, token, uid):
params = super(StravaOAuth, self).revoke_token_params(token, uid)
params['access_token'] = token
return params
| """
Strava OAuth2 backend, docs at:
https://python-social-auth.readthedocs.io/en/latest/backends/strava.html
"""
from .oauth import BaseOAuth2
class StravaOAuth(BaseOAuth2):
name = 'strava'
AUTHORIZATION_URL = 'https://www.strava.com/oauth/authorize'
ACCESS_TOKEN_URL = 'https://www.strava.com/oauth/token'
ACCESS_TOKEN_METHOD = 'POST'
# Strava doesn't check for parameters in redirect_uri and directly appends
# the auth parameters to it, ending with an URL like:
# http://example.com/complete/strava?redirect_state=xxx?code=xxx&state=xxx
# Check issue #259 for details.
REDIRECT_STATE = False
REVOKE_TOKEN_URL = 'https://www.strava.com/oauth/deauthorize'
SCOPE_SEPARATOR = ','
def get_user_id(self, details, response):
return response['athlete']['id']
def get_user_details(self, response):
"""Return user details from Strava account"""
# because there is no usernames on strava
username = response['athlete']['id']
email = response['athlete'].get('email', '')
fullname, first_name, last_name = self.get_user_names(
first_name=response['athlete'].get('firstname', ''),
last_name=response['athlete'].get('lastname', ''),
)
return {'username': str(username),
'fullname': fullname,
'first_name': first_name,
'last_name': last_name,
'email': email}
def user_data(self, access_token, *args, **kwargs):
"""Loads user data from service"""
return self.get_json('https://www.strava.com/api/v3/athlete',
params={'access_token': access_token})
def revoke_token_params(self, token, uid):
params = super(StravaOAuth, self).revoke_token_params(token, uid)
params['access_token'] = token
return params
| bsd-3-clause | Python |
3d1552677cbe0b3c91f71240b9685c55e04e72fa | Remove commented debugger | engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,admiral96/mulungwishi-webhook,admiral96/public-webhooks,engagespark/public-webhooks,admiral96/mulungwishi-webhook,admiral96/public-webhooks,engagespark/public-webhooks | app/weather_parser.py | app/weather_parser.py | import forecastio
from config import FORECAST_API_KEY
class WeatherForecast:
def generate_forecast(self, latitude, longitude, frequency):
forecast = self.get_forecast_request(latitude, longitude)
if frequency == 'hourly':
return forecast.hourly()
return forecast.currently()
def get_forecast_request(self, latitude, longitude):
return forecastio.load_forecast(FORECAST_API_KEY, latitude, longitude)
| import forecastio
from config import FORECAST_API_KEY
class WeatherForecast:
def generate_forecast(self, latitude, longitude, frequency):
forecast = self.get_forecast_request(latitude, longitude)
# import pdb; pdb.set_trace();
if frequency == 'hourly':
return forecast.hourly()
return forecast.currently()
def get_forecast_request(self, latitude, longitude):
return forecastio.load_forecast(FORECAST_API_KEY, latitude, longitude)
| mit | Python |
dbe7aea203d35fbc60b916ae5ec9e8394936dc17 | Simplify conditional statement | unixsurfer/haproxytool | haproxytool/utils.py | haproxytool/utils.py | # -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Created by: Pavlos Parissis <pavlos.parissis@gmail.com>
#
from six.moves import input
def get_arg_option(args):
for key, value in args.items():
if (key != '--force' and key.startswith('--') and
isinstance(value, bool) and value):
return key.replace('-', '')
def read_user(msg):
"""Read user input.
:param msg: A message to prompt
:type msg: ``str``
:return: ``True`` if user gives 'y' otherwhise False.
:rtype: ``bool``
"""
user_input = input("{msg} y/n?: ".format(msg=msg))
return user_input == 'y'
def abort_command(command, object_type, objects, force):
nbobjects = len(objects)
msg = "Are you sure we want to {cmd} {n} {obg_type}".format(
cmd=command, n=nbobjects, obg_type=object_type)
if not force and nbobjects > 1:
if not read_user(msg):
return True
return False
def print_cmd_output(output):
for output_per_proc in output:
print("Process number: {n}".format(n=output_per_proc[0]))
for line in output_per_proc[1]:
print(line)
| # -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Created by: Pavlos Parissis <pavlos.parissis@gmail.com>
#
from six.moves import input
def get_arg_option(args):
for key, value in args.items():
if (key != '--force' and key.startswith('--') and
isinstance(value, bool) and value):
return key.replace('-', '')
def read_user(msg):
"""Read user input.
:param msg: A message to prompt
:type msg: ``str``
:return: ``True`` if user gives 'y' otherwhise False.
:rtype: ``bool``
"""
user_input = input("{msg} y/n?: ".format(msg=msg))
if user_input == 'y':
return True
else:
return False
def abort_command(command, object_type, objects, force):
nbobjects = len(objects)
msg = "Are you sure we want to {cmd} {n} {obg_type}".format(
cmd=command, n=nbobjects, obg_type=object_type)
if not force and nbobjects > 1:
if not read_user(msg):
return True
return False
def print_cmd_output(output):
for output_per_proc in output:
print("Process number: {n}".format(n=output_per_proc[0]))
for line in output_per_proc[1]:
print(line)
| apache-2.0 | Python |
3be0bc09f0ea1f5f86fadd17b8c3460849418c66 | Fix incorrect import in hardware | Gleamo/gleamo-device,Gleamo/gleamo-device | hardware/hardware.py | hardware/hardware.py | import RPi.GPIO as GPIO
from .ihardware import IHardware
from colors.color import Color
'''
The Hardware class is set up to be used in a with statement
'''
class Hardware(IHardware):
def __init__(
self,
red_pin: int = 14,
green_pin: int = 15,
blue_pin: int = 18,
motor_pin: int = 2
):
self.red_pin = red_pin
self.green_pin = green_pin
self.blue_pin = blue_pin
self.motor_pin = motor_pin
def __enter__(self):
# set board mode to Broadcom (versus Board)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.red_pin, GPIO.OUT)
GPIO.setup(self.green_pin, GPIO.OUT)
GPIO.setup(self.blue_pin, GPIO.OUT)
GPIO.setup(self.motor_pin, GPIO.OUT)
self.red_channel = GPIO.PWM(self.red_pin, 100)
self.green_channel = GPIO.PWM(self.green_pin, 100)
self.blue_channel = GPIO.PWM(self.blue_pin, 100)
self.motor_channel = GPIO.PWM(self.motor_pin, 0)
self.red_channel.start(0)
self.green_channel.start(0)
self.blue_channel.start(0)
self.motor_channel.start(0)
return self;
def __exit__(self, exec_type, exec_val, exec_tb):
GPIO.cleanup()
def set_color(self, color: Color):
# Convert from 0-255 to 0-100
rgb = [
color.r / 255.0 * 100,
color.g / 255.0 * 100,
color.b / 255.0 * 100
]
self.red_channel.ChangeDutyCycle(rgb[0])
self.green_channel.ChangeDutyCycle(rgb[1])
self.blue_channel.ChangeDutyCycle(rgb[2])
def run_motor(self, strength: float = 1):
self.motor_channel.ChangeDutyCycle(strength)
def stop_motor(self):
self.motor_channel.ChangeDutyCycle(0)
| import RPi.GPIO as GPIO
from .ihardware import IHardware
from color import Color
'''
The Hardware class is set up to be used in a with statement
'''
class Hardware(IHardware):
def __init__(
self,
red_pin: int = 14,
green_pin: int = 15,
blue_pin: int = 18,
motor_pin: int = 2
):
self.red_pin = red_pin
self.green_pin = green_pin
self.blue_pin = blue_pin
self.motor_pin = motor_pin
def __enter__(self):
# set board mode to Broadcom (versus Board)
GPIO.setmode(GPIO.BCM)
GPIO.setup(self.red_pin, GPIO.OUT)
GPIO.setup(self.green_pin, GPIO.OUT)
GPIO.setup(self.blue_pin, GPIO.OUT)
GPIO.setup(self.motor_pin, GPIO.OUT)
self.red_channel = GPIO.PWM(self.red_pin, 100)
self.green_channel = GPIO.PWM(self.green_pin, 100)
self.blue_channel = GPIO.PWM(self.blue_pin, 100)
self.motor_channel = GPIO.PWM(self.motor_pin, 0)
self.red_channel.start(0)
self.green_channel.start(0)
self.blue_channel.start(0)
self.motor_channel.start(0)
return self;
def __exit__(self, exec_type, exec_val, exec_tb):
GPIO.cleanup()
def set_color(self, color: Color):
# Convert from 0-255 to 0-100
rgb = [
color.r / 255.0 * 100,
color.g / 255.0 * 100,
color.b / 255.0 * 100
]
self.red_channel.ChangeDutyCycle(rgb[0])
self.green_channel.ChangeDutyCycle(rgb[1])
self.blue_channel.ChangeDutyCycle(rgb[2])
def run_motor(self, strength: float = 1):
self.motor_channel.ChangeDutyCycle(strength)
def stop_motor(self):
self.motor_channel.ChangeDutyCycle(0)
| bsd-2-clause | Python |
6bf7a242078e03486abde2e8b1acdd4e4596bcb6 | Fix in readarrcfg() for case when the cfg file only has one row and np.loadtxt returns a 0-d (scalar) array. This func should always return a 1-d array for each field. | 2baOrNot2ba/dreamBeam,2baOrNot2ba/dreamBeam | dreambeam/telescopes/geometry_ingest.py | dreambeam/telescopes/geometry_ingest.py | """This package retrieves the metadata for a telescope, such as position,
alignment and bands.
The metadata for a telescope should be in the folder '<telescope>/share/'.
Subfolders should be 'simmos' (for array configurations of stations) and
'alignment' for station rotation.
"""
import os
import numpy as np
CASA_CFG_DTYPE = [('X', float), ('Y', float), ('Z', float), ('Diam', float),
('Name', 'S7')]
CASA_CFG_FMT = '%12f %12f %12f %4.1f %s'
SIMOBS_PATH = os.path.dirname(os.path.realpath(__file__))
def readarrcfg(telescope, band):
"""Read a CASA array configuration file. This gives the positions of all
the stations that make up the telescope.
"""
arrcfg_folder = os.path.join(SIMOBS_PATH, telescope, 'share/simmos')
arrcfg_file = os.path.join(arrcfg_folder, '{}_{}.cfg'.format(telescope,
band))
x, y, z, diam, name = np.loadtxt(arrcfg_file, CASA_CFG_DTYPE, unpack=True)
if name.ndim == 0:
x, y, z, diam, name = (np.array([x]), np.array([y]), np.array([z]),
np.array([diam]), np.array([name]))
return x, y, z, diam, name
def readalignment(telescope, stnid, band):
"""Read a alignment matrix file for a telescope station band.
The alignment is 3x3 matrix that represents the rotation between the
feed coord sys and the ITRF.
"""
stnrot_folder = os.path.join(SIMOBS_PATH, telescope, 'share/alignment')
stnrot_file = os.path.join(stnrot_folder, '{}_{}.txt'.format(stnid, band))
stnrot = np.loadtxt(stnrot_file)
return stnrot
def getArrayBandParams(telescope, stnid, band):
"""Get array and band parameters for a telescope, station and band."""
x, y, z, diam, names = readarrcfg(telescope, band)
stnid_idx = names.tolist().index(stnid)
stnPos = [x[stnid_idx], y[stnid_idx], z[stnid_idx]]
stnRot = readalignment(telescope, stnid, band)
return stnPos, stnRot
def list_stations(telescope, band=None):
"""List all available stations."""
x, y, z, diam, names = readarrcfg(telescope, band)
return names
if __name__ == "__main__":
print list_stations('LOFAR')
stnPos, stnRot = getArrayBandParams('LOFAR', 'SE607', 'HBA')
print stnPos
print stnRot
| """This package retrieves the metadata for a telescope, such as position,
alignment and bands.
The metadata for a telescope should be in the folder '<telescope>/share/'.
Subfolders should be 'simmos' (for array configurations of stations) and
'alignment' for station rotation.
"""
import os
import numpy as np
CASA_CFG_DTYPE = [('X', float), ('Y', float), ('Z', float), ('Diam', float),
('Name', 'S7')]
CASA_CFG_FMT = '%12f %12f %12f %4.1f %s'
SIMOBS_PATH = os.path.dirname(os.path.realpath(__file__))
def readarrcfg(telescope, band):
"""Read a CASA array configuration file. This gives the positions of all
the stations that make up the telescope.
"""
arrcfg_folder = os.path.join(SIMOBS_PATH, telescope, 'share/simmos')
arrcfg_file = os.path.join(arrcfg_folder, '{}_{}.cfg'.format(telescope,
band))
x, y, z, diam, name = np.loadtxt(arrcfg_file, CASA_CFG_DTYPE, unpack=True)
return x, y, z, diam, name
def readalignment(telescope, stnid, band):
"""Read a alignment matrix file for a telescope station band.
The alignment is 3x3 matrix that represents the rotation between the
feed coord sys and the ITRF.
"""
stnrot_folder = os.path.join(SIMOBS_PATH, telescope, 'share/alignment')
stnrot_file = os.path.join(stnrot_folder, '{}_{}.txt'.format(stnid, band))
stnrot = np.loadtxt(stnrot_file)
return stnrot
def getArrayBandParams(telescope, stnid, band):
"""Get array and band parameters for a telescope, station and band."""
x, y, z, diam, names = readarrcfg(telescope, band)
stnid_idx = names.tolist().index(stnid)
stnPos = [x[stnid_idx], y[stnid_idx], z[stnid_idx]]
stnRot = readalignment(telescope, stnid, band)
return stnPos, stnRot
def list_stations(telescope, band=None):
"""List all available stations."""
x, y, z, diam, names = readarrcfg(telescope, band)
return names
if __name__ == "__main__":
print list_stations('LOFAR')
stnPos, stnRot = getArrayBandParams('LOFAR', 'SE607', 'HBA')
print stnPos
print stnRot
| isc | Python |
04a6a59530034904baf33752e204912e59d64ed4 | Increase log level of workers | Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger | dallinger/heroku/worker.py | dallinger/heroku/worker.py | """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# Make sure gevent patches are applied early.
import gevent.monkey
gevent.monkey.patch_all()
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
from rq import (
Queue,
Connection
)
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
with Connection(conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
| """Heroku web worker."""
import os
import redis
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDIS_URL', 'redis://localhost:6379')
conn = redis.from_url(redis_url)
if __name__ == '__main__': # pragma: nocover
# Make sure gevent patches are applied early.
import gevent.monkey
gevent.monkey.patch_all()
# These imports are inside the __main__ block
# to make sure that we only import from rq_gevent_worker
# (which has the side effect of applying gevent monkey patches)
# in the worker process. This way other processes can import the
# redis connection without that side effect.
from rq import (
Queue,
Connection
)
from dallinger.heroku.rq_gevent_worker import GeventWorker as Worker
from dallinger.config import initialize_experiment_package
initialize_experiment_package(os.getcwd())
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
with Connection(conn):
worker = Worker(list(map(Queue, listen)))
worker.work()
| mit | Python |
4215a155a6f0be6273a47b1208960a34d801cec6 | fix quote_plus import | jqnatividad/ckanext-officedocs,jqnatividad/ckanext-officedocs,jqnatividad/ckanext-officedocs | ckanext/officedocs/plugin.py | ckanext/officedocs/plugin.py | from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import ckan.lib.helpers as h
import ckan.plugins as p
import ckan.plugins.toolkit as toolkit
from six.moves.urllib.parse import quote_plus
class OfficeDocsPlugin(p.SingletonPlugin):
p.implements(p.IConfigurer)
p.implements(p.IResourceView)
def update_config(self, config_):
toolkit.add_template_directory(config_, "templates")
toolkit.add_public_directory(config_, "public")
toolkit.add_resource("fanstatic", "officedocs")
def info(self):
return {
"name": "officedocs_view",
"title": toolkit._("Office Previewer"),
"default_title": toolkit._("Preview"),
"icon": "compass",
"always_available": True,
"iframed": False,
}
def setup_template_variables(self, context, data_dict):
url = quote_plus(data_dict["resource"]["url"])
return {
"resource_url": url
}
def can_view(self, data_dict):
supported_formats = [
"DOC", "DOCX", "XLS",
"XLSX", "PPT", "PPTX",
"PPS", "ODT", "ODS", "ODP"
]
try:
res = data_dict["resource"].get("format", "").upper()
return res in supported_formats
except:
return False
def view_template(self, context, data_dict):
return "officedocs/preview.html"
def form_template(self, context, data_dict):
return "officedocs/form.html"
| from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import ckan.lib.helpers as h
import ckan.plugins as p
import ckan.plugins.toolkit as toolkit
from urllib import quote_plus
class OfficeDocsPlugin(p.SingletonPlugin):
p.implements(p.IConfigurer)
p.implements(p.IResourceView)
def update_config(self, config_):
toolkit.add_template_directory(config_, "templates")
toolkit.add_public_directory(config_, "public")
toolkit.add_resource("fanstatic", "officedocs")
def info(self):
return {
"name": "officedocs_view",
"title": toolkit._("Office Previewer"),
"default_title": toolkit._("Preview"),
"icon": "compass",
"always_available": True,
"iframed": False,
}
def setup_template_variables(self, context, data_dict):
url = quote_plus(data_dict["resource"]["url"])
return {
"resource_url": url
}
def can_view(self, data_dict):
supported_formats = [
"DOC", "DOCX", "XLS",
"XLSX", "PPT", "PPTX",
"PPS", "ODT", "ODS", "ODP"
]
try:
res = data_dict["resource"].get("format", "").upper()
return res in supported_formats
except:
return False
def view_template(self, context, data_dict):
return "officedocs/preview.html"
def form_template(self, context, data_dict):
return "officedocs/form.html"
| agpl-3.0 | Python |
dde1a9f835e29b7bd1d551f113e376af1f69e496 | Fix prompt import handling in reindex library. | edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform,edx-solutions/edx-platform | cms/djangoapps/contentstore/management/commands/reindex_library.py | cms/djangoapps/contentstore/management/commands/reindex_library.py | """ Management command to update libraries' search index """
from django.core.management import BaseCommand, CommandError
from optparse import make_option
from textwrap import dedent
from contentstore.courseware_index import LibrarySearchIndexer
from opaque_keys.edx.keys import CourseKey
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from opaque_keys.edx.locator import LibraryLocator
from util.prompt import query_yes_no
from xmodule.modulestore.django import modulestore
class Command(BaseCommand):
"""
Command to reindex content libraries (single, multiple or all available)
Examples:
./manage.py reindex_library lib1 lib2 - reindexes libraries with keys lib1 and lib2
./manage.py reindex_library --all - reindexes all available libraries
"""
help = dedent(__doc__)
can_import_settings = True
args = "<library_id library_id ...>"
option_list = BaseCommand.option_list + (
make_option(
'--all',
action='store_true',
dest='all',
default=False,
help='Reindex all libraries'
),)
CONFIRMATION_PROMPT = u"Reindexing all libraries might be a time consuming operation. Do you want to continue?"
def _parse_library_key(self, raw_value):
""" Parses library key from string """
try:
result = CourseKey.from_string(raw_value)
except InvalidKeyError:
result = SlashSeparatedCourseKey.from_deprecated_string(raw_value)
if not isinstance(result, LibraryLocator):
raise CommandError(u"Argument {0} is not a library key".format(raw_value))
return result
def handle(self, *args, **options):
"""
By convention set by django developers, this method actually executes command's actions.
So, there could be no better docstring than emphasize this once again.
"""
if len(args) == 0 and not options.get('all', False):
raise CommandError(u"reindex_library requires one or more arguments: <library_id>")
store = modulestore()
if options.get('all', False):
if query_yes_no(self.CONFIRMATION_PROMPT, default="no"):
library_keys = [library.location.library_key.replace(branch=None) for library in store.get_libraries()]
else:
return
else:
library_keys = map(self._parse_library_key, args)
for library_key in library_keys:
LibrarySearchIndexer.do_library_reindex(store, library_key)
| """ Management command to update libraries' search index """
from django.core.management import BaseCommand, CommandError
from optparse import make_option
from textwrap import dedent
from contentstore.courseware_index import LibrarySearchIndexer
from opaque_keys.edx.keys import CourseKey
from opaque_keys import InvalidKeyError
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from opaque_keys.edx.locator import LibraryLocator
from .prompt import query_yes_no
from xmodule.modulestore.django import modulestore
class Command(BaseCommand):
"""
Command to reindex content libraries (single, multiple or all available)
Examples:
./manage.py reindex_library lib1 lib2 - reindexes libraries with keys lib1 and lib2
./manage.py reindex_library --all - reindexes all available libraries
"""
help = dedent(__doc__)
can_import_settings = True
args = "<library_id library_id ...>"
option_list = BaseCommand.option_list + (
make_option(
'--all',
action='store_true',
dest='all',
default=False,
help='Reindex all libraries'
),)
CONFIRMATION_PROMPT = u"Reindexing all libraries might be a time consuming operation. Do you want to continue?"
def _parse_library_key(self, raw_value):
""" Parses library key from string """
try:
result = CourseKey.from_string(raw_value)
except InvalidKeyError:
result = SlashSeparatedCourseKey.from_deprecated_string(raw_value)
if not isinstance(result, LibraryLocator):
raise CommandError(u"Argument {0} is not a library key".format(raw_value))
return result
def handle(self, *args, **options):
"""
By convention set by django developers, this method actually executes command's actions.
So, there could be no better docstring than emphasize this once again.
"""
if len(args) == 0 and not options.get('all', False):
raise CommandError(u"reindex_library requires one or more arguments: <library_id>")
store = modulestore()
if options.get('all', False):
if query_yes_no(self.CONFIRMATION_PROMPT, default="no"):
library_keys = [library.location.library_key.replace(branch=None) for library in store.get_libraries()]
else:
return
else:
library_keys = map(self._parse_library_key, args)
for library_key in library_keys:
LibrarySearchIndexer.do_library_reindex(store, library_key)
| agpl-3.0 | Python |
ca8f5d2e7e0e08ab3788d84907ae9470b3ceb22a | Add a QUEST_REWARDS map | HearthSim/python-hearthstone | hearthstone/utils.py | hearthstone/utils.py | try:
from lxml import etree as ElementTree # noqa
except ImportError:
from xml.etree import ElementTree # noqa
from .enums import CardClass, Rarity
CARDCLASS_HERO_MAP = {
CardClass.DRUID: "HERO_06",
CardClass.HUNTER: "HERO_05",
CardClass.MAGE: "HERO_08",
CardClass.PALADIN: "HERO_04",
CardClass.PRIEST: "HERO_09",
CardClass.ROGUE: "HERO_03",
CardClass.SHAMAN: "HERO_02",
CardClass.WARLOCK: "HERO_07",
CardClass.WARRIOR: "HERO_01",
}
CRAFTING_COSTS = {
Rarity.COMMON: (40, 400),
Rarity.RARE: (100, 800),
Rarity.EPIC: (400, 1600),
Rarity.LEGENDARY: (1600, 3200),
}
DISENCHANT_COSTS = {
Rarity.COMMON: (5, 50),
Rarity.RARE: (20, 100),
Rarity.EPIC: (100, 400),
Rarity.LEGENDARY: (400, 1600),
}
# QuestController.cs
QUEST_REWARDS = {
"UNG_940": "UNG_940t8",
"UNG_954": "UNG_954t1",
"UNG_934": "UNG_934t1",
"UNG_829": "UNG_829t1",
"UNG_028": "UNG_028t",
"UNG_067": "UNG_067t1",
"UNG_116": "UNG_116t",
"UNG_920": "UNG_920t1",
"UNG_942": "UNG_942t",
}
| try:
from lxml import etree as ElementTree # noqa
except ImportError:
from xml.etree import ElementTree # noqa
from .enums import CardClass, Rarity
CARDCLASS_HERO_MAP = {
CardClass.DRUID: "HERO_06",
CardClass.HUNTER: "HERO_05",
CardClass.MAGE: "HERO_08",
CardClass.PALADIN: "HERO_04",
CardClass.PRIEST: "HERO_09",
CardClass.ROGUE: "HERO_03",
CardClass.SHAMAN: "HERO_02",
CardClass.WARLOCK: "HERO_07",
CardClass.WARRIOR: "HERO_01",
}
CRAFTING_COSTS = {
Rarity.COMMON: (40, 400),
Rarity.RARE: (100, 800),
Rarity.EPIC: (400, 1600),
Rarity.LEGENDARY: (1600, 3200),
}
DISENCHANT_COSTS = {
Rarity.COMMON: (5, 50),
Rarity.RARE: (20, 100),
Rarity.EPIC: (100, 400),
Rarity.LEGENDARY: (400, 1600),
}
| mit | Python |
2bf6d37599ce59e04916cc9c0d1fff348c33ac8e | Add time display to note mod | billyvg/piebot | modules/notemod.py | modules/notemod.py | """Handles user notes
@package ppbot
@syntax tell <user> <note>
@syntax showtells
"""
from datetime import datetime
from dateutil.relativedelta import relativedelta
from modules import *
class Notemod(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
def _register_events(self):
self.add_command('tell')
self.add_event('pubmsg', 'parse_message')
def tell(self, event):
"""Adds a new tell."""
if event['nick'] != event['args'][0]:
data = {'note': ' '.join(event['args'][1:]),
'added_by': event['source'],
'time': datetime.now(),
'active': True,
'target': event['args'][0].lower()}
self.db.notes.insert(data)
self.notice(event['nick'], 'Note added for %s.' % (event['args'][0]))
def parse_message(self, event):
""" Checks to see if user has notes waiting for them """
notes = self.db.notes.find({'target': event['nick'].lower(), 'active': True}).sort('time', 0)
if notes.count() > 0:
for note in notes:
rd = relativedelta(datetime.now(), note['time'])
self.notice(event['nick'], '%s said to you %s ago: "%s"' % (note['added_by'].split('!')[0], self.pretty_time_duration(rd), note['note'].encode('ascii', 'ignore')))
self.db.notes.update({'_id': note['_id']}, {'$set': {'active': False}})
def pretty_time_duration(self, rd):
"""Formats the time difference in a pretty string"""
output = ''
delta = {'years': rd.years,
'months': rd.months,
'days': rd.days,
'hours': rd.hours,
'minutes': rd.minutes,
'seconds': rd.seconds}
if rd.years > 1:
output += '%(years)d years '
elif rd.years > 0:
output += '%(years)d year '
elif rd.months > 1:
output += '%(months)d months '
elif rd.months > 0:
output += '%(months)d month '
elif rd.days > 1:
output += '%(days)d days '
elif rd.days > 0:
output += '%(days)d day '
elif rd.hours > 1:
output += '%(hours)d hours '
elif rd.hours > 0:
output += '%(hours)d hour '
elif rd.minutes > 1:
output += '%(minutes)d minutes '
elif rd.minutes > 0:
output += '%(minutes)d minute '
elif rd.seconds > 1:
output += '%(seconds)d seconds '
elif rd.seconds > 0:
output += '%(seconds)d second '
return output.strip() % delta
| """Handles user notes
@package ppbot
@syntax tell <user> <note>
@syntax showtells
"""
from datetime import datetime
from modules import *
class Notemod(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
def _register_events(self):
self.add_command('tell')
self.add_event('pubmsg', 'parse_message')
def tell(self, event):
"""Adds a new tell."""
if event['nick'] != event['args'][0]:
data = {'note': ' '.join(event['args'][1:]),
'added_by': event['source'],
'time': datetime.now(),
'active': True,
'target': event['args'][0].lower()}
self.db.notes.insert(data)
self.notice(event['nick'], 'Note added for %s.' % (event['args'][0]))
def parse_message(self, event):
""" Checks to see if user has notes waiting for them """
notes = self.db.notes.find({'target': event['nick'].lower(), 'active': True}).sort('time', 0)
if notes.count() > 0:
for note in notes:
self.notice(event['nick'], '%s told you some time ago: %s' % (note['added_by'].split('!')[0], note['note'].encode('ascii', 'ignore')))
self.db.notes.update({'_id': note['_id']}, {'$set': {'active': False}})
| mit | Python |
7b2b1f6efa5775483bc32edd6bf0fd6281ef0974 | Update mecanumjoystick.py | ragulbalaji/Random-Cool-Things,ragulbalaji/Random-Cool-Things,ragulbalaji/Random-Cool-Things,ragulbalaji/Random-Cool-Things | mecanumbot/mecanumjoystick.py | mecanumbot/mecanumjoystick.py | import time
import math
from gpiozero import Motor
# Motors P+ N-
# FL 4 17
# FR 23 24
# BL 27 22
# BR 26 19
motorFL = Motor( 4, 17, pwm=True)
motorFR = Motor(23, 24, pwm=True)
motorBL = Motor(27, 22, pwm=True)
motorBR = Motor(26, 19, pwm=True)
from pygame import display, joystick, event
from pygame import QUIT, JOYAXISMOTION, JOYBALLMOTION, JOYHATMOTION, JOYBUTTONUP, JOYBUTTONDOWN
display.init()
joystick.init()
joyaxisstate = [0,0,0,0,0,0,0,0,0,0] # LX, LY, LT, RX, RY, RT, ...
for i in range(joystick.get_count()):
joystick.Joystick(i).init()
e = event.wait()
while e.type != QUIT:
if e.type == JOYAXISMOTION: joyaxisstate[e.axis] = round(e.value, 2)
#elif e.type == JOYBALLMOTION: print('js', e.joy, 'ball', e.ball, round(e.rel, P))
#elif e.type == JOYHATMOTION: print('js', e.joy, 'hat', e.hat, h[e.value])
#elif e.type == JOYBUTTONUP: print('js', e.joy, 'button', e.button, 'up')
#elif e.type == JOYBUTTONDOWN: print('js', e.joy, 'button', e.button, 'down')
print(joyaxisstate)
motorFL.value = min(max(joyaxisstate[3] - joyaxisstate[1] + joyaxisstate[0],-1.0),1.0)
motorFR.value = min(max(joyaxisstate[3] + joyaxisstate[1] + joyaxisstate[0],-1.0),1.0)
motorBL.value = min(max(joyaxisstate[3] - joyaxisstate[1] - joyaxisstate[0],-1.0),1.0)
motorBR.value = min(max(joyaxisstate[3] + joyaxisstate[1] - joyaxisstate[0],-1.0),1.0)
e = event.wait()
| from gpiozero import Motor
import time
import math
# Motors P+ N-
# FL 4 17
# FR 27 22
# BL 23 24
# BR 26 19
motorFL = Motor( 4, 17, pwm=True)
motorFR = Motor(27, 22, pwm=True)
motorBL = Motor(23, 24, pwm=True)
motorBR = Motor(26, 19, pwm=True)
while True:
spd = math.sin(time.time())
motorFL.value = spd
motorFR.value = spd
motorBL.value = spd
motorBR.value = spd
print(spd)
| mit | Python |
e60930a57f3fdd9e960e5f4f4c96d320faf59aaf | Add verified field to user admin | pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016 | src/users/admin.py | src/users/admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User
from .forms import AdminUserChangeForm, UserCreationForm
@admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = (
(
None,
{'fields': ('email', 'password')}
),
(
_('Personal info'),
{
'fields': (
'speaker_name', 'bio', 'photo',
'twitter_id', 'github_id', 'facebook_id',
),
},
),
(
_('Permissions'),
{
'fields': (
'verified', 'is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions',
),
},
),
(
_('Important dates'),
{'fields': ('last_login', 'date_joined')},
),
)
add_fieldsets = (
(
None, {
'classes': ('wide',),
'fields': (
'email', 'password1', 'password2',
'speaker_name', 'bio', 'verified',
),
},
),
)
form = AdminUserChangeForm
add_form = UserCreationForm
list_display = ('email', 'is_staff')
list_filter = (
'verified', 'is_active', 'is_staff', 'is_superuser',
'groups',
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions',)
| from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _
from .models import User
from .forms import AdminUserChangeForm, UserCreationForm
@admin.register(User)
class UserAdmin(UserAdmin):
fieldsets = (
(
None,
{'fields': ('email', 'password')}
),
(
_('Personal info'),
{
'fields': (
'speaker_name', 'bio', 'photo',
'twitter_id', 'github_id', 'facebook_id',
),
},
),
(
_('Permissions'),
{
'fields': (
'is_active', 'is_staff', 'is_superuser',
'groups', 'user_permissions',
),
},
),
(
_('Important dates'),
{'fields': ('last_login', 'date_joined')},
),
)
add_fieldsets = (
(
None, {
'classes': ('wide',),
'fields': (
'email', 'password1', 'password2',
'speaker_name', 'bio', 'photo',
'twitter_id', 'github_id', 'facebook_id',
),
},
),
)
form = AdminUserChangeForm
add_form = UserCreationForm
list_display = ('email', 'is_staff')
list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ('groups', 'user_permissions',)
| mit | Python |
97f64d01199efc65d18a08c47812d2820e872eb0 | update dev version after 0.57.1 tag [ci skip] | desihub/desitarget,desihub/desitarget | py/desitarget/_version.py | py/desitarget/_version.py | __version__ = '0.57.1.dev4806'
| __version__ = '0.57.1'
| bsd-3-clause | Python |
51a505747d29198ea3df0a43c32b1018a40e6bc9 | Move ratelimit functionality into its own class | laneshetron/monopoly | monopoly/Bank/g.py | monopoly/Bank/g.py | import time
import json
import sqlite3
import socket
from collections import deque
class ratelimit:
def __init__(self, max, duration):
self.max = max
self.duration = duration # in milliseconds
self.rateQueue = deque([0] * max, maxlen=max)
def queue(self, job):
elapsed = int(time.time() * 1000) - self.rateQueue[0]
if elapsed / self.max < self.duration:
time.sleep((self.duration - elapsed / self.max) / 1000)
self.rateQueue.append(int(time.time() * 1000))
# TODO need to adapt this for the event loop so we can yield on delays
class safesocket(socket.socket):
def __init__(self, *args):
self.floodQueue = ratelimit(10, 100)
super().__init__(*args)
def send(self, message, *args):
try:
if not isinstance(message, bytes):
message = message.encode()
# Start rate limiting after 10 messages within 100ms
# to avoid IRC kicking us for flooding
self.floodQueue.queue()
super().send(message, *args)
except Exception as e:
print('Could not write to socket: ', e)
starttime = int(time.time())
lastDisconnect = 0
with open('config/config.json') as config_file:
config = json.load(config_file)
channels = config['irc']['channels']
silent_channels = config['irc']['silent_channels']
db = sqlite3.connect(config['db']['location'])
cursor = db.cursor()
ircsock = None
| import time
import json
import sqlite3
import socket
from collections import deque
class safesocket(socket.socket):
def __init__(self, *args):
self.floodQueue = deque([0] * 10, maxlen=10)
super().__init__(*args)
def send(self, message, *args):
try:
elapsed = int(time.time() * 1000) - self.floodQueue[0]
if not isinstance(message, bytes):
message = message.encode()
if elapsed / 10 < 100:
# Start rate limiting after 10 messages within 100ms
# to avoid IRC kicking us for flooding
time.sleep((100 - elapsed / 10) / 1000)
super().send(message, *args)
self.floodQueue.append(int(time.time() * 1000))
except Exception as e:
print('Could not write to socket: ', e)
starttime = int(time.time())
lastDisconnect = 0
with open('config/config.json') as config_file:
config = json.load(config_file)
channels = config['irc']['channels']
silent_channels = config['irc']['silent_channels']
db = sqlite3.connect(config['db']['location'])
cursor = db.cursor()
ircsock = None
| mit | Python |
7444c4e3b3549a6caf09ca85566ba4834e63a256 | Add iso8601 translator. | django-pci/django-axes,jazzband/django-axes,svenhertle/django-axes | axes/utils.py | axes/utils.py | from axes.models import AccessAttempt
def reset(ip=None, username=None):
"""Reset records that match ip or username, and
return the count of removed attempts.
"""
count = 0
attempts = AccessAttempt.objects.all()
if ip:
attempts = attempts.filter(ip_address=ip)
if username:
attempts = attempts.filter(username=username)
if attempts:
count = attempts.count()
attempts.delete()
return count
def iso8601(value):
"""Returns datetime.timedelta translated to ISO 8601 formatted duration.
"""
seconds = value.total_seconds()
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
date = '{:.0f}D'.format(days) if days else ''
time_values = hours, minutes, seconds
time_designators = 'H', 'M', 'S'
time = ''.join(
[('{:.0f}'.format(value) + designator)
for value, designator in zip(time_values, time_designators)
if value]
)
return u'P' + date + time
| from axes.models import AccessAttempt
def reset(ip=None, username=None):
"""Reset records that match ip or username, and
return the count of removed attempts.
"""
count = 0
attempts = AccessAttempt.objects.all()
if ip:
attempts = attempts.filter(ip_address=ip)
if username:
attempts = attempts.filter(username=username)
if attempts:
count = attempts.count()
attempts.delete()
return count
| mit | Python |
455a948621983a23dd1d0d966152b8f14fcb6d42 | Update Ch. 16 PracticeQuestions: removed comment | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/CrackingCodesWithPython/Chapter16/PracticeQuestions.py | books/CrackingCodesWithPython/Chapter16/PracticeQuestions.py | # Chapter 16 Practice Questions
# 1. Why can't a brute-force attack be used against a simple substitution
# cipher, even with a powerful supercomputer?
# Hint: Check page 208
from math import factorial
numKeys = factorial(26)
print(numKeys)
# 2. What does the spam variable contain after running this code?
spam = [4, 6, 2, 8]
spam.sort()
print(spam)
# 3. What is a wrapper function?
# Hint: Check page 213
def calculator(num1, num2, mode):
if mode == "add":
return num1 + num2
elif mode == "subtract":
return num1 - num2
return None
def addition(num1, num2):
return calculator(num1, num2, "add")
def subtraction(num1, num2):
return calculator(num1, num2, "subtract")
print(addition(3, 4))
print(subtraction(2, 1))
# 4. What does 'hello'.islower() evaluate to?
print('hello'.islower())
# 5. What does 'HELLO 123'.isupper() evaluate to?
print('HELLO 123'.isupper())
# 6. What does '123'.islower() evaluate to?
print('123'.islower())
| # Chapter 16 Practice Questions
# 1. Why can't a brute-force attack be used against a simple substitution
# cipher, even with a powerful supercomputer?
# Hint: Check page 208
from math import factorial # Don't do this - imports should be at the top of the file
numKeys = factorial(26)
print(numKeys)
# 2. What does the spam variable contain after running this code?
spam = [4, 6, 2, 8]
spam.sort()
print(spam)
# 3. What is a wrapper function?
# Hint: Check page 213
def calculator(num1, num2, mode):
if mode == "add":
return num1 + num2
elif mode == "subtract":
return num1 - num2
return None
def addition(num1, num2):
return calculator(num1, num2, "add")
def subtraction(num1, num2):
return calculator(num1, num2, "subtract")
print(addition(3, 4))
print(subtraction(2, 1))
# 4. What does 'hello'.islower() evaluate to?
print('hello'.islower())
# 5. What does 'HELLO 123'.isupper() evaluate to?
print('HELLO 123'.isupper())
# 6. What does '123'.islower() evaluate to?
print('123'.islower())
| mit | Python |
f52287bfc6a38b35daf9d880886cc159550a157c | Make sure to avoid loading hacks on mutant loading | charettes/django-mutant | mutant/__init__.py | mutant/__init__.py | import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
| import logging
__version__ = VERSION = (0, 0, 1)
logger = logging.getLogger('mutant')
import hacks | mit | Python |
e33d44ca880f31c93dc5eef8d5162fec71f8d090 | Add PostgresqlDialect. | SunDwarf/asyncqlio | katagawa/backends/postgresql/__init__.py | katagawa/backends/postgresql/__init__.py | # used for namespace packages
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
from katagawa.backends.base import BaseDialect
DEFAULT_CONNECTOR = "asyncpg"
class PostgresqlDialect(BaseDialect):
"""
The dialect for Postgres.
"""
def has_checkpoints(self):
return True
def has_serial(self):
return True
| # used for namespace packages
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
DEFAULT_CONNECTOR = "asyncpg"
| mit | Python |
4585ab22a4185122162b987cf8cc845a63ed5a05 | Make it possible for modules to send a response | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot | pyheufybot/modules/say.py | pyheufybot/modules/say.py | from module_interface import Module, ModuleType
from message import IRCResponse, ResponseType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line"
def execute(self, message, serverInfo):
return [ IRCResponse(message.replyTo, ResponseType.MESSAGE, message.messageText) ]
| from module_interface import Module, ModuleType
class Say(Module):
def __init__(self):
self.trigger = "say"
self.moduleType = ModuleType.ACTIVE
self.messagesTypes = ["PRIVMSG"]
self.helpText = "Usage: say <message> | Makes the bot say the given line"
def execute(self, message, serverInfo):
pass
| mit | Python |
85513edd0a2b0e3c0e64e8a00bef6381d5f370d1 | Bump version to 2.5.1.dev0 | pyQode/pyqode.python,mmolero/pyqode.python,pyQode/pyqode.python,zwadar/pyqode.python | pyqode/python/__init__.py | pyqode/python/__init__.py | # -*- coding: utf-8 -*-
"""
pyqode.python is an extension of pyqode.core that brings support
for the python programming language. It provides a set of additional modes and
panels for the frontend and a series of worker for the backend (code
completion, documentation lookups, code linters, and so on...).
"""
__version__ = '2.5.1.dev0'
| # -*- coding: utf-8 -*-
"""
pyqode.python is an extension of pyqode.core that brings support
for the python programming language. It provides a set of additional modes and
panels for the frontend and a series of worker for the backend (code
completion, documentation lookups, code linters, and so on...).
"""
__version__ = '2.5.0'
| mit | Python |
cc2e44d76c20b5eb03a645ce6ef3601be05e3f69 | Modify imports | thombashi/pytablewriter | pytablewriter/__init__.py | pytablewriter/__init__.py | """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from dataproperty import LineBreakHandling
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._factory import TableWriterFactory
from ._function import dump_tabledata, dumps_tabledata
from ._logger import set_log_level, set_logger
from ._table_format import FormatAttr, TableFormat
from .error import (
EmptyTableDataError,
EmptyTableNameError,
EmptyValueError,
NotSupportedError,
WriterNotFoundError,
)
from .style import Align, Format
from .typehint import (
Bool,
DateTime,
Dictionary,
Infinity,
Integer,
IpAddress,
List,
Nan,
NoneType,
NullString,
RealNumber,
String,
)
from .writer import (
AbstractTableWriter,
BoldUnicodeTableWriter,
BorderlessTableWriter,
CssTableWriter,
CsvTableWriter,
ElasticsearchWriter,
ExcelXlsTableWriter,
ExcelXlsxTableWriter,
HtmlTableWriter,
JavaScriptTableWriter,
JsonLinesTableWriter,
JsonTableWriter,
LatexMatrixWriter,
LatexTableWriter,
LtsvTableWriter,
MarkdownTableWriter,
MediaWikiTableWriter,
NullTableWriter,
NumpyTableWriter,
PandasDataFramePickleWriter,
PandasDataFrameWriter,
PythonCodeTableWriter,
RstCsvTableWriter,
RstGridTableWriter,
RstSimpleTableWriter,
SpaceAlignedTableWriter,
SqliteTableWriter,
TomlTableWriter,
TsvTableWriter,
UnicodeTableWriter,
YamlTableWriter,
)
| """
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from dataproperty import LineBreakHandling
from typepy import (
Bool,
DateTime,
Dictionary,
Infinity,
Integer,
IpAddress,
List,
Nan,
NoneType,
NullString,
RealNumber,
String,
)
from .__version__ import __author__, __copyright__, __email__, __license__, __version__
from ._factory import TableWriterFactory
from ._function import dump_tabledata, dumps_tabledata
from ._logger import set_log_level, set_logger
from ._table_format import FormatAttr, TableFormat
from .error import (
EmptyTableDataError,
EmptyTableNameError,
EmptyValueError,
NotSupportedError,
WriterNotFoundError,
)
from .style import Align, Format
from .writer import (
AbstractTableWriter,
BoldUnicodeTableWriter,
BorderlessTableWriter,
CssTableWriter,
CsvTableWriter,
ElasticsearchWriter,
ExcelXlsTableWriter,
ExcelXlsxTableWriter,
HtmlTableWriter,
JavaScriptTableWriter,
JsonLinesTableWriter,
JsonTableWriter,
LatexMatrixWriter,
LatexTableWriter,
LtsvTableWriter,
MarkdownTableWriter,
MediaWikiTableWriter,
NullTableWriter,
NumpyTableWriter,
PandasDataFramePickleWriter,
PandasDataFrameWriter,
PythonCodeTableWriter,
RstCsvTableWriter,
RstGridTableWriter,
RstSimpleTableWriter,
SpaceAlignedTableWriter,
SqliteTableWriter,
TomlTableWriter,
TsvTableWriter,
UnicodeTableWriter,
YamlTableWriter,
)
| mit | Python |
244485f85024ef23e05aaedacbf94f5949b38733 | Clean imports, separate prints to functions | gjcooper/repovisor,gjcooper/repovisor | repovisor/repovisor.py | repovisor/repovisor.py | from .repostate import GitRepoState
from git.exc import InvalidGitRepositoryError
from colorama import Fore, Style, init
import os
init()
def reposearch(*folders):
for folder in folders:
for dir, subdirs, files in os.walk(folder):
try:
yield GitRepoState(dir)
subdirs[:] = []
continue
except InvalidGitRepositoryError:
pass
def ahead_behind(ref):
if ref['ahead']:
glyph = Fore.RED + '+' + str(ref['ahead']) + Style.RESET_ALL
else:
glyph = '-'
glyph += '/'
if ref['behind']:
glyph += Fore.RED + '-' + str(ref['behind']) + Style.RESET_ALL
else:
glyph += '-'
return glyph
def branch_representation(branch):
refview = ' Name: {:10.10} Upstream: '.format(branch['name'])
if branch['upstream']:
refview += '{!s:17.17} Status: {!s}'.format(branch['upstream'],
ahead_behind(branch))
else:
refview += Fore.YELLOW + 'None' + Style.RESET_ALL
return refview
def state_representation(repo):
"""Print the state for a repository"""
loc = 'Location: ' + repo.path
state = repo.state
mod = 'Modified: '
if state['dirty']:
mod += Fore.RED + 'Yes' + Style.RESET_ALL
else:
mod += Fore.GREEN + 'No' + Style.RESET_ALL
untracked = 'Untracked: ' + Fore.YELLOW
untracked += str(state['untracked']) + Style.RESET_ALL
refs = 'Branches: \n'
refs += '\n'.join([branch_representation(b) for b in state['refcheck']])
return '\n'.join([loc, mod, untracked, refs])
def print_all(*repos):
"""Print all repo current state to terminal"""
for repo in repos:
print('‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾')
print(state_representation(repo))
print('________________________________________')
| from .repostate import GitRepoState
from git import Repo
from git.exc import InvalidGitRepositoryError
from colorama import Fore, Style, init
import os
import warnings
init()
def reposearch(*folders):
for folder in folders:
for dir, subdirs, files in os.walk(folder):
try:
yield GitRepoState(dir)
subdirs[:] = []
continue
except InvalidGitRepositoryError:
pass
def ahead_behind(ref):
if ref['ahead']:
glyph = Fore.RED + '+' + str(ref['ahead']) + Style.RESET_ALL
else:
glyph = '-'
glyph += '/'
if ref['behind']:
glyph += Fore.RED + '-' + str(ref['behind']) + Style.RESET_ALL
else:
glyph += '-'
return glyph
def state_representation(repo):
"""Print the state for a repository"""
loc = 'Location: ' + repo.path
state = repo.state
mod = 'Modified: '
if state['dirty']:
def print_all(*repos):
"""Print all repo current state to terminal"""
for repo in repos:
print('‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾')
print('Location: ', repo.path)
state = repo.state
print('Modified: ', Fore.RED, state['dirty'], Style.RESET_ALL)
print('Untracked: \n', Fore.YELLOW, '\n'.join(state['untracked']),
Style.RESET_ALL)
print('Refs:')
for ref in state['refcheck']:
ab_notifier = ''
if ref['upstream']:
ab_notifier = ahead_behind(ref)
print('\tName: ', ref['name'], ' Upstream: ', ref['upstream'],
'Status: ', ab_notifier)
print('________________________________________')
| bsd-3-clause | Python |
b723289c95333ddfcf07fb167d8af59d4fba31b2 | Update test_basics | openfisca/openfisca-tunisia,openfisca/openfisca-tunisia | openfisca_tunisia/tests/test_basics.py | openfisca_tunisia/tests/test_basics.py | # -*- coding: utf-8 -*-
from __future__ import division
import datetime
from openfisca_tunisia.model.data import CAT
from openfisca_tunisia.tests import base
scenarios_arguments = [
dict(
period = year,
parent1 = dict(
date_naissance = datetime.date(1972, 1, 1),
salaire_de_base = 2000,
categorie_salarie = CAT['rsna'],
),
parent2 = dict(
date_naissance = datetime.date(1972, 1, 1),
),
)
for year in range(2012, 2007, -1)
]
def check_run(simulation, period):
assert simulation.calculate('revenu_disponible') is not None, "Can't compute revdisp on period {}".format(period)
assert simulation.calculate('salaire_super_brut') is not None, \
"Can't compute salaire_super_brut on period {}".format(period)
def test_basics():
for scenario_arguments in scenarios_arguments:
scenario = base.tax_benefit_system.new_scenario()
scenario.init_single_entity(**scenario_arguments)
simulation = scenario.new_simulation(debug = False)
period = scenario_arguments['period']
yield check_run, simulation, period
if __name__ == '__main__':
import logging
import sys
logging.basicConfig(level = logging.ERROR, stream = sys.stdout)
for _, simulation, period in test_basics():
check_run(simulation, period)
print u'OpenFisca-Tunisia basic test was executed successfully.'.encode('utf-8')
| # -*- coding: utf-8 -*-
from __future__ import division
import datetime
from openfisca_tunisia.model.data import CAT
from openfisca_tunisia.tests import base
scenarios_arguments = [
dict(
period = year,
parent1 = dict(
date_naissance = datetime.date(1972, 1, 1),
salaire_de_base = 2000,
categorie_salarie = CAT['rsna'],
),
parent2 = dict(
date_naissance = datetime.date(1972, 1, 1),
),
)
for year in range(2012, 2007, -1)
]
def check_run(simulation, period):
assert simulation.calculate('revenu_disponible') is not None, "Can't compute revdisp on period {}".format(period)
assert simulation.calculate('salaire_super_brut') is not None, \
"Can't compute salaire_super_brut on period {}".format(period)
def test_basics():
for scenario_arguments in scenarios_arguments:
scenario = base.tax_benefit_system.new_scenario()
scenario.init_single_entity(**scenario_arguments)
simulation = scenario.new_simulation(debug = False)
period = scenario_arguments['period']
yield check_run, simulation, period
if __name__ == '__main__':
import logging
import sys
logging.basicConfig(level = logging.ERROR, stream = sys.stdout)
for _, simulation, period in test_basics():
check_run(simulation, period)
print u'OpenFisca-France basic test was executed successfully.'.encode('utf-8')
| agpl-3.0 | Python |
577c5b61f936f59d3ff08a0aacf1411014e600e0 | Remove unnecessary context | gems-uff/labsys,gems-uff/labsys,gems-uff/labsys | manage.py | manage.py | #!/usr/bin/env python
import os
from flask_admin import Admin
from flask_admin.menu import MenuLink
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from labsys.app import create_app
from labsys.extensions import db
from labsys.auth.models import User, Role, PreAllowedUser
from labsys.auth.views import ProtectedModelView
from labsys.inventory.models import Product, Transaction, StockProduct
from labsys.admissions.models import (
Admission, Symptom, ObservedSymptom, Vaccine, Method, Sample, Patient,
CdcExam, Hospitalization, UTIHospitalization, ClinicalEvolution, Country,
Region, State, City, Address,
)
app = create_app(os.environ.get('FLASK_CONFIG'))
manager = Manager(app)
migrate = Migrate(app, db)
admin = Admin(app, name='labsys', template_mode='bootstrap3')
# region Add ModelView
admin.add_views(
ProtectedModelView(User, db.session),
ProtectedModelView(Role, db.session),
ProtectedModelView(PreAllowedUser, db.session),
#ProtectedModelView(Admission, db.session),
#ProtectedModelView(Patient, db.session),
#ProtectedModelView(Address, db.session),
#ProtectedModelView(Sample, db.session),
#ProtectedModelView(CdcExam, db.session),
#ProtectedModelView(Vaccine, db.session),
#ProtectedModelView(Hospitalization, db.session),
#ProtectedModelView(UTIHospitalization, db.session),
#ProtectedModelView(ClinicalEvolution, db.session),
#ProtectedModelView(ObservedSymptom, db.session),
#ProtectedModelView(Method, db.session),
#ProtectedModelView(Symptom, db.session),
#ProtectedModelView(Country, db.session),
#ProtectedModelView(Region, db.session),
#ProtectedModelView(State, db.session),
#ProtectedModelView(City, db.session),
ProtectedModelView(Product, db.session),
ProtectedModelView(Transaction, db.session),
ProtectedModelView(StockProduct, db.session), )
admin.add_link(MenuLink(name='Voltar para Dashboard', url=('/')))
# endregion
def make_shell_context():
return dict(
app=app, db=db, User=User, Role=Role,
)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the tests."""
if app.config['DATABASE_URI_ENV_KEY'] != 'TEST_DATABASE_URL':
raise EnvironmentError(
'Trying to run tests outside testing environment!')
import pytest
rv = pytest.main(['--verbose'])
exit(rv)
@manager.command
def load_initial_data():
"""Load initial models data"""
import labsys.utils.data_loader as dl
dl.load_data(db)
@manager.command
def deploy():
"""Run deployment tasks"""
from flask_migrate import upgrade
upgrade()
load_initial_data()
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
import os
from flask_admin import Admin
from flask_admin.menu import MenuLink
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager, Shell
from labsys.app import create_app
from labsys.extensions import db
from labsys.auth.models import User, Role, PreAllowedUser
from labsys.auth.views import ProtectedModelView
from labsys.inventory.models import Product, Transaction, StockProduct
from labsys.admissions.models import (
Admission, Symptom, ObservedSymptom, Vaccine, Method, Sample, Patient,
CdcExam, Hospitalization, UTIHospitalization, ClinicalEvolution, Country,
Region, State, City, Address,
)
app = create_app(os.environ.get('FLASK_CONFIG'))
manager = Manager(app)
migrate = Migrate(app, db)
admin = Admin(app, name='labsys', template_mode='bootstrap3')
# region Add ModelView
admin.add_views(
ProtectedModelView(User, db.session),
ProtectedModelView(Role, db.session),
ProtectedModelView(PreAllowedUser, db.session),
ProtectedModelView(Admission, db.session),
ProtectedModelView(Patient, db.session),
ProtectedModelView(Address, db.session),
ProtectedModelView(Sample, db.session),
ProtectedModelView(CdcExam, db.session),
ProtectedModelView(Vaccine, db.session),
ProtectedModelView(Hospitalization, db.session),
ProtectedModelView(UTIHospitalization, db.session),
ProtectedModelView(ClinicalEvolution, db.session),
ProtectedModelView(ObservedSymptom, db.session),
ProtectedModelView(Method, db.session),
ProtectedModelView(Symptom, db.session),
ProtectedModelView(Country, db.session),
ProtectedModelView(Region, db.session),
ProtectedModelView(State, db.session),
ProtectedModelView(City, db.session),
ProtectedModelView(Product, db.session),
ProtectedModelView(Transaction, db.session),
ProtectedModelView(StockProduct, db.session), )
admin.add_link(MenuLink(name='Voltar para Dashboard', url=('/')))
# endregion
def make_shell_context():
return dict(
app=app, db=db, User=User, Role=Role,
Product=Product, StockProduct=StockProduct,
)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test():
"""Run the tests."""
if app.config['DATABASE_URI_ENV_KEY'] != 'TEST_DATABASE_URL':
raise EnvironmentError(
'Trying to run tests outside testing environment!')
import pytest
rv = pytest.main(['--verbose'])
exit(rv)
@manager.command
def load_initial_data():
"""Load initial models data"""
import labsys.utils.data_loader as dl
dl.load_data(db)
@manager.command
def deploy():
"""Run deployment tasks"""
from flask_migrate import upgrade
upgrade()
load_initial_data()
if __name__ == '__main__':
manager.run()
| mit | Python |
d8a388d9c11efffb3266586acbf3e950a09f7dc3 | Comment and pep8 validation for TestEnv class | pombredanne/pythran,pombredanne/pythran,artas360/pythran,artas360/pythran,hainm/pythran,pbrunet/pythran,pbrunet/pythran,serge-sans-paille/pythran,pbrunet/pythran,artas360/pythran,pombredanne/pythran,hainm/pythran,hainm/pythran,serge-sans-paille/pythran | pythran/tests/test_env.py | pythran/tests/test_env.py | from pythran import cxx_generator
from pythran import compile as pythran_compile
from imp import load_dynamic
import unittest
import os
class TestEnv(unittest.TestCase):
"""
Test environment to validate a pythran execution against python
"""
# default options used for the c++ compiler
PYTHRAN_CXX_FLAGS = ["-O0", "-fno-implicit-inline-templates", "-fopenmp"]
def assertAlmostEqual(self, ref, res):
if hasattr(ref, '__iter__'):
self.assertEqual(len(ref), len(res))
for iref, ires in zip(ref, res):
self.assertAlmostEqual(iref, ires)
else:
unittest.TestCase.assertAlmostEqual(self, ref, res)
def run_test(self, code, *params, **interface):
"""Test if a function call return value is unchanged when
executed using python eval or compiled with pythran.
Args:
code (str): python (pythran valid) module to test.
params (tuple): arguments to pass to the function to test.
interface (dict): pythran interface for the module to test.
Each key is the name of a function to call,
the value is a list of the arguments' type.
Returns: nothing.
Raises:
AssertionError by 'unittest' if return value differ.
SyntaxError if code is not python valid.
CalledProcessError if pythran generated code cannot be compiled.
...possible others...
"""
for name in sorted(interface.keys()):
# Build the python function call.
modname = "test_" + name
arglist = ",".join(("'{0}'".format(p) if isinstance(p, str)
else str(p)) for p in params)
function_call = "{0}({1})".format(name, arglist)
# Compile the python module, python-way, 'env' contains the module
# and allow to call functions.
# This may be done once before the loop, but the context might
# need to be reset.
compiled_code = compile(code, "", "exec")
env = {}
eval(compiled_code, env)
python_ref = eval(function_call, env) # Produce the reference
# Compile the code using pythran
cxx_code = cxx_generator(modname, code, interface)
cxx_compiled = pythran_compile(os.environ.get("CXX", "c++"),
cxx_code,
cxxflags=TestEnv.PYTHRAN_CXX_FLAGS,
check=False)
pymod = load_dynamic(modname, cxx_compiled)
# Produce the pythran result
pythran_res = getattr(pymod, name)(*params)
# Compare pythran result against python ref and raise if mismatch
if python_ref != pythran_res:
print python_ref, pythran_res
self.assertAlmostEqual(python_ref, pythran_res)
| from pythran import cxx_generator
from pythran import compile as pythran_compile
from imp import load_dynamic
import unittest
import os
class TestEnv(unittest.TestCase):
def assertAlmostEqual(self, ref, res):
if hasattr(ref,'__iter__'):
self.assertEqual(len(ref), len(res))
for iref, ires in zip(ref,res):
self.assertAlmostEqual(iref, ires)
else:
unittest.TestCase.assertAlmostEqual(self,ref, res)
def run_test(self, code, *params, **interface):
for name in sorted(interface.keys()):
modname="test_"+name
print modname
compiled_code=compile(code,"","exec")
env={}
eval(compiled_code, env)
ref=eval("{0}({1})".format(name, ",".join(("'{0}'".format(p) if isinstance(p,str) else str(p)) for p in params)),env)
mod = cxx_generator(modname, code, interface)
pymod = load_dynamic(modname,pythran_compile(os.environ.get("CXX","c++"),mod, cxxflags=["-O0","-fno-implicit-inline-templates", "-fopenmp"], check=False))
res = getattr(pymod,name)(*params)
if ref != res:
print ref, res
self.assertAlmostEqual(ref, res)
| bsd-3-clause | Python |
eff2461087bea6b0959dcdbd48d1873fd350e880 | Change config settings in manage.py | andela-hoyeboade/bucketlist-api | manage.py | manage.py | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from app import app
app = Flask(__name__)
app.config.from_object('config.DevelopmentConfig')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from app import app
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run() | mit | Python |
b56a14d247395f65fe54c22227b599b66270ded9 | Update spinthewheel.py | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis | jarviscli/plugins/spinthewheel.py | jarviscli/plugins/spinthewheel.py | from plugin import plugin
import random
'''This code picks one of the random inputs given by the user
like spin wheel'''
@plugin("spin wheel")
def spin(jarvis, s):
jarvis.say(' ')
jarvis.say('welcome to spin the wheel\n')
jarvis.say('enter the number of elements in the wheel')
num = jarvis.input()
intnum = int(num)
jarvis.say('enter the elements one after another\n')
wheel = []
for i in range(0, intnum):
entry = jarvis.input()
wheel.append(entry)
jarvis.say('Let the wheel spin !!!!!!!!!\n')
jarvis.say('result is: ' + random.choice(wheel))
| from plugin import plugin
import random
'''This code picks one of the random inputs given by the user
like spin wheel'''
@plugin("spin wheel")
def spin(jarvis, s):
jarvis.say(' ')
jarvis.say('welcome to spin the wheel\n')
jarvis.say('enter the number of elements in the wheel')
num = jarvis.input()
jarvis.say('enter the elements one after another\n')
wheel = []
for i in range(0, num):
entry = jarvis.input()
wheel.append(entry)
jarvis.say('Let the wheel spin !!!!!!!!!\n')
jarvis.say('result is: ' + random.choice(wheel))
| mit | Python |
884cdda7304edfed8c026aac02217b4087f49d81 | fix recipe | samuel/kokki | kokki/cookbooks/mdadm/recipes/default.py | kokki/cookbooks/mdadm/recipes/default.py |
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
env.cookbooks.mdadm.Array(notifies = [("run", env.resources["Execute"]["mdadm-update-conf"])], **array)
if array.get('fstype'):
if array['fstype'] == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if array.get('mount_point'):
Mount(array['mount_point'],
device = array['name'],
fstype = array['fstype'],
options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
action = ["mount", "enable"])
|
from kokki import *
if env.config.mdadm.arrays:
Package("mdadm")
Execute("mdadm-update-conf",
action = "nothing",
command = ("("
"echo DEVICE partitions > /etc/mdadm/mdadm.conf"
"; mdadm --detail --scan >> /etc/mdadm/mdadm.conf"
")"
))
for array in env.config.mdadm.arrays:
env.cookbooks.mdadm.Array(notifies = [("run", env.resources["Execute"]["mdadm-update-conf"])], **array)
if array.get('fstype'):
if array['fstype'], == "xfs":
Package("xfsprogs")
Execute("mkfs.%(fstype)s -f %(device)s" % dict(fstype=array['fstype'], device=array['name']),
not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % dict(device=array['name']))
if array.get('mount_point'):
Mount(array['mount_point'],
device = array['name'],
fstype = array['fstype'],
options = array['fsoptions'] if array.get('fsoptions') is not None else ["noatime"],
action = ["mount", "enable"])
| bsd-3-clause | Python |
bafea222db835f4f2fee8ad603b2b997b33922d4 | Fix call to create_tunnel and some other small things. | peplin/astral | astral/node/tunnel.py | astral/node/tunnel.py | import threading
import asyncore
import time
from astral.net.tunnel import Tunnel
from astral.models import Ticket
from astral.models.ticket import TUNNEL_QUEUE
import logging
log = logging.getLogger(__name__)
class TunnelControlThread(threading.Thread):
def __init__(self):
super(TunnelControlThread, self).__init__()
self.daemon = True
self.tunnels = dict()
def run(self):
while True:
ticket_id = TUNNEL_QUEUE.get()
ticket = Ticket.get_by(id=ticket_id)
log.debug("Found %s in tunnel queue", ticket)
port = self.create_tunnel(ticket.id, ticket.source.ip_address,
ticket.source_port, ticket.destination.ip_address,
ticket.destination_port)
TUNNEL_QUEUE.task_done()
ticket.source_port = port
self.close_expired_tunnels()
def create_tunnel(self, ticket_id, source_ip, source_port,
destination_ip, destination_port):
tunnel = Tunnel(destination_ip, destination_port)
log.info("Starting %s", tunnel)
self.tunnels[ticket_id] = tunnel
return tunnel.source_port()
def destroy_tunnel(self, ticket_id):
tunnel = self.tunnels.pop(ticket_id)
log.info("Stopping %s", tunnel)
tunnel.handle_close()
def close_expired_tunnels(self):
for ticket_id, tunnel in self.tunnels.items():
if not Ticket.get_by(id=ticket_id):
self.destroy_tunnel(ticket_id)
class TunnelLoopThread(threading.Thread):
def __init__(self):
super(TunnelLoopThread, self).__init__()
self.daemon = True
def run(self):
# TODO this is going to just spin when we first start up and have no
# existing tunnels. we talked about having everyone with the rtmp server
# access that not directly, but through a tunnel, so we could use that
# to control the on/off. still need that?
while True:
asyncore.loop()
# TODO this is a little workaround to make sure we don't eat up 100%
# CPU at the moment
time.sleep(1)
| import threading
import asyncore
import time
from astral.net.tunnel import Tunnel
from astral.models import Ticket
from astral.models.ticket import TUNNEL_QUEUE
import logging
log = logging.getLogger(__name__)
class TunnelControlThread(threading.Thread):
def __init__(self):
super(TunnelControlThread, self).__init__()
self.daemon = True
def run(self):
while True:
ticket_id = TUNNEL_QUEUE.get()
ticket = Ticket.get_by(id=ticket_id)
log.debug("Found %s in tunnel queue", ticket)
port = self.create_tunnel(ticket.source.ip_address, ticket.source_port,
ticket.destination.ip_address, ticket.destination_port)
TUNNEL_QUEUE.task_done()
ticket.source_port = port
self.close_expired_tunnels()
def create_tunnel(self, ticket_id, source_ip, source_port,
destination_ip, destination_port):
tunnel = Tunnel(destination_ip, destination_port)
log.info("Starting %s", tunnel)
self.tunnels[ticket_id] = tunnel
return tunnel.source_port()
def destroy_tunnel(self, ticket_id):
tunnel = self.tunnels.pop(ticket_id)
log.info("Stopping %s", tunnel)
tunnel.handle_close()
def close_expired_tunnels(self):
for ticket_id, tunnel in self.tunnels.values():
if not Ticket.get_by(id=ticket_id):
self.destroy_tunnel(ticket_id)
class TunnelLoopThread(threading.Thread):
def __init__(self):
super(TunnelLoopThread, self).__init__()
self.daemon = True
self.tunnels = dict()
def run(self):
# TODO this is going to just spin when we first start up and have no
# existing tunnels. we talked about having everyone with the rtmp server
# access that not directly, but through a tunnel, so we could use that
# to control the on/off. still need that?
while True:
asyncore.loop()
# TODO this is a little workaround to make sure we don't eat up 100%
# CPU at the moment
time.sleep(1)
| mit | Python |
abcb8e05914efd47d071039bb143e993542c09ee | use CherryPy as the HTTP server | schettino72/serveronduty | manage.py | manage.py | #!/usr/bin/env python
from werkzeug import script
from cherrypy import wsgiserver
def make_app():
from websod.application import WebSod
return WebSod('sqlite:///sod.db')
def make_shell():
from websod import models, utils
application = make_app()
return locals()
def make_server(hostname="localhost", port=9000):
def start_server(hostname=('h', hostname), port=('p', port)):
"""start a serveronduty server
"""
server = wsgiserver.CherryPyWSGIServer((hostname, port), make_app())
try:
server.start()
except KeyboardInterrupt:
print '\nstopping...'
server.stop()
return start_server
action_start = make_server()
action_runserver = script.make_runserver(make_app, use_reloader=True,
use_debugger=True)
action_shell = script.make_shell(make_shell)
action_initdb = lambda: make_app().init_database()
script.run()
| #!/usr/bin/env python
from werkzeug import script
def make_app():
from websod.application import WebSod
return WebSod('sqlite:///sod.db')
def make_shell():
from websod import models, utils
application = make_app()
return locals()
action_runserver = script.make_runserver(make_app, use_reloader=True,
use_debugger=True)
action_shell = script.make_shell(make_shell)
action_initdb = lambda: make_app().init_database()
script.run()
| mit | Python |
59fec8fdcf811aefec7a03e0fc107a24ecb1d5ed | Refactor manager | reubano/pkutils,reubano/pkutils | manage.py | manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A script to manage development tasks """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from os import path as p
from manager import Manager
from subprocess import call
manager = Manager()
_basedir = p.dirname(__file__)
@manager.command
def clean():
"""Remove Python file and build artifacts"""
call(p.join(_basedir, 'helpers', 'clean'))
@manager.command
def check():
"""Check staged changes for lint errors"""
call(p.join(_basedir, 'helpers', 'check-stage'))
@manager.arg('where', 'w', help='Modules to check')
@manager.arg('strict', 's', help='Check with pylint')
@manager.command
def lint(where=None, strict=False):
"""Check style with linters"""
call(['flake8', where] if where else 'flake8')
if strict:
args = 'pylint --rcfile=tests/standard.rc -rn -fparseable pkutils'
call(args.split(' '))
@manager.command
def pipme():
"""Install requirements.txt"""
call('pip install -r requirements.txt'.split(' '))
@manager.command
def require():
"""Create requirements.txt"""
cmd = 'pip freeze -l | grep -vxFf dev-requirements.txt > requirements.txt'
call(cmd, shell=True)
@manager.arg('where', 'w', help='test path', default=None)
@manager.arg(
'stop', 'x', help='Stop after first error', type=bool, default=False)
@manager.command
def test(where=None, stop=False):
"""Run nose and script tests"""
opts = '-xv' if stop else '-v'
opts += 'w %s' % where if where else ''
call([p.join(_basedir, 'helpers', 'test'), opts])
@manager.command
def register():
"""Register package with PyPI"""
call('python %s register' % p.join(_basedir, 'setup.py'), shell=True)
@manager.command
def release():
"""Package and upload a release"""
sdist()
wheel()
upload()
@manager.command
def build():
"""Create a source distribution and wheel package"""
sdist()
wheel()
@manager.command
def upload():
"""Upload distribution files"""
call('twine upload %s' % p.join(_basedir, 'dist', '*'), shell=True)
@manager.command
def sdist():
"""Create a source distribution package"""
call(p.join(_basedir, 'helpers', 'srcdist'))
@manager.command
def wheel():
"""Create a wheel package"""
call(p.join(_basedir, 'helpers', 'wheel'))
if __name__ == '__main__':
manager.main()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A script to manage development tasks """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from os import path as p
from manager import Manager
from subprocess import call
manager = Manager()
_basedir = p.dirname(__file__)
@manager.command
def clean():
"""Remove Python file and build artifacts"""
call(p.join(_basedir, 'helpers', 'clean'), shell=True)
@manager.command
def check():
"""Check staged changes for lint errors"""
call(p.join(_basedir, 'helpers', 'check-stage'), shell=True)
@manager.arg('where', 'w', help='Modules to check')
@manager.command
def lint(where=None):
"""Check style with flake8"""
call('flake8 %s' % (where if where else ''), shell=True)
@manager.command
def pipme():
"""Install requirements.txt"""
call('pip install -r requirements.txt', shell=True)
@manager.command
def require():
"""Create requirements.txt"""
cmd = 'pip freeze -l | grep -vxFf dev-requirements.txt > requirements.txt'
call(cmd, shell=True)
@manager.arg('where', 'w', help='test path', default=None)
@manager.arg(
'stop', 'x', help='Stop after first error', type=bool, default=False)
@manager.command
def test(where=None, stop=False):
"""Run nose and script tests"""
opts = '-xv' if stop else '-v'
opts += 'w %s' % where if where else ''
call([p.join(_basedir, 'helpers', 'test'), opts])
@manager.command
def register():
"""Register package with PyPI"""
call('python %s register' % p.join(_basedir, 'setup.py'), shell=True)
@manager.command
def release():
"""Package and upload a release"""
sdist()
wheel()
upload()
@manager.command
def build():
"""Create a source distribution and wheel package"""
sdist()
wheel()
@manager.command
def upload():
"""Upload distribution files"""
call('twine upload %s' % p.join(_basedir, 'dist', '*'), shell=True)
@manager.command
def sdist():
"""Create a source distribution package"""
call(p.join(_basedir, 'helpers', 'srcdist'), shell=True)
@manager.command
def wheel():
"""Create a wheel package"""
call(p.join(_basedir, 'helpers', 'wheel'), shell=True)
if __name__ == '__main__':
manager.main()
| mit | Python |
0f4fd0d49ba06963b0b97e032fd2e6eedf8e597a | Fix missing space between lede and rest of article | ahalterman/cloacina | cloacina/extract_from_b64.py | cloacina/extract_from_b64.py | from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
doc = re.sub('<div class="BODY-2">', " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.find("meta", {"name":"sourceName"})['content']
article_title = soup.find("title").text.strip()
try:
publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip()
except AttributeError:
publication_date = soup.find("div", {"class":"DATE"}).text.strip()
article_body = soup.find("div", {"class":"BODY"}).text.strip()
doc_id = soup.find("meta", {"name":"documentToken"})['content']
data = {"news_source" : news_source,
"publication_date_raw" : publication_date,
"article_title" : article_title,
"article_body" : article_body,
"doc_id" : doc_id}
return data
| from bs4 import BeautifulSoup
import json
import re
def extract_from_b64(encoded_doc):
#doc = base64.urlsafe_b64decode(encoded_doc)
doc = encoded_doc.decode("base64")
doc = re.sub("</p><p>", " ", doc)
soup = BeautifulSoup(doc)
news_source = soup.find("meta", {"name":"sourceName"})['content']
article_title = soup.find("title").text.strip()
try:
publication_date = soup.find("div", {"class":"PUB-DATE"}).text.strip()
except AttributeError:
publication_date = soup.find("div", {"class":"DATE"}).text.strip()
article_body = soup.find("div", {"class":"BODY"}).text.strip()
doc_id = soup.find("meta", {"name":"documentToken"})['content']
data = {"news_source" : news_source,
"publication_date_raw" : publication_date,
"article_title" : article_title,
"article_body" : article_body,
"doc_id" : doc_id}
return data
| mit | Python |
8b3d641c2cb1f43f5ddb122b68fd37df6d0ab1e3 | Update MIDDLEWARE to be compatible with Django 1.11+ | bugsnag/bugsnag-python,bugsnag/bugsnag-python | tests/fixtures/django1/bugsnag_demo/settings.py | tests/fixtures/django1/bugsnag_demo/settings.py | """
Django settings for bugsnag_demo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import django
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3n3h7r@tpqnwqtt8#avxh_t75k_6zf3x)@6cg!u(&xmz79(26h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
_MIDDLEWARE = (
"bugsnag.django.middleware.BugsnagMiddleware",
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
)
if django.VERSION >= (1, 10):
MIDDLEWARE = _MIDDLEWARE
else:
MIDDLEWARE_CLASSES = _MIDDLEWARE
ROOT_URLCONF = 'bugsnag_demo.urls'
WSGI_APPLICATION = 'bugsnag_demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
BUGSNAG = {
"api_key": "066f5ad3590596f9aa8d601ea89af845",
"endpoint": os.environ.get('BUGSNAG_API', 'https://notify.bugsnag.com'),
"asynchronous": False,
}
| """
Django settings for bugsnag_demo project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '3n3h7r@tpqnwqtt8#avxh_t75k_6zf3x)@6cg!u(&xmz79(26h'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
"bugsnag.django.middleware.BugsnagMiddleware",
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware'
)
ROOT_URLCONF = 'bugsnag_demo.urls'
WSGI_APPLICATION = 'bugsnag_demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
BUGSNAG = {
"api_key": "066f5ad3590596f9aa8d601ea89af845",
"endpoint": os.environ.get('BUGSNAG_API', 'https://notify.bugsnag.com'),
"asynchronous": False,
}
| mit | Python |
a154ccdf9bb0d6ba06b4038789437bd98d656282 | fix incorrect url pattern for archived studentships | evildmp/Arkestra,bubenkoff/Arkestra,bubenkoff/Arkestra,evildmp/Arkestra,bubenkoff/Arkestra,evildmp/Arkestra | vacancies_and_studentships/urls.py | vacancies_and_studentships/urls.py | from django.conf.urls.defaults import patterns, url
import views
urlpatterns = patterns('',
# vacancies and studentships items
url(r"^vacancy/(?P<slug>[-\w]+)/$", views.vacancy, name="vacancy"),
url(r"^studentship/(?P<slug>[-\w]+)/$", views.studentship, name="studentship"),
# entities' vacancies and studentships
url(r'^archived-vacancies/(?:(?P<slug>[-\w]+)/)?$', views.archived_vacancies, name="archived_vacancies"),
url(r'^all-open-vacancies/(?:(?P<slug>[-\w]+)/)?$', views.all_current_vacancies, name="all_current_vacancies"),
url(r'^archived-studentships/(?:(?P<slug>[-\w]+)/)?$', views.archived_studentships, name="archived_studentships"),
url(r"^all-open-studentships/(?:(?P<slug>[-\w]+)/)?$", views.all_current_studentships, name="all_current_studentships"),
url(r"^vacancies-and-studentships/(?:(?P<slug>[-\w]+)/)?$", views.vacancies_and_studentships, name="vacancies_and_studentships"),
)
| from django.conf.urls.defaults import patterns, url
import views
urlpatterns = patterns('',
# vacancies and studentships items
url(r"^vacancy/(?P<slug>[-\w]+)/$", views.vacancy, name="vacancy"),
url(r"^studentship/(?P<slug>[-\w]+)/$", views.studentship, name="studentship"),
# entities' vacancies and studentships
url(r'^archived-vacancies/(?:(?P<slug>[-\w]+)/)?$', views.archived_vacancies, name="archived_vacancies"),
url(r'^all-open-vacancies/(?:(?P<slug>[-\w]+)/)?$', views.all_current_vacancies, name="all_current_vacancies"),
url(r'^archived-studentships/(?:(?P<slug>[-\w]+)/)?$', views.vacancies_and_studentships, name="vacancies_and_studentships"),
url(r"^all-open-studentships/(?:(?P<slug>[-\w]+)/)?$", views.all_current_studentships, name="all_current_studentships"),
url(r"^vacancies-and-studentships/(?:(?P<slug>[-\w]+)/)?$", views.vacancies_and_studentships, name="vacancies_and_studentships"),
)
| bsd-2-clause | Python |
29ca88405f37019932ea82042ebdadaafbda69af | Remove lang arg, dont need it ...yet | durden/dash,durden/dash | apps/codrspace/templatetags/short_codes.py | apps/codrspace/templatetags/short_codes.py | """Custom filters to grab code from the web via short codes"""
import requests
import re
from django.utils import simplejson
from django import template
from django.utils.safestring import mark_safe
from codrspace.templatetags.syntax_color import _colorize_table
import markdown
register = template.Library()
@register.filter(name='explosivo')
def explosivo(value):
"""
Search text for any references to supported short codes and explode them
"""
# Round-robin through all functions as if they are filter methods so we
# don't have to update some silly list of available ones when they are
# added
import sys, types
module = sys.modules[__name__]
for name, var in vars(module).items():
if type(var) == types.FunctionType and name.startswith('filter_'):
value, match = var(value)
if not match:
value = markdown.markdown(value)
return mark_safe(value)
def filter_gist(value):
pattern = re.compile('\[gist (\d+) *\]', flags=re.IGNORECASE)
match = re.search(pattern, value)
if match is None:
return value, None
gist_id = int(match.group(1))
resp = requests.get('https://api.github.com/gists/%d' % (gist_id))
if resp.status_code != 200:
return value
content = simplejson.loads(resp.content)
gist_text = ""
# Go through all files in gist and smash 'em together
for name in content['files']:
gist_text += "%s" % (
_colorize_table(content['files'][name]['content'], None)
)
return (re.sub(pattern, gist_text, markdown.markdown(value)), match)
def filter_url(value):
pattern = re.compile('\[url (\S+) *\]', flags=re.IGNORECASE)
match = re.search(pattern, value)
if match is None:
return value, None
url = match.group(1)
# FIXME: Validate that value is actually a url
resp = requests.get(url)
if resp.status_code != 200:
return value
return (re.sub(pattern, _colorize_table(resp.content, None),
markdown.markdown(value)), match)
def filter_upload(value):
return value, None
if __name__ == "__main__":
explosivo('test')
| """Custom filters to grab code from the web via short codes"""
import requests
import re
from django.utils import simplejson
from django import template
from django.utils.safestring import mark_safe
from codrspace.templatetags.syntax_color import _colorize_table
import markdown
register = template.Library()
@register.filter(name='explosivo')
def explosivo(value, lang):
"""
Search text for any references to supported short codes and explode them
"""
# Round-robin through all functions as if they are filter methods so we
# don't have to update some silly list of available ones when they are
# added
import sys, types
module = sys.modules[__name__]
for name, var in vars(module).items():
if type(var) == types.FunctionType and name.startswith('filter_'):
value, match = var(value, lang)
if not match:
value = markdown.markdown(value)
return mark_safe(value)
def filter_gist(value, lang):
pattern = re.compile('\[gist (\d+) *\]', flags=re.IGNORECASE)
match = re.search(pattern, value)
if match is None:
return value, None
gist_id = int(match.group(1))
resp = requests.get('https://api.github.com/gists/%d' % (gist_id))
if resp.status_code != 200:
return value
content = simplejson.loads(resp.content)
gist_text = ""
# Go through all files in gist and smash 'em together
for name in content['files']:
gist_text += "%s" % (
_colorize_table(content['files'][name]['content'], None)
)
return (
re.sub(pattern, gist_text, markdown.markdown(value)),
match
)
def filter_url(value, lang):
pattern = re.compile('\[url (\S+) *\]', flags=re.IGNORECASE)
match = re.search(pattern, value)
if match is None:
return value, None
url = match.group(1)
# FIXME: Validate that value is actually a url
resp = requests.get(url)
if resp.status_code != 200:
return value
return (
re.sub(pattern, _colorize_table(resp.content, None), markdown.markdown(value)),
match
)
def filter_upload(value, lang):
return value, None
if __name__ == "__main__":
explosivo('test')
| mit | Python |
51d37f7ac6bebf9b1d4c6efd16a968b7410a7791 | Save mul at the end to force execution. | marianotepper/csnmf | rcnmf/tests/test_tsqr2.py | rcnmf/tests/test_tsqr2.py | import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
data = into(da.Array, uri, blockshape=(100, 100))
omega = da.random.standard_normal(size=(100, 20), blockshape=(100, 20))
mat_h = data.dot(omega)
q, r = rcnmf. tsqr.tsqr(mat_h, blockshape=(100, 20))
print data.shape
print q.shape
mul = data.dot(q)
dot_graph(data.dask, filename='data')
dot_graph(omega.dask, filename='omega')
dot_graph(q.dask, filename='q')
dot_graph(mul.dask, filename='mul')
uri = temp_file.name + '::/mul'
into(uri, mul)
temp_file.close()
| import dask.array as da
from into import into
from dask.array.into import discover
from dask.dot import dot_graph
import tempfile
import rcnmf.tsqr
x = da.random.standard_normal(size=(100, 100), blockshape=(100, 50))
temp_file = tempfile.NamedTemporaryFile(suffix='.hdf5')
uri = temp_file.name + '::/X'
into(uri, x)
data = into(da.Array, uri, blockshape=(100, 100))
omega = da.random.standard_normal(size=(100, 20), blockshape=(100, 20))
mat_h = data.dot(omega)
q, r = rcnmf. tsqr.tsqr(mat_h, blockshape=(100, 20))
print data.shape
print q.shape
mul = data.dot(q)
dot_graph(data.dask, filename='data')
dot_graph(omega.dask, filename='omega')
dot_graph(q.dask, filename='q')
dot_graph(mul.dask, filename='mul')
temp_file.close()
| bsd-2-clause | Python |
d707426caae0038609fcc71531fd5d7aa61f4f47 | Bump jaxlib version to 0.1.5 in preparation for building new wheels. | google/jax,google/jax,tensorflow/probability,google/jax,tensorflow/probability,google/jax | build/setup.py | build/setup.py | # Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
from glob import glob
import os
binary_libs = [os.path.basename(f) for f in glob('jaxlib/*.so*')]
setup(
name='jaxlib',
version='0.1.5',
description='XLA library for JAX',
author='JAX team',
author_email='jax-dev@google.com',
packages=['jaxlib'],
install_requires=['scipy', 'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py'],
url='https://github.com/google/jax',
license='Apache-2.0',
package_data={'jaxlib': binary_libs},
)
| # Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
from glob import glob
import os
binary_libs = [os.path.basename(f) for f in glob('jaxlib/*.so*')]
setup(
name='jaxlib',
version='0.1.4',
description='XLA library for JAX',
author='JAX team',
author_email='jax-dev@google.com',
packages=['jaxlib'],
install_requires=['scipy', 'numpy>=1.12', 'six', 'protobuf>=3.6.0', 'absl-py'],
url='https://github.com/google/jax',
license='Apache-2.0',
package_data={'jaxlib': binary_libs},
)
| apache-2.0 | Python |
6703427bb70ebec3df22844df7b22026266c0b04 | Set PYTHONPATH during runtime | rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck,rburchell/ck | tests/python-test-library/testcases/runtests.py | tests/python-test-library/testcases/runtests.py | #!/usr/bin/env python2.5
##
## @file runtests.py
##
## Copyright (C) 2008 Nokia. All rights reserved.
##
##
##
##
## Requires python2.5-gobject and python2.5-dbus
##
## Implements also some testing API:
##
##
import sys
sys.path.append("../testcases")
sys.path.append("../stubs")
import os
from time import sleep
import dbus
import commands
import dbus_emulator
import conf
import contextGetPropertiesTCs
import contextSubscribeTCs
import test
def module_setUp():
dbus_emulator.createBus(dbus_emulator.SYSTEM,conf.sessionConfigPath)
dbus_emulator.createBus(dbus_emulator.SESSION,conf.sessionConfigPath)
sleep (5)
os.system(conf.contextSrcPath + os.sep + "tests/python-test-library/stubs/mce_stub.py &")
sleep (5)
os.system(conf.contextSrcPath + os.sep + "contextd &")
#sleep (5)
#os.system(conf.contextSrcPath + os.sep + "tests/python-test-library/testcases/test.py &")
#sleep (5)
def module_tearDown():
os.kill(int(commands.getoutput('pidof contextd')),15)
dbus_emulator.deleteBus(dbus_emulator.SYSTEM)
dbus_emulator.deleteBus(dbus_emulator.SESSION)
# Main stuff
if __name__ == "__main__":
module_setUp()
#contextGetPropertiesTCs.testRun()
#test.testRun()
#module_tearDown()
sysBus = dbus.SystemBus()
try:
object = sysBus.get_object("com.nokia.mce","/com/nokia/mce/request")
ifceMCE = dbus.Interface(object,"com.nokia.mce.request")
except dbus.DBusException:
traceback.print_exc()
sys.exit(1)
ifceMCE.req_device_facing_change("face_down")
ifceMCE.req_device_facing_change("face_up")
module_tearDown() | #!/usr/bin/env python2.5
##
## @file runtests.py
##
## Copyright (C) 2008 Nokia. All rights reserved.
##
##
##
##
## Requires python2.5-gobject and python2.5-dbus
##
## Implements also some testing API:
##
##
import os
from time import sleep
import dbus
import commands
import dbus_emulator
import conf
import contextGetPropertiesTCs
import contextSubscribeTCs
import test
def module_setUp():
dbus_emulator.createBus(dbus_emulator.SYSTEM,conf.sessionConfigPath)
dbus_emulator.createBus(dbus_emulator.SESSION,conf.sessionConfigPath)
sleep (5)
os.system(conf.contextSrcPath + os.sep + "tests/python-test-library/stubs/mce_stub.py &")
sleep (5)
os.system(conf.contextSrcPath + os.sep + "contextd &")
#sleep (5)
#os.system(conf.contextSrcPath + os.sep + "tests/python-test-library/testcases/test.py &")
#sleep (5)
def module_tearDown():
os.kill(int(commands.getoutput('pidof contextd')),15)
dbus_emulator.deleteBus(dbus_emulator.SYSTEM)
dbus_emulator.deleteBus(dbus_emulator.SESSION)
# Main stuff
if __name__ == "__main__":
module_setUp()
#contextGetPropertiesTCs.testRun()
#test.testRun()
#module_tearDown()
sysBus = dbus.SystemBus()
try:
object = sysBus.get_object("com.nokia.mce","/com/nokia/mce/request")
ifceMCE = dbus.Interface(object,"com.nokia.mce.request")
except dbus.DBusException:
traceback.print_exc()
sys.exit(1)
ifceMCE.req_device_facing_change("face_down")
ifceMCE.req_device_facing_change("face_up")
module_tearDown() | lgpl-2.1 | Python |
bc4b6e80688f9bebd3220fed12645aeb58d710c9 | Update : client db_name param renamed | oleiade/Elevator | client/base.py | client/base.py | from __future__ import absolute_import
import zmq
import msgpack
from .message import Message
from .error import ELEVATOR_ERROR
from elevator.constants import FAILURE_STATUS
from elevator.db import DatabaseOptions
class Client(object):
def __init__(self, db=None, *args, **kwargs):
self.protocol = kwargs.pop('protocol', 'tcp')
self.bind = kwargs.pop('bind', '127.0.0.1')
self.port = kwargs.pop('port', '4141')
self._db_uid = None
self.timeout = kwargs.pop('timeout', 10 * 10000)
self.host = "%s://%s:%s" % (self.protocol, self.bind, self.port)
db = 'default' if not db else db
self._connect(db=db)
def __del__(self):
self._close()
def _connect(self, db):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.XREQ)
self.socket.connect(self.host)
self.connect(db)
def _close(self):
self.socket.close()
self.context.term()
def connect(self, db_name):
self.db_uid = self.send(db_name, 'DBCONNECT', {'db_name': db_name})
self.db_name = db_name
return
def listdb(self):
return self.send(self.db_uid, 'DBLIST', {})
def createdb(self, key, db_options=None):
db_options = db_options if not None else DatabaseOptions()
return self.send(self.db_uid, 'DBCREATE', [key, db_options])
def dropdb(self, key):
return self.send(self.db_uid, 'DBDROP', [key])
def repairdb(self):
return self.send(self.db_uid, 'DBREPAIR', {})
def send(self, db_uid, command, datas):
self.socket.send_multipart([Message(db_uid=db_uid, command=command, data=datas)])
status, content = msgpack.unpackb(self.socket.recv_multipart()[0])
if status == FAILURE_STATUS:
error_code, error_msg = content
raise ELEVATOR_ERROR[error_code](error_msg)
return content
| from __future__ import absolute_import
import zmq
import msgpack
from .message import Message
from .error import ELEVATOR_ERROR
from elevator.constants import FAILURE_STATUS
from elevator.db import DatabaseOptions
class Client(object):
def __init__(self, db_name=None, *args, **kwargs):
self.protocol = kwargs.pop('protocol', 'tcp')
self.bind = kwargs.pop('bind', '127.0.0.1')
self.port = kwargs.pop('port', '4141')
self._db_uid = None
self.timeout = kwargs.pop('timeout', 10 * 10000)
self.host = "%s://%s:%s" % (self.protocol, self.bind, self.port)
db_name = 'default' if not db_name else db_name
self._connect(db_name=db_name)
def __del__(self):
self._close()
def _connect(self, db_name):
self.context = zmq.Context()
self.socket = self.context.socket(zmq.XREQ)
self.socket.connect(self.host)
self.connect(db_name)
def _close(self):
self.socket.close()
self.context.term()
def connect(self, db_name):
self.db_uid = self.send(db_name, 'DBCONNECT', {'db_name': db_name})
self.db_name = db_name
return
def listdb(self):
return self.send(self.db_uid, 'DBLIST', {})
def createdb(self, key, db_options=None):
db_options = db_options if not None else DatabaseOptions()
return self.send(self.db_uid, 'DBCREATE', [key, db_options])
def dropdb(self, key):
return self.send(self.db_uid, 'DBDROP', [key])
def repairdb(self):
return self.send(self.db_uid, 'DBREPAIR', {})
def send(self, db_uid, command, datas):
self.socket.send_multipart([Message(db_uid=db_uid, command=command, data=datas)])
status, content = msgpack.unpackb(self.socket.recv_multipart()[0])
if status == FAILURE_STATUS:
error_code, error_msg = content
raise ELEVATOR_ERROR[error_code](error_msg)
return content
| mit | Python |
54bcdb0ca215c1d76b096240778354c30d16f453 | fix a few bugs in shape features | Radiomics/pyradiomics,Radiomics/pyradiomics,Radiomics/pyradiomics,Radiomics/pyradiomics | bin/helloRadiomics.py | bin/helloRadiomics.py | from radiomics import firstorder, glcm, preprocessing, shape, rlgl
import SimpleITK as sitk
import sys, os
#imageName = sys.argv[1]
#maskName = sys.argv[2]
testBinWidth = 25
#testResampledPixelSpacing = (3,3,3) no resampling for now.
dataDir = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".." + os.path.sep + "data"
imageName = dataDir + os.path.sep + 'prostate_phantom-subvolume.nrrd'
maskName = dataDir + os.path.sep + 'prostate_phantom_label-subvolume.nrrd'
image = sitk.ReadImage(imageName)
mask = sitk.ReadImage(maskName)
#
# Show the first order feature calculations
#
firstOrderFeatures = firstorder.RadiomicsFirstOrder(image,mask)
firstOrderFeatures.setBinWidth(testBinWidth)
firstOrderFeatures.enableFeatureByName('MeanIntensity', True)
# firstOrderFeatures.enableAllFeatures()
print 'Will calculate the following first order features: '
for f in firstOrderFeatures.enabledFeatures.keys():
print ' ',f
print eval('firstOrderFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating first order features...',
firstOrderFeatures.calculateFeatures()
print 'done'
print 'Calculated first order features: '
for (key,val) in firstOrderFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show Shape features
#
shapeFeatures = shape.RadiomicsShape(image, mask)
shapeFeatures.setBinWidth(testBinWidth)
shapeFeatures.enableAllFeatures()
print 'Will calculate the following Shape features: '
for f in shapeFeatures.enabledFeatures.keys():
print ' ',f
print eval('shapeFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating Shape features...',
shapeFeatures.calculateFeatures()
print 'done'
print 'Calculated Shape features: '
for (key,val) in shapeFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show GLCM features
#
glcmFeatures = glcm.RadiomicsGLCM(image, mask)
glcmFeatures.setBinWidth(testBinWidth)
glcmFeatures.enableAllFeatures()
print 'Will calculate the following GLCM features: '
for f in glcmFeatures.enabledFeatures.keys():
print ' ',f
print eval('glcmFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating GLCM features...',
glcmFeatures.calculateFeatures()
print 'done'
print 'Calculated GLCM features: '
for (key,val) in glcmFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show RLGL features
#
rlglFeatures = rlgl.RadiomicsRLGL(image, mask, 10)
rlglFeatures.enableAllFeatures()
print 'Will calculate the following RLGL features: '
for f in rlglFeatures.enabledFeatures.keys():
print ' ',f
print eval('rlglFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating RLGL features...',
rlglFeatures.calculateFeatures()
print 'done'
print 'Calculated RLGL features: '
for (key,val) in rlglFeatures.featureValues.iteritems():
print ' ',key,':',val
| from radiomics import firstorder, glcm, preprocessing, shape, rlgl
import SimpleITK as sitk
import sys, os
#imageName = sys.argv[1]
#maskName = sys.argv[2]
testBinWidth = 25
#testResampledPixelSpacing = (3,3,3) no resampling for now.
dataDir = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".." + os.path.sep + "data"
imageName = dataDir + os.path.sep + 'prostate_phantom-subvolume.nrrd'
maskName = dataDir + os.path.sep + 'prostate_phantom_label-subvolume.nrrd'
image = sitk.ReadImage(imageName)
mask = sitk.ReadImage(maskName)
#
# Show the first order feature calculations
#
firstOrderFeatures = firstorder.RadiomicsFirstOrder(image,mask)
firstOrderFeatures.setBinWidth(testBinWidth)
firstOrderFeatures.enableFeatureByName('MeanIntensity', True)
# firstOrderFeatures.enableAllFeatures()
print 'Will calculate the following first order features: '
for f in firstOrderFeatures.enabledFeatures.keys():
print ' ',f
print eval('firstOrderFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating first order features...',
firstOrderFeatures.calculateFeatures()
print 'done'
print 'Calculated first order features: '
for (key,val) in firstOrderFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show Shape features
#
shapeFeatures = shape.RadiomicsShape(image, mask)
shapeFeatures.setBinWidth(testBinWidth)
shapeFeatures.enableAllFeatures()
print 'Will calculate the following Shape features: '
for f in shapeFeatures.enabledFeatures.keys():
print ' ',f
print eval('shapeFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating Shape features...',
shapeFeatures.calculateFeatures()
print 'done'
print 'Calculated Shape features: '
for (key,val) in shapeFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show GLCM features
#
glcmFeatures = glcm.RadiomicsGLCM(image, mask)
glcmFeatures.setBinWidth(testBinWidth)
glcmFeatures.enableAllFeatures()
print 'Will calculate the following GLCM features: '
for f in glcmFeatures.enabledFeatures.keys():
print ' ',f
print eval('glcmFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating GLCM features...',
glcmFeatures.calculateFeatures()
print 'done'
print 'Calculated GLCM features: '
for (key,val) in glcmFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show Shape features
#
shapeFeatures = shape.RadiomicsShape(image, mask, 10)
shapeFeatures.enableAllFeatures()
print 'Will calculate the following Shape features: '
for f in shapeFeatures.enabledFeatures.keys():
print ' ',f
print eval('shapeFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating Shape features...',
shapeFeatures.calculateFeatures()
print 'done'
print 'Calculated Shape features: '
for (key,val) in shapeFeatures.featureValues.iteritems():
print ' ',key,':',val
#
# Show RLGL features
#
rlglFeatures = rlgl.RadiomicsRLGL(image, mask, 10)
rlglFeatures.enableAllFeatures()
print 'Will calculate the following RLGL features: '
for f in rlglFeatures.enabledFeatures.keys():
print ' ',f
print eval('rlglFeatures.get'+f+'FeatureValue.__doc__')
print 'Calculating RLGL features...',
rlglFeatures.calculateFeatures()
print 'done'
print 'Calculated RLGL features: '
for (key,val) in rlglFeatures.featureValues.iteritems():
print ' ',key,':',val
| bsd-3-clause | Python |
359040acc4b8c54db84e154b15cabfb23b4e18a6 | Use VISION_BONNET_MODELS_PATH env var for custom models path. | google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian,google/aiyprojects-raspbian | src/aiy/vision/models/utils.py | src/aiy/vision/models/utils.py | """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.environ.get('VISION_BONNET_MODELS_PATH', '/opt/aiy/models')
with open(os.path.join(path, name), 'rb') as f:
return f.read()
| """Utility to load compute graphs from diffrent sources."""
import os
def load_compute_graph(name):
path = os.path.join('/opt/aiy/models', name)
with open(path, 'rb') as f:
return f.read()
| apache-2.0 | Python |
9cb4ba7bd05b8a7b6bd69bcc33cd791580f84be1 | write longest sequence to a file | linsalrob/EdwardsLab,linsalrob/EdwardsLab,linsalrob/EdwardsLab,linsalrob/EdwardsLab,linsalrob/EdwardsLab | bin/longest_contig.py | bin/longest_contig.py | """
Print the length of the longest contig for each file in a directory of fasta files.
"""
import os
import sys
import argparse
from roblib import read_fasta, bcolors
__author__ = 'Rob Edwards'
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Print the length of the longest contig for each file in a directory of fasta files')
parser.add_argument('-d', help='Directory of fasta files', required=True)
parser.add_argument('-f', help='fasta file to write the longest sequence to')
parser.add_argument('-v', help='verbose output', action='store_true')
args = parser.parse_args()
endings = {'.fna', '.fasta', '.fa'}
for f in os.listdir(args.d):
longest = [0, None, None]
isfasta = False
for e in endings:
if f.endswith(e):
isfasta = True
break
if not isfasta:
if args.v:
sys.stderr.write(f"{bcolors.PINK}Don't think {f} is a fasta file. Skipped\n{bcolors.ENDC}")
continue
if args.v:
sys.stderr.write(f"{bcolors.GREEN}{f}{bcolors.ENDC}\n")
fa = read_fasta(os.path.join(args.d, f))
for x in fa:
if len(fa[x]) > longest[0]:
longest = [len(fa[x]), x, fa[x]]
if 0 == longest[0]:
continue
print("{}\t{}".format(f, longest[0]))
if args.f:
with open(args.f, 'a') as out:
out.write(f">{longest[1]} [from {f}]\n{longest[2]}\n")
| """
Print the length of the longest contig for each file in a directory of fasta files.
"""
import os
import sys
import argparse
from roblib import read_fasta
__author__ = 'Rob Edwards'
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Print the length of the longest contig for each file in a directory of fasta files')
parser.add_argument('-d', help='Directory of fasta files', required=True)
args = parser.parse_args()
for f in os.listdir(args.d):
fa = read_fasta(os.path.join(args.d, f))
lengths = [len(fa[x]) for x in fa]
lengths.sort()
print("{}\t{}".format(f, lengths[-1]))
| mit | Python |
274e0eaa2c60ea116d798e1aaa7429ac59c60fbd | make manage.py is more simple | ownport/pywebase,ownport/pywebase | manage.py | manage.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Manager for pywebase
#
from packages import pywebase
# -----------------------------------------------
# Application functions (they can be changed
# in your application)
# -----------------------------------------------
pywebase.add_routes(
('/', 'GET', pywebase.handle_index),
('/favicon.ico', 'GET', pywebase.handle_favicon),
('/static/<filepath:path>', 'GET', pywebase.handle_static),
('/login', 'GET', pywebase.handle_login),
('/logout', 'GET', pywebase.handle_logout),
)
# -----------------------------------------------
# Main
# -----------------------------------------------
if __name__ == '__main__':
import sys
from packages import pyservice
if len(sys.argv) == 2 and sys.argv[1] in 'start stop restart status'.split():
pyservice.service('packages.pywebase.PywebaseProcess', sys.argv[1])
else:
print 'usage: manage <start,stop,restart,status>'
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Manager for pywebase
#
import os
import sys
import settings
from packages import bottle
from packages import pywebase
# -----------------------------------------------
# Application functions (they can be changed
# in your application)
# -----------------------------------------------
pywebase.add_routes(
('/', 'GET', pywebase.handle_index),
('/favicon.ico', 'GET', pywebase.handle_favicon),
('/static/<filepath:path>', 'GET', pywebase.handle_static),
('/login', 'GET', pywebase.handle_login),
('/logout', 'GET', pywebase.handle_logout),
)
# -----------------------------------------------
# Main
# -----------------------------------------------
if __name__ == '__main__':
from packages import pyservice
if len(sys.argv) == 2 and sys.argv[1] in 'start stop restart status'.split():
pyservice.service('packages.pywebase.PywebaseProcess', sys.argv[1])
else:
print 'usage: manager <start,stop,restart,status>'
| bsd-2-clause | Python |
84c5ac764b6ca2f452db2f387d0f838d395e31fa | Remove duplicate import of "sys" module. | silentbob73/kitsune,chirilo/kitsune,feer56/Kitsune1,H1ghT0p/kitsune,feer56/Kitsune2,brittanystoroz/kitsune,asdofindia/kitsune,H1ghT0p/kitsune,MikkCZ/kitsune,MziRintu/kitsune,mythmon/kitsune,turtleloveshoes/kitsune,NewPresident1/kitsune,chirilo/kitsune,feer56/Kitsune2,philipp-sumo/kitsune,feer56/Kitsune2,chirilo/kitsune,MikkCZ/kitsune,MziRintu/kitsune,MziRintu/kitsune,dbbhattacharya/kitsune,dbbhattacharya/kitsune,dbbhattacharya/kitsune,feer56/Kitsune1,safwanrahman/kitsune,safwanrahman/linuxdesh,brittanystoroz/kitsune,iDTLabssl/kitsune,feer56/Kitsune1,iDTLabssl/kitsune,H1ghT0p/kitsune,mozilla/kitsune,rlr/kitsune,Osmose/kitsune,chirilo/kitsune,MziRintu/kitsune,philipp-sumo/kitsune,anushbmx/kitsune,safwanrahman/linuxdesh,anushbmx/kitsune,asdofindia/kitsune,silentbob73/kitsune,silentbob73/kitsune,iDTLabssl/kitsune,Osmose/kitsune,mozilla/kitsune,turtleloveshoes/kitsune,safwanrahman/kitsune,mythmon/kitsune,YOTOV-LIMITED/kitsune,brittanystoroz/kitsune,philipp-sumo/kitsune,anushbmx/kitsune,safwanrahman/kitsune,orvi2014/kitsune,brittanystoroz/kitsune,rlr/kitsune,safwanrahman/kitsune,safwanrahman/linuxdesh,feer56/Kitsune2,YOTOV-LIMITED/kitsune,NewPresident1/kitsune,YOTOV-LIMITED/kitsune,MikkCZ/kitsune,turtleloveshoes/kitsune,MikkCZ/kitsune,orvi2014/kitsune,mythmon/kitsune,Osmose/kitsune,asdofindia/kitsune,orvi2014/kitsune,asdofindia/kitsune,YOTOV-LIMITED/kitsune,mozilla/kitsune,rlr/kitsune,mozilla/kitsune,Osmose/kitsune,mythmon/kitsune,H1ghT0p/kitsune,NewPresident1/kitsune,orvi2014/kitsune,NewPresident1/kitsune,silentbob73/kitsune,anushbmx/kitsune,rlr/kitsune,dbbhattacharya/kitsune,iDTLabssl/kitsune,turtleloveshoes/kitsune | manage.py | manage.py | #!/usr/bin/env python
import os
import site
import sys
ROOT = os.path.dirname(os.path.abspath(__file__))
path = lambda *a: os.path.join(ROOT, *a)
prev_sys_path = list(sys.path)
site.addsitedir(path('apps'))
site.addsitedir(path('lib'))
site.addsitedir(path('vendor'))
# Move the new items to the front of sys.path.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
# Now we can import from third-party libraries.
# Monkey patch for Bug 663236: Make |safe less necessary for form fields
from lib import safe_django_forms
safe_django_forms.monkeypatch()
from django.core.management import execute_manager, setup_environ
try:
import settings_local as settings
except ImportError:
try:
import settings # Assumed to be in the same directory.
except ImportError:
sys.stderr.write(
"Error: Tried importing 'settings_local.py' and 'settings.py' "
"but neither could be found (or they're throwing an ImportError)."
" Please come back and try again later.")
raise
# The first thing execute_manager does is call `setup_environ`. Logging config
# needs to access settings, so we'll setup the environ early.
setup_environ(settings)
# Monkey patch django's csrf
import session_csrf
session_csrf.monkeypatch()
# Import for side-effect: configures our logging handlers.
import log_settings
if __name__ == "__main__":
execute_manager(settings)
| #!/usr/bin/env python
import os
import site
import sys
ROOT = os.path.dirname(os.path.abspath(__file__))
path = lambda *a: os.path.join(ROOT, *a)
prev_sys_path = list(sys.path)
site.addsitedir(path('apps'))
site.addsitedir(path('lib'))
site.addsitedir(path('vendor'))
# Move the new items to the front of sys.path.
new_sys_path = []
for item in list(sys.path):
if item not in prev_sys_path:
new_sys_path.append(item)
sys.path.remove(item)
sys.path[:0] = new_sys_path
# Now we can import from third-party libraries.
# Monkey patch for Bug 663236: Make |safe less necessary for form fields
from lib import safe_django_forms
safe_django_forms.monkeypatch()
from django.core.management import execute_manager, setup_environ
try:
import settings_local as settings
except ImportError:
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write(
"Error: Tried importing 'settings_local.py' and 'settings.py' "
"but neither could be found (or they're throwing an ImportError)."
" Please come back and try again later.")
raise
# The first thing execute_manager does is call `setup_environ`. Logging config
# needs to access settings, so we'll setup the environ early.
setup_environ(settings)
# Monkey patch django's csrf
import session_csrf
session_csrf.monkeypatch()
# Import for side-effect: configures our logging handlers.
import log_settings
if __name__ == "__main__":
execute_manager(settings)
| bsd-3-clause | Python |
7127132e0a0c7c478ed1aa29dc9c6ffe9ed670d2 | Add comments and NotImplementedErrors for _ParticleFilterSetOperations | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | hoomd/filter/set_.py | hoomd/filter/set_.py | from hoomd.filter.filter_ import _ParticleFilter
from hoomd import _hoomd
class _ParticleFilterSetOperations(_ParticleFilter):
"""An abstract class for `ParticleFilters` with set operations.
Should not be instantiated directly."""
@property
def _cpp_cls_name(self):
"""The name of the C++ class in the `_hoomd` module.
Used for Python class's inheritance.
"""
raise NotImplementedError
@property
def _symmetric(self):
"""Whether the class implements a symmetric set operation.
Determines behavior of __eq__.
"""
raise NotImplementedError
def __init__(self, f, g):
if f == g:
raise ValueError("Cannot use same filter for {}"
"".format(self.__class__.__name__))
else:
self._f = f
self._g = g
# Grab the C++ class constructor for the set operation using the class
# variable _cpp_cls_name
getattr(_hoomd, self._cpp_cls_name).__init__(self, f, g)
def __hash__(self):
return hash(hash(self._f) + hash(self._g))
def __eq__(self, other):
if self._symmetric:
return type(self) == type(other) and \
(self._f == other._f or self._f == other._g) and \
(self._g == other._g or self._g == other._f)
else:
return type(self) == type(other) and \
self._f == other._f and self._g == other._g
class SetDifference(_ParticleFilterSetOperations,
_hoomd.ParticleFilterSetDifference):
_cpp_cls_name = 'ParticleFilterSetDifference'
_symmetric = False
class Union(_ParticleFilterSetOperations, _hoomd.ParticleFilterUnion):
_cpp_cls_name = 'ParticleFilterUnion'
_symmetric = True
class Intersection(_ParticleFilterSetOperations,
_hoomd.ParticleFilterIntersection):
_cpp_cls_name = 'ParticleFilterIntersection'
_symmetric = True
| from hoomd.filter.filter_ import _ParticleFilter
from hoomd import _hoomd
class _ParticleFilterSetOperations(_ParticleFilter):
def __init__(self, f, g):
if f == g:
raise ValueError("Cannot use same filter for {}"
"".format(self.__class__.__name__))
else:
self._f = f
self._g = g
# Grab the C++ class constructor for the set operation using the class
# variable _cpp_cls_name
getattr(_hoomd, self._cpp_cls_name).__init__(self, f, g)
def __hash__(self):
return hash(hash(self._f) + hash(self._g))
def __eq__(self, other):
if self._symmetric:
return type(self) == type(other) and \
(self._f == other._f or self._f == other._g) and \
(self._g == other._g or self._g == other._f)
else:
return type(self) == type(other) and \
self._f == other._f and self._g == other._g
class SetDifference(_ParticleFilterSetOperations,
_hoomd.ParticleFilterSetDifference):
_cpp_cls_name = 'ParticleFilterSetDifference'
_symmetric = False
class Union(_ParticleFilterSetOperations, _hoomd.ParticleFilterUnion):
_cpp_cls_name = 'ParticleFilterUnion'
_symmetric = True
class Intersection(_ParticleFilterSetOperations,
_hoomd.ParticleFilterIntersection):
_cpp_cls_name = 'ParticleFilterIntersection'
_symmetric = True
| bsd-3-clause | Python |
b001530004d856462b1edd5c6053e3c4cb0ea466 | Use reloader for runserver | KanColleTool/kcsrv,KanColleTool/kcsrv,KanColleTool/kcsrv | manage.py | manage.py | #!/usr/bin/env python
from flask.ext.script import Manager, Server
from flask.ext.migrate import MigrateCommand
from kcsrv import app
manager = Manager(app)
manager.add_command('runserver', Server(host='0.0.0.0', use_reloader=True))
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand
from kcsrv import app
manager = Manager(app)
manager.add_command('db', MigrateCommand)
if __name__ == '__main__':
manager.run()
| mit | Python |
85f8e7e79c56caa9c37fead6b650f6c0321207e9 | Rebase master | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas | manage.py | manage.py | # coding: utf-8
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mbaas.settings")
import pymysql
pymysql.install_as_MySQLdb()
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| # coding: utf-8
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mbaas.settings")
import pymysql
pymysql.install_as_MySQLdb()
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| apache-2.0 | Python |
63dd856fad5f6afd0927d9b051c4e59ed85dd092 | Remove unnecessary variable | datamicroscopes/lda,datamicroscopes/lda,datamicroscopes/lda | cmake/print_cmake_command.py | cmake/print_cmake_command.py | import sys
import os
from subprocess import check_output
if __name__ == '__main__':
build_type = "RelWithDebInfo"
if len(sys.argv) > 1:
build_type = sys.argv[1]
if build_type not in ('Debug', 'Release', 'RelWithDebInfo'):
raise ValueError("invalid build type: {}".format(build_type))
## XXX: handle virtualenv
conda_full_path = check_output("which conda", shell=True).strip()
if 'CONDA_DEFAULT_ENV' in os.environ:
a, b = os.path.split(conda_full_path)
assert b == 'conda'
a, b = os.path.split(a)
assert b == 'bin'
conda_env_path = a
a, b = os.path.split(a)
assert b == os.environ['CONDA_DEFAULT_ENV']
else:
a, b = os.path.split(conda_full_path)
assert b == 'conda'
a, b = os.path.split(a)
assert b == 'bin'
conda_env_path = a
print 'cmake -DCMAKE_BUILD_TYPE={} -DCMAKE_INSTALL_PREFIX={} -DCMAKE_PREFIX_PATH={} ..'.format(
build_type,
conda_env_path,
conda_env_path)
| import sys
import os
from subprocess import check_output
if __name__ == '__main__':
build_type = "RelWithDebInfo"
if len(sys.argv) > 1:
build_type = sys.argv[1]
ValidBuildTypes = ('Debug', 'Release', 'RelWithDebInfo')
if not build_type in ValidBuildTypes:
raise ValueError("invalid build type: {}".format(build_type))
## XXX: handle virtualenv
conda_full_path = check_output("which conda", shell=True).strip()
if 'CONDA_DEFAULT_ENV' in os.environ:
a, b = os.path.split(conda_full_path)
assert b == 'conda'
a, b = os.path.split(a)
assert b == 'bin'
conda_env_path = a
a, b = os.path.split(a)
assert b == os.environ['CONDA_DEFAULT_ENV']
else:
a, b = os.path.split(conda_full_path)
assert b == 'conda'
a, b = os.path.split(a)
assert b == 'bin'
conda_env_path = a
print 'cmake -DCMAKE_BUILD_TYPE={} -DCMAKE_INSTALL_PREFIX={} -DCMAKE_PREFIX_PATH={} ..'.format(
build_type,
conda_env_path,
conda_env_path)
| bsd-3-clause | Python |
7b82626201812710c4013d05279572a06e641bbd | remove unnecessary imports | dschmaryl/golf-flask,dschmaryl/golf-flask,dschmaryl/golf-flask | manage.py | manage.py | from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from golf_stats import app, db
from golf_stats.utils import export_all, import_all
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def create_db():
db.create_all()
@manager.command
def import_db():
import_all()
@manager.command
def export_db():
export_all()
if __name__ == '__main__':
manager.run()
| from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from golf_stats import app, db
from golf_stats.utils import export_all, import_all
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
@manager.command
def create_db():
db.create_all()
@manager.command
def import_db():
import_all()
@manager.command
def export_db():
export_all()
if __name__ == '__main__':
manager.run()
| mit | Python |
7725f1af0134c6d9db5b9ed116118fd6a9dd1295 | make server candlestick demo sync with file demo | jakirkham/bokeh,msarahan/bokeh,percyfal/bokeh,jakirkham/bokeh,bokeh/bokeh,ericmjl/bokeh,daodaoliang/bokeh,saifrahmed/bokeh,DuCorey/bokeh,maxalbert/bokeh,Karel-van-de-Plassche/bokeh,satishgoda/bokeh,khkaminska/bokeh,ChinaQuants/bokeh,ericmjl/bokeh,canavandl/bokeh,caseyclements/bokeh,canavandl/bokeh,ahmadia/bokeh,ptitjano/bokeh,htygithub/bokeh,maxalbert/bokeh,philippjfr/bokeh,srinathv/bokeh,paultcochrane/bokeh,awanke/bokeh,stuart-knock/bokeh,paultcochrane/bokeh,srinathv/bokeh,srinathv/bokeh,xguse/bokeh,tacaswell/bokeh,jplourenco/bokeh,ericdill/bokeh,paultcochrane/bokeh,bsipocz/bokeh,KasperPRasmussen/bokeh,ChristosChristofidis/bokeh,percyfal/bokeh,eteq/bokeh,josherick/bokeh,lukebarnard1/bokeh,ChristosChristofidis/bokeh,PythonCharmers/bokeh,azjps/bokeh,aiguofer/bokeh,ericdill/bokeh,daodaoliang/bokeh,josherick/bokeh,caseyclements/bokeh,khkaminska/bokeh,rhiever/bokeh,msarahan/bokeh,DuCorey/bokeh,stonebig/bokeh,aiguofer/bokeh,azjps/bokeh,bokeh/bokeh,mutirri/bokeh,gpfreitas/bokeh,ahmadia/bokeh,abele/bokeh,eteq/bokeh,carlvlewis/bokeh,jakirkham/bokeh,KasperPRasmussen/bokeh,srinathv/bokeh,laurent-george/bokeh,aavanian/bokeh,Karel-van-de-Plassche/bokeh,tacaswell/bokeh,PythonCharmers/bokeh,rs2/bokeh,timothydmorton/bokeh,Karel-van-de-Plassche/bokeh,almarklein/bokeh,htygithub/bokeh,CrazyGuo/bokeh,percyfal/bokeh,birdsarah/bokeh,aavanian/bokeh,bsipocz/bokeh,KasperPRasmussen/bokeh,evidation-health/bokeh,bokeh/bokeh,draperjames/bokeh,philippjfr/bokeh,rothnic/bokeh,draperjames/bokeh,draperjames/bokeh,jplourenco/bokeh,birdsarah/bokeh,clairetang6/bokeh,gpfreitas/bokeh,akloster/bokeh,CrazyGuo/bokeh,rothnic/bokeh,matbra/bokeh,quasiben/bokeh,tacaswell/bokeh,ericdill/bokeh,PythonCharmers/bokeh,xguse/bokeh,maxalbert/bokeh,dennisobrien/bokeh,mutirri/bokeh,stuart-knock/bokeh,ericmjl/bokeh,mindriot101/bokeh,clairetang6/bokeh,satishgoda/bokeh,alan-unravel/bokeh,phobson/bokeh,azjps/bokeh,ChinaQuants/bokeh,eteq/bokeh,roxyboy/bokeh,timothydmorton/bokeh,bsipocz/bokeh,schoolie/bokeh,bsipocz/bokeh,deeplook/bokeh,ericmjl/bokeh,mindriot101/bokeh,ChinaQuants/bokeh,dennisobrien/bokeh,DuCorey/bokeh,phobson/bokeh,CrazyGuo/bokeh,draperjames/bokeh,mutirri/bokeh,evidation-health/bokeh,mindriot101/bokeh,rhiever/bokeh,matbra/bokeh,akloster/bokeh,schoolie/bokeh,timsnyder/bokeh,schoolie/bokeh,josherick/bokeh,rs2/bokeh,philippjfr/bokeh,draperjames/bokeh,abele/bokeh,ericmjl/bokeh,phobson/bokeh,ptitjano/bokeh,percyfal/bokeh,ChinaQuants/bokeh,htygithub/bokeh,birdsarah/bokeh,justacec/bokeh,ChristosChristofidis/bokeh,ericdill/bokeh,timsnyder/bokeh,bokeh/bokeh,dennisobrien/bokeh,rothnic/bokeh,justacec/bokeh,ptitjano/bokeh,awanke/bokeh,jplourenco/bokeh,aiguofer/bokeh,xguse/bokeh,justacec/bokeh,caseyclements/bokeh,deeplook/bokeh,satishgoda/bokeh,aavanian/bokeh,saifrahmed/bokeh,paultcochrane/bokeh,philippjfr/bokeh,stonebig/bokeh,phobson/bokeh,mutirri/bokeh,philippjfr/bokeh,evidation-health/bokeh,aiguofer/bokeh,aiguofer/bokeh,rs2/bokeh,muku42/bokeh,canavandl/bokeh,CrazyGuo/bokeh,timsnyder/bokeh,percyfal/bokeh,abele/bokeh,jakirkham/bokeh,daodaoliang/bokeh,schoolie/bokeh,akloster/bokeh,laurent-george/bokeh,timothydmorton/bokeh,dennisobrien/bokeh,rothnic/bokeh,eteq/bokeh,PythonCharmers/bokeh,khkaminska/bokeh,matbra/bokeh,ahmadia/bokeh,roxyboy/bokeh,bokeh/bokeh,almarklein/bokeh,aavanian/bokeh,deeplook/bokeh,azjps/bokeh,abele/bokeh,birdsarah/bokeh,alan-unravel/bokeh,jakirkham/bokeh,phobson/bokeh,quasiben/bokeh,sahat/bokeh,rs2/bokeh,akloster/bokeh,roxyboy/bokeh,carlvlewis/bokeh,quasiben/bokeh,timothydmorton/bokeh,lukebarnard1/bokeh,ahmadia/bokeh,jplourenco/bokeh,DuCorey/bokeh,stuart-knock/bokeh,DuCorey/bokeh,azjps/bokeh,lukebarnard1/bokeh,ChristosChristofidis/bokeh,saifrahmed/bokeh,almarklein/bokeh,aavanian/bokeh,muku42/bokeh,josherick/bokeh,rs2/bokeh,stuart-knock/bokeh,khkaminska/bokeh,sahat/bokeh,laurent-george/bokeh,roxyboy/bokeh,awanke/bokeh,caseyclements/bokeh,ptitjano/bokeh,alan-unravel/bokeh,muku42/bokeh,timsnyder/bokeh,laurent-george/bokeh,alan-unravel/bokeh,rhiever/bokeh,daodaoliang/bokeh,tacaswell/bokeh,msarahan/bokeh,carlvlewis/bokeh,KasperPRasmussen/bokeh,dennisobrien/bokeh,gpfreitas/bokeh,evidation-health/bokeh,clairetang6/bokeh,mindriot101/bokeh,matbra/bokeh,satishgoda/bokeh,Karel-van-de-Plassche/bokeh,awanke/bokeh,sahat/bokeh,maxalbert/bokeh,carlvlewis/bokeh,stonebig/bokeh,timsnyder/bokeh,rhiever/bokeh,ptitjano/bokeh,canavandl/bokeh,msarahan/bokeh,muku42/bokeh,deeplook/bokeh,KasperPRasmussen/bokeh,schoolie/bokeh,stonebig/bokeh,xguse/bokeh,Karel-van-de-Plassche/bokeh,htygithub/bokeh,justacec/bokeh,saifrahmed/bokeh,lukebarnard1/bokeh,clairetang6/bokeh,gpfreitas/bokeh | examples/plotting/server/candlestick.py | examples/plotting/server/candlestick.py |
import pandas as pd
from bokeh.sampledata.stocks import MSFT
from bokeh.plotting import *
output_server("candlestick.py example")
hold()
df = pd.DataFrame(MSFT)[:50]
df['date'] = pd.to_datetime(df['date'])
dates = df.date.astype(int)
mids = (df.open + df.close)/2
spans = abs(df.close-df.open)
inc = df.close > df.open
dec = df.open > df.close
w = (dates[1]-dates[0])*0.7
segment(dates, df.high, dates, df.low, color='#000000', tools="pan,zoom,resize", width=1000)
rect(dates[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="#000000" )
rect(dates[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="#000000" )
curplot().title = "MSFT Candlestick"
xgrid()[0].grid_line_dash=""
xgrid()[0].grid_line_alpha=0.3
ygrid()[0].grid_line_dash=""
ygrid()[0].grid_line_alpha=0.3
# open a browser
show()
|
import pandas as pd
from bokeh.sampledata.stocks import MSFT
from bokeh.plotting import *
output_server("candlestick.py example")
hold()
df = pd.DataFrame(MSFT)
df['date'] = pd.to_datetime(df['date'])
dates = df.date.astype(int)
mids = (df.open + df.close)/2
spans = abs(df.close-df.open)
inc = df.close > df.open
dec = df.open > df.close
w = (dates[1]-dates[0])*0.7
segment(dates, df.high, dates, df.low, color='#000000', tools="pan,zoom,resize", width=1000)
rect(dates[inc], mids[inc], 5, spans[inc], fill_color="#D5E1DD", line_color="#000000" )
rect(dates[dec], mids[dec], 5, spans[dec], fill_color="#F2583E", line_color="#000000" )
curplot().title = "MSFT Candlestick"
xgrid()[0].grid_line_dash=""
xgrid()[0].grid_line_alpha=0.3
ygrid()[0].grid_line_dash=""
ygrid()[0].grid_line_alpha=0.3
# open a browser
show()
| bsd-3-clause | Python |
26811edc8023c24377a5cfae9d4699ae91df47f8 | Add required module | xeroc/python-bitshares | bitshares/proposal.py | bitshares/proposal.py | from .instance import BlockchainInstance
from .account import Account
from .exceptions import ProposalDoesNotExistException
from .blockchainobject import BlockchainObject, ObjectCache
from .utils import parse_time
import logging
log = logging.getLogger(__name__)
class Proposal(BlockchainObject):
""" Read data about a Proposal Balance in the chain
:param str id: Id of the proposal
:param bitshares blockchain_instance: BitShares() instance to use when accesing a RPC
"""
type_id = 10
def refresh(self):
proposal = self.blockchain.rpc.get_objects([self.identifier])
if not any(proposal):
raise ProposalDoesNotExistException
super(Proposal, self).__init__(proposal[0], blockchain_instance=self.blockchain)
@property
def proposed_operations(self):
yield from self["proposed_transaction"]["operations"]
@property
def proposer(self):
""" Return the proposer of the proposal if available in the backend,
else returns None
"""
if "proposer" in self:
return self["proposer"]
@property
def expiration(self):
return parse_time(self.get("expiration_time"))
@property
def review_period(self):
return parse_time(self.get("review_period_time"))
@property
def is_in_review(self):
from datetime import datetime, timezone
now = datetime.utcnow().replace(tzinfo=timezone.utc)
return now > self.review_period
class Proposals(list):
""" Obtain a list of pending proposals for an account
:param str account: Account name
:param bitshares blockchain_instance: BitShares() instance to use when accesing a RPC
"""
cache = ObjectCache()
def __init__(self, account, **kwargs):
BlockchainInstance.__init__(self, **kwargs)
account = Account(account)
if account["id"] in Proposals.cache:
proposals = Proposals.cache[account["id"]]
else:
proposals = self.blockchain.rpc.get_proposed_transactions(account["id"])
Proposals.cache[account["id"]] = proposals
super(Proposals, self).__init__(
[
Proposal(x, blockchain_instance=self.blockchain)
for x in proposals
]
)
| from .instance import BlockchainInstance
from .account import Account
from .exceptions import ProposalDoesNotExistException
from .blockchainobject import BlockchainObject
from .utils import parse_time
import logging
log = logging.getLogger(__name__)
class Proposal(BlockchainObject):
""" Read data about a Proposal Balance in the chain
:param str id: Id of the proposal
:param bitshares blockchain_instance: BitShares() instance to use when accesing a RPC
"""
type_id = 10
def refresh(self):
proposal = self.blockchain.rpc.get_objects([self.identifier])
if not any(proposal):
raise ProposalDoesNotExistException
super(Proposal, self).__init__(proposal[0], blockchain_instance=self.blockchain)
@property
def proposed_operations(self):
yield from self["proposed_transaction"]["operations"]
@property
def proposer(self):
""" Return the proposer of the proposal if available in the backend,
else returns None
"""
if "proposer" in self:
return self["proposer"]
@property
def expiration(self):
return parse_time(self.get("expiration_time"))
@property
def review_period(self):
return parse_time(self.get("review_period_time"))
@property
def is_in_review(self):
from datetime import datetime, timezone
now = datetime.utcnow().replace(tzinfo=timezone.utc)
return now > self.review_period
class Proposals(list):
""" Obtain a list of pending proposals for an account
:param str account: Account name
:param bitshares blockchain_instance: BitShares() instance to use when accesing a RPC
"""
cache = ObjectCache()
def __init__(self, account, **kwargs):
BlockchainInstance.__init__(self, **kwargs)
account = Account(account)
if account["id"] in Proposals.cache:
proposals = Proposals.cache[account["id"]]
else:
proposals = self.blockchain.rpc.get_proposed_transactions(account["id"])
Proposals.cache[account["id"]] = proposals
super(Proposals, self).__init__(
[
Proposal(x, blockchain_instance=self.blockchain)
for x in proposals
]
)
| mit | Python |
26b2eb5efd7d1be8c19cb7395cae7d5b2ac9f3df | Fix url prefix. | quantumlib/OpenFermion-FQE,quantumlib/OpenFermion-FQE,quantumlib/OpenFermion-FQE | dev/docs/build_api_docs.py | dev/docs/build_api_docs.py | # Copyright 2021 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool to generate external api_docs for FQE (Shameless copy from TFQ)."""
import os
from absl import app
from absl import flags
from tensorflow_docs.api_generator import doc_controls
from tensorflow_docs.api_generator import generate_lib
from tensorflow_docs.api_generator import public_api
import fqe
flags.DEFINE_string("output_dir", "/tmp/openfermion_api",
"Where to output the docs")
flags.DEFINE_string("code_url_prefix",
("https://github.com/quantumlib/OpenFermion-FQE/tree/master/src/"
"fqe"), "The url prefix for links to code.")
flags.DEFINE_bool("search_hints", True,
"Include metadata search hints in the generated files")
flags.DEFINE_string("site_path", "quark/openfermion_fqe/api_docs/python",
"Path prefix in the _toc.yaml")
FLAGS = flags.FLAGS
def main(unused_argv):
doc_generator = generate_lib.DocGenerator(
root_title="OpenFermion-FQE",
py_modules=[("fqe", fqe)],
base_dir=os.path.dirname(fqe.__file__),
code_url_prefix=FLAGS.code_url_prefix,
search_hints=FLAGS.search_hints,
site_path=FLAGS.site_path,
callbacks=[public_api.local_definitions_filter],
)
doc_generator.build(output_dir=FLAGS.output_dir)
if __name__ == "__main__":
app.run(main)
| # Copyright 2021 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tool to generate external api_docs for FQE (Shameless copy from TFQ)."""
import os
from absl import app
from absl import flags
from tensorflow_docs.api_generator import doc_controls
from tensorflow_docs.api_generator import generate_lib
from tensorflow_docs.api_generator import public_api
import fqe
flags.DEFINE_string("output_dir", "/tmp/openfermion_api",
"Where to output the docs")
flags.DEFINE_string("code_url_prefix",
("https://github.com/quantumlib/OpenFermion-FQE/tree/master/src"
"fqe"), "The url prefix for links to code.")
flags.DEFINE_bool("search_hints", True,
"Include metadata search hints in the generated files")
flags.DEFINE_string("site_path", "quark/openfermion_fqe/api_docs/python",
"Path prefix in the _toc.yaml")
FLAGS = flags.FLAGS
def main(unused_argv):
doc_generator = generate_lib.DocGenerator(
root_title="OpenFermion-FQE",
py_modules=[("fqe", fqe)],
base_dir=os.path.dirname(fqe.__file__),
code_url_prefix=FLAGS.code_url_prefix,
search_hints=FLAGS.search_hints,
site_path=FLAGS.site_path,
callbacks=[public_api.local_definitions_filter],
)
doc_generator.build(output_dir=FLAGS.output_dir)
if __name__ == "__main__":
app.run(main)
| apache-2.0 | Python |
917a38845f3fd03805b99c3a8df6f09b047ed0e0 | Fix tvseries preprocess script to accomodate literal NER refactor. | machinalis/iepy,mrshu/iepy,machinalis/iepy,mrshu/iepy,machinalis/iepy,mrshu/iepy | examples/tvseries/scripts/preprocess.py | examples/tvseries/scripts/preprocess.py | """
Wikia Series Pre Processing
Usage:
preprocess.py <dbname>
"""
import re
from docopt import docopt
from mwtextextractor import get_body_text
from iepy.db import connect, DocumentManager
from iepy.models import set_custom_entity_kinds
from iepy.preprocess import PreProcessPipeline
from iepy.tokenizer import TokenizeSentencerRunner
from iepy.lit_tagger import LiteralNERRunner
from iepy.tagger import StanfordTaggerRunner
from iepy.ner import StanfordNERRunner
from iepy.combined_ner import CombinedNERRunner
from iepy.segmenter import SyntacticSegmenterRunner
def media_wiki_to_txt(doc):
if not doc.text and doc.metadata.get('raw_text', ''):
# After MW strip, titles will not be recognizable. If they dont
# with a dot, will be very hard to split in sentences correctly.
raw = doc.metadata['raw_text']
raw = re.subn(r'(=+)(.*)\1', r'\1\2.\1', raw)[0]
doc.text = get_body_text(raw)
doc.save()
FREEBASE_ENTITIES = ['DISEASE', 'SYMPTOM', 'MEDICAL_TEST']
FREEBASE_FILES = ['examples/tvseries/disease.txt',
'examples/tvseries/symptom.txt',
'examples/tvseries/diagnostic_test.txt']
if __name__ == '__main__':
import logging
logger = logging.getLogger('iepy')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
opts = docopt(__doc__, version=0.1)
connect(opts['<dbname>'])
docs = DocumentManager()
set_custom_entity_kinds(zip(map(lambda x: x.lower(), FREEBASE_ENTITIES),
FREEBASE_ENTITIES))
pipeline = PreProcessPipeline([
media_wiki_to_txt,
TokenizeSentencerRunner(),
StanfordTaggerRunner(),
CombinedNERRunner(
LiteralNERRunner(FREEBASE_ENTITIES, FREEBASE_FILES),
StanfordNERRunner()),
SyntacticSegmenterRunner(),
], docs
)
pipeline.process_everything()
| """
Wikia Series Pre Processing
Usage:
preprocess.py <dbname>
"""
import re
from docopt import docopt
from mwtextextractor import get_body_text
from iepy.db import connect, DocumentManager
from iepy.models import set_custom_entity_kinds
from iepy.preprocess import PreProcessPipeline
from iepy.tokenizer import TokenizeSentencerRunner
from iepy.lit_tagger import LitTaggerRunner
from iepy.tagger import StanfordTaggerRunner
from iepy.ner import StanfordNERRunner
from iepy.combined_ner import CombinedNERRunner
from iepy.segmenter import SyntacticSegmenterRunner
def media_wiki_to_txt(doc):
if not doc.text and doc.metadata.get('raw_text', ''):
# After MW strip, titles will not be recognizable. If they dont
# with a dot, will be very hard to split in sentences correctly.
raw = doc.metadata['raw_text']
raw = re.subn(r'(=+)(.*)\1', r'\1\2.\1', raw)[0]
doc.text = get_body_text(raw)
doc.save()
MEDIC_ENTITIES = ['DISEASE', 'SYMPTOM', 'MEDICAL_TEST']
class MedicNERRunner(LitTaggerRunner):
def __init__(self):
labels = MEDIC_ENTITIES
filenames = ['tvseries/disease.txt', 'tvseries/symptom.txt',
'tvseries/diagnostic_test.txt']
super(MedicNERRunner, self).__init__(labels, filenames)
if __name__ == '__main__':
import logging
logger = logging.getLogger('iepy')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
opts = docopt(__doc__, version=0.1)
connect(opts['<dbname>'])
docs = DocumentManager()
set_custom_entity_kinds(zip(map(lambda x: x.lower(), MEDIC_ENTITIES),
MEDIC_ENTITIES))
pipeline = PreProcessPipeline([
media_wiki_to_txt,
TokenizeSentencerRunner(),
StanfordTaggerRunner(),
CombinedNERRunner(MedicNERRunner(), StanfordNERRunner()),
SyntacticSegmenterRunner(),
], docs
)
pipeline.process_everything()
| bsd-3-clause | Python |
379ca60d8b79a8b6ce5ae7256ccae8a90bb83be8 | Remove experimental. | LettError/glyphNameFormatter,LettError/glyphNameFormatter | Lib/glyphNameFormatter/rangeProcessors/mathematical_alphanumeric_symbols.py | Lib/glyphNameFormatter/rangeProcessors/mathematical_alphanumeric_symbols.py |
def process(self):
self.edit("MATHEMATICAL")
self.edit("EPSILON SYMBOL", "epsilonsymbol")
self.edit("CAPITAL THETA SYMBOL", "Thetasymbol")
self.edit("THETA SYMBOL", "thetasymbol")
self.edit("KAPPA SYMBOL", "kappasymbol")
self.edit("PHI SYMBOL", "phisymbol")
self.edit("PI SYMBOL", "pisymbol")
self.edit("RHO SYMBOL", "rhosymbol")
self.edit("MONOSPACE", "mono")
self.edit("BOLD ITALIC", "bolditalic")
self.edit("ITALIC", "italic")
self.edit("BOLD", "bold")
self.edit("SANS-SERIF", "sans")
self.edit("FRAKTUR", "fraktur")
self.edit("BLACK-LETTER", "fraktur")
self.edit("PARTIAL DIFFERENTIAL", "partialdiff")
self.edit("DOUBLE-STRUCK", "dblstruck")
self.edit("SCRIPT", "script")
self.edit("NABLA", "nabla")
self.handleCase()
if self.has("DIGIT"):
self.edit("DIGIT")
self.lower()
self.compress()
#self.scriptPrefix()
if __name__ == "__main__":
from glyphNameFormatter.exporters import printRange
printRange("Mathematical Alphanumeric Symbols")
|
def process(self):
self.setExperimental()
self.edit("MATHEMATICAL")
self.edit("EPSILON SYMBOL", "epsilonsymbol")
self.edit("CAPITAL THETA SYMBOL", "Thetasymbol")
self.edit("THETA SYMBOL", "thetasymbol")
self.edit("KAPPA SYMBOL", "kappasymbol")
self.edit("PHI SYMBOL", "phisymbol")
self.edit("PI SYMBOL", "pisymbol")
self.edit("RHO SYMBOL", "rhosymbol")
self.edit("MONOSPACE", "mono")
self.edit("BOLD ITALIC", "bolditalic")
self.edit("ITALIC", "italic")
self.edit("BOLD", "bold")
self.edit("SANS-SERIF", "sans")
self.edit("FRAKTUR", "fraktur")
self.edit("BLACK-LETTER", "fraktur")
self.edit("PARTIAL DIFFERENTIAL", "partialdiff")
self.edit("DOUBLE-STRUCK", "dblstruck")
self.edit("SCRIPT", "script")
self.edit("NABLA", "nabla")
self.handleCase()
if self.has("DIGIT"):
self.edit("DIGIT")
self.lower()
self.compress()
#self.scriptPrefix()
if __name__ == "__main__":
from glyphNameFormatter.exporters import printRange
printRange("Mathematical Alphanumeric Symbols")
| bsd-3-clause | Python |
389e0bd3ee306811cfd433fb19c1bf776c7ddff4 | Revise documentation | berkeley-stat159/project-delta | code/utils/utils.py | code/utils/utils.py | import matplotlib.pyplot as plt
import nibabel as nib
import numpy as np
def load_data(filename):
"""
Loads the data in a file, given its path.
Parameters
----------
filename : str
The path to the file containing fMRI data
Returns
-------
np.ndarray of data to be saved to the python environment
"""
return nib.load(filename).get_data()
def plot_nii(data):
"""
Plots the middle slice of an anatomy image
Parameters
----------
data : np.ndarray
fMRI data
Returns
-------
2D plot of horizontal slice at center depth (and center time, if necessary).
"""
mid_depth = data.shape[2] // 2
if (data.ndim==3):
plt.imshow(data[..., mid_depth], interpolation="nearest")
else:
mid_time = data.shape[3] // 2
plt.imshow(data[..., mid_depth, mid_time], interpolation="nearest")
def outlier_prop(data, iqs_scale=1.5):
"""
Computes the proportion of outliers with respect to time in a data set.
Parameters
----------
data : np.ndarray
fMRI data
iqr_scale : float, optional
Multiples of IQR outside which to consider a point an outlier
Returns
-------
Proportion of volumes considered outliers in time
"""
data2d = data.reshape([-1, data.shape[3]])
std = data2d.std(axis=0)
IQR = np.percentile(std, 75) - np.percentile(std, 25)
low_threshold = np.percentile(std, 25) - iqr_scale * IQR
high_threshold = np.percentile(std, 75) + iqr_scale * IQR
outlier_i = np.nonzero((std < low_threshold) + (std > high_threshold))[0]
return len(outlier_i) / len(std)
def plot_bold_nii(data, time):
"""
Plot all horizontal slices of fMRI image at a given point in time.
Parameters:
-----------
data : np.ndarray
4D array of fMRI data
time : int
The index (with respect to time) of the volume to plot
Return:
-------
Canvas of horizontal slices of the brain at a given time
"""
assert time <= data.shape[3]
length, width, depth, timespan = data.shape
len_side = int(np.ceil(np.sqrt(depth))) # Number slices per side of canvas
canvas = np.zeros((length * len_side, width * len_side))
depth_i = 0 # The ith slice with respect to depth
for row in range(len_side):
column = 0
while plot < len_side and depth_i < depth:
x_range = np.arange(length * row, width * (column + 1))
y_start = np.arange(width * column, width * (column + 1))
canvas[x_range, y_range] = data[..., depth_i, time]
depth_i += 1
column += 1
plt.imshow(canvas, interpolation="nearest", cmap="gray")
return None
| import matplotlib.pyplot as plt
import nibabel as nib
import numpy as np
def plot_nii(filename):
"""
Plots the middle slice of an anatomy image
Parameters
----------
filename: str
The path to the file comtaining the anatomy
Returns
-------
Plot of the middle
"""
img = nib.load(filename)
data = img.get_data()
if (data.ndim == 3):
plt.imshow(data[:,:,(data.shape[3]//2)], interpolation="nearest")
else:
mid_time =
plt.imshow(data[:,:,(data.shape[3]//2),(data.shape[4]//2)], interpolation="nearest")
def outlier_prop(filename):
img = nib.load(filename)
data = img.get_data()
data2d = np.reshape(data, (np.prod(data.shape[:-1]),data.shape[-1]))
std = np.std(data2d, axis=0)
IQR = np.percentile(std, 75) - np.percentile(std, 25)
low_threshold = np.percentile(std, 25) - 1.5 * IQR
high_threshold = np.percentile(std, 75) + 1.5 * IQR
outlier_indices=np.nonzero((std < low_threshold) + (std > high_threshold))[0]
return len(outlier_indices)/len(std)
def plot_bold_nii(filename, timepoint):
"""Plot all slices of a fMRI image in one plot at a specific time point
Parameters:
-----------
filename: BOLD.nii.gz
timepoint: the time point chose
Return:
-------
None
Note:
-----
The function produce a plot
"""
img = nib.load(filename)
data = img.get_data()
assert timepoint <= data.shape[-1]
plot_per_row = int(np.ceil(np.sqrt(data.shape[2])))
frame = np.zeros((data.shape[0]*plot_per_row, data.shape[1]*plot_per_row))
num_of_plots = 0
for i in range(plot_per_row):
j = 0
while j < plot_per_row and num_of_plots < data.shape[2]:
frame[data.shape[0]*i:data.shape[0]*(i+1), data.shape[1]*j:data.shape[1]*(j+1)] = data[:,:,num_of_plots,timepoint]
num_of_plots+=1
j+=1
plt.imshow(frame, interpolation="nearest",cmap="gray")
return None
| bsd-3-clause | Python |
45663d2eb5ad1309f309978aecce25dc74994d17 | fix packagist | nikitanovosibirsk/vedro | vedro/hooks/packagist/packagist.py | vedro/hooks/packagist/packagist.py | import os
from ..hook import Hook
class Packagist(Hook):
def __get_files(self, path):
files = []
for filename in os.listdir(path):
if (not filename.startswith('_')) and (not filename.startswith('.')):
files += [filename[:-3] if filename.endswith('.py') else filename]
return files
def __get_directories(self, path):
directories = []
for filename in os.listdir(path):
filename = os.path.join(path, filename)
if not filename.endswith('_') and os.path.isdir(filename):
directories += [filename]
return directories
def __make_init_file(self, files):
return '\n'.join(['from .{} import *'.format(x) for x in files]) + '\n'
def __generate_init_files(self, directories):
for directory in directories:
files = self.__get_files(directory)
self.__generate_init_files(self.__get_directories(directory))
with open(os.path.join(directory, '__init__.py'), 'w') as init_file:
init_file.write(self.__make_init_file(files))
def __on_config_load(self, event):
supported_directories = event.config['vedro']['support'].strip().split()
self.directories = [x for x in supported_directories if os.path.exists(x)]
self.__generate_init_files(self.directories)
def __on_cleanup(self, event):
for directory in self.directories:
for path, _, files in os.walk(directory):
init_file = os.path.join(path, '__init__.py')
if os.path.exists(init_file): os.remove(init_file)
def subscribe(self, events):
events.listen('config_load', self.__on_config_load)
# events.listen('cleanup', self.__on_cleanup)
| import os
from ..hook import Hook
class Packagist(Hook):
def __get_files(self, path):
files = []
for filename in os.listdir(path):
if not filename.startswith('_'):
files += [filename[:-3] if filename.endswith('.py') else filename]
return files
def __get_directories(self, path):
directories = []
for filename in os.listdir(path):
filename = os.path.join(path, filename)
if not filename.endswith('_') and os.path.isdir(filename):
directories += [filename]
return directories
def __make_init_file(self, files):
return '\n'.join(['from .{} import *'.format(x) for x in files]) + '\n'
def __generate_init_files(self, directories):
for directory in directories:
files = self.__get_files(directory)
self.__generate_init_files(self.__get_directories(directory))
with open(os.path.join(directory, '__init__.py'), 'w') as init_file:
init_file.write(self.__make_init_file(files))
def __on_config_load(self, event):
supported_directories = event.config['vedro']['support'].strip().split()
self.directories = [x for x in supported_directories if os.path.exists(x)]
self.__generate_init_files(self.directories)
def __on_cleanup(self, event):
for directory in self.directories:
for path, _, files in os.walk(directory):
init_file = os.path.join(path, '__init__.py')
if os.path.exists(init_file): os.remove(init_file)
def subscribe(self, events):
events.listen('config_load', self.__on_config_load)
# events.listen('cleanup', self.__on_cleanup)
| apache-2.0 | Python |
91a2cdeffbce65d4ca65e9429fee198ed76ef230 | Reduce num params | charanpald/APGL | exp/viroscopy/model/RunEpidemicModel.py | exp/viroscopy/model/RunEpidemicModel.py |
import logging
import sys
import numpy
from apgl.graph import *
from apgl.util import *
from exp.viroscopy.model.HIVGraph import HIVGraph
from exp.viroscopy.model.HIVEpidemicModel import HIVEpidemicModel
from exp.viroscopy.model.HIVRates import HIVRates
from exp.viroscopy.model.HIVModelUtils import HIVModelUtils
import matplotlib.pyplot as plt
"""
This is the epidemic model for the HIV spread in cuba. We try to get more bisexual
contacts
"""
assert False, "Must run with -O flag"
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
numpy.seterr(all='raise')
numpy.random.seed(24)
numpy.set_printoptions(suppress=True, precision=4, linewidth=100)
startDate, endDate, recordStep, M, targetGraph = HIVModelUtils.realSimulationParams()
endDate = startDate + 10000
meanTheta, sigmaTheta = HIVModelUtils.estimatedRealTheta()
meanTheta = numpy.array([ 50, 0.3242, 0.1, 0.001, 0.001, 325, 0.34, 0.001])
outputDir = PathDefaults.getOutputDir() + "viroscopy/"
undirected = True
graph = HIVGraph(M, undirected)
logging.info("Created graph: " + str(graph))
alpha = 2
zeroVal = 0.9
p = Util.powerLawProbs(alpha, zeroVal)
hiddenDegSeq = Util.randomChoice(p, graph.getNumVertices())
rates = HIVRates(graph, hiddenDegSeq)
model = HIVEpidemicModel(graph, rates)
model.setT0(startDate)
model.setT(endDate)
model.setRecordStep(recordStep)
model.setParams(meanTheta)
logging.debug("MeanTheta=" + str(meanTheta))
times, infectedIndices, removedIndices, graph = model.simulate(True)
times, vertexArray, removedGraphStats = HIVModelUtils.generateStatistics(graph, startDate, endDate, recordStep)
plt.figure(0)
plt.plot(times, vertexArray[:, 0])
plt.xlabel("Time")
plt.ylabel("Removed")
plt.figure(1)
plt.plot(times, vertexArray[:, 4])
plt.xlabel("Time")
plt.ylabel("Bi Detect")
plt.figure(2)
plt.plot(times, vertexArray[:, 5])
plt.xlabel("Time")
plt.ylabel("Rand Detect")
plt.figure(3)
plt.plot(times, vertexArray[:, 6])
plt.xlabel("Time")
plt.ylabel("Contact Trace")
plt.show() |
import logging
import sys
import numpy
from apgl.graph import *
from apgl.util import *
from exp.viroscopy.model.HIVGraph import HIVGraph
from exp.viroscopy.model.HIVEpidemicModel import HIVEpidemicModel
from exp.viroscopy.model.HIVRates import HIVRates
from exp.viroscopy.model.HIVModelUtils import HIVModelUtils
import matplotlib.pyplot as plt
"""
This is the epidemic model for the HIV spread in cuba. We try to get more bisexual
contacts
"""
assert False, "Must run with -O flag"
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
numpy.seterr(all='raise')
numpy.random.seed(24)
numpy.set_printoptions(suppress=True, precision=4, linewidth=100)
startDate, endDate, recordStep, M, targetGraph = HIVModelUtils.realSimulationParams()
endDate = startDate + 10000
meanTheta, sigmaTheta = HIVModelUtils.estimatedRealTheta()
meanTheta = numpy.array([ 50, 0.5131, 0.3242, 0.1, 0.0001, 0.0, 325, 0.34, 0.001, 0.1])
outputDir = PathDefaults.getOutputDir() + "viroscopy/"
undirected = True
graph = HIVGraph(M, undirected)
logging.info("Created graph: " + str(graph))
alpha = 2
zeroVal = 0.9
p = Util.powerLawProbs(alpha, zeroVal)
hiddenDegSeq = Util.randomChoice(p, graph.getNumVertices())
rates = HIVRates(graph, hiddenDegSeq)
model = HIVEpidemicModel(graph, rates)
model.setT0(startDate)
model.setT(endDate)
model.setRecordStep(recordStep)
model.setParams(meanTheta)
logging.debug("MeanTheta=" + str(meanTheta))
times, infectedIndices, removedIndices, graph = model.simulate(True)
times, vertexArray, removedGraphStats = HIVModelUtils.generateStatistics(graph, startDate, endDate, recordStep)
plt.figure(0)
plt.plot(times, vertexArray[:, 0])
plt.xlabel("Time")
plt.ylabel("Removed")
plt.figure(1)
plt.plot(times, vertexArray[:, 4])
plt.xlabel("Time")
plt.ylabel("Bi Detect")
plt.figure(2)
plt.plot(times, vertexArray[:, 5])
plt.xlabel("Time")
plt.ylabel("Rand Detect")
plt.figure(3)
plt.plot(times, vertexArray[:, 6])
plt.xlabel("Time")
plt.ylabel("Contact Trace")
plt.show() | bsd-3-clause | Python |
0ac3d7cf48bbeda33e319e149b1a2d36b04fbf94 | Add base pipeline data source class | povilasb/pycollection-pipelines | collection_pipelines/core.py | collection_pipelines/core.py | import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
raise NotImplementedError
def on_done(self):
if self.receiver:
self.receiver.close()
def source(self, start_source):
self.start_source = start_source
def return_value(self):
"""Processor return value when used with __or__ operator.
Returns:
CollectionPipelineProcessor: when processor is to be chained
with other processors.
any: any other value when processor is used as an output and is
meant to return value. In this way we can assign
the output result to python variable.
"""
return self
@coroutine
def make_generator(self):
while True:
try:
item = yield
self.process(item)
except GeneratorExit:
self.on_done()
break
def __or__(self, other):
"""Overwrites the '|' operator.
Args:
other (CollectionPipelineProcessor)
Returns:
whatever other.return_value() returns.
"""
self.sink = other
def exec():
self.receiver = self.sink.make_generator()
self.start_source()
other.source(exec)
return other.return_value()
class CollectionPipelineOutput(CollectionPipelineProcessor):
"""Pipeline processor that ends the chain and starts outputing stream.
Output processor immediately starts consuming from the source.
Thus triggering the whole pipeline start.
"""
def source(self, start_source):
start_source()
def return_value(self):
return None
class CollectionPipelineSource(CollectionPipelineProcessor):
"""Pipeline data source processor."""
def __init__(self):
self.source(self.make_generator)
def make_generator(self):
"""Constructs the items generator."""
raise NotImplementedError
| import functools
def coroutine(fn):
def wrapper(*args, **kwargs):
generator = fn(*args, **kwargs)
next(generator)
return generator
return wrapper
class CollectionPipelineProcessor:
sink = None
start_source = None
receiver = None
def process(self, item):
raise NotImplementedError
def on_done(self):
if self.receiver:
self.receiver.close()
def source(self, start_source):
self.start_source = start_source
def return_value(self):
"""Processor return value when used with __or__ operator.
Returns:
CollectionPipelineProcessor: when processor is to be chained
with other processors.
any: any other value when processor is used as an output and is
meant to return value. In this way we can assign
the output result to python variable.
"""
return self
@coroutine
def make_generator(self):
while True:
try:
item = yield
self.process(item)
except GeneratorExit:
self.on_done()
break
def __or__(self, other):
"""Overwrites the '|' operator.
Args:
other (CollectionPipelineProcessor)
Returns:
whatever other.return_value() returns.
"""
self.sink = other
def exec():
self.receiver = self.sink.make_generator()
self.start_source()
other.source(exec)
return other.return_value()
class CollectionPipelineOutput(CollectionPipelineProcessor):
"""Pipeline processor that ends the chain and starts outputing stream.
Output processor immediately starts consuming from the source.
Thus triggering the whole pipeline start.
"""
def source(self, start_source):
start_source()
def return_value(self):
return None
| mit | Python |
550fd42b1e66436cdc814fa77d39b9ba414beb87 | Refactor with lambda | moritzdannhauer/SCIRunGUIPrototype,jcollfont/SCIRun,collint8/SCIRun,collint8/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,collint8/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,collint8/SCIRun,ajanson/SCIRun,collint8/SCIRun,jcollfont/SCIRun,ajanson/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,jessdtate/SCIRun,collint8/SCIRun,jcollfont/SCIRun,moritzdannhauer/SCIRunGUIPrototype,collint8/SCIRun,ajanson/SCIRun,jcollfont/SCIRun,jcollfont/SCIRun,ajanson/SCIRun,ajanson/SCIRun,collint8/SCIRun,ajanson/SCIRun,jcollfont/SCIRun,jessdtate/SCIRun,ajanson/SCIRun | src/Testing/Python/Unit/add_module.py | src/Testing/Python/Unit/add_module.py | def scirun_assert(func):
if not func():
scirun_add_module("ReadMatrix") # guarantee errored network
scirun_quit_after_execute()
scirun_execute_all()
else:
scirun_force_quit() # SCIRun returns 0 to console
m1 = scirun_add_module("ReadMatrix")
m2 = scirun_add_module("ReportMatrixInfo")
scirun_assert(lambda: len(scirun_module_ids()) == 2)
| import sys
m1 = scirun_add_module("ReadMatrix")
m2 = scirun_add_module("ReportMatrixInfo")
if len(scirun_module_ids()) != 2:
scirun_quit_after_execute()
scirun_execute_all()
else:
scirun_force_quit()
| mit | Python |
b5936f07c88ae260babb1850949b26dc6a06ab65 | fix counter today | niemandkun/diaphragm,niemandkun/diaphragm,niemandkun/diaphragm | diaphragm/counter/views.py | diaphragm/counter/views.py | from datetime import datetime
from flask import Blueprint, request, abort
from diaphragm.counter.models import Visitor
from diaphragm.database import db
from diaphragm.utils import render_ajax, json_dict
counter = Blueprint('counter', __name__,
template_folder="templates")
@counter.route('/api/counter')
def show_status():
ipaddr = request.environ.get('REMOTE_ADDR')
visitor = Visitor.query.filter(Visitor.ipaddr == ipaddr).first()
return render_ajax("counter.html", visitor=visitor,
visits_today=Visitor.total_today_visits(),
visits_total=Visitor.total_visits(),
views_today=Visitor.total_today_views(),
views_total=Visitor.total_views())
@counter.before_app_request
def accept_visitor():
ip, visitor = get_current_visitor()
if ip is None:
return
if visitor is None:
visitor = Visitor(ip, request.path)
db.session.add(visitor)
db.session.commit()
return
if visitor.last_visit.date() < datetime.today().date():
visitor.visits_today = 1
visitor.views_today = 1
db.session.add(visitor)
db.session.commit()
if is_too_fast(visitor):
return json_dict(content="Wait-wait! You click too fast!", title="Fast")
def is_too_fast(visitor):
too_fast = (datetime.utcnow() - visitor.last_visit).total_seconds() < 0.2
same_page = request.path == visitor.last_page
return too_fast and same_page
@counter.after_app_request
def count_visitor(r):
ip, visitor = get_current_visitor()
if not visitor:
return r
current_time = datetime.utcnow()
if (current_time - visitor.last_visit).total_seconds() > 30 * 60:
visitor.visits_today += 1
visitor.visits_total += 1
if visitor.last_page != request.path:
visitor.views_today += 1
visitor.views_total += 1
visitor.last_visit = current_time
visitor.last_page = request.path
db.session.add(visitor)
db.session.commit()
return r
def get_current_visitor():
if not request.path.startswith('/api') or request.path.startswith('/static'):
return None, None
ip = request.environ.get('REMOTE_ADDR')
return ip, Visitor.query.filter(Visitor.ipaddr == ip).first()
| from datetime import datetime
from flask import Blueprint, request, abort
from diaphragm.counter.models import Visitor
from diaphragm.database import db
from diaphragm.utils import render_ajax, json_dict
counter = Blueprint('counter', __name__,
template_folder="templates")
@counter.route('/api/counter')
def show_status():
ipaddr = request.environ.get('REMOTE_ADDR')
visitor = Visitor.query.filter(Visitor.ipaddr == ipaddr).first()
return render_ajax("counter.html", visitor=visitor,
visits_today=Visitor.total_today_visits(),
visits_total=Visitor.total_visits(),
views_today=Visitor.total_today_views(),
views_total=Visitor.total_views())
@counter.before_app_request
def accept_visitor():
ip, visitor = get_current_visitor()
if ip is None:
return
if visitor is None:
visitor = Visitor(ip, request.path)
db.session.add(visitor)
db.session.commit()
return
if visitor.last_visit.date() > datetime.today().date():
visitor.visits_today = 0
visitor.views_today = 0
db.session.add(visitor)
db.session.commit()
if is_too_fast(visitor):
return json_dict(content="Wait-wait! You click too fast!", title="Fast")
def is_too_fast(visitor):
too_fast = (datetime.utcnow() - visitor.last_visit).total_seconds() < 0.2
same_page = request.path == visitor.last_page
return too_fast and same_page
@counter.after_app_request
def count_visitor(r):
ip, visitor = get_current_visitor()
if not visitor:
return r
current_time = datetime.utcnow()
if (current_time - visitor.last_visit).total_seconds() > 30 * 60:
visitor.visits_today += 1
visitor.visits_total += 1
if (visitor.last_page != request.path):
visitor.views_today += 1
visitor.views_total += 1
visitor.last_visit = current_time
visitor.last_page = request.path
db.session.add(visitor)
db.session.commit()
return r
def get_current_visitor():
if not request.path.startswith('/api') or request.path.startswith('/static'):
return None, None
ip = request.environ.get('REMOTE_ADDR')
return ip, Visitor.query.filter(Visitor.ipaddr == ip).first()
| mit | Python |
955d55293e8a2a96b2427af8d2c5de4cba6b1e79 | Refactor to Linter v2 API | ankit01ojha/coala-bears,SanketDG/coala-bears,yash-nisar/coala-bears,ku3o/coala-bears,srisankethu/coala-bears,srisankethu/coala-bears,naveentata/coala-bears,SanketDG/coala-bears,aptrishu/coala-bears,ankit01ojha/coala-bears,shreyans800755/coala-bears,ankit01ojha/coala-bears,LWJensen/coala-bears,yash-nisar/coala-bears,refeed/coala-bears,aptrishu/coala-bears,ankit01ojha/coala-bears,ku3o/coala-bears,refeed/coala-bears,dosarudaniel/coala-bears,Vamshi99/coala-bears,LWJensen/coala-bears,madhukar01/coala-bears,horczech/coala-bears,shreyans800755/coala-bears,refeed/coala-bears,sounak98/coala-bears,Asnelchristian/coala-bears,naveentata/coala-bears,ankit01ojha/coala-bears,vijeth-aradhya/coala-bears,yash-nisar/coala-bears,coala-analyzer/coala-bears,srisankethu/coala-bears,horczech/coala-bears,SanketDG/coala-bears,Shade5/coala-bears,arjunsinghy96/coala-bears,yash-nisar/coala-bears,incorrectusername/coala-bears,ku3o/coala-bears,shreyans800755/coala-bears,sounak98/coala-bears,Shade5/coala-bears,coala-analyzer/coala-bears,madhukar01/coala-bears,arjunsinghy96/coala-bears,Vamshi99/coala-bears,dosarudaniel/coala-bears,gs0510/coala-bears,Asnelchristian/coala-bears,srisankethu/coala-bears,aptrishu/coala-bears,coala/coala-bears,madhukar01/coala-bears,Shade5/coala-bears,srisankethu/coala-bears,coala/coala-bears,dosarudaniel/coala-bears,dosarudaniel/coala-bears,kaustubhhiware/coala-bears,yash-nisar/coala-bears,naveentata/coala-bears,Vamshi99/coala-bears,dosarudaniel/coala-bears,gs0510/coala-bears,horczech/coala-bears,madhukar01/coala-bears,Vamshi99/coala-bears,Vamshi99/coala-bears,gs0510/coala-bears,kaustubhhiware/coala-bears,refeed/coala-bears,LWJensen/coala-bears,gs0510/coala-bears,Vamshi99/coala-bears,madhukar01/coala-bears,LWJensen/coala-bears,kaustubhhiware/coala-bears,Asnelchristian/coala-bears,coala/coala-bears,incorrectusername/coala-bears,gs0510/coala-bears,vijeth-aradhya/coala-bears,yashtrivedi96/coala-bears,incorrectusername/coala-bears,yash-nisar/coala-bears,kaustubhhiware/coala-bears,sounak98/coala-bears,arjunsinghy96/coala-bears,SanketDG/coala-bears,aptrishu/coala-bears,shreyans800755/coala-bears,vijeth-aradhya/coala-bears,coala/coala-bears,incorrectusername/coala-bears,damngamerz/coala-bears,Shade5/coala-bears,Shade5/coala-bears,naveentata/coala-bears,seblat/coala-bears,coala-analyzer/coala-bears,madhukar01/coala-bears,coala/coala-bears,naveentata/coala-bears,ankit01ojha/coala-bears,ku3o/coala-bears,sounak98/coala-bears,dosarudaniel/coala-bears,kaustubhhiware/coala-bears,LWJensen/coala-bears,LWJensen/coala-bears,seblat/coala-bears,coala/coala-bears,yashtrivedi96/coala-bears,coala/coala-bears,seblat/coala-bears,ku3o/coala-bears,ankit01ojha/coala-bears,madhukar01/coala-bears,ankit01ojha/coala-bears,ankit01ojha/coala-bears,gs0510/coala-bears,shreyans800755/coala-bears,aptrishu/coala-bears,damngamerz/coala-bears,Vamshi99/coala-bears,arjunsinghy96/coala-bears,SanketDG/coala-bears,ankit01ojha/coala-bears,dosarudaniel/coala-bears,madhukar01/coala-bears,srisankethu/coala-bears,horczech/coala-bears,aptrishu/coala-bears,shreyans800755/coala-bears,SanketDG/coala-bears,horczech/coala-bears,coala/coala-bears,meetmangukiya/coala-bears,incorrectusername/coala-bears,srisankethu/coala-bears,Vamshi99/coala-bears,srisankethu/coala-bears,arjunsinghy96/coala-bears,kaustubhhiware/coala-bears,incorrectusername/coala-bears,refeed/coala-bears,refeed/coala-bears,Shade5/coala-bears,sounak98/coala-bears,horczech/coala-bears,dosarudaniel/coala-bears,coala-analyzer/coala-bears,refeed/coala-bears,kaustubhhiware/coala-bears,arjunsinghy96/coala-bears,gs0510/coala-bears,horczech/coala-bears,Shade5/coala-bears,aptrishu/coala-bears,LWJensen/coala-bears,yashtrivedi96/coala-bears,coala/coala-bears,SanketDG/coala-bears,coala-analyzer/coala-bears,coala/coala-bears,meetmangukiya/coala-bears,seblat/coala-bears,yashtrivedi96/coala-bears,sounak98/coala-bears,meetmangukiya/coala-bears,horczech/coala-bears,sounak98/coala-bears,refeed/coala-bears,Asnelchristian/coala-bears,horczech/coala-bears,gs0510/coala-bears,horczech/coala-bears,naveentata/coala-bears,vijeth-aradhya/coala-bears,incorrectusername/coala-bears,sounak98/coala-bears,aptrishu/coala-bears,meetmangukiya/coala-bears,SanketDG/coala-bears,Asnelchristian/coala-bears,incorrectusername/coala-bears,SanketDG/coala-bears,Asnelchristian/coala-bears,meetmangukiya/coala-bears,Asnelchristian/coala-bears,ku3o/coala-bears,damngamerz/coala-bears,Asnelchristian/coala-bears,yash-nisar/coala-bears,coala/coala-bears,sounak98/coala-bears,LWJensen/coala-bears,aptrishu/coala-bears,vijeth-aradhya/coala-bears,damngamerz/coala-bears,shreyans800755/coala-bears,yash-nisar/coala-bears,refeed/coala-bears,ku3o/coala-bears,refeed/coala-bears,Vamshi99/coala-bears,srisankethu/coala-bears,arjunsinghy96/coala-bears,coala-analyzer/coala-bears,shreyans800755/coala-bears,seblat/coala-bears,vijeth-aradhya/coala-bears,madhukar01/coala-bears,incorrectusername/coala-bears,coala-analyzer/coala-bears,yash-nisar/coala-bears,damngamerz/coala-bears,vijeth-aradhya/coala-bears,dosarudaniel/coala-bears,Shade5/coala-bears,ankit01ojha/coala-bears,horczech/coala-bears,coala/coala-bears,meetmangukiya/coala-bears,coala-analyzer/coala-bears,naveentata/coala-bears,Shade5/coala-bears,yashtrivedi96/coala-bears,ku3o/coala-bears,naveentata/coala-bears,aptrishu/coala-bears,naveentata/coala-bears,yash-nisar/coala-bears,shreyans800755/coala-bears,srisankethu/coala-bears,Vamshi99/coala-bears,aptrishu/coala-bears,vijeth-aradhya/coala-bears,ku3o/coala-bears,meetmangukiya/coala-bears,damngamerz/coala-bears,Asnelchristian/coala-bears,damngamerz/coala-bears,shreyans800755/coala-bears,yashtrivedi96/coala-bears,meetmangukiya/coala-bears,yashtrivedi96/coala-bears,arjunsinghy96/coala-bears,damngamerz/coala-bears,LWJensen/coala-bears,gs0510/coala-bears,Vamshi99/coala-bears,seblat/coala-bears,damngamerz/coala-bears,yashtrivedi96/coala-bears,shreyans800755/coala-bears,yash-nisar/coala-bears,yashtrivedi96/coala-bears,damngamerz/coala-bears,seblat/coala-bears,refeed/coala-bears,arjunsinghy96/coala-bears,kaustubhhiware/coala-bears,kaustubhhiware/coala-bears,damngamerz/coala-bears,vijeth-aradhya/coala-bears,srisankethu/coala-bears,coala-analyzer/coala-bears,meetmangukiya/coala-bears,seblat/coala-bears | bears/xml2/XMLBear.py | bears/xml2/XMLBear.py | import itertools
import re
from coalib.bearlib.abstractions.Linter import linter
from coalib.bears.requirements.DistributionRequirement import (
DistributionRequirement)
from coalib.settings.Setting import path, url
def path_or_url(xml_dtd):
'''
Coverts the setting value to url or path.
:param xml_dtd: Setting key.
:return: Returns a converted setting value.
'''
try:
return url(xml_dtd)
except ValueError:
return path(xml_dtd)
@linter(executable='xmllint',
use_stdout=True,
use_stderr=True)
class XMLBear:
"""
Checks the code with ``xmllint``.
"""
LANGUAGES = {"XML"}
REQUIREMENTS = {DistributionRequirement(apt_get='libxml2')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'
CAN_DETECT = {'Formatting', 'Syntax'}
_output_regex = re.compile(r'.*:(?P<line>\d+): (?P<message>.*)\n.*\n.*')
@staticmethod
def create_arguments(filename, file, config_file,
xml_schema: path='',
xml_dtd: path_or_url=''):
"""
:param xml_schema: ``W3C XML Schema`` file used for validation.
:param xml_dtd: ``Document type Definition (DTD)`` file or
url used for validation.
"""
args = (filename,)
if xml_schema:
args += ('-schema', xml_schema)
if xml_dtd:
args += ('-dtdvalid', xml_dtd)
return args
def process_output(self, output, filename, file):
if output[0]:
# Return issues from stderr and stdout if stdout is not empty
return itertools.chain(
self.process_output_regex(
output[1], filename, file,
output_regex=self._output_regex),
self.process_output_corrected(
output[0], filename, file,
result_message="XML can be formatted better."))
else:
# Return issues from stderr if stdout is empty
return self.process_output_regex(
output[1], filename, file,
output_regex=self._output_regex)
| import itertools
from coalib.bearlib.abstractions.Lint import Lint, escape_path_argument
from coalib.bears.LocalBear import LocalBear
from coalib.bears.requirements.DistributionRequirement import (
DistributionRequirement)
from coalib.settings.Setting import path, url
def path_or_url(xml_dtd):
'''
Coverts the setting value to url or path.
:param xml_dtd: Setting key.
:return: Returns a converted setting value.
'''
try:
return url(xml_dtd)
except ValueError:
return path(xml_dtd)
class XMLBear(LocalBear, Lint):
executable = 'xmllint'
diff_message = "XML can be formatted better."
output_regex = r'(.*\.xml):(?P<line>\d+): (?P<message>.*)\n.*\n.*'
gives_corrected = True
use_stderr = True
LANGUAGES = {"XML"}
REQUIREMENTS = {DistributionRequirement(apt_get='libxml2')}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'
CAN_DETECT = {'Formatting', 'Syntax'}
def process_output(self, output, filename, file):
if self.stdout_output:
# Return issues from stderr and stdout if stdout is not empty
return itertools.chain(
self._process_issues(self.stderr_output, filename),
self._process_corrected(self.stdout_output, filename, file))
else: # Return issues from stderr if stdout is empty
return self._process_issues(self.stderr_output, filename)
def run(self, filename, file,
xml_schema: path="",
xml_dtd: path_or_url=""):
'''
Checks the code with ``xmllint``.
:param xml_schema: ``W3C XML Schema`` file used for validation.
:param xml_dtd: ``Document type Definition (DTD)`` file or
url used for validation.
'''
self.arguments = "{filename} "
if xml_schema:
self.arguments += " -schema " + escape_path_argument(xml_schema)
if xml_dtd:
self.arguments += " -dtdvalid " + xml_dtd
return self.lint(filename, file)
| agpl-3.0 | Python |
2944b50b0ef6b341a8d60aed8c2371292e81a255 | update tests | mupi/tecsaladeaula,mupi/tecsaladeaula,mupi/escolamupi,hacklabr/timtec,GustavoVS/timtec,mupi/escolamupi,mupi/tecsaladeaula,GustavoVS/timtec,virgilio/timtec,mupi/tecsaladeaula,mupi/timtec,AllanNozomu/tecsaladeaula,mupi/timtec,virgilio/timtec,hacklabr/timtec,GustavoVS/timtec,GustavoVS/timtec,AllanNozomu/tecsaladeaula,mupi/timtec,hacklabr/timtec,AllanNozomu/tecsaladeaula,AllanNozomu/tecsaladeaula,virgilio/timtec,mupi/timtec,virgilio/timtec,hacklabr/timtec | accounts/tests/test_acceptance.py | accounts/tests/test_acceptance.py | import pytest
@pytest.mark.django_db
def test_custom_login_view(client):
response = client.get('/login/')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated() is False
response = client.post('/login/', {'username':'abcd',
'password': 'x'})
assert response.status_code == 302
response = client.get('/course/dbsql')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated()
@pytest.mark.django_db
def test_custom_login_view_with_next_field(client):
response = client.get('/login/')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated() is False
response = client.post('/login/', {'username':'abcd',
'password': 'x',
'next': '/profile/edit'})
assert response.status_code == 302
assert response['Location'] == 'http://testserver/profile/edit'
@pytest.mark.django_db
def test_custom_login_redirect_already_authenticated_user(client):
response = client.post('/login/', {'username':'abcd', 'password': 'x'})
assert response.status_code == 302
response = client.get('/login/')
assert response.status_code == 302
@pytest.mark.django_db
def test_custom_login_page(client):
response = client.get('/login/', {'next': 'http://fakenext.com/profile/edit'})
assert response.status_code == 200
assert 'login' in response.content
@pytest.mark.django_db
def test_custom_login_does_not_redirect_to_unsafe_next(admin_client):
response = admin_client.get('/login/', {'next': 'http://fakenext.com/profile/edit'})
assert response.status_code == 302
assert response['Location'] == 'http://testserver/'
@pytest.mark.django_db
def test_custom_login_has_login_form_in_context_when_login_fail(client):
response = client.post('/login/', {'username':'invalid',
'password': 'invalid'})
assert response.status_code == 200
assert 'login_form' in response.context_data
@pytest.mark.django_db
def test_user_instance_for_profile_edit_form_is_the_same_of_request(client):
response = client.post('/login/', {'username':'abcd', 'password': 'x',})
response = client.get('/profile/edit')
assert response.status_code == 200
assert response.context_data['form'].instance.username == 'abcd'
@pytest.mark.django_db
def test_edit_profile(admin_client):
response = admin_client.post('/profile/edit', {'username': 'admin', 'email': 'admin@b.cd'})
assert response.status_code == 302
assert response['Location'] == 'http://testserver/profile/edit'
| import pytest
@pytest.mark.django_db
def test_custom_login_view(client):
response = client.get('/login/')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated() is False
response = client.post('/login/', {'username':'abcd',
'password': 'x'})
assert response.status_code == 302
response = client.get('/course/dbsql')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated()
@pytest.mark.django_db
def test_custom_login_view_with_next_field(client):
response = client.get('/login/')
assert response.status_code == 200
assert response.context['request'].user.is_authenticated() is False
response = client.post('/login/', {'username':'abcd',
'password': 'x',
'next': '/profile/edit'})
assert response.status_code == 302
assert response['Location'] == 'http://testserver/profile/edit'
@pytest.mark.django_db
def test_custom_login_redirect_already_authenticated_user(client):
response = client.post('/login/', {'username':'abcd', 'password': 'x'})
assert response.status_code == 302
response = client.get('/login/')
assert response.status_code == 302
@pytest.mark.django_db
def test_custom_login_does_not_redirect_to_unsafe_next(client):
response = client.post('/login/', {'username':'abcd',
'password': 'x',
'next': 'http://fakenext.com/profile/edit'})
assert response.status_code == 302
assert response['Location'].startswith('http://testserver/')
@pytest.mark.django_db
def test_custom_login_has_login_form_in_context_when_login_fail(client):
response = client.post('/login/', {'username':'invalid',
'password': 'invalid'})
assert response.status_code == 200
assert 'login_form' in response.context_data
@pytest.mark.django_db
def test_user_instance_for_profile_edit_form_is_the_same_of_request(client):
response = client.post('/login/', {'username':'abcd', 'password': 'x',})
response = client.get('/profile/edit')
assert response.status_code == 200
assert response.context_data['form'].instance.username == 'abcd'
| agpl-3.0 | Python |
e02570e3f22d24d12228c3ea51199d587735917c | Add newline add end of post. | allanino/rnn-music-of-the-day,allanino/rnn-music-of-the-day,allanino/rnn-music-of-the-day | create_post.py | create_post.py | #!/usr/bin/env python
import argparse
import dropbox
import os
from time import gmtime, strftime
def get_link(client, folder_path, opus_number):
folder_metadata = client.metadata(folder_path)
path = folder_metadata['contents'][opus_number-1]['path']
url = client.share(path, short_url=False)['url']
# For streaming to work
url = url[:-1] + '1'
return url
def add_post(blog_root, date, opus_number, mp3_url):
filename = date + '-opus-%d.md' % opus_number
post_path = os.path.join(blog_root, '_posts', filename)
with open(post_path, 'wb') as f:
s = '---\nlayout: post\ntitle: Opus %d\nimg: %d.svg\nmp3: %s\n---\n' % (opus_number, opus_number, mp3_url)
s += '\n{% include post_content.html %}\n'
f.write(s)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('access_token', help="Dropbox access token.")
parser.add_argument('mp3_path', help="Dropbox path to MP3 folder.")
parser.add_argument('svg_path', help="Dropbox path to SVG folder.")
parser.add_argument('opus_number', type=int, help="Opus number n. Used to get n.mp3 and n.svg.")
parser.add_argument('blog_root', help="Directory to write the new post")
parser.add_argument('--date', help="Date to use on the blog post.")
args = parser.parse_args()
client = dropbox.client.DropboxClient(args.access_token)
mp3_url = get_link(client, args.mp3_path, args.opus_number)
img = open(os.path.join(args.blog_root, 'img', '%d.svg' % args.opus_number), 'wb')
with client.get_file(args.svg_path + '/%d.svg' % args.opus_number) as f:
img.write(f.read())
if args.date:
date = args.date
else:
date = strftime("%Y-%m-%d", gmtime())
add_post(args.blog_root, date, args.opus_number, mp3_url)
| #!/usr/bin/env python
import argparse
import dropbox
import os
from time import gmtime, strftime
def get_link(client, folder_path, opus_number):
folder_metadata = client.metadata(folder_path)
path = folder_metadata['contents'][opus_number-1]['path']
url = client.share(path, short_url=False)['url']
# For streaming to work
url = url[:-1] + '1'
return url
def add_post(blog_root, date, opus_number, mp3_url):
filename = date + '-opus-%d.md' % opus_number
post_path = os.path.join(blog_root, '_posts', filename)
with open(post_path, 'wb') as f:
s = '---\nlayout: post\ntitle: Opus %d\nimg: %d.svg\nmp3: %s\n---\n' % (opus_number, opus_number, mp3_url)
s += '\n{% include post_content.html %}'
f.write(s)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('access_token', help="Dropbox access token.")
parser.add_argument('mp3_path', help="Dropbox path to MP3 folder.")
parser.add_argument('svg_path', help="Dropbox path to SVG folder.")
parser.add_argument('opus_number', type=int, help="Opus number n. Used to get n.mp3 and n.svg.")
parser.add_argument('blog_root', help="Directory to write the new post")
parser.add_argument('--date', help="Date to use on the blog post.")
args = parser.parse_args()
client = dropbox.client.DropboxClient(args.access_token)
mp3_url = get_link(client, args.mp3_path, args.opus_number)
img = open(os.path.join(args.blog_root, 'img', '%d.svg' % args.opus_number), 'wb')
with client.get_file(args.svg_path + '/%d.svg' % args.opus_number) as f:
img.write(f.read())
if args.date:
date = args.date
else:
date = strftime("%Y-%m-%d", gmtime())
add_post(args.blog_root, date, args.opus_number, mp3_url)
| mit | Python |
4ee6ce2b8d59266ed7b08422088d20edda1effe2 | Simplify a bit | rafaelmartins/rst2pdf,rafaelmartins/rst2pdf | rst2pdf/tests/input/test_issue_216.py | rst2pdf/tests/input/test_issue_216.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.platypus.doctemplate import Indenter
from reportlab.platypus.flowables import *
from reportlab.platypus.xpreformatted import *
from reportlab.lib.styles import getSampleStyleSheet
from copy import copy
def go():
Story=[]
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("issue216.pdf")
knstyle=copy(styles['Normal'])
heading=Paragraph('A heading at the beginning of the document',knstyle)
heading.keepWithNext=True
content= XPreformatted('This is the content\n'*120,styles['Normal'])
Story=[heading,content]
doc.build(Story)
go()
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from reportlab.platypus import SimpleDocTemplate, Paragraph
from reportlab.platypus.doctemplate import Indenter
from reportlab.platypus.flowables import *
from reportlab.platypus.xpreformatted import *
from reportlab.lib.styles import getSampleStyleSheet
from copy import copy
def go():
Story=[]
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("issue216.pdf")
space=Spacer(0,0)
knstyle=copy(styles['Normal'])
heading1=Paragraph('Heading 1',knstyle)
heading1.keepWithNext=True
content= XPreformatted('This is the content\n'*120,styles['Normal'])
Story=[space,heading1,content]
doc.build(Story)
go()
| mit | Python |
b1ee34bcc827e6ac08d445f694f9cec035d4c85f | Update version | cloudboss/bossimage,cloudboss/bossimage | bossimage/__init__.py | bossimage/__init__.py | __version__ = '0.1.4'
| __version__ = '0.1.3'
| mit | Python |
f02ad2f5b4a8444d7aae5a53a5a5a842b5935fc7 | Update update-episodes/anime1_me | Xi-Plus/Xiplus-Wikipedia-Bot,Xi-Plus/Xiplus-Wikipedia-Bot | my-ACG/update-episodes/anime1_me.py | my-ACG/update-episodes/anime1_me.py | # -*- coding: utf-8 -*-
import argparse
import importlib
import os
import sys
os.environ['PYWIKIBOT_DIR'] = os.path.dirname(os.path.realpath(__file__))
import pywikibot
sys.path.append('..')
animeSite = importlib.import_module('util.anime1_me', 'Anime1Me').Anime1Me()
site = pywikibot.Site()
site.login()
datasite = site.data_repository()
def updateEpisodes(title):
print(title)
myitem = pywikibot.ItemPage(datasite, title)
claims = myitem.get()['claims']
if 'P38' in claims:
claim = claims['P38'][0]
url = claim.getTarget()
data = animeSite.getData(url)
new_episodes = data['episodes']
print('\t url', url)
print('\t new_episodes', new_episodes)
if 'P27' in claims:
episodesValue = claims['P27'][0].getTarget()
old_episodes = episodesValue.amount
print('\t old_episodes', old_episodes)
if new_episodes > old_episodes:
episodesValue.amount = new_episodes
print('\t Update episodes from {} to {}'.format(old_episodes, new_episodes))
claims['P27'][0].changeTarget(episodesValue, summary='更新總集數')
else:
print('\t Not update')
else:
new_claim = pywikibot.page.Claim(datasite, 'P27')
new_claim.setTarget(pywikibot.WbQuantity(new_episodes, site=datasite))
print('\t Add new episodes {}'.format(new_episodes))
myitem.addClaim(new_claim, summary='新增總集數')
else:
print('\t Not gamer')
def main():
moegirlitem = pywikibot.ItemPage(datasite, 'Q56')
for backlink in moegirlitem.backlinks(namespaces=[120]):
updateEpisodes(backlink.title())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('title', nargs='?')
args = parser.parse_args()
if args.title is None:
main()
else:
updateEpisodes(args.title)
| # -*- coding: utf-8 -*-
import argparse
import importlib
import os
import sys
os.environ['PYWIKIBOT_DIR'] = os.path.dirname(os.path.realpath(__file__))
import pywikibot
sys.path.append('..')
animeSite = importlib.import_module('util.anime1_me', 'Anime1Me').Anime1Me()
site = pywikibot.Site()
site.login()
datasite = site.data_repository()
def updateEpisodes(title):
if title < 'Item:Q756':
return
print(title)
myitem = pywikibot.ItemPage(datasite, title)
claims = myitem.get()['claims']
if 'P38' in claims:
claim = claims['P38'][0]
url = claim.getTarget()
data = animeSite.getData(url)
new_episodes = data['episodes']
print('\t url', url)
print('\t new_episodes', new_episodes)
if 'P27' in claims:
episodesValue = claims['P27'][0].getTarget()
old_episodes = episodesValue.amount
print('\t old_episodes', old_episodes)
if new_episodes > old_episodes:
episodesValue.amount = new_episodes
print('\t Update episodes from {} to {}'.format(old_episodes, new_episodes))
input()
claims['P27'][0].changeTarget(episodesValue, summary='更新總集數')
else:
print('\t Not update')
else:
new_claim = pywikibot.page.Claim(datasite, 'P27')
new_claim.setTarget(pywikibot.WbQuantity(new_episodes, site=datasite))
print('\t Add new episodes {}'.format(new_episodes))
input()
myitem.addClaim(new_claim, summary='新增總集數')
else:
print('\t Not gamer')
def main():
moegirlitem = pywikibot.ItemPage(datasite, 'Q56')
for backlink in moegirlitem.backlinks(namespaces=[120]):
updateEpisodes(backlink.title())
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('title', nargs='?')
args = parser.parse_args()
if args.title is None:
main()
else:
updateEpisodes(args.title)
| mit | Python |
39639d45fea8753869feeed4f879533811a9222d | Bump version to 4.1.0rc7 | platformio/platformio-core,platformio/platformio,platformio/platformio-core | platformio/__init__.py | platformio/__init__.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
VERSION = (4, 1, "0rc7")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"An open source ecosystem for IoT development. "
"Cross-platform IDE and unified debugger. "
"Remote unit testing and firmware updates. "
"Arduino, ARM mbed, Espressif (ESP8266/ESP32), STM32, PIC32, nRF51/nRF52, "
"FPGA, CMSIS, SPL, AVR, Samsung ARTIK, libOpenCM3"
)
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
| # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
VERSION = (4, 1, "0rc6")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"An open source ecosystem for IoT development. "
"Cross-platform IDE and unified debugger. "
"Remote unit testing and firmware updates. "
"Arduino, ARM mbed, Espressif (ESP8266/ESP32), STM32, PIC32, nRF51/nRF52, "
"FPGA, CMSIS, SPL, AVR, Samsung ARTIK, libOpenCM3"
)
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
| apache-2.0 | Python |
b42d0efa73c0c9e8daf8756753eb3303bdaf79e1 | Bump version to 3.6.2b5 | platformio/platformio-core,platformio/platformio,platformio/platformio-core | platformio/__init__.py | platformio/__init__.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (3, 6, "2b5")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"An open source ecosystem for IoT development. "
"Cross-platform IDE and unified debugger. "
"Remote unit testing and firmware updates. "
"Arduino, ARM mbed, Espressif (ESP8266/ESP32), STM32, PIC32, nRF51/nRF52, "
"FPGA, CMSIS, SPL, AVR, Samsung ARTIK, libOpenCM3")
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
msg = ("PlatformIO Core v%s does not run under Python version %s.\n"
"Minimum supported version is 2.7, please upgrade Python.\n"
"Python 3 is not yet supported.\n")
sys.stderr.write(msg % (__version__, sys.version))
sys.exit(1)
| # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (3, 6, "2b4")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"An open source ecosystem for IoT development. "
"Cross-platform IDE and unified debugger. "
"Remote unit testing and firmware updates. "
"Arduino, ARM mbed, Espressif (ESP8266/ESP32), STM32, PIC32, nRF51/nRF52, "
"FPGA, CMSIS, SPL, AVR, Samsung ARTIK, libOpenCM3")
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
msg = ("PlatformIO Core v%s does not run under Python version %s.\n"
"Minimum supported version is 2.7, please upgrade Python.\n"
"Python 3 is not yet supported.\n")
sys.stderr.write(msg % (__version__, sys.version))
sys.exit(1)
| apache-2.0 | Python |
a93028d6e4dc1439666f7bbed6c4643268542a49 | Bump version to 3.2.0b3 | platformio/platformio,platformio/platformio-core,platformio/platformio-core | platformio/__init__.py | platformio/__init__.py | # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (3, 2, "0b3")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = ("An open source ecosystem for IoT development. "
"Cross-platform build system and library manager. "
"Continuous and IDE integration. "
"Arduino, ESP8266 and ARM mbed compatible")
__url__ = "http://platformio.org"
__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
msg = ("PlatformIO version %s does not run under Python version %s.\n"
"Python 3 is not yet supported.\n")
sys.stderr.write(msg % (__version__, sys.version.split()[0]))
sys.exit(1)
| # Copyright 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (3, 2, "0b2")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = ("An open source ecosystem for IoT development. "
"Cross-platform build system and library manager. "
"Continuous and IDE integration. "
"Arduino, ESP8266 and ARM mbed compatible")
__url__ = "http://platformio.org"
__author__ = "Ivan Kravets"
__email__ = "me@ikravets.com"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__apiurl__ = "https://api.platformio.org"
if sys.version_info < (2, 7, 0) or sys.version_info >= (3, 0, 0):
msg = ("PlatformIO version %s does not run under Python version %s.\n"
"Python 3 is not yet supported.\n")
sys.stderr.write(msg % (__version__, sys.version.split()[0]))
sys.exit(1)
| apache-2.0 | Python |
f39c9fb597facb92701afbfc687e37898e7bf43d | Bump version to 4.4.0b4 | platformio/platformio-core,platformio/platformio,platformio/platformio-core | platformio/__init__.py | platformio/__init__.py | # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (4, 4, "0b4")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"A professional collaborative platform for embedded development. "
"Cross-platform IDE and Unified Debugger. "
"Static Code Analyzer and Remote Unit Testing. "
"Multi-platform and Multi-architecture Build System. "
"Firmware File Explorer and Memory Inspection. "
"IoT, Arduino, CMSIS, ESP-IDF, FreeRTOS, libOpenCM3, mbedOS, Pulp OS, SPL, "
"STM32Cube, Zephyr RTOS, ARM, AVR, Espressif (ESP8266/ESP32), FPGA, "
"MCS-51 (8051), MSP430, Nordic (nRF51/nRF52), NXP i.MX RT, PIC32, RISC-V, "
"STMicroelectronics (STM8/STM32), Teensy"
)
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__accounts_api__ = "https://api.accounts.platformio.org"
__registry_api__ = [
"https://api.registry.platformio.org",
"https://api.registry.ns1.platformio.org",
]
__pioremote_endpoint__ = "ssl:host=remote.platformio.org:port=4413"
__default_requests_timeout__ = (10, None) # (connect, read)
__core_packages__ = {
"contrib-piohome": "~3.2.3",
"contrib-pysite": "~2.%d%d.0" % (sys.version_info.major, sys.version_info.minor),
"tool-unity": "~1.20500.0",
"tool-scons": "~2.20501.7" if sys.version_info.major == 2 else "~4.40001.0",
"tool-cppcheck": "~1.190.0",
"tool-clangtidy": "~1.100000.0",
"tool-pvs-studio": "~7.7.0",
}
__check_internet_hosts__ = [
"140.82.118.3", # Github.com
"35.231.145.151", # Gitlab.com
"88.198.170.159", # platformio.org
"github.com",
"platformio.org",
]
| # Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
VERSION = (4, 4, "0b3")
__version__ = ".".join([str(s) for s in VERSION])
__title__ = "platformio"
__description__ = (
"A professional collaborative platform for embedded development. "
"Cross-platform IDE and Unified Debugger. "
"Static Code Analyzer and Remote Unit Testing. "
"Multi-platform and Multi-architecture Build System. "
"Firmware File Explorer and Memory Inspection. "
"IoT, Arduino, CMSIS, ESP-IDF, FreeRTOS, libOpenCM3, mbedOS, Pulp OS, SPL, "
"STM32Cube, Zephyr RTOS, ARM, AVR, Espressif (ESP8266/ESP32), FPGA, "
"MCS-51 (8051), MSP430, Nordic (nRF51/nRF52), NXP i.MX RT, PIC32, RISC-V, "
"STMicroelectronics (STM8/STM32), Teensy"
)
__url__ = "https://platformio.org"
__author__ = "PlatformIO"
__email__ = "contact@platformio.org"
__license__ = "Apache Software License"
__copyright__ = "Copyright 2014-present PlatformIO"
__accounts_api__ = "https://api.accounts.platformio.org"
__registry_api__ = [
"https://api.registry.platformio.org",
"https://api.registry.ns1.platformio.org",
]
__pioremote_endpoint__ = "ssl:host=remote.platformio.org:port=4413"
__default_requests_timeout__ = (10, None) # (connect, read)
__core_packages__ = {
"contrib-piohome": "~3.2.3",
"contrib-pysite": "~2.%d%d.0" % (sys.version_info.major, sys.version_info.minor),
"tool-unity": "~1.20500.0",
"tool-scons": "~2.20501.7" if sys.version_info.major == 2 else "~4.40001.0",
"tool-cppcheck": "~1.190.0",
"tool-clangtidy": "~1.100000.0",
"tool-pvs-studio": "~7.7.0",
}
__check_internet_hosts__ = [
"140.82.118.3", # Github.com
"35.231.145.151", # Gitlab.com
"88.198.170.159", # platformio.org
"github.com",
"platformio.org",
]
| apache-2.0 | Python |
a3f3f37f7a978c1a5b39007c08f956addedc5bd1 | Update Battle_ship.py | kejrp23/Python | Battle_ship.py | Battle_ship.py | """
Created on Code Academy in python lauguage project.
Created by Jason R. Pittman
Created on 3/19/16
Code partially modified from orginial state.
"""
from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's Play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
"""
REMOVE THESE COMMENTS TO REVEAL
LOCATION OF SHIP FOR DEBUGGING
print ship_row
print ship_col
"""
#This is the main part of the game
for turn in range(4):
print "turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
#This is the winning guess area of the game.
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship you bum!"
break
#These are the losing combinations
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship Ha Ha !"
board[guess_row][guess_col] = "X"
if turn == 3:
print "Game Over"
# Print (turn + 1) here!
print_board(board)
| """
Created on Code Academy in python lauguage project.
Created by Jason R. Pittman
Created on 3/19/16
Code partially modified from orginial state.
"""
from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's Play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#This is the main part of the game
for turn in range(4):
print "turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
#This is the winning guess area of the game.
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship you bum!"
break
#These are the losing combinations
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship Ha Ha !"
board[guess_row][guess_col] = "X"
if turn == 3:
print "Game Over"
# Print (turn + 1) here!
print_board(board)
| artistic-2.0 | Python |
16844f9063d84cac85e04cd48bbb4364f909038c | Bump version number | nabla-c0d3/sslyze | sslyze/__init__.py | sslyze/__init__.py |
__author__ = 'Alban Diquet'
__license__ = 'GPLv2'
__version__ = '0.13.3'
__email__ = 'nabla.c0d3@gmail.com'
PROJECT_URL = 'https://github.com/nabla-c0d3/sslyze'
PROJECT_DESC = 'Fast and full-featured SSL scanner.'
|
__author__ = 'Alban Diquet'
__license__ = 'GPLv2'
__version__ = '0.13.2'
__email__ = 'nabla.c0d3@gmail.com'
PROJECT_URL = 'https://github.com/nabla-c0d3/sslyze'
PROJECT_DESC = 'Fast and full-featured SSL scanner.'
| agpl-3.0 | Python |
429e419f3baa067002f0b6a832fa3fe8fff72288 | Remove senstive data from settings.py. | editorsnotes/editorsnotes,editorsnotes/editorsnotes | editorsnotes/settings.py | editorsnotes/settings.py | # Django settings for editorsnotes project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Ryan Shaw', 'ryanshaw@ischool.berkeley.edu'),
)
MANAGERS = ADMINS
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/django_admin_media/'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'editorsnotes.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.admindocs',
'editorsnotes.main'
)
from settings_local import *
| # Django settings for editorsnotes project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('Ryan Shaw', 'ryanshaw@ischool.berkeley.edu'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'editorsnotes'
DATABASE_USER = 'editorsnotes'
DATABASE_PASSWORD = 'Beev0dir'
DATABASE_HOST = '' # localhost
DATABASE_PORT = '' # default
TIME_ZONE = 'America/Los_Angeles'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = False
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/django_admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '$!d663ao9sgc$=aq%(-0$fe1f4(0&v7*dhb!#_n*_qky5$_x-g'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'editorsnotes.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.admindocs',
'editorsnotes.main'
)
| agpl-3.0 | Python |
4084b31a97fd85b81e80e0af5e6007c367c4582f | correct allowed_hosts | ewjoachim/bttn_finds_my_phone | bttn/settings.py | bttn/settings.py | """
Django settings for bttn project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gywo&mlr!^(z+0evkt*ht@w%t#g#z&+7_i87vy!2*e#v*hg$xt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["127.0.0.1", "powerful-wave-5962.herokuapp.com"]
ADMINS = ["ewjoachim@gmail.com"]
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = (
'icloud_warn',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'bttn.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bttn.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| """
Django settings for bttn project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'gywo&mlr!^(z+0evkt*ht@w%t#g#z&+7_i87vy!2*e#v*hg$xt'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["powerful-wave-5962.herokuapp.com/"]
# Application definition
INSTALLED_APPS = (
'icloud_warn',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'bttn.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'bttn.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
| mit | Python |
f0b7c9024fc8c8cdfe084bc52bd23560c60c7c96 | Make modules uninstallable | brain-tec/l10n-switzerland,brain-tec/l10n-switzerland,brain-tec/l10n-switzerland | l10n_ch_hr_payroll/__openerp__.py | l10n_ch_hr_payroll/__openerp__.py | # -*- coding: utf-8 -*-
#
# File: __openerp__.py
# Module: l10n_ch_hr_payroll
#
# Created by sge@open-net.ch
#
# Copyright (c) 2014-TODAY Open-Net Ltd. <http://www.open-net.ch>
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Switzerland - Payroll',
'summary': 'Swizerland Payroll Rules',
'category': 'Localization',
'author': "Open Net Sàrl,Odoo Community Association (OCA)",
'depends': [
'decimal_precision',
'hr_payroll',
'hr_payroll_account',
'hr_contract',
'hr_attendance',
'account'
],
'version': '9.0.1.3.0',
'auto_install': False,
'demo': [],
'website': 'http://open-net.ch',
'license': 'AGPL-3',
'data': [
'data/hr.salary.rule.category.xml',
'data/hr.salary.rule.xml',
'views/hr_employee_view.xml',
'views/hr_contract_view.xml'
],
'installable': False
}
| # -*- coding: utf-8 -*-
#
# File: __openerp__.py
# Module: l10n_ch_hr_payroll
#
# Created by sge@open-net.ch
#
# Copyright (c) 2014-TODAY Open-Net Ltd. <http://www.open-net.ch>
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-TODAY OpenERP S.A. <http://www.openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Switzerland - Payroll',
'summary': 'Swizerland Payroll Rules',
'category': 'Localization',
'author': "Open Net Sàrl,Odoo Community Association (OCA)",
'depends': [
'decimal_precision',
'hr_payroll',
'hr_payroll_account',
'hr_contract',
'hr_attendance',
'account'
],
'version': '9.0.1.3.0',
'auto_install': False,
'demo': [],
'website': 'http://open-net.ch',
'license': 'AGPL-3',
'data': [
'data/hr.salary.rule.category.xml',
'data/hr.salary.rule.xml',
'views/hr_employee_view.xml',
'views/hr_contract_view.xml'
],
'installable': True
}
| agpl-3.0 | Python |
86d2fd8fef263e85d305fef5cc300cd9e3e04a4e | Add date_created to User model | tortxof/flask-password,tortxof/flask-password,tortxof/flask-password | models.py | models.py | import os
import secrets
from urllib.parse import urlparse
import datetime
from peewee import *
from playhouse.postgres_ext import PostgresqlExtDatabase, TSVectorField
def gen_id():
return secrets.token_urlsafe(24)
database = PostgresqlExtDatabase(
os.environ.get('PG_NAME', 'passwords'),
host = os.environ.get('PG_HOST', 'localhost'),
user = os.environ.get('PG_USER', 'postgres'),
password = os.environ.get('PG_PASSWORD', 'postgres'),
register_hstore = False,
)
def migrate():
database.get_conn()
database.create_tables([User, Password, Search, LoginEvent], safe=True)
database.close()
class BaseModel(Model):
class Meta:
database = database
class User(BaseModel):
id = CharField(primary_key=True, default=gen_id)
username = CharField(unique=True)
password = CharField()
salt = CharField()
key = CharField()
session_time = IntegerField(default=10)
hide_passwords = BooleanField(default=True)
date_created = DateTimeField(default=datetime.datetime.utcnow)
class Password(BaseModel):
id = CharField(primary_key=True, default=gen_id)
title = CharField()
url = CharField()
username = CharField()
password = CharField()
other = TextField()
search_content = TSVectorField(default='')
user = ForeignKeyField(User)
def update_search_content(self):
search_content = [
str(getattr(self, field)) for field in
(
'title',
'url',
'username',
)
]
search_content += urlparse(self.url).netloc.split(':')[0].split('.')
self.search_content = fn.to_tsvector('simple', ' '.join(search_content))
self.save()
class Search(BaseModel):
id = CharField(primary_key=True, default=gen_id)
name = CharField()
query = CharField()
user = ForeignKeyField(User)
class LoginEvent(BaseModel):
date = DateTimeField(default=datetime.datetime.utcnow)
ip = CharField()
user = ForeignKeyField(User)
class Meta:
order_by = ('-date',)
| import os
import secrets
from urllib.parse import urlparse
import datetime
from peewee import *
from playhouse.postgres_ext import PostgresqlExtDatabase, TSVectorField
def gen_id():
return secrets.token_urlsafe(24)
database = PostgresqlExtDatabase(
os.environ.get('PG_NAME', 'passwords'),
host = os.environ.get('PG_HOST', 'localhost'),
user = os.environ.get('PG_USER', 'postgres'),
password = os.environ.get('PG_PASSWORD', 'postgres'),
register_hstore = False,
)
def migrate():
database.get_conn()
database.create_tables([User, Password, Search, LoginEvent], safe=True)
database.close()
class BaseModel(Model):
class Meta:
database = database
class User(BaseModel):
id = CharField(primary_key=True, default=gen_id)
username = CharField(unique=True)
password = CharField()
salt = CharField()
key = CharField()
session_time = IntegerField(default=10)
hide_passwords = BooleanField(default=True)
class Password(BaseModel):
id = CharField(primary_key=True, default=gen_id)
title = CharField()
url = CharField()
username = CharField()
password = CharField()
other = TextField()
search_content = TSVectorField(default='')
user = ForeignKeyField(User)
def update_search_content(self):
search_content = [
str(getattr(self, field)) for field in
(
'title',
'url',
'username',
)
]
search_content += urlparse(self.url).netloc.split(':')[0].split('.')
self.search_content = fn.to_tsvector('simple', ' '.join(search_content))
self.save()
class Search(BaseModel):
id = CharField(primary_key=True, default=gen_id)
name = CharField()
query = CharField()
user = ForeignKeyField(User)
class LoginEvent(BaseModel):
date = DateTimeField(default=datetime.datetime.utcnow)
ip = CharField()
user = ForeignKeyField(User)
class Meta:
order_by = ('-date',)
| mit | Python |
9bb97d0545f7283fea55b50263fd980fab5cb824 | Update ThreadPool.py | Salandora/OctoPrint-FileManager,Salandora/OctoPrint-FileManager,Salandora/OctoPrint-FileManager | octoprint_filemanager/ThreadPool.py | octoprint_filemanager/ThreadPool.py | # http://code.activestate.com/recipes/577187-python-thread-pool/
from Queue import Queue
from threading import Thread
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception as e: print(e)
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
| # http://code.activestate.com/recipes/577187-python-thread-pool/
from Queue import Queue
from threading import Thread
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception, e: print(e)
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
| agpl-3.0 | Python |
4309705d00d3f3f09ddb1d9c2acc76fd9477af4c | Add error code mapping that is consistent with Discord. | SunDwarf/curious | curious/exc.py | curious/exc.py | """
Exceptions raised from within the library.
"""
import enum
from curious.http.curio_http import Response
class CuriousError(Exception):
"""
The base class for all curious exceptions.
"""
# HTTP based exceptions.
class ErrorCode(enum.IntEnum):
UNKNOWN_ACCOUNT = 10001
UNKNOWN_APPLICATION = 10002
UNKNOWN_CHANNEL = 10003
UNKNOWN_GUILD = 10004
UNKNOWN_INTEGRATION = 10005
UNKNOWN_INVITE = 10006
UNKNOWN_MEMBER = 10007
UNKNOWN_MESSAGE = 10008
UNKNOWN_OVERWRITE = 1009
UNKNOWN_PROVIDER = 10010
UNKNOWN_ROLE = 10011
UNKNOWN_TOKEN = 10012
UNKNOWN_USER = 10013
UNKNOWN_EMOJI = 10014
NO_BOTS = 20001
ONLY_BOTS = 20002
MAX_GUILDS = 30001 # technically user only
MAX_FRIENDS = 30002
MAX_PINS = 30003
MAX_ROLES = 30005
MAX_REACTIONS = 30010
UNAUTHORIZED = 40001
MISSING_ACCESS = 50001
INVALID_ACCOUNT = 50002
NO_DMS = 50003
EMBED_DISABLED = 50004
CANNOT_EDIT = 50005
CANNOT_SEND_EMPTY_MESSAGE = 50006
CANNOT_SEND_TO_USER = 50007
CANNOT_SEND_TO_VC = 50008
VERIFICATION_TOO_HIGH = 50009
OAUTH2_NO_BOT = 50009
OAUTH2_LIMIT = 50011
INVALID_OAUTH_STATE = 50012
MISSING_PERMISSIONS = 50013
INVALID_AUTH_TOKEN = 50014
NOTE_TOO_LONG = 50015
INVALID_MESSAGE_COUNT = 50016
CANNOT_PIN = 50019
TOO_OLD_TO_BULK_DELETE = 50019
REACTION_BLOCKED = 90001
UNKNOWN = 0
class HTTPException(CuriousError):
"""
Raised when a HTTP request fails with a 400 <= e < 600 error code.
"""
def __init__(self, response: Response, error: dict):
self.response = response
#: The error code for this response.
self.error_code = ErrorCode(error.get("code", 0))
self.error_message = error.get("message")
def __str__(self):
return "{}: {}".format(self.error_code, self.error_code.name, self.error_message)
__repr__ = __str__
class Unauthorized(HTTPException):
"""
Raised when your bot token is invalid.
"""
class Forbidden(HTTPException):
"""
Raised when you don't have permission for something.
"""
class NotFound(HTTPException):
"""
Raised when something could not be found.
"""
class PermissionsError(CuriousError):
"""
Raised when you do not have sufficient permission to perform an action.
:ivar permission_required: The string of the permission required to perform this action.
"""
def __init__(self, permission_required: str):
self.permission_required = permission_required
def __str__(self):
return "Bot requires the permission {} to perform this action".format(self.permission_required)
__repr__ = __str__
class HierachyError(CuriousError):
"""
Raised when you can't do something due to the hierachy.
"""
| """
Exceptions raised from within the library.
"""
from curious.http.curio_http import Response
class CuriousError(Exception):
"""
The base class for all curious exceptions.
"""
class HTTPException(CuriousError):
"""
Raised when a HTTP request fails with a 400 <= e < 600 error code.
"""
def __init__(self, response: Response, error: dict):
self.response = response
self.error = error
def __repr__(self):
return repr(self.error)
def __str__(self):
return str(self.error)
class Unauthorized(HTTPException):
"""
Raised when your bot token is invalid.
"""
class Forbidden(HTTPException):
"""
Raised when you don't have permission for something.
"""
class NotFound(HTTPException):
"""
Raised when something could not be found.
"""
class PermissionsError(CuriousError):
"""
Raised when you do not have sufficient permission to perform an action.
:ivar permission_required: The string of the permission required to perform this action.
"""
def __init__(self, permission_required: str):
self.permission_required = permission_required
def __str__(self):
return "Bot requires the permission {} to perform this action".format(self.permission_required)
__repr__ = __str__
class HierachyError(CuriousError):
"""
Raised when you can't do something due to the hierachy.
"""
| mit | Python |
06d4b5dde3a566f50ec5c2d12358fce842a42ceb | Add files via upload | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | locations/spiders/olivegarden.py | locations/spiders/olivegarden.py | # -*- coding: utf-8 -*-
import scrapy
import re
from locations.items import GeojsonPointItem
class OliveGardenSpider(scrapy.Spider):
name = "olivegarden"
allowed_domains = ['olivegarden.com']
start_urls = (
'http://www.olivegarden.com/en-locations-sitemap.xml',
)
def address(self, address):
if not address:
return None
addr_tags = {
"addr_full": address[0].split('value="')[1].split('"')[0].split(',')[0],
"city": address[0].split('value="')[1].split('"')[0].split(',')[1],
"state": address[0].split('value="')[1].split('"')[0].split(',')[-2],
"postcode": address[0].split('value="')[1].split('"')[0].split(',')[-1],
}
return addr_tags
def parse(self, response):
response.selector.remove_namespaces()
city_urls = response.xpath('//url/loc/text()').extract()
for path in city_urls:
locationURL = re.compile(r'http:/(/|/www.)olivegarden.com/locations/\S+')
if not re.search(locationURL, path):
pass
else:
yield scrapy.Request(
path.strip(),
callback=self.parse_store,
)
def parse_store(self, response):
properties = {
'name': response.xpath('/html/body/div[3]/div/div/div/div/div/div/div[1]/h1').extract()[0].split('\n')[1].split('<br>')[0],
'website': response.xpath('//head/link[@rel="canonical"]/@href').extract_first(),
'ref': " ".join(response.xpath('/html/head/title/text()').extract()[0].split('|')[0].split()),
'lon': float(response.xpath('//input[@id="restLatLong"]').extract()[0].split('value="')[1].split('"')[0].split(',')[1]),
'lat': float(response.xpath('//input[@id="restLatLong"]').extract()[0].split('value="')[1].split('"')[0].split(',')[0]),
}
address = self.address(response.xpath('//input[@id="restAddress"]').extract())
if address:
properties.update(address)
yield GeojsonPointItem(**properties) | # -*- coding: utf-8 -*-
import scrapy
import re
from locations.items import GeojsonPointItem
class OliveGardenSpider(scrapy.Spider):
name = "olivegarden"
allowed_domains = ['olivegarden.com']
start_urls = (
'http://www.olivegarden.com/en-locations-sitemap.xml',
)
def address(self, address):
if not address:
return None
addr_tags = {
"addr_full": address[0].split('value="')[1].split('"')[0].split(',')[0],
"city": address[0].split('value="')[1].split('"')[0].split(',')[1],
"state": address[0].split('value="')[1].split('"')[0].split(',')[-2],
"postcode": address[0].split('value="')[1].split('"')[0].split(',')[-1],
}
return addr_tags
def parse(self, response):
response.selector.remove_namespaces()
city_urls = response.xpath('//url/loc/text()').extract()
for path in city_urls:
regex = re.compile(r'http\S+olivegarden.com/locations/\S+')
if not re.search(regex, path):
pass
else:
yield scrapy.Request(
path.strip(),
callback=self.parse_store,
)
def parse_store(self, response):
properties = {
'name': response.xpath('/html/body/div[3]/div/div/div/div/div/div/div[1]/h1').extract()[0].split('\n')[1].split('<br>')[0],
'website': response.xpath('//head/link[@rel="canonical"]/@href').extract_first(),
'ref': " ".join(response.xpath('/html/head/title/text()').extract()[0].split('|')[0].split()),
'lon': float(response.xpath('//input[@id="restLatLong"]').extract()[0].split('value="')[1].split('"')[0].split(',')[1]),
'lat': float(response.xpath('//input[@id="restLatLong"]').extract()[0].split('value="')[1].split('"')[0].split(',')[0]),
}
address = self.address(response.xpath('//input[@id="restAddress"]').extract())
if address:
properties.update(address)
yield GeojsonPointItem(**properties) | mit | Python |
c434a5f4c4ca55ba8fbea81637dfe4db610bd5d1 | backup view actions | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | nodeconductor/backup/views.py | nodeconductor/backup/views.py | from django.shortcuts import get_object_or_404
from rest_framework import permissions as rf_permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from nodeconductor.core import viewsets
from nodeconductor.backup import models
from nodeconductor.backup import serializers
from nodeconductor.structure import filters as structure_filters
class BackupScheduleViewSet(viewsets.ModelViewSet):
queryset = models.BackupSchedule.objects.all()
serializer_class = serializers.BackupScheduleSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
class BackupViewSet(viewsets.CreateModelViewSet):
queryset = models.Backup.objects.all()
serializer_class = serializers.BackupSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
def post_save(self, backup, created):
"""
Starts backup process if backup was created successfully
"""
if created:
backup.start_backup()
@action()
def restore(self, request, uuid):
backup = get_object_or_404(models.Backup, uuid=uuid)
replace_original = request.POST.get('replace_original', False)
backup.start_restoration(replace_original=replace_original)
return Response({'status': 'Backup restoration process was started'})
@action()
def delete(self, request, uuid):
backup = get_object_or_404(models.Backup, uuid=uuid)
backup.start_deletion()
return Response({'status': 'Backup deletion process was started'})
| from django.shortcuts import get_object_or_404
from rest_framework import permissions as rf_permissions
from rest_framework import views
from rest_framework.response import Response
from nodeconductor.core import viewsets
from nodeconductor.backup import models
from nodeconductor.backup import serializers
from nodeconductor.structure import filters as structure_filters
class BackupScheduleViewSet(viewsets.ModelViewSet):
queryset = models.BackupSchedule.objects.all()
serializer_class = serializers.BackupScheduleSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
class BackupViewSet(viewsets.CreateModelViewSet):
queryset = models.Backup.objects.all()
serializer_class = serializers.BackupSerializer
lookup_field = 'uuid'
filter_backends = (structure_filters.GenericRoleFilter,)
permission_classes = (rf_permissions.IsAuthenticated,
rf_permissions.DjangoObjectPermissions)
def get_object(self):
"""
When backup is created manually - it starts backuping
"""
backup = super(viewsets.CreateModelViewSet, self).get_object()
backup.start_backup()
return backup
class BackupOperationView(views.APIView):
def post(self, request, uuid, action):
backup = get_object_or_404(models.Backup, uuid=uuid)
if action == 'restore':
replace_original = request.POST.get('replace_original', False)
backup.start_restoration(replace_original=replace_original)
elif action == 'delete':
backup.start_deletion()
return Response({'backup_state': backup.state}, status=200)
| mit | Python |
209c0d0201b76a0f2db7d8b507b2eaa2df03fcae | Replace custom GRW dist with scipy gengamma. Implement file fitting function. | jbernhard/ebe-analysis | lib/stats.py | lib/stats.py | """
Statistics.
"""
import numpy as np
from scipy.stats import gengamma, norm
"""
Set default starting parameters for fitting a generalized gamma distribution.
These parameters are sensible for ATLAS v_n distributions.
Order: (a, c, loc, scale) where a,c are shape params.
"""
gengamma._fitstart = lambda data: (1.0, 2.0, 0.0, 0.1)
def fit_file(fname,dist='gengamma',**kwargs):
"""
Fit a distribution to each column of a data file.
Arguments
---------
fname -- file name or object containing data columns to fit
dist -- distribution to fit, either 'gengamma' (default) or 'norm'
kwargs -- for np.loadtxt, except 'unpack' or 'ndmin' are ignored
Returns
-------
iterable of MLE parameters:
params_0, ... , params_N
for each column, where params are tuples of the form
(*shapes, loc, scale)
as produced by scipy.stats.rv_continuous.fit
"""
# remove 'unpack' and 'ndmin' kwargs if set
for key in ['unpack','ndmin']:
try:
del kwargs[key]
except KeyError:
pass
# read file
cols = np.loadtxt(fname,unpack=True,ndmin=2,**kwargs)
# set fitting distribution
try:
dist = eval(dist)
except NameError:
raise ValueError('invalid distribution: ' + dist)
return (dist.fit(c) for c in cols)
| """
Statistics.
"""
from numpy import exp
from scipy.stats import rv_continuous
from scipy.special import gamma
class grw_gen(rv_continuous):
"""
Generalized Reverse Weibull distribution.
PDF:
a/gamma(g) * x^(a*g-1) * exp(-x^a)
for x,a,g >= 0
"""
def _pdf(self,x,a,g):
return a/gamma(g) * pow(x,a*g-1) * exp(-pow(x,a))
def _fitstart(self,data):
return (2.0,1.0,0.0,0.02)
grw = grw_gen(a=0.0, name='grw', shapes='a,g')
| mit | Python |
e0367ccff78768d8e0cb0f2274bafe6871d6d392 | Fix filters | genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio,genialis/resolwe-bio | resolwe_bio/filters.py | resolwe_bio/filters.py | """.. Ignore pydocstyle D400.
===================
Resolwe Bio Filters
===================
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import rest_framework_filters as filters
from resolwe.flow.filters import CollectionFilter, DataFilter
from resolwe_bio.models import Sample
class BioCollectionFilter(CollectionFilter):
"""Filter the collection endpoint.
Enable filtering collections by the entity.
.. IMPORTANT::
:class:`CollectionViewSet` must be patched before using it in
urls to enable this feature:
.. code:: python
CollectionViewSet.filter_class = BioCollectionFilter
"""
sample = filters.ModelChoiceFilter(name='entity', queryset=Sample.objects.all())
class BioDataFilter(DataFilter):
"""Filter the data endpoint.
Enable filtering data by the sample.
.. IMPORTANT::
:class:`DataViewSet` must be patched before using it in urls to
enable this feature:
.. code:: python
DataViewSet.filter_class = BioDataFilter
"""
sample = filters.ModelChoiceFilter(name='entity', queryset=Sample.objects.all())
| """.. Ignore pydocstyle D400.
===================
Resolwe Bio Filters
===================
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import rest_framework_filters as filters
from resolwe.flow.filters import CollectionFilter, DataFilter
from resolwe_bio.models import Sample
class BioCollectionFilter(CollectionFilter):
"""Filter the collection endpoint.
Enable filtering collections by the entity.
.. IMPORTANT::
:class:`CollectionViewSet` must be patched before using it in
urls to enable this feature:
.. code:: python
CollectionViewSet.filter_class = BioCollectionFilter
"""
sample = filters.ModelChoiceFilter(queryset=Sample.objects.all())
class BioDataFilter(DataFilter):
"""Filter the data endpoint.
Enable filtering data by the sample.
.. IMPORTANT::
:class:`DataViewSet` must be patched before using it in urls to
enable this feature:
.. code:: python
DataViewSet.filter_class = BioDataFilter
"""
sample = filters.ModelChoiceFilter(queryset=Sample.objects.all())
| apache-2.0 | Python |
313aafc11f76888614e2a0523e9e858e71765eaa | Add some more tests for wc module. | jelmer/subvertpy,jelmer/subvertpy | tests/test_wc.py | tests/test_wc.py | # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Subversion ra library tests."""
from bzrlib.tests import TestCase
import wc
class VersionTest(TestCase):
def test_version_length(self):
self.assertEquals(4, len(wc.version()))
class WorkingCopyTests(TestCase):
def test_get_adm_dir(self):
self.assertEquals(".svn", wc.get_adm_dir())
def test_is_normal_prop(self):
self.assertTrue(wc.is_normal_prop("svn:ignore"))
def test_is_entry_prop(self):
self.assertTrue(wc.is_entry_prop("svn:entry:foo"))
def test_is_wc_prop(self):
self.assertTrue(wc.is_wc_prop("svn:wc:foo"))
def test_get_default_ignores(self):
self.assertIsInstance(wc.get_default_ignores({}), list)
| # Copyright (C) 2005-2007 Jelmer Vernooij <jelmer@samba.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Subversion ra library tests."""
from bzrlib.tests import TestCase
import ra
class VersionTest(TestCase):
def test_version_length(self):
self.assertEquals(4, len(ra.version()))
| lgpl-2.1 | Python |
c99bfaf3d09b1926603a7fef52187e89572a606c | fix cibuild for brave_electron_version auditors: @bbondy | pmkary/braver,pmkary/braver,willy-b/browser-laptop,luixxiul/browser-laptop,luixxiul/browser-laptop,darkdh/browser-laptop,luixxiul/browser-laptop,diasdavid/browser-laptop,darkdh/browser-laptop,timborden/browser-laptop,jonathansampson/browser-laptop,diasdavid/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,willy-b/browser-laptop,dcposch/browser-laptop,dcposch/browser-laptop,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,Sh1d0w/browser-laptop,willy-b/browser-laptop,pmkary/braver,timborden/browser-laptop,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,pmkary/braver,diasdavid/browser-laptop,luixxiul/browser-laptop,darkdh/browser-laptop,timborden/browser-laptop,willy-b/browser-laptop,diasdavid/browser-laptop,darkdh/browser-laptop | tools/cibuild.py | tools/cibuild.py | #!/usr/bin/env python
import os
import subprocess
import sys
import os.path
BRAVE_ELECTRON = process.env.npm_config_brave_electron_version
UPSTREAM_ELECTRON = '1.4.0'
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
TARGET_ARCH= os.environ['TARGET_ARCH'] if os.environ.has_key('TARGET_ARCH') else 'x64'
os.environ['npm_config_arch'] = TARGET_ARCH
def execute(argv, env=os.environ):
print ' '.join(argv)
try:
output = subprocess.check_output(argv, stderr=subprocess.STDOUT, env=env)
print output
return output
except subprocess.CalledProcessError as e:
print e.output
raise e
def write_npmrc():
data = 'runtime = electron\n' \
'target = %s\n' \
'target_arch = %s\n' \
'brave_electron_version = %s\n' \
'disturl = https://atom.io/download/atom-shell\n' % (UPSTREAM_ELECTRON, TARGET_ARCH, BRAVE_ELECTRON)
f = open('.npmrc','wb')
f.write(data)
f.close()
def run_script(script, args=[]):
sys.stderr.write('\nRunning ' + script +'\n')
sys.stderr.flush()
script = os.path.join(SOURCE_ROOT, 'tools', script)
subprocess.check_call([sys.executable, script] + args)
PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
is_linux = PLATFORM == 'linux'
is_windows = PLATFORM == 'win32'
is_darwin = PLATFORM == 'darwin'
deps = []
if is_darwin:
deps = ['GITHUB_TOKEN', 'CHANNEL', 'IDENTIFIER']
elif is_windows:
deps = ['GITHUB_TOKEN', 'CHANNEL', 'CERT_PASSWORD', 'TARGET_ARCH']
else:
deps = ['GITHUB_TOKEN', 'CHANNEL']
if any(not os.environ.has_key(v) for v in deps):
print 'Missing some environment variables', deps
sys.exit(1)
execute(['git', 'pull'])
execute(['rm', '-Rf', 'node_modules'])
execute(['rm', '-Rf', 'Brave-%s-%s' % (PLATFORM, TARGET_ARCH)])
execute(['rm', '-Rf', 'dist'])
write_npmrc()
npm = 'npm.cmd' if is_windows else 'npm'
execute([npm, 'install'])
if is_darwin:
execute(['node', './tools/electronBuilderHack.js'])
# For whatever reason on linux pstinstall webpack isn't running
elif is_linux:
execute([npm, 'run', 'webpack'])
execute([npm, 'run', 'build-package'])
execute([npm, 'run', 'build-installer'])
run_script('upload.py')
| #!/usr/bin/env python
import os
import subprocess
import sys
import os.path
UPSTREAM_ELECTRON = '1.4.0'
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
TARGET_ARCH= os.environ['TARGET_ARCH'] if os.environ.has_key('TARGET_ARCH') else 'x64'
os.environ['npm_config_arch'] = TARGET_ARCH
def execute(argv, env=os.environ):
print ' '.join(argv)
try:
output = subprocess.check_output(argv, stderr=subprocess.STDOUT, env=env)
print output
return output
except subprocess.CalledProcessError as e:
print e.output
raise e
def write_npmrc():
data = 'runtime = electron\n' \
'target = %s\n' \
'target_arch = %s\n' \
'disturl = https://atom.io/download/atom-shell\n' % (UPSTREAM_ELECTRON, TARGET_ARCH)
f = open('.npmrc','wb')
f.write(data)
f.close()
def run_script(script, args=[]):
sys.stderr.write('\nRunning ' + script +'\n')
sys.stderr.flush()
script = os.path.join(SOURCE_ROOT, 'tools', script)
subprocess.check_call([sys.executable, script] + args)
PLATFORM = {
'cygwin': 'win32',
'darwin': 'darwin',
'linux2': 'linux',
'win32': 'win32',
}[sys.platform]
is_linux = PLATFORM == 'linux'
is_windows = PLATFORM == 'win32'
is_darwin = PLATFORM == 'darwin'
deps = []
if is_darwin:
deps = ['GITHUB_TOKEN', 'CHANNEL', 'IDENTIFIER']
elif is_windows:
deps = ['GITHUB_TOKEN', 'CHANNEL', 'CERT_PASSWORD', 'TARGET_ARCH']
else:
deps = ['GITHUB_TOKEN', 'CHANNEL']
if any(not os.environ.has_key(v) for v in deps):
print 'Missing some environment variables', deps
sys.exit(1)
execute(['git', 'pull'])
execute(['rm', '-Rf', 'node_modules'])
execute(['rm', '-Rf', 'Brave-%s-%s' % (PLATFORM, TARGET_ARCH)])
execute(['rm', '-Rf', 'dist'])
write_npmrc()
npm = 'npm.cmd' if is_windows else 'npm'
execute([npm, 'install'])
if is_darwin:
execute(['node', './tools/electronBuilderHack.js'])
# For whatever reason on linux pstinstall webpack isn't running
elif is_linux:
execute([npm, 'run', 'webpack'])
execute([npm, 'run', 'build-package'])
execute([npm, 'run', 'build-installer'])
run_script('upload.py')
| mpl-2.0 | Python |
5b557fe66fab24b6daf2300d7681a7d274301bbb | add models.py | yosukesuzuki/deep-link-app,yosukesuzuki/deep-link-app,yosukesuzuki/deep-link-app | project/core/models.py | project/core/models.py | # -*- coding: utf-8 -*-
# core.models
from google.appengine.ext import db
# Create your models here.
class Article(db.Model):
title = db.StringProperty()
updated_at = db.DateTimeProperty(auto_now=True)
created_at = db.DateTimeProperty(auto_now_add=True)
def __unicode__(self):
return self.title
class ShortURL(db.Model):
long_url = db.StringProperty(verbose_name='long URL', required=True)
fallback_url = db.StringProperty(verbose_name='Fallback URL')
ipad_url = db.StringProperty(verbose_name='iPad URL')
android_url = db.StringProperty(verbose_name='Android URL')
wp_url = db.StringProperty(verbose_name='WindowsPhone URL')
firefox_url = db.StringProperty(verbose_name='FireFox URL')
updated_at = db.DateTimeProperty(auto_now=True)
created_at = db.DateTimeProperty(auto_now_add=True)
| # -*- coding: utf-8 -*-
# core.models
from google.appengine.ext import db
# Create your models here.
class Article(db.Model):
title = db.StringProperty()
updated_at = db.DateTimeProperty(auto_now=True)
created_at = db.DateTimeProperty(auto_now_add=True)
def __unicode__(self):
return self.title
| mit | Python |
35fe01413e1e8868776704c8b3492877f3df63e6 | add head sord | turbidsoul/tsutil | tsutil/sorted.py | tsutil/sorted.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Turbidsoul Chen
# @Date: 2014-07-30 10:07:05
# @Last Modified by: Turbidsoul Chen
# @Last Modified time: 2014-08-07 17:51:57
def quick_sorted(lst, func=lambda a, b: cmp(a, b), reversed=False):
if len(lst) <= 1:
return lst
pivot = lst[0]
before = []
after = []
for s in lst[1:]:
res = func(s, pivot)
if res > 0:
after.append(s)
else:
before.append(s)
before = quick_sorted(before, func=func)
after = quick_sorted(after, func=func)
if reversed:
return (before + [pivot] + after)[::-1]
else:
return before + [pivot] + after
def head_sort(lst, func=lambda a, b: cmp(a, b), reversed=False):
def make_maxhead(lst, start, end):
root = start
while 1:
left = root * 2 + 1
right = root * 2 + 2
if left > end:
break
child = left
if right <= end and func(lst[left], lst[right]) < 0:
child = right
if func(lst[root], lst[child]) < 0:
lst[root], lst[child] = lst[child],lst[root]
root = child
else:
break
n = len(lst)
for i in range(n, -1, -1):
make_maxhead(lst, i, n-1)
for end in range(n-1, -1, -1):
lst[0], lst[end] = lst[end], lst[0]
make_maxhead(lst, 0, end-1)
return lst if reversed else lst[::-1]
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Turbidsoul Chen
# @Date: 2014-07-30 10:07:05
# @Last Modified by: Turbidsoul Chen
# @Last Modified time: 2014-07-30 10:14:44
def quick_sorted(lst, func=lambda a, b: cmp(a, b), reversed=False):
if len(lst) <= 1:
return lst
pivot = lst[0]
before = []
after = []
for s in lst[1:]:
res = func(s, pivot)
if res > 0:
after.append(s)
else:
before.append(s)
before = quick_sorted(before, func=func)
after = quick_sorted(after, func=func)
if reversed:
return (before + [pivot] + after)[::-1]
else:
return before + [pivot] + after
| mit | Python |
53e46daf96d903b94d43d0911c637a3bc388d630 | Change minimum length of query on dm+d simple search to 3 | ebmdatalab/openprescribing,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,annapowellsmith/openpresc | openprescribing/dmd2/forms.py | openprescribing/dmd2/forms.py | from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineCheckboxes
obj_types_choices = [
("vtm", "VTMs"),
("vmp", "VMPs"),
("amp", "AMPs"),
("vmpp", "VMPPs"),
("ampp", "AMPPs"),
]
include_choices = [
("unavailable", "Unavailable items"),
("invalid", "Invalid items"),
("no_bnf_code", "Items with no BNF code"),
]
class SearchForm(forms.Form):
q = forms.CharField(label="Query, SNOMED code, or BNF code/prefix", min_length=3)
obj_types = forms.MultipleChoiceField(
label="Search...",
choices=obj_types_choices,
required=False,
initial=[tpl[0] for tpl in obj_types_choices],
)
include = forms.MultipleChoiceField(
label="Include...",
choices=include_choices,
required=False,
help_text="Unavailable items are not available to be prescribed and/or have been discontinued.",
)
# This is only used in tests
max_results_per_obj_type = forms.IntegerField(
required=False, widget=forms.HiddenInput()
)
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = "GET"
self.helper.layout = Layout(
Field("q"),
InlineCheckboxes("obj_types"),
InlineCheckboxes("include"),
ButtonHolder(Submit("submit", "Search")),
)
class AdvancedSearchForm(forms.Form):
search = forms.CharField(required=True, widget=forms.HiddenInput())
include = forms.MultipleChoiceField(
label="Include...",
choices=include_choices,
required=False,
help_text="Unavailable items are not available to be prescribed and/or have been discontinued.",
)
def __init__(self, *args, **kwargs):
super(AdvancedSearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = "GET"
self.helper.layout = Layout(Field("search"), InlineCheckboxes("include"))
| from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field, ButtonHolder, Submit
from crispy_forms.bootstrap import InlineCheckboxes
obj_types_choices = [
("vtm", "VTMs"),
("vmp", "VMPs"),
("amp", "AMPs"),
("vmpp", "VMPPs"),
("ampp", "AMPPs"),
]
include_choices = [
("unavailable", "Unavailable items"),
("invalid", "Invalid items"),
("no_bnf_code", "Items with no BNF code"),
]
class SearchForm(forms.Form):
q = forms.CharField(label="Query, SNOMED code, or BNF code/prefix", min_length=6)
obj_types = forms.MultipleChoiceField(
label="Search...",
choices=obj_types_choices,
required=False,
initial=[tpl[0] for tpl in obj_types_choices],
)
include = forms.MultipleChoiceField(
label="Include...",
choices=include_choices,
required=False,
help_text="Unavailable items are not available to be prescribed and/or have been discontinued.",
)
# This is only used in tests
max_results_per_obj_type = forms.IntegerField(
required=False, widget=forms.HiddenInput()
)
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = "GET"
self.helper.layout = Layout(
Field("q"),
InlineCheckboxes("obj_types"),
InlineCheckboxes("include"),
ButtonHolder(Submit("submit", "Search")),
)
class AdvancedSearchForm(forms.Form):
search = forms.CharField(required=True, widget=forms.HiddenInput())
include = forms.MultipleChoiceField(
label="Include...",
choices=include_choices,
required=False,
help_text="Unavailable items are not available to be prescribed and/or have been discontinued.",
)
def __init__(self, *args, **kwargs):
super(AdvancedSearchForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = "GET"
self.helper.layout = Layout(Field("search"), InlineCheckboxes("include"))
| mit | Python |
d49262b0329df8c4ebb53f3c4c4161d2269348a6 | remove unused imports | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | meinberlin/apps/contrib/views.py | meinberlin/apps/contrib/views.py | from django.shortcuts import redirect
from django.views import generic
class ComponentLibraryView(generic.base.TemplateView):
template_name = 'meinberlin_contrib/component_library.html'
class CanonicalURLDetailView(generic.DetailView):
"""DetailView redirecting to the canonical absolute url of an object."""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
# Redirect to the absolute url if it differs from the current path
if hasattr(self.object, 'get_absolute_url'):
absolute_url = self.object.get_absolute_url()
if absolute_url != request.path:
return redirect(absolute_url)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
| from django.http import Http404
from django.shortcuts import get_object_or_404
from django.shortcuts import redirect
from django.views import generic
class ComponentLibraryView(generic.base.TemplateView):
template_name = 'meinberlin_contrib/component_library.html'
class CanonicalURLDetailView(generic.DetailView):
"""DetailView redirecting to the canonical absolute url of an object."""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
# Redirect to the absolute url if it differs from the current path
if hasattr(self.object, 'get_absolute_url'):
absolute_url = self.object.get_absolute_url()
if absolute_url != request.path:
return redirect(absolute_url)
context = self.get_context_data(object=self.object)
return self.render_to_response(context)
| agpl-3.0 | Python |
6074202fdc8fa0e707c21edf78dd6c78cfce668a | Fix static file locations in setup.py | schandrika/volttron,schandrika/volttron,schandrika/volttron,schandrika/volttron | Agents/PlatformManagerAgent/setup.py | Agents/PlatformManagerAgent/setup.py | # -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2013, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation
# are those of the authors and should not be interpreted as representing
# official policies, either expressed or implied, of the FreeBSD
# Project.
#
# This material was prepared as an account of work sponsored by an
# agency of the United States Government. Neither the United States
# Government nor the United States Department of Energy, nor Battelle,
# nor any of their employees, nor any jurisdiction or organization that
# has cooperated in the development of these materials, makes any
# warranty, express or implied, or assumes any legal liability or
# responsibility for the accuracy, completeness, or usefulness or any
# information, apparatus, product, software, or process disclosed, or
# represents that its use would not infringe privately owned rights.
#
# Reference herein to any specific commercial product, process, or
# service by trade name, trademark, manufacturer, or otherwise does not
# necessarily constitute or imply its endorsement, recommendation, or
# favoring by the United States Government or any agency thereof, or
# Battelle Memorial Institute. The views and opinions of authors
# expressed herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
#
# PACIFIC NORTHWEST NATIONAL LABORATORY
# operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
#}}}
from setuptools import setup, find_packages
#get environ for agent name/identifier
packages = find_packages('.')
package = packages[0]
setup(
name = package + 'agent',
version = "0.1",
install_requires = ['volttron'],
packages = packages,
package_data = {
package: ['webroot/*.*', 'webroot/css/*.css', , 'webroot/js/*.js']
},
entry_points = {
'setuptools.installation': [
'eggsecutable = ' + package + '.agent:main',
]
}
)
| # -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2013, Battelle Memorial Institute
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation
# are those of the authors and should not be interpreted as representing
# official policies, either expressed or implied, of the FreeBSD
# Project.
#
# This material was prepared as an account of work sponsored by an
# agency of the United States Government. Neither the United States
# Government nor the United States Department of Energy, nor Battelle,
# nor any of their employees, nor any jurisdiction or organization that
# has cooperated in the development of these materials, makes any
# warranty, express or implied, or assumes any legal liability or
# responsibility for the accuracy, completeness, or usefulness or any
# information, apparatus, product, software, or process disclosed, or
# represents that its use would not infringe privately owned rights.
#
# Reference herein to any specific commercial product, process, or
# service by trade name, trademark, manufacturer, or otherwise does not
# necessarily constitute or imply its endorsement, recommendation, or
# favoring by the United States Government or any agency thereof, or
# Battelle Memorial Institute. The views and opinions of authors
# expressed herein do not necessarily state or reflect those of the
# United States Government or any agency thereof.
#
# PACIFIC NORTHWEST NATIONAL LABORATORY
# operated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY
# under Contract DE-AC05-76RL01830
#}}}
from setuptools import setup, find_packages
#get environ for agent name/identifier
packages = find_packages('.')
package = packages[0]
setup(
name = package + 'agent',
version = "0.1",
install_requires = ['volttron'],
packages = packages,
package_data = {
package: ['webroot/*.*', 'webroot/vendor/*.*']
},
entry_points = {
'setuptools.installation': [
'eggsecutable = ' + package + '.agent:main',
]
}
)
| bsd-2-clause | Python |
30726ed0ed50af7deb50ddce569968d937f96fa3 | Implement TagForm clean_slug method. | jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8 | organizer/forms.py | organizer/forms.py | from django import forms
from django.core.exceptions import ValidationError
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def clean_slug(self):
new_slug = (
self.cleaned_data['slug'].lower())
if new_slug == 'create':
raise ValidationError(
'Slug may not be "create".')
return new_slug
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
| from django import forms
from .models import Tag
class TagForm(forms.Form):
name = forms.CharField(max_length=31)
slug = forms.SlugField(
max_length=31,
help_text='A label for URL config')
def clean_name(self):
return self.cleaned_data['name'].lower()
def save(self):
new_tag = Tag.objects.create(
name=self.cleaned_data['name'],
slug=self.cleaned_data['slug'])
return new_tag
| bsd-2-clause | Python |
eadc0eb76fc027e5eaee5b9c3c734eaa42a73bf1 | set up... | IQSS/miniverse,IQSS/miniverse,IQSS/miniverse | miniverse/settings/heroku_dev.py | miniverse/settings/heroku_dev.py | from __future__ import absolute_import
import os
from os.path import join#, normpath, isdir, isfile
import dj_database_url
from .base import *
# Set the secret key
SECRET_KEY = os.environ['SECRET_KEY']
# Cookie name
SESSION_COOKIE_NAME = 'dv_metrics_dev'
#INTERNAL_IPS = () # Heroku IP
ALLOWED_HOSTS = ['54.235.72.96',]
## Database settings via Heroku url
#
# We have two databases:
# - Heroku db for django + "installations" app
# - external Dataverse db for reading stats
#
DATABASE_ROUTERS = ['miniverse.settings.db_django_contrib_router.DjangoContribRouter', ]
# Set the Dataverse url
DV_DEMO_DATABASE_URL = dj_database_url.parse(os.environ['DV_DEMO_DATABASE_URL'])
DATABASES['default'].update(DV_DEMO_DATABASE_URL)
# Set the Miniverse admin url
HEROKU_DB_CONFIG = dj_database_url.config(conn_max_age=500)
DATABASES['miniverse_admin_db'].update(HEROKU_DB_CONFIG)
DATABASES['miniverse_admin_db']['TEST'] = {'MIRROR': 'default'}
# Heroku specific urls
ROOT_URLCONF = 'miniverse.urls_heroku_dev'
"""
DATABASES = {
'miniverse_admin_db': HEROKU_DB_CONFIG,
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dvn_thedata', # dvn_thedata dvndb_demo
'USER': 'postgres', # dv_readonly, postgres
'PASSWORD': '123',
'HOST': 'localhost'
}
}
"""
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
join(PROJECT_ROOT, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
| from __future__ import absolute_import
import os
from os.path import join#, normpath, isdir, isfile
import dj_database_url
from .base import *
# Set the secret key
SECRET_KEY = os.environ['SECRET_KEY']
# Cookie name
SESSION_COOKIE_NAME = 'dv_metrics_dev'
#INTERNAL_IPS = () # Heroku IP
ALLOWED_HOSTS = ['54.235.72.96',]
## Database settings via Heroku url
#
# We have two databases:
# - Heroku db for django + "installations" app
# - external Dataverse db for reading stats
#
DATABASE_ROUTERS = ['miniverse.settings.db_django_contrib_router.DjangoContribRouter', ]
HEROKU_DB_CONFIG = dj_database_url.config(conn_max_age=500)
# Set the Miniverse admin url
DATABASES['miniverse_admin_db'].update(HEROKU_DB_CONFIG)
DATABASES['miniverse_admin_db']['TEST'] = {'MIRROR': 'default'}
# Set the Dataverse url
DV_DEMO_DATABASE_URL = dj_database_url.parse(os.environ['DV_DEMO_DATABASE_URL'])
DATABASES['default'].update(DV_DEMO_DATABASE_URL)
# Heroku specific urls
ROOT_URLCONF = 'miniverse.urls_heroku_dev'
"""
DATABASES = {
'miniverse_admin_db': HEROKU_DB_CONFIG,
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dvn_thedata', # dvn_thedata dvndb_demo
'USER': 'postgres', # dv_readonly, postgres
'PASSWORD': '123',
'HOST': 'localhost'
}
}
"""
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
join(PROJECT_ROOT, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
| mit | Python |
e5f662d9cebe4133705eca74a300c325d432ad04 | Remove destruction of pips/test requires entries that don't exist. | stackforge/anvil,stackforge/anvil,mc2014/anvil,mc2014/anvil | anvil/components/cinder_client.py | anvil/components/cinder_client.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from anvil import components as comp
class CinderClientUninstaller(comp.PythonUninstallComponent):
def __init__(self, *args, **kargs):
comp.PythonUninstallComponent.__init__(self, *args, **kargs)
class CinderClientInstaller(comp.PythonInstallComponent):
def __init__(self, *args, **kargs):
comp.PythonInstallComponent.__init__(self, *args, **kargs)
class CinderClientRuntime(comp.EmptyRuntime):
def __init__(self, *args, **kargs):
comp.EmptyRuntime.__init__(self, *args, **kargs)
| # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (C) 2012 Yahoo! 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from anvil import components as comp
class CinderClientUninstaller(comp.PythonUninstallComponent):
def __init__(self, *args, **kargs):
comp.PythonUninstallComponent.__init__(self, *args, **kargs)
class CinderClientInstaller(comp.PythonInstallComponent):
def __init__(self, *args, **kargs):
comp.PythonInstallComponent.__init__(self, *args, **kargs)
def _filter_pip_requires_line(self, line):
if line.lower().find('keystoneclient') != -1:
return None
if line.lower().find('novaclient') != -1:
return None
if line.lower().find('glanceclient') != -1:
return None
return line
class CinderClientRuntime(comp.EmptyRuntime):
def __init__(self, *args, **kargs):
comp.EmptyRuntime.__init__(self, *args, **kargs)
| apache-2.0 | Python |
e1e7589b805072ff741eeb7b31ba326f45ea0504 | Implement an authorization system | vtemian/buffpy,bufferapp/buffer-python | buffpy/api.py | buffpy/api.py | import json
import urllib
from rauth import OAuth2Session, OAuth2Service
from buffpy.response import ResponseObject
BASE_URL = 'https://api.bufferapp.com/1/%s'
PATHS = {
'INFO': 'info/configuration.json'
}
AUTHORIZE_URL = 'https://bufferapp.com/oauth2/authorize'
ACCESS_TOKEN = 'https://api.bufferapp.com/1/oauth2/token.json'
class API(object):
'''
Small and clean class that embrace all basic
operations with the buffer app
'''
def __init__(self, client_id, client_secret, access_token=None):
self.session = OAuth2Session(client_id=client_id,
client_secret=client_secret,
access_token=access_token)
@property
def access_token(self):
return self.session.access_token
@access_token.setter
def access_token(self, value):
self.session.access_token = value
def get(self, url, parser=None):
if parser is None:
parser = json.loads
if not self.session.access_token:
raise ValueError('Please set an access token first!')
response = self.session.get(url=BASE_URL % url)
return parser(response.content)
def post(self, url, parser=None, **params):
if parser is None:
parser = json.loads
if not self.session.access_token:
raise ValueError('Please set an access token first!')
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = self.session.post(url=BASE_URL % url, headers=headers, **params)
return parser(response.content)
@property
def info(self):
'''
Returns an object with the current configuration that Buffer is using,
including supported services, their icons and the varying limits of
character and schedules.
The services keys map directly to those on profiles and updates so that
you can easily show the correct icon or calculate the correct character
length for an update.
'''
response = self.get(url=PATHS['INFO'])
return ResponseObject(response)
class AuthService(object):
def __init__(self, client_id, client_secret, redirect_uri):
self.outh_service = OAuth2Service(client_id=client_id,
client_secret=client_secret,
name='buffer',
authorize_url=AUTHORIZE_URL,
access_token_url=ACCESS_TOKEN,
base_url=BASE_URL % '')
self.redirect_uri = redirect_uri
def create_session(self, access_token=None):
return self.outh_service.get_session(access_token)
def get_access_token(self, auth_code):
auth_code = urllib.unquote(auth_code).decode('utf8')
data = {'code': auth_code,
'grant_type': 'authorization_code',
'redirect_uri': self.redirect_uri}
return self.outh_service.get_access_token(data=data, decoder=json.loads)
@property
def authorize_url(self):
return self.outh_service.get_authorize_url(response_type='code', redirect_uri=self.redirect_uri)
| import json
from rauth import OAuth2Session
from buffpy.response import ResponseObject
BASE_URL = 'https://api.bufferapp.com/1/%s'
PATHS = {
'INFO': 'info/configuration.json'
}
class API(object):
'''
Small and clean class that embrace all basic
operations with the buffer app
'''
def __init__(self, client_id, client_secret, access_token=None):
self.session = OAuth2Session( client_id=client_id,
client_secret=client_secret,
access_token=access_token)
@property
def access_token(self):
return self.session.access_token
@access_token.setter
def access_token(self, value):
self.session.access_token = value
def get(self, url, parser=None):
if parser is None:
parser = json.loads
if not self.session.access_token:
raise ValueError('Please set an access token first!')
response = self.session.get(url=BASE_URL % url)
return parser(response.content)
def post(self, url, parser=None, **params):
if parser is None:
parser = json.loads
if not self.session.access_token:
raise ValueError('Please set an access token first!')
headers = {'Content-Type':'application/x-www-form-urlencoded'}
response = self.session.post(url=BASE_URL % url, headers=headers, **params)
return parser(response.content)
@property
def info(self):
'''
Returns an object with the current configuration that Buffer is using,
including supported services, their icons and the varying limits of
character and schedules.
The services keys map directly to those on profiles and updates so that
you can easily show the correct icon or calculate the correct character
length for an update.
'''
response = self.get(url=PATHS['INFO'])
return ResponseObject(response)
| mit | Python |
7bb5f463dfeb39b8ba84a63147756d27901a2f56 | fix cymysql's _extact_error_code() for py3 | graingert/sqlalchemy,Cito/sqlalchemy,robin900/sqlalchemy,olemis/sqlalchemy,276361270/sqlalchemy,epa/sqlalchemy,halfcrazy/sqlalchemy,sandan/sqlalchemy,itkovian/sqlalchemy,epa/sqlalchemy,robin900/sqlalchemy,sqlalchemy/sqlalchemy,Akrog/sqlalchemy,bootandy/sqlalchemy,bdupharm/sqlalchemy,hsum/sqlalchemy,ThiefMaster/sqlalchemy,alex/sqlalchemy,Akrog/sqlalchemy,wujuguang/sqlalchemy,elelianghh/sqlalchemy,j5int/sqlalchemy,bootandy/sqlalchemy,itkovian/sqlalchemy,elelianghh/sqlalchemy,wfxiang08/sqlalchemy,dstufft/sqlalchemy,brianv0/sqlalchemy,sandan/sqlalchemy,monetate/sqlalchemy,dstufft/sqlalchemy,hsum/sqlalchemy,EvaSDK/sqlalchemy,halfcrazy/sqlalchemy,davidfraser/sqlalchemy,pdufour/sqlalchemy,inspirehep/sqlalchemy,pdufour/sqlalchemy,wujuguang/sqlalchemy,Cito/sqlalchemy,graingert/sqlalchemy,inspirehep/sqlalchemy,j5int/sqlalchemy,brianv0/sqlalchemy,alex/sqlalchemy,davidjb/sqlalchemy,alex/sqlalchemy,wfxiang08/sqlalchemy,WinterNis/sqlalchemy,ThiefMaster/sqlalchemy,276361270/sqlalchemy,olemis/sqlalchemy,bdupharm/sqlalchemy,monetate/sqlalchemy,davidfraser/sqlalchemy,Cito/sqlalchemy,EvaSDK/sqlalchemy,davidjb/sqlalchemy,WinterNis/sqlalchemy,zzzeek/sqlalchemy | lib/sqlalchemy/dialects/mysql/cymysql.py | lib/sqlalchemy/dialects/mysql/cymysql.py | # mysql/cymysql.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+cymysql
:name: CyMySQL
:dbapi: cymysql
:connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]
:url: https://github.com/nakagami/CyMySQL
"""
from .mysqldb import MySQLDialect_mysqldb
class MySQLDialect_cymysql(MySQLDialect_mysqldb):
driver = 'cymysql'
description_encoding = None
@classmethod
def dbapi(cls):
return __import__('cymysql')
def _extract_error_code(self, exception):
v = exception.args[0]
if not isinstance(v, int):
v = v.args[0]
return v
dialect = MySQLDialect_cymysql
| # mysql/cymysql.py
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+cymysql
:name: CyMySQL
:dbapi: cymysql
:connectstring: mysql+cymysql://<username>:<password>@<host>/<dbname>[?<options>]
:url: https://github.com/nakagami/CyMySQL
"""
from .mysqldb import MySQLDialect_mysqldb
class MySQLDialect_cymysql(MySQLDialect_mysqldb):
driver = 'cymysql'
description_encoding = None
@classmethod
def dbapi(cls):
return __import__('cymysql')
def _extract_error_code(self, exception):
return exception.args[0]
dialect = MySQLDialect_cymysql
| mit | Python |
8e86727c52b4a6e2277be6ab270aa1ec67441526 | use all_to_dicts | uranusjr/mosql,moskytw/mosql | examples/40_join.py | examples/40_join.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
from pprint import pprint
from mosql.query import select, left_join
from mosql.db import Database, all_to_dicts
db = Database(psycopg2, host='127.0.0.1')
with db as cur:
cur.execute(select(
'person',
{'person_id': 'mosky'},
# It is same as using keyword argument:
#where = {'person_id': 'mosky'},
joins = left_join('detail', using='person_id'),
# You can also use tuple to add multiple join statements:
#joins = (left_join('detail', using='person_id'), )
))
pprint(all_to_dicts(cur))
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
import psycopg2
from pprint import pprint
from mosql.query import select, left_join
from mosql.db import Database
db = Database(psycopg2, host='127.0.0.1')
with db as cur:
cur.execute(select(
'person',
{'person_id': 'mosky'},
# It is same as using keyword argument:
#where = {'person_id': 'mosky'},
joins = left_join('detail', using='person_id'),
# You can also use tuple to add multiple join statements:
#joins = (left_join('detail', using='person_id'), )
))
pprint(cur.fetchall())
| mit | Python |
f9837d8c661a4f8354574a82b1aea0ac4658a8be | add v6.1.6 (#22713) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/qwt/package.py | var/spack/repos/builtin/packages/qwt/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Qwt(QMakePackage):
"""The Qwt library contains GUI Components and utility classes which are
primarily useful for programs with a technical background. Beside a
framework for 2D plots it provides scales, sliders, dials, compasses,
thermometers, wheels and knobs to control or display values, arrays, or
ranges of type double.
"""
homepage = "http://qwt.sourceforge.net/"
url = "https://sourceforge.net/projects/qwt/files/qwt/6.1.3/qwt-6.1.3.tar.bz2"
version('6.1.6', sha256='99460d31c115ee4117b0175d885f47c2c590d784206f09815dc058fbe5ede1f6')
version('6.1.4', sha256='1529215329e51fc562e0009505a838f427919a18b362afff441f035b2d9b5bd9')
version('6.1.3', sha256='f3ecd34e72a9a2b08422fb6c8e909ca76f4ce5fa77acad7a2883b701f4309733')
version('5.2.2', sha256='36bf2ee51ca9c74fde1322510ffd39baac0db60d5d410bb157968a78d9c1464b')
variant('designer', default=False,
description="Build extensions to QT designer")
patch('no-designer.patch', when='~designer')
depends_on('qt@:5.14.2+opengl')
depends_on('qt+tools', when='+designer')
# Qwt 6.1.1 and older use a constant that was removed in Qt 5.4
# https://bugs.launchpad.net/ubuntu/+source/qwt-qt5/+bug/1485213
depends_on('qt@:5.3', when='@:6.1.1')
def patch(self):
# Subvert hardcoded prefix
filter_file(r'/usr/local/qwt-\$\$(QWT_)?VERSION.*',
self.prefix, 'qwtconfig.pri')
| # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Qwt(QMakePackage):
"""The Qwt library contains GUI Components and utility classes which are
primarily useful for programs with a technical background. Beside a
framework for 2D plots it provides scales, sliders, dials, compasses,
thermometers, wheels and knobs to control or display values, arrays, or
ranges of type double.
"""
homepage = "http://qwt.sourceforge.net/"
url = "https://sourceforge.net/projects/qwt/files/qwt/6.1.3/qwt-6.1.3.tar.bz2"
version('6.1.4', sha256='1529215329e51fc562e0009505a838f427919a18b362afff441f035b2d9b5bd9')
version('6.1.3', sha256='f3ecd34e72a9a2b08422fb6c8e909ca76f4ce5fa77acad7a2883b701f4309733')
version('5.2.2', sha256='36bf2ee51ca9c74fde1322510ffd39baac0db60d5d410bb157968a78d9c1464b')
variant('designer', default=False,
description="Build extensions to QT designer")
patch('no-designer.patch', when='~designer')
depends_on('qt@:5.14.2+opengl')
depends_on('qt+tools', when='+designer')
# Qwt 6.1.1 and older use a constant that was removed in Qt 5.4
# https://bugs.launchpad.net/ubuntu/+source/qwt-qt5/+bug/1485213
depends_on('qt@:5.3', when='@:6.1.1')
def patch(self):
# Subvert hardcoded prefix
filter_file(r'/usr/local/qwt-\$\$(QWT_)?VERSION.*',
self.prefix, 'qwtconfig.pri')
| lgpl-2.1 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.