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 |
|---|---|---|---|---|---|---|---|---|
9349adb2efa5f0242cf9250d74d714a7e6aea1e9 | Make version compatible with PEP386 | xguse/scikit-bio,wdwvt1/scikit-bio,johnchase/scikit-bio,xguse/scikit-bio,colinbrislawn/scikit-bio,Achuth17/scikit-bio,Achuth17/scikit-bio,jdrudolph/scikit-bio,Kleptobismol/scikit-bio,jensreeder/scikit-bio,Jorge-C/bipy,jairideout/scikit-bio,kdmurray91/scikit-bio,averagehat/scikit-bio,wdwvt1/scikit-bio,Kleptobismol/scikit-bio,corburn/scikit-bio,anderspitman/scikit-bio,johnchase/scikit-bio,SamStudio8/scikit-bio,averagehat/scikit-bio,anderspitman/scikit-bio,gregcaporaso/scikit-bio,jensreeder/scikit-bio,corburn/scikit-bio,colinbrislawn/scikit-bio,demis001/scikit-bio,Kleptobismol/scikit-bio,jdrudolph/scikit-bio,jairideout/scikit-bio,kdmurray91/scikit-bio,gregcaporaso/scikit-bio,demis001/scikit-bio,SamStudio8/scikit-bio | ordination/__init__.py | ordination/__init__.py | from .base import CA, RDA, CCA
__all__ = ['CA', 'RDA', 'CCA']
#
#from numpy.testing import Tester
#test = Tester().test
# Compatible with PEP386
__version__ = '0.1.dev'
| from .base import CA, RDA, CCA
__all__ = ['CA', 'RDA', 'CCA']
#
#from numpy.testing import Tester
#test = Tester().test
__version__ = '0.1-dev'
| bsd-3-clause | Python |
df77b24a730190342b2f6384bcaf052532c82632 | Add files via upload | Croutonix/dmtcheat,Croutonix/dmtcheat,Croutonix/dmtcheat | find_min_max.py | find_min_max.py | path = "wordlist.txt"
maxWordCount = 3
file = open(path, "r")
words = file.read().replace("\n", "").split(",")
file.close()
maxlen = []
minlen = []
for i in range(maxWordCount):
maxlen.append([])
minlen.append([])
for j in range(i+1):
maxlen[i].append(0)
minlen[i].append(100)
for word in words:
parts = word.split(" ")
wordCount = len(parts)
for i in range(wordCount):
length = len(parts[i]);
if (length < minlen[wordCount-1][i]): minlen[wordCount-1][i] = length
if (length > maxlen[wordCount-1][i]): maxlen[wordCount-1][i] = length
print("MIN: " + str(minlen))
print("MAX: " + str(maxlen))
| mit | Python | |
c0d9c0aa93a5e32e04eaba3bfc8d4cf30a88395d | add configuration class | tkosciol/micronota,biocore/micronota,tkosciol/micronota,RNAer/micronota,biocore/micronota,mortonjt/micronota,mortonjt/micronota,RNAer/micronota | micronota/config.py | micronota/config.py | # ----------------------------------------------------------------------------
# Copyright (c) 2015--, micronota development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from os.path import abspath, dirname, join, expanduser
from configparser import ConfigParser
from importlib.util import find_spec
import logging
import re
from . import app_dir
class ConfigParsingError(Exception):
''''''
pass
class Configuration(object):
def __init__(self, local_fp):
''''''
data_dir = 'support_files'
config_fp = 'micronota.cfg'
default_fp = join(dirname(abspath(__name__)), data_dir, config_fp)
global_fp = join(app_dir, config_fp)
workflow, param, log = self._read([default_fp, global_fp, local_fp])
self._tools = []
self.workflow = self._set_workflow(workflow)
self.param = self._set_param(param)
self._set_log(log)
self._check_avail()
@staticmethod
def _read(fps):
'''Return a list of 3 lists of strings.
The order in fps matters. The later cfg can override the previous.'''
s = [[], [], []]
pattern = re.compile(r'^#{9,} +\w+ +#{9,}\n', re.MULTILINE)
for fp in fps:
with open(fp) as f:
s = f.read()
items = re.split(pattern, s)
try:
_, wf, param, log = items
except ValueError:
raise ConfigParsingError(
'There should be 3 parts in the config file')
s[0].append(wf)
s[1].append(param)
s[2].append(log)
@staticmethod
def _read_config(ss):
'''Read in list of config strings.'''
config = ConfigParser()
for s in ss:
config.read_string(s)
return config
def _set_workflow(self, s):
'''read in the config for workflow.
also check if the implementation is available.
'''
config = self._read_config(s)
config['general']['db_path'] = expanduser(config['general']['db_path'])
secs = ['feature', 'cds']
for s in secs:
sec = config[s]
for k in sec:
self._tools.append(k)
try:
v = sec.getboolean(k)
sec[k] = v
except ValueError:
v = sec[k]
return config
def _set_param(self, s):
config = self._read_config(s)
for sec in config:
if sec not in self._tools:
self._tools.append(sec)
return config
def _set_log(self, s):
config = self._read_config(s)
logging.config.fileConfig(config)
def _check_avail(self):
mod = dirname(__name__)
submod = 'bfillings'
for i in self._tools:
found = find_spec('.'.join([mod, submod, i]))
if found is None:
raise NotImplementedError('%s not implemented.' % i)
| bsd-3-clause | Python | |
cb210e39fc6dc9bc3654dad0a70f29bc206688b4 | Create feedback.py | WebShark025/TheZigZagProject,WebShark025/TheZigZagProject | plugins/feedback.py | plugins/feedback.py | @bot.message_handler(commands=['feedback', 'sendfeedback'])
def send_feedbackz(message):
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
return
if userid not in messanger_list:
bot.reply_to(message, MESSANGER_JOIN_MSG, parse_mode="Markdown")
messanger_list.append(userid)
return
| mit | Python | |
c5e047ff0e1cfe35692838365b907db8c3746c4b | Add join_segmentations example to the gallery | Midafi/scikit-image,rjeli/scikit-image,youprofit/scikit-image,GaZ3ll3/scikit-image,keflavich/scikit-image,michaelaye/scikit-image,chintak/scikit-image,rjeli/scikit-image,youprofit/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,almarklein/scikit-image,ClinicalGraphics/scikit-image,Britefury/scikit-image,Britefury/scikit-image,warmspringwinds/scikit-image,keflavich/scikit-image,SamHames/scikit-image,vighneshbirodkar/scikit-image,paalge/scikit-image,rjeli/scikit-image,GaZ3ll3/scikit-image,WarrenWeckesser/scikits-image,jwiggins/scikit-image,WarrenWeckesser/scikits-image,michaelpacer/scikit-image,paalge/scikit-image,ofgulban/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,Midafi/scikit-image,bennlich/scikit-image,warmspringwinds/scikit-image,emon10005/scikit-image,vighneshbirodkar/scikit-image,bsipocz/scikit-image,almarklein/scikit-image,SamHames/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,pratapvardhan/scikit-image,chintak/scikit-image,newville/scikit-image,juliusbierk/scikit-image,ofgulban/scikit-image,blink1073/scikit-image,chriscrosscutler/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,SamHames/scikit-image,paalge/scikit-image,SamHames/scikit-image,dpshelio/scikit-image,Hiyorimi/scikit-image,almarklein/scikit-image,dpshelio/scikit-image,jwiggins/scikit-image,robintw/scikit-image,ClinicalGraphics/scikit-image,ajaybhat/scikit-image,Hiyorimi/scikit-image,michaelpacer/scikit-image,ajaybhat/scikit-image,blink1073/scikit-image,oew1v07/scikit-image,michaelaye/scikit-image,emon10005/scikit-image,ofgulban/scikit-image,chintak/scikit-image,robintw/scikit-image,oew1v07/scikit-image,chriscrosscutler/scikit-image | doc/examples/plot_join_segmentations.py | doc/examples/plot_join_segmentations.py | """
==========================================
Find the intersection of two segmentations
==========================================
When segmenting an image, you may want to combine multiple alternative
segmentations. The `skimage.segmentation.join_segmentations` function
computes the join of two segmentations, in which a pixel is placed in
the same segment if and only if it is in the same segment in _both_
segmentations.
"""
import numpy as np
from scipy import ndimage as nd
import matplotlib.pyplot as plt
import matplotlib as mpl
from skimage.filter import sobel
from skimage.segmentation import slic, join_segmentations
from skimage.morphology import watershed
from skimage import data
coins = data.coins()
# make segmentation using edge-detection and watershed
edges = sobel(coins)
markers = np.zeros_like(coins)
foreground, background = 1, 2
markers[coins < 30] = background
markers[coins > 150] = foreground
ws = watershed(edges, markers)
seg1 = nd.label(ws == foreground)[0]
# make segmentation using SLIC superpixels
# make the RGB equivalent of `coins`
coins_colour = np.tile(coins[..., np.newaxis], (1, 1, 3))
seg2 = slic(coins_colour, max_iter=20, sigma=0, convert2lab=False)
# combine the two
segj = join_segmentations(seg1, seg2)
### Display the result ###
# make a random colormap for a set number of values
def random_cmap(im):
np.random.seed(9)
cmap_array = np.concatenate(
(np.zeros((1, 3)), np.random.rand(np.ceil(im.max()), 3)))
return mpl.colors.ListedColormap(cmap_array)
# show the segmentations
fig, axes = plt.subplots(ncols=4, figsize=(9, 2.5))
axes[0].imshow(coins, cmap=plt.cm.gray, interpolation='nearest')
axes[0].set_title('Image')
axes[1].imshow(seg1, cmap=random_cmap(seg1), interpolation='nearest')
axes[1].set_title('Sobel+Watershed')
axes[2].imshow(seg2, cmap=random_cmap(seg2), interpolation='nearest')
axes[2].set_title('SLIC superpixels')
axes[3].imshow(segj, cmap=random_cmap(segj), interpolation='nearest')
axes[3].set_title('Join')
for ax in axes:
ax.axis('off')
plt.subplots_adjust(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)
plt.show()
| bsd-3-clause | Python | |
c231a440cd0b79a2e64fc050849ce3bc8e9b6f98 | Annotate zerver/templatetags/minified_js.py. | jrowan/zulip,showell/zulip,eeshangarg/zulip,hackerkid/zulip,showell/zulip,SmartPeople/zulip,isht3/zulip,verma-varsha/zulip,Galexrt/zulip,timabbott/zulip,sup95/zulip,umkay/zulip,reyha/zulip,aakash-cr7/zulip,KingxBanana/zulip,sonali0901/zulip,vikas-parashar/zulip,dattatreya303/zulip,TigorC/zulip,dhcrzf/zulip,krtkmj/zulip,hackerkid/zulip,ryanbackman/zulip,souravbadami/zulip,jphilipsen05/zulip,tommyip/zulip,christi3k/zulip,paxapy/zulip,timabbott/zulip,peguin40/zulip,umkay/zulip,paxapy/zulip,Galexrt/zulip,vikas-parashar/zulip,shubhamdhama/zulip,paxapy/zulip,mohsenSy/zulip,showell/zulip,samatdav/zulip,hackerkid/zulip,mahim97/zulip,vabs22/zulip,andersk/zulip,krtkmj/zulip,vabs22/zulip,vaidap/zulip,susansls/zulip,rht/zulip,punchagan/zulip,vikas-parashar/zulip,zulip/zulip,vikas-parashar/zulip,TigorC/zulip,vabs22/zulip,dattatreya303/zulip,brockwhittaker/zulip,AZtheAsian/zulip,kou/zulip,shubhamdhama/zulip,reyha/zulip,jphilipsen05/zulip,brockwhittaker/zulip,umkay/zulip,jrowan/zulip,souravbadami/zulip,grave-w-grave/zulip,dhcrzf/zulip,calvinleenyc/zulip,mahim97/zulip,Diptanshu8/zulip,ahmadassaf/zulip,dhcrzf/zulip,j831/zulip,showell/zulip,dhcrzf/zulip,showell/zulip,TigorC/zulip,ryanbackman/zulip,jrowan/zulip,samatdav/zulip,paxapy/zulip,brainwane/zulip,andersk/zulip,synicalsyntax/zulip,ahmadassaf/zulip,SmartPeople/zulip,christi3k/zulip,brainwane/zulip,Juanvulcano/zulip,JPJPJPOPOP/zulip,zacps/zulip,arpith/zulip,SmartPeople/zulip,niftynei/zulip,christi3k/zulip,niftynei/zulip,arpith/zulip,tommyip/zulip,sharmaeklavya2/zulip,hackerkid/zulip,jainayush975/zulip,jackrzhang/zulip,Juanvulcano/zulip,kou/zulip,tommyip/zulip,Galexrt/zulip,zulip/zulip,cosmicAsymmetry/zulip,timabbott/zulip,amyliu345/zulip,krtkmj/zulip,cosmicAsymmetry/zulip,dattatreya303/zulip,sup95/zulip,zulip/zulip,verma-varsha/zulip,zulip/zulip,KingxBanana/zulip,synicalsyntax/zulip,sup95/zulip,jrowan/zulip,JPJPJPOPOP/zulip,mahim97/zulip,shubhamdhama/zulip,grave-w-grave/zulip,jainayush975/zulip,niftynei/zulip,calvinleenyc/zulip,PhilSk/zulip,tommyip/zulip,grave-w-grave/zulip,brainwane/zulip,eeshangarg/zulip,brainwane/zulip,tommyip/zulip,rishig/zulip,sonali0901/zulip,dhcrzf/zulip,aakash-cr7/zulip,peguin40/zulip,vikas-parashar/zulip,jphilipsen05/zulip,umkay/zulip,isht3/zulip,KingxBanana/zulip,brainwane/zulip,brockwhittaker/zulip,rht/zulip,JPJPJPOPOP/zulip,ahmadassaf/zulip,jackrzhang/zulip,ahmadassaf/zulip,jackrzhang/zulip,timabbott/zulip,vaidap/zulip,Juanvulcano/zulip,sharmaeklavya2/zulip,jackrzhang/zulip,cosmicAsymmetry/zulip,synicalsyntax/zulip,zacps/zulip,AZtheAsian/zulip,andersk/zulip,timabbott/zulip,rishig/zulip,zulip/zulip,amanharitsh123/zulip,niftynei/zulip,jainayush975/zulip,amyliu345/zulip,Jianchun1/zulip,souravbadami/zulip,umkay/zulip,souravbadami/zulip,sharmaeklavya2/zulip,blaze225/zulip,synicalsyntax/zulip,isht3/zulip,cosmicAsymmetry/zulip,jrowan/zulip,joyhchen/zulip,eeshangarg/zulip,jphilipsen05/zulip,susansls/zulip,Jianchun1/zulip,jphilipsen05/zulip,blaze225/zulip,mohsenSy/zulip,eeshangarg/zulip,showell/zulip,dawran6/zulip,Juanvulcano/zulip,shubhamdhama/zulip,calvinleenyc/zulip,joyhchen/zulip,TigorC/zulip,andersk/zulip,mohsenSy/zulip,vikas-parashar/zulip,rht/zulip,brockwhittaker/zulip,jackrzhang/zulip,tommyip/zulip,dattatreya303/zulip,arpith/zulip,reyha/zulip,JPJPJPOPOP/zulip,mahim97/zulip,calvinleenyc/zulip,andersk/zulip,sup95/zulip,brainwane/zulip,Jianchun1/zulip,punchagan/zulip,shubhamdhama/zulip,JPJPJPOPOP/zulip,Galexrt/zulip,eeshangarg/zulip,sonali0901/zulip,synicalsyntax/zulip,joyhchen/zulip,krtkmj/zulip,jackrzhang/zulip,rishig/zulip,arpith/zulip,hackerkid/zulip,grave-w-grave/zulip,vabs22/zulip,umkay/zulip,mahim97/zulip,kou/zulip,calvinleenyc/zulip,souravbadami/zulip,ahmadassaf/zulip,susansls/zulip,kou/zulip,zacps/zulip,krtkmj/zulip,sharmaeklavya2/zulip,jainayush975/zulip,hackerkid/zulip,PhilSk/zulip,blaze225/zulip,dawran6/zulip,PhilSk/zulip,AZtheAsian/zulip,rishig/zulip,j831/zulip,isht3/zulip,brockwhittaker/zulip,zulip/zulip,timabbott/zulip,paxapy/zulip,samatdav/zulip,KingxBanana/zulip,mahim97/zulip,rht/zulip,zulip/zulip,christi3k/zulip,Diptanshu8/zulip,PhilSk/zulip,Diptanshu8/zulip,vaidap/zulip,verma-varsha/zulip,eeshangarg/zulip,arpith/zulip,reyha/zulip,eeshangarg/zulip,punchagan/zulip,Galexrt/zulip,Juanvulcano/zulip,Diptanshu8/zulip,amyliu345/zulip,blaze225/zulip,rht/zulip,kou/zulip,shubhamdhama/zulip,sonali0901/zulip,showell/zulip,Diptanshu8/zulip,arpith/zulip,andersk/zulip,zacps/zulip,Galexrt/zulip,paxapy/zulip,amanharitsh123/zulip,SmartPeople/zulip,amanharitsh123/zulip,jrowan/zulip,ryanbackman/zulip,dattatreya303/zulip,blaze225/zulip,SmartPeople/zulip,punchagan/zulip,joyhchen/zulip,souravbadami/zulip,punchagan/zulip,peguin40/zulip,amanharitsh123/zulip,jphilipsen05/zulip,krtkmj/zulip,cosmicAsymmetry/zulip,joyhchen/zulip,vaidap/zulip,rishig/zulip,dhcrzf/zulip,kou/zulip,brockwhittaker/zulip,samatdav/zulip,zacps/zulip,amyliu345/zulip,Jianchun1/zulip,tommyip/zulip,verma-varsha/zulip,verma-varsha/zulip,reyha/zulip,TigorC/zulip,vabs22/zulip,rishig/zulip,niftynei/zulip,ahmadassaf/zulip,sonali0901/zulip,SmartPeople/zulip,KingxBanana/zulip,j831/zulip,peguin40/zulip,peguin40/zulip,christi3k/zulip,jackrzhang/zulip,PhilSk/zulip,susansls/zulip,j831/zulip,ryanbackman/zulip,ryanbackman/zulip,isht3/zulip,jainayush975/zulip,dawran6/zulip,sharmaeklavya2/zulip,umkay/zulip,grave-w-grave/zulip,mohsenSy/zulip,niftynei/zulip,aakash-cr7/zulip,calvinleenyc/zulip,PhilSk/zulip,dhcrzf/zulip,timabbott/zulip,AZtheAsian/zulip,aakash-cr7/zulip,blaze225/zulip,AZtheAsian/zulip,dattatreya303/zulip,sharmaeklavya2/zulip,mohsenSy/zulip,ryanbackman/zulip,amanharitsh123/zulip,zacps/zulip,susansls/zulip,isht3/zulip,jainayush975/zulip,rishig/zulip,joyhchen/zulip,reyha/zulip,sup95/zulip,vabs22/zulip,christi3k/zulip,verma-varsha/zulip,synicalsyntax/zulip,samatdav/zulip,JPJPJPOPOP/zulip,sonali0901/zulip,peguin40/zulip,hackerkid/zulip,dawran6/zulip,amyliu345/zulip,mohsenSy/zulip,krtkmj/zulip,Diptanshu8/zulip,punchagan/zulip,kou/zulip,TigorC/zulip,rht/zulip,dawran6/zulip,andersk/zulip,vaidap/zulip,cosmicAsymmetry/zulip,KingxBanana/zulip,Jianchun1/zulip,shubhamdhama/zulip,aakash-cr7/zulip,Jianchun1/zulip,rht/zulip,ahmadassaf/zulip,vaidap/zulip,Galexrt/zulip,AZtheAsian/zulip,synicalsyntax/zulip,aakash-cr7/zulip,dawran6/zulip,samatdav/zulip,punchagan/zulip,amyliu345/zulip,amanharitsh123/zulip,grave-w-grave/zulip,susansls/zulip,brainwane/zulip,sup95/zulip,j831/zulip,Juanvulcano/zulip,j831/zulip | zerver/templatetags/minified_js.py | zerver/templatetags/minified_js.py | from __future__ import absolute_import
from typing import Any
from django.template import Node, Library, TemplateSyntaxError
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
if False:
# no need to add dependency
from django.template.base import Parser, Token
register = Library()
class MinifiedJSNode(Node):
def __init__(self, sourcefile):
# type: (str) -> None
self.sourcefile = sourcefile
def render(self, context):
# type: (Dict[str, Any]) -> str
if settings.DEBUG:
scripts = settings.JS_SPECS[self.sourcefile]['source_filenames']
else:
scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']]
script_urls = [staticfiles_storage.url(script) for script in scripts]
script_tags = ['<script type="text/javascript" src="%s" charset="utf-8"></script>'
% url for url in script_urls]
return '\n'.join(script_tags)
@register.tag
def minified_js(parser, token):
# type: (Parser, Token) -> MinifiedJSNode
try:
tag_name, sourcefile = token.split_contents()
except ValueError:
raise TemplateSyntaxError("%s tag requires an argument" % (tag_name,))
if not (sourcefile[0] == sourcefile[-1] and sourcefile[0] in ('"', "'")):
raise TemplateSyntaxError("%s tag should be quoted" % (tag_name,))
sourcefile = sourcefile[1:-1]
if sourcefile not in settings.JS_SPECS:
raise TemplateSyntaxError("%s tag invalid argument: no JS file %s"
% (tag_name, sourcefile))
return MinifiedJSNode(sourcefile)
| from __future__ import absolute_import
from django.template import Node, Library, TemplateSyntaxError
from django.conf import settings
from django.contrib.staticfiles.storage import staticfiles_storage
register = Library()
class MinifiedJSNode(Node):
def __init__(self, sourcefile):
self.sourcefile = sourcefile
def render(self, context):
if settings.DEBUG:
scripts = settings.JS_SPECS[self.sourcefile]['source_filenames']
else:
scripts = [settings.JS_SPECS[self.sourcefile]['output_filename']]
script_urls = [staticfiles_storage.url(script) for script in scripts]
script_tags = ['<script type="text/javascript" src="%s" charset="utf-8"></script>'
% url for url in script_urls]
return '\n'.join(script_tags)
@register.tag
def minified_js(parser, token):
try:
tag_name, sourcefile = token.split_contents()
except ValueError:
raise TemplateSyntaxError("%s tag requires an argument" % (tag_name,))
if not (sourcefile[0] == sourcefile[-1] and sourcefile[0] in ('"', "'")):
raise TemplateSyntaxError("%s tag should be quoted" % (tag_name,))
sourcefile = sourcefile[1:-1]
if sourcefile not in settings.JS_SPECS:
raise TemplateSyntaxError("%s tag invalid argument: no JS file %s"
% (tag_name, sourcefile))
return MinifiedJSNode(sourcefile)
| apache-2.0 | Python |
6536a5893e44a40a776fe98c97ed0326299cc27b | Create 03.py | Pouf/CodingCompetition,Pouf/CodingCompetition | Euler/03.py | Euler/03.py | def prime_sieve(limit):
is_prime = [False] * (limit + 1)
for x in range(1,int(limit**.5)+1):
for y in range(1,int(limit**.5)+1):
n = 4*x**2 + y**2
if n<=limit and (n%12==1 or n%12==5):
# print "1st if"
is_prime[n] = not is_prime[n]
n = 3*x**2+y**2
if n<= limit and n%12==7:
# print "Second if"
is_prime[n] = not is_prime[n]
n = 3*x**2 - y**2
if x>y and n<=limit and n%12==11:
# print "third if"
is_prime[n] = not is_prime[n]
for n in range(5,int(limit**.5)):
if is_prime[n]:
for k in range(n**2,limit+1,n**2):
is_prime[k] = False
return [2,3]+[i for i in range(5,limit) if is_prime[i]]
def trial_division(n):
if n < 2:
return []
prime_factors = []
for p in prime_sieve(int(n**.5)+1):
if p*p > n:
break
while not n % p:
prime_factors.append(p)
n //= p
if n > 1:
prime_factors.append(n)
return prime_factors
print (trial_division(600851475143))
| mit | Python | |
ebb3af21130c817eb41ecc0b79ec0dab2f5f64bf | Implement pull_request event | brantje/telegram-github-bot,brantje/captain_hook,brantje/captain_hook,brantje/telegram-github-bot,brantje/captain_hook,brantje/telegram-github-bot | captain_hook/services/github/events/pull_request.py | captain_hook/services/github/events/pull_request.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from ...base.events import BaseEvent
class PullRequestEvent(BaseEvent):
def process(self):
pr_link = str(self.body['pull_request']['url']).replace('https://api.github.com/', '')
params = {
'username': self.body['pull_request']['user']['login'],
'user_link': self.body['pull_request']['user']['html_url'],
'pull_request_number': str(self.body['pull_request']['number']),
'pull_request_link': self.body['pull_request']['html_url'],
'pull_request_title': self.body['pull_request']['title'],
'body': str(self.body['pull_request']['body']).strip(),
'repository_name': self.body['repository']['full_name'],
'repository_link': self.body['repository']['html_url'],
}
message = False
if self.body['action'] == 'opened':
message = "[⛓]({pull_request_link}) [{username}]({user_link}) opened new pull request [#{pull_request_number} {pull_request_title}]({pull_request_link}) in [{repository_name}]({repository_link})"
if self.body['action'] == 'closed' and self.body['pull_request']['merged'] == True:
message = "[⛓]({pull_request_link}) [{username}]({user_link}) merged pull request [#{pull_request_number} {pull_request_title}]({pull_request_link})"
if self.body['action'] == 'closed' and self.body['pull_request']['merged'] == False:
message = "[⛓]({pull_request_link}) [{username}]({user_link}) closed pull request [#{pull_request_number} {pull_request_title}]({pull_request_link}) in [{repository_name}](repository_link)"
message = message.format(**params)
return {"telegram": str(message)} | apache-2.0 | Python | |
b8db983c3b901ea45fabbfd87a1e92ae3722e8fe | Initialize 04.sameName | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/AutomateTheBoringStuffWithPython/Chapter03/04.sameName.py | books/AutomateTheBoringStuffWithPython/Chapter03/04.sameName.py | # This program uses the same variable name throughout
def spam():
eggs = 'spam local'
print(eggs) # prints 'spam local'
def bacon():
eggs = 'bacon local'
print(eggs) # prints 'bacon local'
spam()
print(eggs) # prints 'bacon local'
eggs = 'global'
bacon()
print(eggs) # prints 'global'
| mit | Python | |
2b146388d1804ca4cb069fa07ea5e614a8ee1d14 | Add example of sending push notification via Firebase Cloud Messaging | sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile,sth-larp/deus-mobile | tools/send_to_fcm.py | tools/send_to_fcm.py | import requests
url = 'https://fcm.googleapis.com/fcm/send'
headers = {'Content-Type': 'application/json',
'Authorization': 'key=AIza...(copy code here)...'}
payload = """
{
"to": "/topics/all",
"notification": {
"title": "Hello world",
"body": "You are beautiful"
}
}
"""
resp = requests.post(url, headers=headers, data=payload)
print(resp)
print(resp.text) | apache-2.0 | Python | |
42ee5971dfd7309e707213d18c2041128a79e901 | add test for overwrite grads | diogo149/treeano,diogo149/treeano,diogo149/treeano | treeano/sandbox/tests/utils_test.py | treeano/sandbox/tests/utils_test.py | import nose.tools as nt
import numpy as np
import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
from treeano.sandbox import utils
fX = theano.config.floatX
def test_overwrite_grad_multiple_args():
class Foo(utils.OverwriteGrad):
def __init__(self):
def fn(a, b):
return a + 2 * b
super(Foo, self).__init__(fn)
def grad(self, inputs, out_grads):
a, b = inputs
grd, = out_grads
return a, a * b * grd
foo_op = Foo()
a = T.scalar()
b = T.scalar()
ga, gb = T.grad(3 * foo_op(a, b), [a, b])
fn = theano.function([a, b], [ga, gb])
res1, res2 = fn(2.7, 11.4)
np.testing.assert_allclose(res1, 2.7)
np.testing.assert_allclose(res2, 2.7 * 11.4 * 3)
| apache-2.0 | Python | |
6557b2fc86c340968755274bbd97262b79dd1115 | Add blank __init__ to make NEURON a package | ProjectPyRhO/PyRhO,ProjectPyRhO/PyRhO | pyrho/NEURON/__init__.py | pyrho/NEURON/__init__.py | bsd-3-clause | Python | ||
ebba34e159704332b26b9211392e7a1b0b3039ba | bump version to 1.0.3 | Cue/scales,URXtech/scales | setup.py | setup.py | #!/usr/bin/env python
# Copyright 2011 The greplin-twisted-utils Authors.
#
# 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.
"""Setup script for greplin-twisted-utils."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='scales',
version='1.0.3',
description='Stats for Python processes',
license='Apache',
author='Greplin, Inc.',
author_email='opensource@greplin.com',
url='https://www.github.com/Cue/scales',
package_dir = {'':'src'},
packages = [
'greplin',
'greplin.scales',
],
namespace_packages = [
'greplin',
],
test_suite = 'nose.collector',
zip_safe = True
)
| #!/usr/bin/env python
# Copyright 2011 The greplin-twisted-utils Authors.
#
# 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.
"""Setup script for greplin-twisted-utils."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='scales',
version='1.0.2',
description='Stats for Python processes',
license='Apache',
author='Greplin, Inc.',
author_email='opensource@greplin.com',
url='https://www.github.com/Cue/scales',
package_dir = {'':'src'},
packages = [
'greplin',
'greplin.scales',
],
namespace_packages = [
'greplin',
],
test_suite = 'nose.collector',
zip_safe = True
)
| apache-2.0 | Python |
067236f0d1afc646967acfe3a37faa6643afbecb | Create setup.py | Kevincavender/the-ends | setup.py | setup.py | # setup.py info things
from distutils.core import setup
setup(
name = "Kevin"
)
| bsd-3-clause | Python | |
b53b228ec81a1d7e65e7056fee2711f6a2f557b0 | Add setup.py | bbayles/scte_55-1_address | setup.py | setup.py | from setuptools import setup, find_packages
import os
import sys
long_description = """This project contains library functions for converting\
between the Unit Address and MAC address representations of SCTE 55-1\
terminals, e.g. Motorola-brand set-top boxes and CableCARDs"""
setup(
name='scte_55-1_address',
version='2014.07.26',
description='SCTE 55-1 terminal identifier converters',
long_description="Library for working with SCTE 55-1 terminal\
identifiers",
url='https://github.com/bbayles/scte_55-1_address',
author='Bo Bayles',
author_email='bbayles@gmail.com',
license='MIT',
classifiers=['Development Status :: 5 - Production/Stable',
'Intended Audience :: Telecommunications Industry',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',],
keywords='scte cable settop cablecard',
packages=find_packages(),
)
| mit | Python | |
3898db5ffff2b3515e6f41e7c17e3f5b5fce9243 | Create setup.py | eduardoklosowski/deduplicated,eduardoklosowski/deduplicated | setup.py | setup.py | from setuptools import find_packages, setup
version = __import__('deduplicated').__version__
setup(
name='deduplicated',
version=version,
description='Check duplicated files',
author='Eduardo Klosowski',
author_email='eduardo_klosowski@yahoo.com',
license='MIT',
packages=find_packages(),
zip_safe=False,
entry_points={
'console_scripts': [
'deduplicated = deduplicated.cmd:main',
],
},
)
| mit | Python | |
a03130d23474efd7c4e2440618453d26e4f19f18 | Create setup.py | Eternity71529/cleverbot | setup.py | setup.py | from setuptools import setup, find_packages
import re, os
requirements = []
with open('requirements.txt') as f:
requirements = f.read().splitlines()
version = ''
with open('cleverbot/__init__.py') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('version is not set')
readme = ''
with open('README.md') as f:
readme = f.read()
setup(name='cleverbot',
author='Eternity71529',
url='https://github.com/Eternity71529/cleverbot',
version=version,
packages=find_packages(),
license='MIT',
description='A basic python wrapper for the Cleverbot.io API',
long_description=readme,
include_package_data=True,
install_requires=requirements,
extras_require=extras_require,
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
]
)
| mit | Python | |
5ae7dcf5c1ebfdb70b1e12ed48dfa42fba348c7c | Add setup.py | k4nar/inbox | setup.py | setup.py | from setuptools import setup, find_packages
import inbox
requirements = [
"click",
]
setup(
name="inbox",
version=inbox.__version__,
url='TODO',
description=inbox.__doc__,
author=inbox.__author__,
license=inbox.__license__,
long_description="TODO",
packages=find_packages(),
install_requires=requirements,
entry_points={
'console_scripts': [
'inbox = inbox.__main__:inbox'
]
},
classifiers=[
"Development Status :: 3 - Alpha",
"Intended Audience :: Customer Service",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Information Technology",
"Intended Audience :: Other Audience",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Topic :: Internet",
"Topic :: Office/Business",
"Topic :: Utilities",
],
keywords='inbox github notifications',
)
| mit | Python | |
cf4c893560bede792e8f1c809d54a89f1c9b9870 | Add setup.py. | jgehrcke/beautiful-readme | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2014 Jan-Philip Gehrcke (http://gehrcke.de).
# See LICENSE file for details.
import re
from setuptools import setup
long_description = \
"""Beautiful-readme converts a single README file into a simple and modern
`Bootstrap`_-powered static website.
Resources:
- Documentation_
- GitHub_
.. _Bootstrap: http://getbootstrap.com/
.. _GitHub: http://github.com/jgehrcke/beautiful-readme
.. _Documentation: http://gehrcke.de/beautiful-readme
"""
version = re.search(
'^__version__\s*=\s*"(.*)"',
open('beautifulreadme/beautifulreadme.py').read(),
re.M
).group(1)
setup(
name = "beautiful-readme",
packages = ["beautifulreadme"],
entry_points = {
"console_scripts": ['beautiful-readme = beautifulreadme.main:main']
},
version = version,
description = "Creates a simple mobile-friendly static website from your README.",
author = "Jan-Philip Gehrcke",
author_email = "jgehrcke@googlemail.com",
url = "http://gehrcke.de/beautiful-readme",
long_description=open("README.rst", "rb").read().decode('utf-8'),
keywords = ["readme", "website", "static", "Bootstrap"],
platforms = ["POSIX", "Windows"],
classifiers = [
"Programming Language :: Python",
"Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Operating System :: POSIX",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Utilities",
"Environment :: Console",
"Intended Audience :: End Users/Desktop",
],
)
| mit | Python | |
450a186d7827b40dbb3a8ddde1f5f3e48b5143af | bump version | johndeng/django_linter,geerk/django_linter | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
setup(
name='django_linter',
version='0.1',
packages=('django_linter', 'django_linter.checkers'),
description='Linter for django projects',
long_description=open('README.rst').read(),
author='Timofey Trukhanov',
author_email='timofey.trukhanov@gmail.com',
license='MIT',
url='https://github.com/geerk/django_linter',
install_requires=('pylint',),
entry_points={
'console_scripts': ['django-linter = django_linter.main:main']},
classifiers = (
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent'))
| #!/usr/bin/env python
from setuptools import setup
setup(
name='django_linter',
version='0.0.3',
packages=('django_linter', 'django_linter.checkers'),
description='Linter for django projects',
long_description=open('README.rst').read(),
author='Timofey Trukhanov',
author_email='timofey.trukhanov@gmail.com',
license='MIT',
url='https://github.com/geerk/django_linter',
install_requires=('pylint',),
entry_points={
'console_scripts': ['django-linter = django_linter.main:main']},
classifiers = (
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: 2.7',
'Operating System :: OS Independent'))
| mit | Python |
49358019f146aa479b75ddb0dc75dffd1ecc351b | Create setup.py | tetherless-world/markdown-rdfa | setup.py | setup.py | #! /usr/bin/env python
from setuptools import setup
setup(
name='rdfa_markdown',
version='0.1',
author='James McCusker',
author_email='mccusj@cs.rpi.edu',
description='Python-Markdown extension to add support for semantic data (RDFa).',
url='https://github.com/tetherless-world/markdown-rdfa',
py_modules=['markdown-rdfa'],
install_requires=['Markdown>=2.0',],
classifiers=[
'Development Status :: 4 - Beta',
'Operating System :: OS Independent',
'License :: OSI Approved :: Apache Software License ',
'Intended Audience :: Developers',
'Environment :: Web Environment',
'Programming Language :: Python',
'Topic :: Text Processing :: Filters',
'Topic :: Text Processing :: Markup :: HTML'
]
)
| apache-2.0 | Python | |
b8bab32410d866f9f547c4bd04de942e2e809816 | Add a setup.py. | gustaebel/python-mpv | setup.py | setup.py | #!/usr/bin/env python3
from distutils.core import setup
kwargs = {
"name": "python-mpv",
"author": "Lars Gustäbel",
"author_email": "lars@gustaebel.de",
"url": "http://github.com/gustaebel/python-mpv/",
"description": "control mpv from Python using JSON IPC",
"license": "MIT",
"py_modules": ["mpv"],
}
setup(**kwargs)
| mit | Python | |
9fa978c6673759142a875d9b05a4f9c110f13718 | add setup.py | suenkler/PostTLS,suenkler/PostTLS | setup.py | setup.py | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-posttls',
version='1.0',
packages=find_packages(),
include_package_data=True,
license='AGPLv3',
description='Postfix' Transport Encryption under Control of the User',
long_description=README.md,
url='https://posttls.com/',
author='Hendrik Suenkler',
author_email='hendrik@posttls.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: 1.8',
'Intended Audience :: Developers',
'License :: OSI Approved :: AGPLv3',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| agpl-3.0 | Python | |
6ae505c2b6d8ad65b6cc61587b28a8de81ecb488 | Add setup.py file | kyleconroy/python-twilio2,kyleconroy/python-twilio2 | setup.py | setup.py | from distutils.core import setup
setup(
name = "twilio",
py_modules = ['twilio'],
version = "3.0.0",
description = "Twilio API client and TwiML generator",
author = "Twilio",
author_email = "help@twilio.com",
url = "http://github.com/twilio/twilio-python/",
download_url = "http://github.com/twilio/twilio-python/tarball/2.0.1",
keywords = ["twilio","twiml"],
requires = ["httplib2"],
classifiers = [
"Programming Language :: Python",
"Operating System :: OS Independent",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Development Status :: 5 - Production/Stable",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Communications :: Telephony"
],
long_description = """\
Python Twilio Helper Library
----------------------------
DESCRIPTION
The Twilio REST SDK simplifies the process of makes calls to the Twilio REST.
The Twilio REST API lets to you initiate outgoing calls, list previous call,
and much more. See http://www.twilio.com/docs for more information.
USAGE
To use the Twilio library, just 'import twilio' in the your current py
file. As shown in example-rest.py, you will need to specify the ACCOUNT_ID
and ACCOUNT_TOKEN given to you by Twilio before you can make REST
requests. In addition, you will need to choose a 'To' and 'From' before
making outgoing calls. See http://www.twilio.com/docs for more
information.
LICENSE The Twilio Python Helper Library is distributed under the MIT
License """ )
| mit | Python | |
ff48d7a242e1b8c67faa7a4b5ab43e641a1dd910 | add setup.py | faycheng/tpl,faycheng/tpl | setup.py | setup.py | # -*- coding:utf-8 -*-
from setuptools import find_packages, setup
README = """# tpl
"""
setup(
name='tpl',
version='0.1.0',
description='Command line utility for generating files or directories from template',
long_description=README,
author='程飞',
url='https://github.com/faycheng/tpl.git',
packages=find_packages(exclude=['tests']),
install_requires=['prompt_toolkit==1.0.15', 'six==1.10.0', 'pytest==3.2.1', 'Jinja2==2.9.6', 'click==6.7', 'delegator.py==0.0.13', 'delegator==0.0.3'],
entry_points={
'console_scripts': ['tpl=cli:tpl'],
},
py_modules=['cli'],
zip_safe=True,
license='MIT License',
classifiers=['development status :: 1 - planning', 'topic :: utilities', 'intended audience :: developers', 'programming language :: python :: 3 :: only', 'environment :: macos x']
) | mit | Python | |
6df13e80a4684a11ccbc53d9b30bb54067ce8196 | correct app URL | sventech/YAK-server,ParableSciences/YAK-server,ParableSciences/YAK-server,yeti/YAK-server,yeti/YAK-server,sventech/YAK-server | setup.py | setup.py | import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='yak-server',
version='0.1',
packages=['yak'],
install_requires=[
'Django>=1.7',
'djangorestframework>=3.0.0, !=3.0.1',
'Pillow>=2.5',
'django-filter>=0.7',
'django-model-utils>=2.0',
'django-oauth-toolkit>=0.7.2',
'facebook-sdk==0.4.0',
'factory-boy>=2.4',
'mock>=1.0',
'python-instagram>=1.3.0',
'python-memcached>=1.53',
'python-social-auth>=0.2',
'python-swiftclient>=2.2',
'requests>=2.1',
'requests-oauthlib>=0.4',
'twython>=3.1'
],
dependency_links=[
"git+ssh://git@github.com/jbalogh/django-cache-machine.git#egg=django_cache_machine-master"
],
include_package_data=True,
license='BSD License',
description='Server-side implementation of Yeti App Kit built on Django',
long_description=README,
url='https://yeti.co/yeti-app-kit/',
author='Baylee Feore',
author_email='baylee@yeti.co',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='yak-server',
version='0.1',
packages=['yak'],
install_requires=[
'Django>=1.7',
'djangorestframework>=3.0.0, !=3.0.1',
'Pillow>=2.5',
'django-filter>=0.7',
'django-model-utils>=2.0',
'django-oauth-toolkit>=0.7.2',
'facebook-sdk==0.4.0',
'factory-boy>=2.4',
'mock>=1.0',
'python-instagram>=1.3.0',
'python-memcached>=1.53',
'python-social-auth>=0.2',
'python-swiftclient>=2.2',
'requests>=2.1',
'requests-oauthlib>=0.4',
'twython>=3.1'
],
dependency_links=[
"git+ssh://git@github.com/jbalogh/django-cache-machine.git#egg=django_cache_machine-master"
],
include_package_data=True,
license='BSD License',
description='Server-side implementation of Yeti App Kit built on Django',
long_description=README,
url='http://www.yetiappkit.com/',
author='Baylee Feore',
author_email='baylee@yeti.co',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
) | mit | Python |
7f9dee365f27bf288fae513739651462b8c78071 | Create setup.py | GhostHackzDev/setbadge | setup.py | setup.py | from setuptools import setup
def readme():
with open('README.rst') as f:
return f.read()
setup(name='setbadge',
version='0.0.1',
description='Set the Pythonista app\'s badge value to a custom text string!',
long_description=readme(),
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.5',
'Topic :: Text Processing :: Linguistic'
],
keywords='pythonista objc ios badge notification',
url='https://github.com/GhostHackzDev/setbadge',
author='Ghost Hackz',
author_email='ghosthackz@pginteractive.ml',
license='MIT',
packages=['setbadge'],
include_package_data=True,
zip_safe=False)
| mit | Python | |
17e66f79118f87aea452f7ca658142e6d5d71a1b | Add shell.py | clayadavis/OpenKasm,clayadavis/OpenKasm | shell.py | shell.py | import pymongo as pm
client = pm.MongoClient()
db = client.kasm
redirects = db.redirects
## list(redirects.find())
| mit | Python | |
1348f5c9068aa4059ed41ee03635c7da6f5b04f0 | add max_path_sum | haandol/algorithm_in_python | tree/max_path_sum.py | tree/max_path_sum.py | # http://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def run(root, s):
if not root:
return 0
max_child = max(run(root.left, s), run(root.right, s))
return s + max(root.value, root.value + max_child)
def solution(root):
left = run(root.left, 0)
right = run(root.right, 0)
return max(
[root.value, root.value + left + right, root.value + max(left, right)]
)
if __name__ == '__main__':
root = Node(10)
root.left = Node(2)
root.right = Node(10)
root.left.left = Node(20)
root.left.right = Node(1)
root.right.right = Node(-25)
root.right.right.left = Node(3)
root.right.right.right = Node(4)
print(solution(root))
| mit | Python | |
71bfe8974e3274c80c2fd6d1be4c54a24345a0e7 | add test_rgw | ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph,ajnelson/ceph | src/test/pybind/test_rgw.py | src/test/pybind/test_rgw.py | from nose.tools import eq_ as eq, assert_raises
from rgw import Rgw
def test_rgw():
rgw = Rgw()
xml = """<AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Owner>
<ID>foo</ID>
<DisplayName>MrFoo</DisplayName>
</Owner>
<AccessControlList>
<Grant>
<Grantee xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"CanonicalUser\">
<ID>bar</ID>
<DisplayName>display-name</DisplayName>
</Grantee>
<Permission>FULL_CONTROL</Permission>
</Grant>
</AccessControlList>
</AccessControlPolicy>"""
blob = rgw.acl_xml2bin(xml)
converted_xml = rgw.acl_bin2xml(blob)
converted_blob = rgw.acl_xml2bin(converted_xml)
eq(blob, converted_blob)
| lgpl-2.1 | Python | |
2c444b9ebc03aaef77b12e7d649f9f7359681420 | Add : first attempt of a webservice commands for the arbiter. | kaji-project/shinken,lets-software/shinken,fpeyre/shinken,titilambert/alignak,mohierf/shinken,lets-software/shinken,KerkhoffTechnologies/shinken,claneys/shinken,geektophe/shinken,staute/shinken_package,titilambert/alignak,geektophe/shinken,geektophe/shinken,h4wkmoon/shinken,fpeyre/shinken,rledisez/shinken,dfranco/shinken,kaji-project/shinken,staute/shinken_deb,lets-software/shinken,KerkhoffTechnologies/shinken,savoirfairelinux/shinken,tal-nino/shinken,peeyush-tm/shinken,Aimage/shinken,gst/alignak,staute/shinken_deb,naparuba/shinken,Alignak-monitoring/alignak,claneys/shinken,gst/alignak,titilambert/alignak,h4wkmoon/shinken,mohierf/shinken,savoirfairelinux/shinken,mohierf/shinken,Aimage/shinken,fpeyre/shinken,tal-nino/shinken,Aimage/shinken,ddurieux/alignak,peeyush-tm/shinken,mohierf/shinken,Simage/shinken,h4wkmoon/shinken,geektophe/shinken,fpeyre/shinken,rledisez/shinken,KerkhoffTechnologies/shinken,ddurieux/alignak,tal-nino/shinken,h4wkmoon/shinken,KerkhoffTechnologies/shinken,Simage/shinken,tal-nino/shinken,xorpaul/shinken,h4wkmoon/shinken,naparuba/shinken,Aimage/shinken,rednach/krill,claneys/shinken,lets-software/shinken,geektophe/shinken,staute/shinken_deb,dfranco/shinken,rednach/krill,KerkhoffTechnologies/shinken,geektophe/shinken,kaji-project/shinken,xorpaul/shinken,Simage/shinken,staute/shinken_package,savoirfairelinux/shinken,xorpaul/shinken,ddurieux/alignak,kaji-project/shinken,rledisez/shinken,xorpaul/shinken,savoirfairelinux/shinken,peeyush-tm/shinken,kaji-project/shinken,staute/shinken_package,titilambert/alignak,claneys/shinken,peeyush-tm/shinken,xorpaul/shinken,lets-software/shinken,naparuba/shinken,Aimage/shinken,fpeyre/shinken,staute/shinken_package,staute/shinken_deb,dfranco/shinken,claneys/shinken,gst/alignak,Aimage/shinken,savoirfairelinux/shinken,Simage/shinken,tal-nino/shinken,peeyush-tm/shinken,naparuba/shinken,mohierf/shinken,KerkhoffTechnologies/shinken,rledisez/shinken,claneys/shinken,staute/shinken_package,Simage/shinken,xorpaul/shinken,savoirfairelinux/shinken,rednach/krill,fpeyre/shinken,rednach/krill,xorpaul/shinken,naparuba/shinken,rledisez/shinken,h4wkmoon/shinken,naparuba/shinken,xorpaul/shinken,h4wkmoon/shinken,dfranco/shinken,kaji-project/shinken,dfranco/shinken,peeyush-tm/shinken,gst/alignak,ddurieux/alignak,Simage/shinken,Alignak-monitoring/alignak,ddurieux/alignak,h4wkmoon/shinken,staute/shinken_deb,staute/shinken_package,ddurieux/alignak,kaji-project/shinken,tal-nino/shinken,dfranco/shinken,mohierf/shinken,rednach/krill,rednach/krill,rledisez/shinken,staute/shinken_deb,lets-software/shinken | shinken/modules/ws_arbiter.py | shinken/modules/ws_arbiter.py | #!/usr/bin/python
#Copyright (C) 2009 Gabes Jean, naparuba@gmail.com
#
#This file is part of Shinken.
#
#Shinken 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.
#
#Shinken 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 Shinken. If not, see <http://www.gnu.org/licenses/>.
# This Class is an Arbiter module for having a webservice
# wher you can push external commands
import os
import select
######################## WIP don't launch it!
from shinken.basemodule import BaseModule
from shinken.external_command import ExternalCommand
from shinken.webui.bottle import Bottle, run, static_file, view, route, request, response, abort
properties = {
'daemons' : ['arbiter', 'receiver'],
'type' : 'ws_arbiter',
'external' : True,
}
#called by the plugin manager to get a broker
def get_instance(plugin): # plugin: dict de la conf
print "aide en une ligne %s" % plugin.get_name()
instance = Ws_arbiter(plugin)
return instance
#Just print some stuff
class Ws_arbiter(BaseModule):
def __init__(self, modconf):
BaseModule.__init__(self, modconf)
try:
username = modconf.username
password = modconf.password
self.port = modconf.port
self.host = '0.0.0.0'
except AttributeError:
print "Error : the module '%s' do not have a property"
raise
def get(self):
buf = os.read(self.fifo, 8096)
r = []
fullbuf = len(buf) == 8096 and True or False
# If the buffer ended with a fragment last time, prepend it here
buf = self.cmd_fragments + buf
buflen = len(buf)
self.cmd_fragments = ''
if fullbuf and buf[-1] != '\n':
# The buffer was full but ends with a command fragment
r.extend([ExternalCommand(s) for s in (buf.split('\n'))[:-1] if s])
self.cmd_fragments = (buf.split('\n'))[-1]
elif buflen:
# The buffer is either half-filled or full with a '\n' at the end.
r.extend([ExternalCommand(s) for s in buf.split('\n') if s])
else:
# The buffer is empty. We "reset" the fifo here. It will be
# re-opened in the main loop.
os.close(self.fifo)
return r
def get_page(self):
print "On me demande la page /push"
time_stamp = request.forms.get('time_stamp', 0)
host_name = request.forms.get('host_name', None)
service_description = request.forms.get('service_description', None)
return_code = request.forms.get('return_code', -1)
output = request.forms.get('output', None)
if time_stamp==0 or not host_name or not service_description or not output or return_code == -1:
print "Je ne suis pas content, je quitte"
abort(400, "blalna")
def init_http(self):
print "Starting WebUI application"
self.srv = run(host=self.host, port=self.port, server='wsgirefselect')
print "Launch server", self.srv
route('/push', callback=self.get_page,method='POST')
# When you are in "external" mode, that is the main loop of your process
def main(self):
self.set_exit_handler()
self.init_http()
input = [self.srv.socket]
# Main blocking loop
while not self.interrupted:
# _reader is the underliying file handle of the Queue()
# so we can select it too :)
input = [self.srv.socket]
inputready,_,_ = select.select(input,[],[], 1)
for s in inputready:
# If it's a web request, ask the webserver to do it
if s == self.srv.socket:
#print "Handle Web request"
self.srv.handle_request()
| agpl-3.0 | Python | |
15c7b734bcd830b819bfbafdf94da48931dd7b7b | Create get-img.py | HaydnAnderson/image-downloader | get-img.py | get-img.py | import urllib, json, sys, os.path, argparse
import hashlib
import time
import re
# //==== EDIT THIS ====\\
log_file = open('log.txt', 'r+')
username = 'dronenerds'
sleep_time = 120
download_img = False
console_log = True
download_img1 = True
path_name = 'images/'
# //==== EDIT THIS ====\\
def find_new_images(images, existing):
ids = [i['id'] for i in existing]
return [i for i in images if i['id'] not in ids]
def get_img(username):
url = 'http://www.instagram.com/{}/media'.format(username)
response = urllib.urlopen(url)
data = json.loads(response.read())
return data['items']
def download_image(url):
filename = url.split('/')[-1]
fullfilename = os.path.join(path_name, filename)
urllib.urlretrieve(url, fullfilename)
def get_url(geturl):
instaurl = geturl['images']['standard_resolution']['url']
path = re.sub(r'\w\d{3}x\d{3}\/', '', instaurl)
path = path.split('?')[0]
return path
def get_args():
parser = argparse.ArgumentParser(description='Download images from Instagram')
parser.add_argument('-u', '--username', type=str, help='Instagram username')
parser.add_argument('-s', '--sleep', type=int, default=120, help='How long to sleep inbetween checks')
parser.add_argument('-d', '--dry-run', action='store_false', help='Don\'t actually download old images, but download new ones')
parser.add_argument('-i', '--i-path', type= str, default='images/', help='Image download folder')
args = parser.parse_args()
return args.username, args.sleep, args.dry_run, args.i_path
def main():
if console_log:
username, sleep_time, download_img1, path_name = get_args()
else:
pass
print "Getting twenty photos from {}".format(username)
images = get_img(username)
if not os.path.exists(path_name):
os.makedirs(path_name)
if download_img:
print "Downloading..."
for i in images:
download_image(get_url(i))
last = images
while True:
time.sleep(sleep_time)
images = get_img(username)
new_images = find_new_images(images, last)
last = images
if new_images:
print "{} new post(s)".format(len(new_images))
if download_img1:
for image in new_images:
download_image(get_url(image))
if __name__ == "__main__":
sys.exit(main())
| mit | Python | |
f4504fdb70cff7089164f0cc9ae30e972d61ec30 | add lux.py | zbanks/aurora,zbanks/aurora,zbanks/aurora,zbanks/aurora,zbanks/aurora,zbanks/aurora,zbanks/aurora | lux/lux.py | lux/lux.py | import logging
import serial
import time
logger = logging.getLogger(__name__)
class SingleLuxDevice(object):
def __init__(self, port, baudrate=115200):
self.ser = serial.Serial(port, baudrate)
self.addresses = {}
def close(self):
self.ser.close()
def raw_packet(self, data):
logger.debug("Serial Data: %s", ';'.join(map(lambda x: "{:02x}".format(x), data)))
#print ("Serial Data: %s", ';'.join(map(lambda x: "{:02x}".format(x), data)))
self.ser.write("".join([chr(d) for d in data]))
def flush(self):
self.ser.flush()
def cobs_packet(self, data):
#print ("Not encoded: %s", ';'.join(map(lambda x: "{:02x}".format(x), data)))
rdata = []
i = 0
for d in data[::-1]:
i += 1
if d == 0:
rdata.append(i)
i = 0
else:
rdata.append(d)
self.raw_packet([0, i+1] + rdata[::-1])
def framed_packet(self, data=None, flags=0x00, addr=0x00):
if data is None or len(data) > 250:
raise Exception("invalid data")
data=list(data)
while len(data) < 8:
data.append(0)
crc_frame = [addr, flags] + data
checksum = sum(crc_frame) & 0xff
frame = [len(data), checksum] + crc_frame
self.cobs_packet(frame)
| mit | Python | |
80b47093f6ccbe75be7e4382e0cfd948c868763d | add new log of media test (#3265) | wandb/client,wandb/client,wandb/client | functional_tests/core/05-log-media.py | functional_tests/core/05-log-media.py | #!/usr/bin/env python
"""Base case - logging sequence of media types multiple times
---
id: 0.core.05-log-media
plugin:
- wandb
- numpy
assert:
- :wandb:runs_len: 1
- :wandb:runs[0][config]: {}
- :wandb:runs[0][summary][media][count]: 2
- :wandb:runs[0][summary][media][_type]: images/separated
- :wandb:runs[0][summary][media][format]: png
- :wandb:runs[0][summary][media][height]: 2
- :wandb:runs[0][summary][media][width]: 2
- :wandb:runs[0][exitcode]: 0
"""
import numpy as np
import wandb
height = width = 2
run = wandb.init()
media = []
for image in [np.random.rand(height, width) for _ in range(2)]:
media.append(wandb.Image(image))
run.log({"media": media}, commit=False)
| mit | Python | |
ee6ab9fc5f580267f089108dc9c27a8a0208ebf0 | Add __init__.py to make it work like a module | akazs/pySMOTE | pySMOTE/__init__.py | pySMOTE/__init__.py | from .smote import SMOTE
| mit | Python | |
76ce99ba04151a00ee1101ebed4f883fd1112433 | Create mad-lib.py | eringrace/hello-world | mad-lib.py | mad-lib.py | skill = raw_input("What's a skill you want to learn?:")
adverb = raw_input("Enter an adverb:")
animal = raw_input("Name an animal:")
body = raw_input("Name a body part:")
event = raw_input("Name a fun event:")
emotion1 = raw_input("Name a positive emotion (past tense):")
emotion2 = raw_input("Name another positive emotion (past tense):")
print "Once upon a time there was a gir who wanted to learn %s. She worked %s every day until she learned how to do it. Then the %ss raised her on their %ss and had a %s in her honor. They were %s and %s that she had learned %s." % (skill, adverb, animal, body, event, emotion1, emotion2, skill)
| mit | Python | |
c20abf6b2ae6cb2518971ea03b7edbf7035b1661 | send email to system managers about gst setup | geekroot/erpnext,gsnbng/erpnext,Aptitudetech/ERPNext,indictranstech/erpnext,indictranstech/erpnext,geekroot/erpnext,gsnbng/erpnext,indictranstech/erpnext,gsnbng/erpnext,geekroot/erpnext,geekroot/erpnext,indictranstech/erpnext,gsnbng/erpnext | erpnext/patches/v8_1/setup_gst_india.py | erpnext/patches/v8_1/setup_gst_india.py | import frappe
from frappe.email import sendmail_to_system_managers
def execute():
frappe.reload_doc('regional', 'doctype', 'gst_hsn_code')
for report_name in ('GST Sales Register', 'GST Purchase Register',
'GST Itemised Sales Register', 'GST Itemised Purchase Register'):
frappe.reload_doc('regional', 'report', frappe.scrub(report_name))
if frappe.db.get_single_value('System Settings', 'country')=='India':
from erpnext.regional.india.setup import setup
setup()
send_gst_update_email()
def send_gst_update_email():
message = """Hello,
<p>ERPNext is now GST Ready.</p>
<p>To start making GST Invoices from 1st of July, you just need to create new Tax Accounts, Templates and update your Customer's and Supplier's GST Numbers.</p>
<p>Please refer {gst_document_link} to know more about how to setup and implement GST in ERPNext.</p>
<p>Please contact us at support@erpnext.com, if you have any questions.</p>
<p>Thanks,</p>
ERPNext Team.
""".format(gst_document_link="<a href='http://frappe.github.io/erpnext/user/manual/en/regional/india/'> ERPNext GST Document </a>")
sendmail_to_system_managers("[Important] ERPNext GST updates", message)
| import frappe
def execute():
frappe.reload_doc('regional', 'doctype', 'gst_hsn_code')
for report_name in ('GST Sales Register', 'GST Purchase Register',
'GST Itemised Sales Register', 'GST Itemised Purchase Register'):
frappe.reload_doc('regional', 'report', frappe.scrub(report_name))
if frappe.db.get_single_value('System Settings', 'country')=='India':
from erpnext.regional.india.setup import setup
setup()
| agpl-3.0 | Python |
0c1ef1267a67ce103f5ba0545bae690ce77c8180 | Add a deploy script | asana/python-asana,asana/python-asana,Asana/python-asana | deploy.py | deploy.py | #!/usr/bin/env python
"""
Script for deploying a new version of the python-asana library.
"""
import argparse
import re
import subprocess
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'version',
help='Version to deploy as, in format x.y.z')
args = parser.parse_args()
if not re.match('[0-9]+[.][0-9]+[.][0-9]+', args.version):
print 'Invalid version: %s' % args.version
sys.exit(1)
version_file = open('asana/version.py', 'w')
print >>version_file, "VERSION = '%s'" % args.version
subprocess.call(
'git commit -m "Releasing version %s"' % args.version, shell=True)
subprocess.call(
'git tag %s' % args.version, shell=True)
subprocess.call(
'git push --tags origin master:master', shell=True)
print 'Successfully deployed version %s' % args.version
| mit | Python | |
8255772770e20f51338da36dc7fa027b4dc0f07e | Allow photos in pages | tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop | awesomeshop/photo.py | awesomeshop/photo.py | import os.path, uuid
from PIL import Image
from flask.ext.babel import lazy_gettext
from . import app, db
thumb_size = app.config['THUMBNAIL_SIZE']
preview_size = app.config['PREVIEW_SIZE']
class Photo(db.EmbeddedDocument):
filename = db.StringField(db_field='fname', max_length=50,
verbose_name=lazy_gettext('Filename'))
@classmethod
def from_request(cls, photo):
filename, file_extension = os.path.splitext(photo.filename)
# Create the directory
if not os.path.exists(os.path.join(app.static_folder, 'photos')):
os.mkdir(os.path.join(app.static_folder, 'photos'))
# Store the image
photo_filename = str(uuid.uuid4()) + file_extension
filepath = os.path.join(app.static_folder, 'photos', photo_filename)
photo.save(filepath)
# Create the thumbnail
thumbpath = os.path.join(app.static_folder, 'photos',
'thumb.'+photo_filename)
image = Image.open(filepath)
image.thumbnail(thumb_size)
image.save(thumbpath, "JPEG")
# Create the preview
previewpath = os.path.join(app.static_folder, 'photos',
'preview.'+photo_filename)
image = Image.open(filepath)
image.thumbnail(preview_size)
image.save(previewpath, "JPEG")
# Return the document
return cls(filename=photo_filename)
def delete_files(self):
n = os.path.join(app.static_folder, 'photos', self.filename)
if os.path.exists(n): os.remove(n)
p = os.path.join(app.static_folder, 'photos', 'preview.'+self.filename)
if os.path.exists(p): os.remove(p)
t = os.path.join(app.static_folder, 'photos', 'thumb.'+self.filename)
if os.path.exists(t): os.remove(t)
@property
def url(self):
return os.path.join(app.static_url_path, 'photos', self.filename)
@property
def preview_url(self):
return os.path.join(app.static_url_path, 'photos',
'preview.'+self.filename)
@property
def thumbnail_url(self):
return os.path.join(app.static_url_path, 'photos',
'thumb.'+self.filename)
| agpl-3.0 | Python | |
6c52676493bbf4d8f64a65712034b18bbee279ba | Create syracuse.py | DavidMellul/Projets,DavidMellul/Projets,DavidMellul/Projets,DavidMellul/Projets,DavidMellul/Projets,DavidMellul/Projets,DavidMellul/Projets | python/syracuse/syracuse.py | python/syracuse/syracuse.py | n = int(input("Veuillez saisir un entier : "))
vol = 0
while(n != 1):
if(n % 2 == 0):
n /= 2
else:
n = n*3 + 1
vol +=1
print("Le temps de vol du nombre ",n," est ",vol)
| mit | Python | |
1064634cb9f3752e890b56bfddb49e51e70e530b | add munin alert script | cuongnb14/cookbook,cuongnb14/cookbook | python/utils/munin_alert.py | python/utils/munin_alert.py | #! /usr/bin/env python3
"""
Script to send email alert for munin
Munin Config: munin.conf
contact.admin.command | /path/to/munin_alert.py
contact.admin.max_messages 1
@author: cuongnb14@gmail.com
"""
import smtplib
import fileinput
import logging
logger = logging.getLogger('munin_alert')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('munin_alert.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
subject = "Munin Alert"
content = ""
from_addr = 'munin@gmail.com'
to_addrs = "cuongnb@gmail.com"
try:
for line in fileinput.input():
content = content + line + "\n"
msg = 'From: {}\nSubject: {}\n\n{}'.format(from_addr, subject, content)
username = from_addr
password = '123456'
print("Sending... mail to {}".format(to_addrs))
logger.info("================================================")
logger.info("Sending... mail to {}".format(to_addrs))
logger.info("------------------------------------------------")
logger.info("Message \n{}".format(msg))
# Example for gmail, change to your server mail.
server = smtplib.SMTP('mail.gmail.com:587')
# identify ourselves, prompting server for supported features
server.ehlo()
# If you can encrypt this session, do it
if server.has_extn('STARTTLS'):
server.starttls()
# re-identify ourselves over TLS connection
server.ehlo()
server.login(username, password)
server.sendmail(from_addr, to_addrs, msg)
server.quit()
except Exception:
logger.exception()
| mit | Python | |
23ad0bf077c846e13e8b970f8928f06d02d658a3 | Make initial migration | EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat | students/migrations/0001_initial.py | students/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('master_data', '0001_initial'),
('back_office', '0007_teacher_nationality'),
]
operations = [
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=25, verbose_name='Name')),
('dob', models.DateField()),
('gender', models.CharField(default=b'M', max_length=1, verbose_name='Gender', choices=[('M', 'Male'), ('F', 'Female')])),
('civil_id', models.CharField(unique=True, max_length=12, verbose_name='Civil ID')),
('mobile_number', models.CharField(max_length=12, verbose_name='Mobile')),
('home_number', models.CharField(max_length=12, verbose_name='Home')),
('parent_number', models.CharField(max_length=12, verbose_name='Parents')),
('grade', models.CharField(max_length=5, verbose_name='Grade')),
('school', models.CharField(max_length=12, verbose_name='School')),
('address', models.CharField(max_length=150, verbose_name='Address')),
('email', models.EmailField(max_length=254, verbose_name='Email')),
('parent_email', models.EmailField(max_length=254, verbose_name='Parent Email')),
('enrollment_date', models.DateField(verbose_name='Enrollment Date')),
('old_enrollment_date', models.DateField(verbose_name='Pervious Center Enrollment Date')),
('chapter_memeorized', models.IntegerField(verbose_name='chapter Memeorized')),
('chapter_memeorized_with_center', models.IntegerField(verbose_name='chapters memeorized with center')),
('status', models.CharField(default=b'P', max_length=1, verbose_name='Status', choices=[(b'P', 'Pending'), (b'A', 'Active'), (b'S', 'Suspended'), (b'L', 'On Leave')])),
('halaqat_class', models.ForeignKey(to='back_office.Class')),
('nationality', models.ForeignKey(verbose_name='Nationality', to='master_data.Nationality', null=True)),
],
),
]
| mit | Python | |
1334b085f76db914ede6b941c23ea61329df1fbd | Create relaycontrol.py | pumanzor/security,pumanzor/security,pumanzor/security | raspberrypi/relaycontrol.py | raspberrypi/relaycontrol.py | import paho.mqtt.client as mqtt
import json, time
import RPi.GPIO as GPIO
from time import sleep
# The script as below using BCM GPIO 00..nn numbers
GPIO.setmode(GPIO.BCM)
# Set relay pins as output
GPIO.setup(24, GPIO.OUT)
# ----- CHANGE THESE FOR YOUR SETUP -----
MQTT_HOST = "190.97.168.236"
MQTT_PORT = 1883
USERNAME = ''
PASSWORD = ""
# ---------------------------------------
def on_connect(client, userdata, rc):
print("\nConnected with result code " + str(rc) + "\n")
#Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/iot/control/")
print("Subscribed to iotcontrol")
def on_message_iotrl(client, userdata, msg):
print("\n\t* Raspberry UPDATED ("+msg.topic+"): " + str(msg.payload))
if msg.payload == "gpio24on":
GPIO.output(24, GPIO.HIGH)
client.publish("/iot/status", "Relay gpio18on", 2)
if msg.payload == "gpio24off":
GPIO.output(24, GPIO.LOW)
client.publish("/iot/status", "Relay gpio18off", 2)
def command_error():
print("Error: Unknown command")
client = mqtt.Client(client_id="rasp-g1")
# Callback declarations (functions run based on certain messages)
client.on_connect = on_connect
client.message_callback_add("/iot/control/", on_message_iotrl)
# This is where the MQTT service connects and starts listening for messages
client.username_pw_set(USERNAME, PASSWORD)
client.connect(MQTT_HOST, MQTT_PORT, 60)
client.loop_start() # Background thread to call loop() automatically
# Main program loop
while True:
time.sleep(10)
| mit | Python | |
f5ca504a390b8db3432dc7d67f934cd29daf3086 | add openssl recipe | cbenhagen/kivy-ios,tonibagur/kivy-ios,tonibagur/kivy-ios,rnixx/kivy-ios,kivy/kivy-ios,rnixx/kivy-ios,cbenhagen/kivy-ios,kivy/kivy-ios,kivy/kivy-ios | recipes/openssl/__init__.py | recipes/openssl/__init__.py | from toolchain import Recipe, shprint
from os.path import join, exists
import sh
import os
arch_mapper = {'i386': 'darwin-i386-cc',
'x86_64': 'darwin64-x86_64-cc',
'armv7': 'iphoneos-cross',
'arm64': 'iphoneos-cross'}
class OpensslRecipe(Recipe):
version = "1.0.2a"
url = "http://www.openssl.org/source/openssl-{version}.tar.gz"
libraries = ["libssl.a", "libcrypto.a"]
include_dir = "include"
include_per_arch = True
def build_arch(self, arch):
options_iphoneos = (
"-isysroot {}".format(arch.sysroot),
"-DOPENSSL_THREADS",
"-D_REENTRANT",
"-DDSO_DLFCN",
"-DHAVE_DLFCN_H",
"-fomit-frame-pointer",
"-fno-common",
"-O3"
)
build_env = arch.get_env()
target = arch_mapper[arch.arch]
shprint(sh.env, _env=build_env)
sh.perl(join(self.build_dir, "Configure"),
target,
_env=build_env)
if target == 'iphoneos-cross':
sh.sed("-ie", "s!^CFLAG=.*!CFLAG={} {}!".format(build_env['CFLAGS'],
" ".join(options_iphoneos)),
"Makefile")
sh.sed("-ie", "s!static volatile sig_atomic_t intr_signal;!static volatile intr_signal;! ",
"crypto/ui/ui_openssl.c")
else:
sh.sed("-ie", "s!^CFLAG=!CFLAG={} !".format(build_env['CFLAGS']),
"Makefile")
shprint(sh.make, "clean")
shprint(sh.make, "-j4", "build_libs")
recipe = OpensslRecipe()
| mit | Python | |
e4bf4091ea267cae2c584c8a442f57d3dda0cbf8 | Create wksp2.py | indigohedgehog/RxWorkshopPy | wksp2.py | wksp2.py | """Rx Workshop: Observables versus Events.
Part 1 - Little Example.
Usage:
python wksp2.py
"""
from __future__ import print_function
import rx
class Program:
"""Main Class.
"""
S = rx.subjects.Subject()
@staticmethod
def main():
"""Main Method.
"""
p = Program()
p.S.subscribe(lambda x: print(x))
p.S.on_next(1)
p.S.on_next(2)
p.S.on_next(3)
if __name__ == '__main__':
p = Program()
p.main()
| mit | Python | |
a1744d6a6f4c369403ac2ed67f167ca1ecd9cb5e | add input output outline | novastorm/Python-Playground | input-output.py | input-output.py | # input-output.py
# review console I/O
# CLI parameters
# file I/O
| mit | Python | |
72a6ca31ac313b89b5e4ce509c635f675484cf3e | Create solution.py | lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms,lilsweetcaligula/Algorithms | data_structures/linked_list/problems/find_length/py/solution.py | data_structures/linked_list/problems/find_length/py/solution.py | import LinkedList
# Problem description: Find the length of a linked list.
# Solution time complexity: O(n)
# Comments:
# Linked List Node inside the LinkedList module is declared as:
#
# class Node:
# def __init__(self, val, nxt=None):
# self.val = val
# self.nxt = nxt
#
def FindLength(head: LinkedList.Node) -> int:
node = head
count = 0
while node != None:
count += 1
node = node.nxt
return count
| mit | Python | |
ed6958f477c65a2973d43d669035de80b7cbd7a5 | Change needs_auth ZeroConf key | bdfoster/blumate,shaftoe/home-assistant,HydrelioxGitHub/home-assistant,LinuxChristian/home-assistant,emilhetty/home-assistant,deisi/home-assistant,jabesq/home-assistant,hexxter/home-assistant,mKeRix/home-assistant,jabesq/home-assistant,miniconfig/home-assistant,ct-23/home-assistant,postlund/home-assistant,Julian/home-assistant,miniconfig/home-assistant,ma314smith/home-assistant,titilambert/home-assistant,Teagan42/home-assistant,JshWright/home-assistant,Duoxilian/home-assistant,ewandor/home-assistant,lukas-hetzenecker/home-assistant,varunr047/homefile,ma314smith/home-assistant,ewandor/home-assistant,w1ll1am23/home-assistant,soldag/home-assistant,Danielhiversen/home-assistant,varunr047/homefile,lukas-hetzenecker/home-assistant,tchellomello/home-assistant,dmeulen/home-assistant,tboyce021/home-assistant,toddeye/home-assistant,sffjunkie/home-assistant,eagleamon/home-assistant,varunr047/homefile,nugget/home-assistant,keerts/home-assistant,Smart-Torvy/torvy-home-assistant,devdelay/home-assistant,Zyell/home-assistant,deisi/home-assistant,FreekingDean/home-assistant,leoc/home-assistant,leoc/home-assistant,robjohnson189/home-assistant,sdague/home-assistant,shaftoe/home-assistant,happyleavesaoc/home-assistant,tboyce1/home-assistant,JshWright/home-assistant,stefan-jonasson/home-assistant,ct-23/home-assistant,kyvinh/home-assistant,rohitranjan1991/home-assistant,jawilson/home-assistant,open-homeautomation/home-assistant,GenericStudent/home-assistant,Cinntax/home-assistant,Smart-Torvy/torvy-home-assistant,ma314smith/home-assistant,molobrakos/home-assistant,rohitranjan1991/home-assistant,balloob/home-assistant,partofthething/home-assistant,keerts/home-assistant,kyvinh/home-assistant,fbradyirl/home-assistant,alexmogavero/home-assistant,mikaelboman/home-assistant,happyleavesaoc/home-assistant,devdelay/home-assistant,alexmogavero/home-assistant,hmronline/home-assistant,mezz64/home-assistant,miniconfig/home-assistant,shaftoe/home-assistant,Zac-HD/home-assistant,varunr047/homefile,molobrakos/home-assistant,hexxter/home-assistant,joopert/home-assistant,keerts/home-assistant,open-homeautomation/home-assistant,nkgilley/home-assistant,persandstrom/home-assistant,HydrelioxGitHub/home-assistant,MungoRae/home-assistant,emilhetty/home-assistant,leoc/home-assistant,sffjunkie/home-assistant,bdfoster/blumate,mKeRix/home-assistant,jabesq/home-assistant,philipbl/home-assistant,pschmitt/home-assistant,LinuxChristian/home-assistant,Duoxilian/home-assistant,bdfoster/blumate,jamespcole/home-assistant,leppa/home-assistant,Teagan42/home-assistant,stefan-jonasson/home-assistant,aequitas/home-assistant,jamespcole/home-assistant,adrienbrault/home-assistant,qedi-r/home-assistant,MartinHjelmare/home-assistant,Julian/home-assistant,tchellomello/home-assistant,tinloaf/home-assistant,LinuxChristian/home-assistant,hexxter/home-assistant,keerts/home-assistant,pschmitt/home-assistant,auduny/home-assistant,srcLurker/home-assistant,srcLurker/home-assistant,hmronline/home-assistant,balloob/home-assistant,GenericStudent/home-assistant,betrisey/home-assistant,sander76/home-assistant,ct-23/home-assistant,molobrakos/home-assistant,PetePriority/home-assistant,DavidLP/home-assistant,persandstrom/home-assistant,FreekingDean/home-assistant,toddeye/home-assistant,turbokongen/home-assistant,dmeulen/home-assistant,JshWright/home-assistant,fbradyirl/home-assistant,bdfoster/blumate,leppa/home-assistant,Julian/home-assistant,xifle/home-assistant,emilhetty/home-assistant,emilhetty/home-assistant,sffjunkie/home-assistant,jaharkes/home-assistant,srcLurker/home-assistant,Danielhiversen/home-assistant,jaharkes/home-assistant,robjohnson189/home-assistant,nugget/home-assistant,hmronline/home-assistant,mKeRix/home-assistant,bdfoster/blumate,deisi/home-assistant,hmronline/home-assistant,jnewland/home-assistant,Julian/home-assistant,florianholzapfel/home-assistant,philipbl/home-assistant,sffjunkie/home-assistant,oandrew/home-assistant,w1ll1am23/home-assistant,Zyell/home-assistant,aronsky/home-assistant,sander76/home-assistant,xifle/home-assistant,balloob/home-assistant,Zac-HD/home-assistant,oandrew/home-assistant,open-homeautomation/home-assistant,dmeulen/home-assistant,stefan-jonasson/home-assistant,MungoRae/home-assistant,JshWright/home-assistant,joopert/home-assistant,open-homeautomation/home-assistant,mezz64/home-assistant,devdelay/home-assistant,florianholzapfel/home-assistant,turbokongen/home-assistant,ma314smith/home-assistant,kyvinh/home-assistant,soldag/home-assistant,morphis/home-assistant,deisi/home-assistant,home-assistant/home-assistant,alexmogavero/home-assistant,PetePriority/home-assistant,HydrelioxGitHub/home-assistant,leoc/home-assistant,betrisey/home-assistant,kyvinh/home-assistant,Zac-HD/home-assistant,nugget/home-assistant,Smart-Torvy/torvy-home-assistant,tinloaf/home-assistant,xifle/home-assistant,stefan-jonasson/home-assistant,Duoxilian/home-assistant,Zac-HD/home-assistant,jaharkes/home-assistant,postlund/home-assistant,jnewland/home-assistant,morphis/home-assistant,LinuxChristian/home-assistant,jawilson/home-assistant,rohitranjan1991/home-assistant,aronsky/home-assistant,Zyell/home-assistant,eagleamon/home-assistant,ewandor/home-assistant,tboyce1/home-assistant,adrienbrault/home-assistant,partofthething/home-assistant,devdelay/home-assistant,shaftoe/home-assistant,aequitas/home-assistant,mikaelboman/home-assistant,PetePriority/home-assistant,auduny/home-assistant,Smart-Torvy/torvy-home-assistant,oandrew/home-assistant,ct-23/home-assistant,nkgilley/home-assistant,jnewland/home-assistant,philipbl/home-assistant,sdague/home-assistant,alexmogavero/home-assistant,oandrew/home-assistant,MungoRae/home-assistant,srcLurker/home-assistant,qedi-r/home-assistant,jamespcole/home-assistant,happyleavesaoc/home-assistant,mikaelboman/home-assistant,ct-23/home-assistant,Duoxilian/home-assistant,aequitas/home-assistant,happyleavesaoc/home-assistant,florianholzapfel/home-assistant,emilhetty/home-assistant,hmronline/home-assistant,tboyce021/home-assistant,hexxter/home-assistant,auduny/home-assistant,fbradyirl/home-assistant,LinuxChristian/home-assistant,mikaelboman/home-assistant,persandstrom/home-assistant,MungoRae/home-assistant,tinloaf/home-assistant,jaharkes/home-assistant,mikaelboman/home-assistant,robjohnson189/home-assistant,dmeulen/home-assistant,sffjunkie/home-assistant,morphis/home-assistant,titilambert/home-assistant,morphis/home-assistant,MartinHjelmare/home-assistant,varunr047/homefile,robbiet480/home-assistant,eagleamon/home-assistant,mKeRix/home-assistant,robbiet480/home-assistant,deisi/home-assistant,MartinHjelmare/home-assistant,kennedyshead/home-assistant,MungoRae/home-assistant,eagleamon/home-assistant,DavidLP/home-assistant,miniconfig/home-assistant,Cinntax/home-assistant,tboyce1/home-assistant,betrisey/home-assistant,kennedyshead/home-assistant,robjohnson189/home-assistant,tboyce1/home-assistant,xifle/home-assistant,DavidLP/home-assistant,philipbl/home-assistant,florianholzapfel/home-assistant,betrisey/home-assistant,home-assistant/home-assistant | homeassistant/components/zeroconf.py | homeassistant/components/zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS).
For more details about Zeroconf, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
REQUIREMENTS = ["zeroconf==0.17.5"]
DEPENDENCIES = ["api"]
_LOGGER = logging.getLogger(__name__)
DOMAIN = "zeroconf"
ZEROCONF_TYPE = "_home-assistant._tcp.local."
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = "{}.{}".format(hass.config.location_name,
ZEROCONF_TYPE)
params = {"version": __version__, "base_url": hass.config.api.base_url,
"requires_api_password": (hass.config.api.api_password is not None)}
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name,
socket.inet_aton(hass.config.api.host),
hass.config.api.port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
| """
This module exposes Home Assistant via Zeroconf.
Zeroconf is also known as Bonjour, Avahi or Multicast DNS (mDNS).
For more details about Zeroconf, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
REQUIREMENTS = ["zeroconf==0.17.5"]
DEPENDENCIES = ["api"]
_LOGGER = logging.getLogger(__name__)
DOMAIN = "zeroconf"
ZEROCONF_TYPE = "_home-assistant._tcp.local."
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = "{}.{}".format(hass.config.location_name,
ZEROCONF_TYPE)
params = {"version": __version__, "base_url": hass.config.api.base_url,
"needs_auth": (hass.config.api.api_password is not None)}
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name,
socket.inet_aton(hass.config.api.host),
hass.config.api.port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
| mit | Python |
9aa368d528448c485c940c646394b44dafd1e62f | Create iomanager.py | lyelindustries/IPM | basemod/iomanager.py | basemod/iomanager.py | mit | Python | ||
d899fbda7c86067fc705de6fb3b04b1a7b3ed962 | add a rest service to send commands to the actors via POST and retrieve information via GET | tahesse/pyCrow | pyCrow/crowlib/rest.py | pyCrow/crowlib/rest.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""REST Actor.
"""
# Python-native imports
import logging.config
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import threading
# Third-party imports
import pykka
# App imports
from pyCrow.crowlib.aux import Action
# prepare logging, i.e. load config and get the root L
L = logging.getLogger()
class RestActor(pykka.ThreadingActor):
def __init__(self, config: dict):
super().__init__()
self._config = config
self._server = Server((self._config.get('address', ''), self._config.get('port', 1337)))
self._server_thread = None
def on_start(self):
L.info(msg=f'Started RestActor ({self.actor_urn})')
self._server_thread = threading.Thread(target=self._server.start, daemon=False)
self._server_thread.start()
def on_stop(self):
L.info('RestActor is stopped.')
def on_failure(self, exception_type, exception_value, traceback):
L.error(f'RestActor failed: {exception_type} {exception_value} {traceback}')
def on_receive(self, msg: dict):
L.info(msg=f'RestActor received message: {msg}')
# process msg and alter state accordingly
_cmd = msg.get('cmd', '').lower()
# introduce actions to modify this actors state, i.e. do alterations to the web server
if _cmd == Action.SERVER_START.get('cmd'):
self._server.start()
elif _cmd == Action.SERVER_RESTART.get('cmd'):
self._server.stop()
self._server = Server((self._config.get('address', ''), self._config.get('port', 1337)))
self._server_thread = threading.Thread(target=self._server.start, daemon=False)
self._server_thread.start()
elif _cmd == Action.SERVER_STOP.get('cmd'):
self._server.stop()
self._server_thread.join()
else:
# default: do nothing but log this event
L.info(msg=f'Received message {msg} which cannot be processed.')
# RESTRequestHandler
class RESTRequestHandler(BaseHTTPRequestHandler):
def __init__(self, request, client_address, server):
super().__init__(request, client_address, server)
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
_headers = str(self.headers).replace('\n\n', '').replace('\n', ', ')
L.debug(f'Method: [GET], Path: [{self.path}], Headers: [{_headers}]')
self._set_response()
pykka.ActorRegistry.get_by_class_name('AppActor')[0].ask({})
# self.wfile.write(f'GET request for {self.path}'.encode('utf-8'))
def do_POST(self):
# size of data
content_length = int(self.headers['Content-Length'])
# POST data itself
post_data = self.rfile.read(content_length)
_headers = str(self.headers).replace('\n\n', '').replace('\n', ', ')
L.debug(f'Method: [POST], Path: [{self.path}], Headers: [{_headers}], '
f'Body: [{post_data.decode("utf-8")}]')
# todo validate msg
msg: dict = json.loads(post_data.decode('utf-8'))
pykka.ActorRegistry.get_by_class_name(msg.pop('target', 'AppActor'))[0].tell(msg)
self._set_response()
# self.wfile.write(f'POST request for {self.path}'.encode('utf-8'))
# Server
class Server(HTTPServer):
pykka_traversable = True
def __init__(self, server_address):
super().__init__(server_address, RESTRequestHandler)
self._started = False
L.info('Initialized REST Server.')
def start(self):
if self._started:
L.warning('REST Server already started. Aborting.')
return
try:
L.info('Starting REST Server.')
self._started = True
self.serve_forever()
except KeyboardInterrupt:
L.exception('Received keyboard interrupt for the Server.')
finally:
self.server_close()
L.info('Closed the REST Servers socket.')
def stop(self):
if self._started:
self.shutdown()
self._started = False
L.info('Gracefully stopped the REST Server.')
| apache-2.0 | Python | |
1a37c09fe0ba755dac04819aea0a6d02327330db | Add files via upload | Gregory93/project2-battleport | module3.py | module3.py | import psycopg2
try:
conn = psycopg2.connect("dbname=battleport user=postgres host=localhost password=gregory123")
except:
print("cannot connect to the database")
cur=conn.cursor()
conn.set_isolation_level(0)
#cur.execute("INSERT INTO score (name,gamesp,gamesw,gamesl) \
#VALUES ('Rens', 10, 4, 6)");
#cur.execute("UPDATE score set gamesp = gamesp + 1, gamesw = gamesw + 1 WHERE name='Gregory'")
#execute row WHERE rnum = 1
cur.execute("SELECT * FROM (SELECT *, row_number() OVER () as rnum FROM score ORDER BY rnum asc, gamesp desc, gamesw desc) ss WHERE rnum = 1")
rows = cur.fetchall()
for row in rows:
print ("Name = ", row[0], "\n")
#execute row WHERE rnum = 2
cur.execute("SELECT * FROM (SELECT *, row_number() OVER () as rnum FROM score ORDER BY rnum asc, gamesp desc, gamesw desc) ss WHERE rnum = 2")
rows2 = cur.fetchall()
for row2 in rows2:
print ("Name = ", row2[0], "\n")
#execute row WHERE rnum = 3
cur.execute("SELECT * FROM (SELECT *, row_number() OVER () as rnum FROM score ORDER BY rnum asc, gamesp desc, gamesw desc) ss WHERE rnum = 3")
rows3 = cur.fetchall()
for row3 in rows3:
print ("Name = ", row3[0], "\n")
#execute row WHERE rnum = 4
cur.execute("SELECT * FROM (SELECT *, row_number() OVER () as rnum FROM score ORDER BY rnum asc, gamesp desc, gamesw desc) ss WHERE rnum = 4")
rows4 = cur.fetchall()
for row4 in rows4:
print ("Name = ", row4[0], "\n")
#execute row WHERE name is TAHSIN
cur.execute("SELECT * FROM (SELECT *, row_number() OVER () as rnum FROM score ORDER BY rnum asc, gamesp desc, gamesw desc) ss WHERE rnum = 5")
rows5 = cur.fetchall()
for row5 in rows5:
print ("Name = ", row5[0], "\n") | mit | Python | |
f60b3f00b7a4675f1bfc4cab1b9d1b5c150d9dfc | Add simple utility class that extends a dictionary but can be used as object. | archman/phantasy,archman/phantasy | phyhlc/util.py | phyhlc/util.py | # encoding: UTF-8
"""Utilities that are used throughout the package.
..moduleauthor:: Dylan Maxwell <maxwelld@frib.msu.edu>
"""
class ObjectDict(dict):
"""Makes a dictionary behave like an object, with attribute-style access.
"""
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
self[name] = value
| bsd-3-clause | Python | |
c9e4c18ea54de5c168994b47f70f0bdac0a76c73 | add ocr_pdf.py | luozhaoyu/deepdive,luozhaoyu/deepdive | ocr_pdf.py | ocr_pdf.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
ocr_pdf.py
~~~~~~~~~~~~~~
A brief description goes here.
"""
import subprocess
def call(cmd, check=True, stdout=None, stderr=None):
"""
Args:
check: check return code or not
"""
if check:
return subprocess.check_call(cmd, stdout=stdout, stderr=stderr, shell=True)
else:
return subprocess.call(cmd, stdout=stdout, stderr=stderr, shell=True)
def k2pdfopt(pdf_file, output_file):
"""
Args:
output_file: this is a required parameter, because k2pdfopt always return 0
Returns:
0: WARNING, k2pdfopt will always return 0, judge its succeed by looking at the output_file
"""
cmd = "./k2pdfopt -ui- -x -w 2160 -h 3840 -odpi 300 %s -o %s" % (pdf_file, output_file)
return call(cmd)
def pdf_to_page(pdf_file):
cmd = "./codes/convert/cde-exec 'gs' -dBATCH -dNOPAUSE -sDEVICE=png16m -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -r300 -sOutputFile=page-%%d.png %s" % pdf_file
call(cmd)
cmd = "./codes/convert/cde-exec 'gs' -SDEVICE=bmpmono -r300x300 -sOutputFile=cuneiform-page-%%04d.bmp -dNOPAUSE -dBATCH -- %s" % pdf_file
return call(cmd)
class OcrPdf(object):
def __init__(self, stdout_filepath, stderr_filepath):
try:
self.stdout = open(stdout_filepath, 'a')
self.stderr = open(stderr_filepath, 'a')
except IOError as e:
print "ERROR\tInvalid filepath %s, %s" % (stdout_filepath, stderr_filepath)
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
raise e
def call(self, cmd, check=True):
return call(cmd, check=check, stdout=self.stdout, stderr=self.stderr)
def main(argv):
output_file = "k2_pdf_%s" % argv[1]
print k2pdfopt(argv[1], output_file)
print pdf_to_page(output_file)
if __name__ == '__main__':
import sys
main(sys.argv)
| apache-2.0 | Python | |
564f1b2287d3825266b82d9b0f2f1c289285a493 | Add vectorfiled class. | ryanpepper/oommf-python,fangohr/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python | pyoommf/vectorfield.py | pyoommf/vectorfield.py | import numpy as np
import matplotlib.pyplot as plt
class VectorField(object):
def __init__(self, filename):
f = open(filename, 'r')
lines = f.readlines()
for line in lines:
if line.startswith('# xmin'):
self.xmin = float(line[7:])
if line.startswith('# ymin'):
self.ymin = float(line[7:])
if line.startswith('# zmin'):
self.zmin = float(line[7:])
if line.startswith('# xmax'):
self.xmax = float(line[7:])
if line.startswith('# ymax'):
self.ymax = float(line[7:])
if line.startswith('# zmax'):
self.zmax = float(line[7:])
if line.startswith('# xstepsize'):
self.dx = float(line[12:])
if line.startswith('# ystepsize'):
self.dy = float(line[12:])
if line.startswith('# zstepsize'):
self.dz = float(line[12:])
if line.startswith('# xnodes'):
self.nx = int(line[9:])
if line.startswith('# ynodes'):
self.ny = int(line[9:])
if line.startswith('# znodes'):
self.nz = int(line[9:])
self.coords = np.zeros([self.nx*self.ny*self.nz, 3])
self.x_array = np.arange(self.xmin+self.dx/2., self.xmax, self.dx)
self.y_array = np.arange(self.ymin+self.dy/2., self.ymax, self.dy)
self.z_array = np.arange(self.zmin+self.dz/2., self.zmax, self.dz)
counter = 0
for z in self.z_array:
for y in self.y_array:
for x in self.x_array:
self.coords[counter, :] = [x, y, z]
counter += 1
self.vf = np.zeros([self.nx*self.ny*self.nz, 3])
counter = 0
for line in lines:
if not line.startswith('#'):
parts = line.split()
self.vf[counter, 0] = float(parts[0])
self.vf[counter, 1] = float(parts[1])
self.vf[counter, 2] = float(parts[2])
counter += 1
def get_coords(self):
return self.coords
def get_vf(self):
return self.vf
def get_index(self, coord):
counter = 0
for i in range(self.nx*self.ny*self.nz):
if self.coords[i, 0] == coord[0] and self.coords[i, 1] == coord[1] and \
self.coords[i, 2] == coord[2]:
return counter
counter += 1
def sample(self, coord):
return self.vf[self.get_index(coord), :]
def z_slice(self, z):
slice_coords = np.zeros([self.nx*self.ny, 2])
slice_vf = np.zeros([self.nx*self.ny, 3])
counter = 0
for y in self.y_array:
for x in self.x_array:
slice_coords[counter, :] = [x, y]
slice_vf[counter, :] = self.sample((x, y, z))
counter += 1
return slice_coords, slice_vf
def plot_z_slice(self, z):
slice_coords, slice_vf = self.z_slice(z)
plt.quiver(slice_coords[:, 0]/1e-9, slice_coords[:, 1]/1e-9,
slice_vf[:, 0], slice_vf[:, 1])
plt.xlabel('x (nm)')
plt.ylabel('y (nm)')
plt.grid()
plt.show()
vf = VectorField('small_example-Oxs_TimeDriver-Magnetization-00-0000725.omf')
print vf.get_coords()
print vf.get_vf()
print vf.get_index((3.75e-8, 3.75e-8, 3.75e-8))
print vf.sample((3.75e-8, 3.75e-8, 3.75e-8))
print vf.z_slice(2.5e-9)
print vf.plot_z_slice(2.5e-9)
| bsd-2-clause | Python | |
d58a021704669a8bb6b7d36d068ca596fc0f813e | add problem0010.py | Furisuke/ProjectEuler,Furisuke/ProjectEuler,Furisuke/ProjectEuler | python3/problem0010.py | python3/problem0010.py | from problem0003 import primes
from itertools import takewhile
print(sum(takewhile(lambda x: x < 2000000, primes())))
| mit | Python | |
91927b441425703463f0ee1e08293ad942a26a93 | Add debounce.py and implementation. | Digirolamo/pythonicqt | pythonicqt/debounce.py | pythonicqt/debounce.py | """module contains datastructures needed to create the @debounce decorator."""
import time
from functools import wraps, partial
from PySide import QtCore
class DebounceTimer(QtCore.QTimer):
"""Used with the debounce decorator, used for delaying/throttling calls."""
def __init__(self, msecs, fire_on_first=False, ignore_delayed=False):
self.is_setup = False
self.msecs_interval = msecs
self.seconds_interval = msecs / 1000.0
self.last_update = time.time() - self.seconds_interval - 1
self.delayed_call = False
self.fire_on_first = fire_on_first
self.ignore_delayed = ignore_delayed
def setup_parent(self, parent):
"""Needs the parent before this object can be setup."""
self.is_setup = True
QtCore.QTimer.__init__(self, parent)
self.timeout.connect(self.call_function)
self.setInterval(self.msecs_interval)
self.start()
def call_function(self, *args):
"""On timeout calls the delayed function if neccessary."""
self.stop()
if self.delayed_call:
self.delayed_call()
self.delayed_call = False
self.last_update = time.time()
self.start(self.msecs_interval)
def debounce(msecs, fire_on_first=False, ignore_delayed=False):
"""Decorator that prevents a function from being called more than once every
time period between calls. Postpones execution when threshold is breached.
If fire_on_first is True, calls are immediately propagated after the time threshold
passes, else the first calls are allows made after an entire msecs period after the
most recent call.
@debounce(msecs=1)
def my_fun(self):
pass
"""
def wrap_wrapper(func):
@wraps(func)
def wrapper(instance, *args, **kwargs):
if not hasattr(instance, "__debounce_dict"):
instance.__debounce_dict = {}
if func not in instance.__debounce_dict:
new_timer = DebounceTimer(msecs, fire_on_first=fire_on_first, ignore_delayed=ignore_delayed)
instance.__debounce_dict[func] = new_timer
new_timer.setup_parent(instance)
debounce_timer = instance.__debounce_dict[func]
debounce_timer.stop()
difference = time.time() - debounce_timer.last_update
if difference > debounce_timer.seconds_interval and debounce_timer.fire_on_first:
debounce_timer.delayed_call = False
func(instance, *args, **kwargs)
debounce_timer.last_update = time.time()
else:
if not debounce_timer.ignore_delayed:
debounce_timer.delayed_call = partial(func, instance, *args, **kwargs)
debounce_timer.start(debounce_timer.msecs_interval)
return wrapper
return wrap_wrapper | mit | Python | |
50795568e35669916f1654d50e5f1bdd1800d41e | Create imposto.py | GestaoPublico/Inss_Issqn_IRF | imposto.py | imposto.py | numero = float(input('Digite o valor Bruto: '))
inss = numero * 11/100
if (inss >= 482.93 ):
real = 482.93
else:
real = inss
Pissqn = numero - real
issqn = Pissqn * 3/100
Pissqn = numero - real - issqn
if (numero <= 1787.77 ):
num = 'Não desconta inposto'
vp = 0
elif (numero <= 2679.29):
num = 'Aliquota 7,5%'
vp = numero * 7.5/100 - 134.08
elif (numero <= 3572.43):
num = 'Aliquota 15%'
vp = numero * 15/100 - 335.03
elif (numero <= 4463.81):
num = 'Aliquota 22,5%'
vp = numero * 22.5/100 - 602.96
elif (numero > 4463.81):
num = 'Aliquota 27,5%'
vp = numero * 27.5/100 - 826.15
vl = numero - real - issqn - vp
print("Vapor do Inss: ", round(real, 2))
print("Vapor do Issqn: ", round(issqn, 2))
print("Vapor do inposto: ", round(vp, 2), num)
print("Valor liquido: ", round(vl, 2))
| mpl-2.0 | Python | |
cebe8dffbf9819c370257b7030848ef0ea4e971c | Initialize stuff | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list | ghlist.py | ghlist.py | import requests
api = 'https://api.github.com/users/{}/repos'
repos = data = requests.get(url=api.format('kshvmdn')).json()
for repo in repos:
print(repo['name'])
| mit | Python | |
62c02c185063465e51bd40e648f75d519e68c1d2 | Create Euler2.py | PaulFay/DT211-3-Cloud | Euler2.py | Euler2.py | def sequence(n):
if n <= 1:
return n
else:
return(sequence(n-1) + sequence(n-2))
i = 1
j = 0
total = 0
while j < 4000000:
j = sequence(i)
if j%2:
print(j)
else:
print(j)
total = total + j
i+=1
print("total is")
print(total)
| mit | Python | |
25b5b8fc89164dc386218ae1edd660735781241d | add simple font comparison tool in examples | adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,niklaskorz/pyglet,niklaskorz/pyglet,niklaskorz/pyglet,niklaskorz/pyglet | examples/font_comparison.py | examples/font_comparison.py | #!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of pyglet nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# 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.
# ----------------------------------------------------------------------------
'''A simple tool that may be used to compare font faces.
Use the left/right cursor keys to change font faces.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import pyglet
FONTS = ['Consolas', 'Andale Mono', 'Inconsolata', 'Inconsolata-dz', 'Monaco',
'Menlo']
SAMPLE = '''class Spam(object):
def __init__(self):
# The quick brown fox
self.spam = {"jumped": 'over'}
@the
def lazy(self, *dog):
self.dog = [lazy, lazy]'''
class Window(pyglet.window.Window):
font_num = 0
def on_text_motion(self, motion):
if motion == pyglet.window.key.MOTION_RIGHT:
self.font_num += 1
if self.font_num == len(FONTS):
self.font_num = 0
elif motion == pyglet.window.key.MOTION_LEFT:
self.font_num -= 1
if self.font_num < 0:
self.font_num = len(FONTS) - 1
face = FONTS[self.font_num]
self.head = pyglet.text.Label(face, font_size=24, y=0,
anchor_y='bottom')
self.text = pyglet.text.Label(SAMPLE, font_name=face, font_size=18,
y=self.height, anchor_y='top', width=self.width, multiline=True)
def on_draw(self):
self.clear()
self.head.draw()
self.text.draw()
window = Window()
window.on_text_motion(None)
pyglet.app.run()
| bsd-3-clause | Python | |
778df30911226a7aac1e45406fa629f7f83e7136 | Add example on robust training | google/jaxopt | examples/robust_training.py | examples/robust_training.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
#
# 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.
"""Robust Training in JAXOpt.
The following code trains a convolutional neural network (CNN) to be robust
with respect to the fast sign gradient (FGSM) method.
The Fast Gradient Sign Method (FGSM) is a simple yet effective method to generate
adversarial images. It constructs an adversarial by adding a small perturbation in
the direction of the sign of the gradient with respect to the input. The gradient
ensures this perturbation locally maximizes the objective, while the sign ensures
that the update is on the boundary of the L-infinity ball.
References:
Goodfellow, Ian J., Jonathon Shlens, and Christian Szegedy. "Explaining
and harnessing adversarial examples." https://arxiv.org/abs/1412.6572
"""
import tensorflow_datasets as tfds
from matplotlib import pyplot as plt
import jax
from jax import numpy as jnp
from flax import linen as nn
import optax
from jaxopt import GradientDescent
from jaxopt import loss
from jaxopt import OptaxSolver
from jaxopt import tree_util
def load_dataset(split, *, is_training, batch_size):
"""Loads the dataset as a generator of batches."""
ds = tfds.load("mnist:3.*.*", split=split).cache().repeat()
if is_training:
ds = ds.shuffle(10 * batch_size, seed=0)
ds = ds.batch(batch_size)
return iter(tfds.as_numpy(ds))
class CNN(nn.Module):
"""A simple CNN model."""
@nn.compact
def __call__(self, x):
x = nn.Conv(features=32, kernel_size=(3, 3))(x)
x = nn.relu(x)
x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
x = nn.Conv(features=64, kernel_size=(3, 3))(x)
x = nn.relu(x)
x = nn.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
x = x.reshape((x.shape[0], -1)) # flatten
x = nn.Dense(features=256)(x)
x = nn.relu(x)
x = nn.Dense(features=10)(x)
return x
net = CNN()
@jax.jit
def accuracy(params, images, labels):
logits = net.apply({"params": params}, images)
return jnp.mean(jnp.argmax(logits, axis=-1) == labels)
logistic_loss = jax.vmap(loss.multiclass_logistic_loss)
def loss_fun(params, l2_regul, images, labels):
"""Compute the loss of the network."""
logits = net.apply({"params": params}, images)
sqnorm = tree_util.tree_l2_norm(params, squared=True)
loss_value = jnp.mean(logistic_loss(labels, logits))
return loss_value + 0.5 * l2_regul * sqnorm
train_ds = load_dataset("train", is_training=True, batch_size=128)
test_ds = load_dataset("test", is_training=False, batch_size=1000)
# Initialize solver and parameters.
solver = OptaxSolver(opt=optax.adam(1e-3), fun=loss_fun)
rng = jax.random.PRNGKey(0)
init_params = CNN().init(rng, jnp.ones([1, 28, 28, 1]))["params"]
l2_regul = 1e-4
params, state = solver.init(init_params)
for it in range(200):
data = next(train_ds)
images = data['image'].astype(jnp.float32) / 255
labels = data['label']
def fsgm_attack(image, label, epsilon=0.1):
"""Fast sign-gradient attack on the L-infinity ball with radius epsilon.
Parameters:
image: array-like, input data for the CNN
label: integer, class label corresponding to image
epsilon: float, radius of the L-infinity ball.
Returns:
perturbed_image: Adversarial image on the boundary of the L-infinity ball of radius
epsilon and centered at image.
"""
# comppute gradient of the loss wrt to the image
grad = jax.grad(loss_fun, argnums=2)(params, l2_regul, image, label)
adv_image = image + epsilon * jnp.sign(grad)
# clip the image to ensure pixels are between 0 and 1
return jnp.clip(adv_image, 0, 1)
images_adv = fsgm_attack(images, labels)
# run adversarial training
params, state = solver.update(params=params, state=state,
l2_regul=l2_regul, images=images_adv, labels=labels)
if it % 10 == 0:
data_test = next(test_ds)
images_test = data_test['image'].astype(jnp.float32) / 255
labels_test = data_test['label']
test_accuracy = accuracy(params, images_test, labels_test)
print("Accuracy on test set", test_accuracy)
images_adv_test = fsgm_attack(images_test, labels_test)
test_adversarial_accuracy = accuracy(params, images_adv_test, labels_test)
print("Accuracy on adversarial images", test_adversarial_accuracy)
print()
| apache-2.0 | Python | |
d300081826f7ebffefb4eeb8ca1077f028b40852 | Add fractal shader example. | certik/scikits.gpu,stefanv/scikits.gpu | examples/shader_onscreen.py | examples/shader_onscreen.py | from scikits.gpu.api import *
import pyglet.window
from pyglet import gl
# GLSL code based on http://nuclear.sdf-eu.org/articles/sdr_fract
# by John Tsiombikas
v_shader = VertexShader("""
uniform vec2 offset;
uniform float zoom;
uniform float width_ratio;
varying vec2 pos;
void main(void) {
pos.x = gl_Vertex.x * width_ratio / zoom + offset.x;
pos.y = gl_Vertex.y / zoom + offset.y;
gl_Position = ftransform();
}
""")
f_shader = FragmentShader("""
varying vec2 pos;
void main() {
float k;
float r = 0.0, i = 0.0;
float a, b;
for (k = 0.0; k < 1.0; k += 0.005) {
a = r*r - i*i + pos.x;
b = 2*r*i + pos.y;
if ((a*a + b*b) > 4) break;
r = a;
i = b;
}
gl_FragColor = vec4(k, 3*sin(k), sin(k*3.141/2.), 1.0);
}
""")
window = pyglet.window.Window(width=800, height=600)
gl.glClear(gl.GL_COLOR_BUFFER_BIT)
gl.glLoadIdentity()
p = Program([v_shader, f_shader])
p.bind()
p.uniformf('offset', [-1.0, 0.0])
p.uniformf('width_ratio', 800/600.)
p.uniformf('zoom', 2.0)
# Draw full-screen canvas
gl.glBegin(gl.GL_QUADS)
for coords in [(-1.0, -1.0),
( 1.0, -1.0),
( 1.0, 1.0),
(-1.0, 1.0)]:
gl.glVertex3f(coords[0], coords[1], 0.0)
gl.glEnd()
gl.glFlush()
p.unbind()
pyglet.app.run()
| mit | Python | |
522201ec9e00ed2fe135a621bde1b288c59ddd25 | Add test utils | jimgoo/keras,LIBOTAO/keras,happyboy310/keras,relh/keras,keras-team/keras,jasonyaw/keras,gavinmh/keras,keskarnitish/keras,kfoss/keras,kod3r/keras,jhauswald/keras,meanmee/keras,jonberliner/keras,xiaoda99/keras,llcao/keras,ypkang/keras,why11002526/keras,daviddiazvico/keras,EderSantana/keras,OlafLee/keras,rodrigob/keras,hhaoyan/keras,keras-team/keras,navyjeff/keras,zhangxujinsh/keras,dxj19831029/keras,imcomking/Convolutional-GRU-keras-extension-,nzer0/keras,bboalimoe/keras,printedheart/keras,harshhemani/keras,JasonTam/keras,jalexvig/keras,wubr2000/keras,ogrisel/keras,yingzha/keras,nehz/keras,ml-lab/keras,stephenbalaban/keras,pjadzinsky/keras,zxytim/keras,vseledkin/keras,chenych11/keras,iamtrask/keras,MagicSen/keras,jayhetee/keras,brainwater/keras,dribnet/keras,3dconv/keras,saurav111/keras,danielforsyth/keras,Aureliu/keras,eulerreich/keras,pthaike/keras,untom/keras,dhruvparamhans/keras,amy12xx/keras,cvfish/keras,ekamioka/keras,zhmz90/keras,gamer13/keras,nebw/keras,ledbetdr/keras,cheng6076/keras,bottler/keras,johmathe/keras,wxs/keras,mikekestemont/keras,iScienceLuvr/keras,dolaameng/keras,ashhher3/keras,xurantju/keras,DLlearn/keras,asampat3090/keras,kuza55/keras,abayowbo/keras,sjuvekar/keras,marchick209/keras,nt/keras,Yingmin-Li/keras,zxsted/keras,jbolinge/keras,kemaswill/keras,rudaoshi/keras,fmacias64/keras,jiumem/keras,Cadene/keras,rlkelly/keras,Smerity/keras,DeepGnosis/keras,tencrance/keras,florentchandelier/keras | keras/utils/test_utils.py | keras/utils/test_utils.py | import numpy as np
def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,), output_shape=(2,),
classification=True, nb_class=2):
'''
classification=True overrides output_shape
(i.e. output_shape is set to (1,)) and the output
consists in integers in [0, nb_class-1].
Otherwise: float output with shape output_shape.
'''
nb_sample = nb_train + nb_test
if classification:
y = np.random.randint(0, nb_class, size=(nb_sample, 1))
X = np.zeros((nb_sample,) + input_shape)
for i in range(nb_sample):
X[i] = np.random.normal(loc=y[i], scale=1.0, size=input_shape)
else:
y_loc = np.random.random((nb_sample,))
X = np.zeros((nb_sample,) + input_shape)
y = np.zeros((nb_sample,) + output_shape)
for i in range(nb_sample):
X[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=input_shape)
y[i] = np.random.normal(loc=y_loc[i], scale=1.0, size=output_shape)
return (X[:nb_train], y[:nb_train]), (X[nb_train:], y[nb_train:])
| mit | Python | |
bd02fd2d163a2f044029ddb0adef031c2dcd824a | Remove deprecated function call | ernstp/kivy,VinGarcia/kivy,adamkh/kivy,Ramalus/kivy,angryrancor/kivy,habibmasuro/kivy,iamutkarshtiwari/kivy,xiaoyanit/kivy,darkopevec/kivy,manthansharma/kivy,inclement/kivy,matham/kivy,MiyamotoAkira/kivy,denys-duchier/kivy,bionoid/kivy,MiyamotoAkira/kivy,arlowhite/kivy,manthansharma/kivy,bionoid/kivy,adamkh/kivy,bob-the-hamster/kivy,autosportlabs/kivy,janssen/kivy,cbenhagen/kivy,yoelk/kivy,jkankiewicz/kivy,tony/kivy,darkopevec/kivy,gonzafirewall/kivy,matham/kivy,vipulroxx/kivy,janssen/kivy,CuriousLearner/kivy,janssen/kivy,bliz937/kivy,vitorio/kivy,JohnHowland/kivy,Ramalus/kivy,cbenhagen/kivy,vipulroxx/kivy,edubrunaldi/kivy,janssen/kivy,darkopevec/kivy,aron-bordin/kivy,angryrancor/kivy,arcticshores/kivy,autosportlabs/kivy,yoelk/kivy,denys-duchier/kivy,vitorio/kivy,jkankiewicz/kivy,ernstp/kivy,tony/kivy,jkankiewicz/kivy,JohnHowland/kivy,jehutting/kivy,dirkjot/kivy,Farkal/kivy,jegger/kivy,bob-the-hamster/kivy,manashmndl/kivy,angryrancor/kivy,xpndlabs/kivy,el-ethan/kivy,viralpandey/kivy,aron-bordin/kivy,arcticshores/kivy,mSenyor/kivy,matham/kivy,yoelk/kivy,viralpandey/kivy,yoelk/kivy,xiaoyanit/kivy,vipulroxx/kivy,adamkh/kivy,bionoid/kivy,vipulroxx/kivy,Cheaterman/kivy,Farkal/kivy,kivy/kivy,jffernandez/kivy,arcticshores/kivy,MiyamotoAkira/kivy,akshayaurora/kivy,kivy/kivy,Cheaterman/kivy,LogicalDash/kivy,rnixx/kivy,jegger/kivy,Shyam10/kivy,aron-bordin/kivy,rafalo1333/kivy,arcticshores/kivy,jegger/kivy,manthansharma/kivy,manashmndl/kivy,jffernandez/kivy,KeyWeeUsr/kivy,iamutkarshtiwari/kivy,andnovar/kivy,kived/kivy,jehutting/kivy,bhargav2408/kivy,JohnHowland/kivy,mSenyor/kivy,autosportlabs/kivy,xpndlabs/kivy,dirkjot/kivy,adamkh/kivy,Shyam10/kivy,jffernandez/kivy,xpndlabs/kivy,aron-bordin/kivy,rafalo1333/kivy,rnixx/kivy,ernstp/kivy,kived/kivy,dirkjot/kivy,LogicalDash/kivy,andnovar/kivy,Cheaterman/kivy,cbenhagen/kivy,MiyamotoAkira/kivy,kived/kivy,Cheaterman/kivy,bob-the-hamster/kivy,dirkjot/kivy,Farkal/kivy,rnixx/kivy,akshayaurora/kivy,bionoid/kivy,el-ethan/kivy,Shyam10/kivy,gonzafirewall/kivy,gonzafirewall/kivy,Farkal/kivy,KeyWeeUsr/kivy,denys-duchier/kivy,jkankiewicz/kivy,inclement/kivy,inclement/kivy,JohnHowland/kivy,youprofit/kivy,Ramalus/kivy,KeyWeeUsr/kivy,bliz937/kivy,edubrunaldi/kivy,manashmndl/kivy,tony/kivy,el-ethan/kivy,mSenyor/kivy,iamutkarshtiwari/kivy,CuriousLearner/kivy,matham/kivy,rafalo1333/kivy,jehutting/kivy,angryrancor/kivy,jegger/kivy,edubrunaldi/kivy,bob-the-hamster/kivy,youprofit/kivy,habibmasuro/kivy,thezawad/kivy,CuriousLearner/kivy,ernstp/kivy,bhargav2408/kivy,LogicalDash/kivy,manthansharma/kivy,Shyam10/kivy,VinGarcia/kivy,andnovar/kivy,arlowhite/kivy,gonzafirewall/kivy,youprofit/kivy,xiaoyanit/kivy,KeyWeeUsr/kivy,LogicalDash/kivy,kivy/kivy,arlowhite/kivy,bliz937/kivy,VinGarcia/kivy,habibmasuro/kivy,bhargav2408/kivy,thezawad/kivy,akshayaurora/kivy,viralpandey/kivy,darkopevec/kivy,vitorio/kivy,thezawad/kivy,jffernandez/kivy,denys-duchier/kivy | kivy/core/clipboard/clipboard_sdl2.py | kivy/core/clipboard/clipboard_sdl2.py | '''
Clipboard SDL2: an implementation of the Clipboard using sdl2.
'''
__all__ = ('ClipboardSDL2', )
from kivy.utils import platform
from kivy.core.clipboard import ClipboardBase
if platform not in ('win', 'linux', 'macosx', 'android', 'ios'):
raise SystemError('unsupported platform for pygame clipboard')
try:
from kivy.core.clipboard._clipboard_sdl2 import _get_text, _has_text, _set_text
except ImportError:
raise SystemError('extension not compiled?')
class ClipboardSDL2(ClipboardBase):
def paste(self):
return _get_text() if _has_text() else ''
def copy(self, data=''):
data = data.encode('utf-8')
_set_text(data)
def get_types(self):
return 'text/plain'
| '''
Clipboard SDL2: an implementation of the Clipboard using sdl2.
'''
__all__ = ('ClipboardSDL2', )
from kivy.utils import platform
from kivy.core.clipboard import ClipboardBase
if platform() not in ('win', 'linux', 'macosx', 'android', 'ios'):
raise SystemError('unsupported platform for pygame clipboard')
try:
from kivy.core.clipboard._clipboard_sdl2 import _get_text, _has_text, _set_text
except ImportError:
raise SystemError('extension not copiled??')
class ClipboardSDL2(ClipboardBase):
def paste(self):
return _get_text() if _has_text() else ''
def copy(self, data=''):
data = data.encode('utf-8')
_set_text(data)
def get_types(self):
return 'text/plain'
| mit | Python |
04b96b35d8d6e56eb1d545bafedc1af4d5914577 | add Proxy pattern | JakubVojvoda/design-patterns-python | proxy/Proxy.py | proxy/Proxy.py | #
# Python Design Patterns: Proxy
# Author: Jakub Vojvoda [github.com/JakubVojvoda]
# 2016
#
# Source code is licensed under MIT License
# (for more details see LICENSE)
#
import sys
#
# Subject
# defines the common interface for RealSubject and Proxy
# so that a Proxy can be used anywhere a RealSubject is expected
#
class Subject:
def request(self):
pass
#
# Real Subject
# defines the real object that the proxy represents
#
class RealSubject(Subject):
def __init__(self):
Subject.__init__(self)
def request(self):
print("Real Subject request.")
#
# Proxy
# maintains a reference that lets the proxy access the real subject
#
class Proxy(Subject):
def __init__(self):
Subject.__init__(self)
self._subject = RealSubject()
def request(self):
self._subject.request()
if __name__ == "__main__":
proxy = Proxy()
proxy.request()
| mit | Python | |
2f82c96257af5e5596c02348621572b08ff99b64 | test mixed returns | thomasvs/pychecker,akaihola/PyChecker,akaihola/PyChecker,thomasvs/pychecker | pychecker2/utest/returns.py | pychecker2/utest/returns.py | from pychecker2.TestSupport import WarningTester
from pychecker2 import ReturnChecks
class ReturnTestCase(WarningTester):
def testReturnChecks(self):
w = ReturnChecks.MixedReturnCheck.mixedReturns
self.silent('def f(): return\n')
self.silent('def f(): return 1\n')
self.silent('def f(x):\n'
' if x:\n'
' return 0\n'
' return 1\n')
self.warning('def f(x):\n'
' if x:\n'
' return\n'
' return 1\n', 3, w, 'f')
self.silent('def f(x):\n'
' def g():\n'
' return\n'
' return x + g()\n')
| bsd-3-clause | Python | |
83580051da3ad427c815dca0ca88cc8005c014f2 | add nightly script to perform test over a wide range of parameters | exafmm/exafmm,exafmm/exafmm,exafmm/exafmm,exafmm/exafmm | nightly.py | nightly.py | import itertools
import os
import subprocess
# the range of each parameter
param_range = { 'n': ['2', '10', '100', '1000', '10000', '100000', '1000000', '10000000'],
'P': ['4', '10', '20', '30', '40'],
't': ['0.5', '0.4', '0.3', '0.2'],
'd': ['c', 's', 'o', 'p'] }
# the parameters of each test
test_params = { 'laplace_kernel': 'P',
'tree': 'nd',
'list': 'ntd',
'laplace': 'nPtd' }
exedir = '3d'
# loop over each test
for test, params in test_params.iteritems():
# concatenate ranges for itertools
ranges_list = [ param_range[param] for param in params]
# nested loop of each parameter's range
for values in itertools.product(*ranges_list):
# add dash before each parameter character (ex. 'n'->'-n')
dash_params = [ '-'+param for param in params]
# interleave parameter character list and their value list
args_list = list(itertools.chain(*zip(dash_params, values)))
# join test name and args list
command_str = os.path.join(exedir, test)+ " " + " ".join(args_list)
print(command_str)
# execute test
try:
subprocess.check_call(command_str, shell=True)
except subprocess.CalledProcessError:
print("Regression Failed @", command_str)
raise SystemExit
| bsd-3-clause | Python | |
7b29e5a735fe495c3504d585acab2826bbd44bf9 | Add tests for classes that use __eq__ | tomashaber/raiden,tomashaber/raiden,hackaugusto/raiden,hackaugusto/raiden,tomashaber/raiden,tomashaber/raiden,tomashaber/raiden | raiden/tests/unit/test_operators.py | raiden/tests/unit/test_operators.py | # -*- coding: utf-8 -*-
from raiden.utils import sha3
from raiden.transfer.state_change import (
ActionCancelTransfer,
ActionTransferDirect,
Block,
ReceiveTransferDirect,
)
from raiden.transfer.state import (
RouteState,
RoutesState,
)
from raiden.transfer.events import (
EventTransferSentSuccess,
EventTransferSentFailed,
EventTransferReceivedSuccess,
)
from raiden.transfer.mediated_transfer.state import LockedTransferState
from raiden.messages import Ack
ADDRESS = sha3('foo')[:20]
ADDRESS2 = sha3('boo')[:20]
ADDRESS3 = sha3('coo')[:20]
ADDRESS4 = sha3('goo')[:20]
SECRET = 'secret'
HASH = sha3(SECRET)
HASH2 = sha3('joo')
def test_transfer_statechange_operators():
a = Block(2)
b = Block(2)
c = Block(3)
assert a == b
assert not a != b
assert a != c
assert not a == c
a = ActionCancelTransfer(2)
b = ActionCancelTransfer(2)
c = ActionCancelTransfer(3)
assert a == b
assert not a != b
assert a != c
assert not a == c
a = ActionTransferDirect(2, 2, ADDRESS, ADDRESS)
b = ActionTransferDirect(2, 2, ADDRESS, ADDRESS)
c = ActionTransferDirect(3, 4, ADDRESS, ADDRESS2)
assert a == b
assert not a != b
assert a != c
assert not a == c
a = ReceiveTransferDirect(2, 2, ADDRESS, ADDRESS)
b = ReceiveTransferDirect(2, 2, ADDRESS, ADDRESS)
c = ReceiveTransferDirect(3, 4, ADDRESS, ADDRESS2)
assert a == b
assert not a != b
assert a != c
assert not a == c
def test_state_operators():
a_route = RouteState('opened', ADDRESS, ADDRESS2, 5, 5, 5, 5)
b_route = RouteState('opened', ADDRESS, ADDRESS2, 5, 5, 5, 5)
c_route = RouteState('closed', ADDRESS3, ADDRESS2, 1, 2, 3, 4)
assert a_route == b_route
assert not a_route != b_route
assert a_route != c_route
assert not a_route == c_route
d_route = RouteState('opened', ADDRESS4, ADDRESS, 1, 2, 3, 4)
a = RoutesState([a_route, d_route])
b = RoutesState([a_route, d_route])
c = RoutesState([a_route, c_route])
assert a == b
assert not a != b
assert a != c
assert not a == c
a = LockedTransferState(1, 2, ADDRESS, ADDRESS2, ADDRESS3, 4, HASH, 'secret')
b = LockedTransferState(1, 2, ADDRESS, ADDRESS2, ADDRESS3, 4, HASH, 'secret')
c = LockedTransferState(2, 4, ADDRESS3, ADDRESS4, ADDRESS, 4, HASH, 'secret')
assert a == b
assert not a != b
assert a != c
assert not a == c
def test_event_operators():
a = EventTransferSentSuccess(2)
b = EventTransferSentSuccess(2)
c = EventTransferSentSuccess(3)
assert a == b
assert not a != b
assert a != c
assert not a == c
a = EventTransferSentFailed(2, 'BECAUSE')
b = EventTransferSentFailed(2, 'BECAUSE')
c = EventTransferSentFailed(3, 'UNKNOWN')
assert a == b
assert not a != b
assert a != c
assert not a == c
a = EventTransferReceivedSuccess(2)
b = EventTransferReceivedSuccess(2)
c = EventTransferReceivedSuccess(3)
assert a == b
assert not a != b
assert a != c
assert not a == c
def test_message_operators():
a = Ack(ADDRESS, HASH)
b = Ack(ADDRESS, HASH)
c = Ack(ADDRESS2, HASH2)
assert a == b
assert not a != b
assert a != c
assert not a == c
| mit | Python | |
e7bbd7f975d478846843e14e83e238294feaee86 | Create mc_tools.py | oyamad/stochevolution | mc_tools.py | mc_tools.py | """
Filename: mc_tools.py
Authors: John Stachurski and Thomas J. Sargent
"""
import numpy as np
from discrete_rv import DiscreteRV
def mc_compute_stationary(P):
"""
Computes the stationary distribution of Markov matrix P.
Parameters
===========
P : a square 2D NumPy array
Returns: A flat array giving the stationary distribution
"""
n = len(P) # P is n x n
I = np.identity(n) # Identity matrix
B, b = np.ones((n, n)), np.ones((n, 1)) # Matrix and vector of ones
A = np.transpose(I - P + B)
solution = np.linalg.solve(A, b)
return solution.flatten() # Return a flat array
def mc_sample_path(P, init=0, sample_size=1000):
"""
Generates one sample path from a finite Markov chain with (n x n) Markov
matrix P on state space S = {0,...,n-1}.
Parameters
==========
P : A nonnegative 2D NumPy array with rows that sum to 1
init : Either an integer in S or a nonnegative array of length n
with elements that sum to 1
sample_size : int
If init is an integer, the integer is treated as the determinstic initial
condition. If init is a distribution on S, then X_0 is drawn from this
distribution.
Returns
========
A NumPy array containing the sample path
"""
# === set up array to store output === #
X = np.empty(sample_size, dtype=int)
if isinstance(init, int):
X[0] = init
else:
X[0] = DiscreteRV(init).draw()
# === turn each row into a distribution === #
# In particular, let P_dist[i] be the distribution corresponding to the
# i-th row P[i,:]
n = len(P)
P_dist = [DiscreteRV(P[i,:]) for i in range(n)]
# === generate the sample path === #
for t in range(sample_size - 1):
X[t+1] = P_dist[X[t]].draw()
return X
| mit | Python | |
a3e9097247f4abe660696e5bd19f06e7e5756249 | Add start of Python solution for day 9 (parsing only) | robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions | python/day9.py | python/day9.py | #!/usr/local/bin/python3
def parse_input(text):
"""Parse a list of destinations and weights
Returns a list of tuples (source, dest, weight).
Edges in this graph and undirected.
The input contains multiple rows appearing like so:
A to B = W
Where A and B are strings and W is the weight to travel
between them in a graph.
"""
def parse_line(line):
"""Parse a single line of the input"""
parts = line.split()
return (parts[0], parts[2], int(parts[4]))
return [parse_line(line) for line in text.splitlines()]
def test_parse():
"""Test parsing of a list of destinations and weights"""
puzzle_input = '''\
London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141'''
result = parse_input(puzzle_input)
assert result == [
('London', 'Dublin', 464),
('London', 'Belfast', 518),
('Dublin', 'Belfast', 141)
]
| mit | Python | |
1f5bd0236e3fd97287891c37bf64cadcae38c444 | add python | exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib,exmo-dev/exmo_api_lib | python/exmo.py | python/exmo.py | import httplib
import urllib
import json
import hashlib
import hmac
import time
api_key = "your_key"
api_secret = "your_secret"
nonce = int(round(time.time()*1000))
params = {"nonce": nonce}
params = urllib.urlencode(params)
H = hmac.new(api_secret, digestmod=hashlib.sha512)
H.update(params)
sign = H.hexdigest()
headers = {"Content-type": "application/x-www-form-urlencoded",
"Key":api_key,
"Sign":sign}
conn = httplib.HTTPSConnection("api.exmo.com")
conn.request("POST", "/v1/user_info", params, headers)
response = conn.getresponse()
print response.status, response.reason
print json.load(response)
conn.close() | mit | Python | |
5ba61a7898a8fe70bd19993f8b0f8c502f514621 | add batch cp | xiilei/pytools,xiilei/pytools | batchmv.py | batchmv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'xilei'
import os
import sys
import hashlib
import shutil
def md5hex(s):
m = hashlib.md5()
m.update(s.encode('UTF-8'))
return m.hexdigest()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("miss args, use like batchmv.py /var/www/pdf")
sys.exit(0)
basePath = sys.argv[1]
print("basePath%s \r\n" % basePath)
for item in os.listdir(basePath):
src = os.path.join(basePath, item)
#只针对文件
if not os.path.isfile(src):
continue
prefix, ext = os.path.splitext(item)
# pdf
if ext != '.pdf':
continue
# hash重命名
newname = md5hex("pdf_"+prefix)+".pdf"
dst = os.path.join(basePath, newname)
shutil.copyfile(src=src, dst=dst)
print("mv:%s to %s \r\n" % (item, newname))
pass
| apache-2.0 | Python | |
422baea7ea6120dae3f7ac0d412a19b66958e3ad | Add migration | dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore | project/apps/api/migrations/0074_catalog_song_name.py | project/apps/api/migrations/0074_catalog_song_name.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0073_auto_20151027_1111'),
]
operations = [
migrations.AddField(
model_name='catalog',
name='song_name',
field=models.CharField(max_length=200, blank=True),
),
]
| bsd-2-clause | Python | |
c1a5bd8268890f359427f578204886fe5d01909e | Add a large, graphical integration test. | probcomp/cgpm,probcomp/cgpm | tests/graphical/one_view.py | tests/graphical/one_view.py | # -*- coding: utf-8 -*-
# Copyright (c) 2015-2016 MIT Probabilistic Computing Project
# 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 cgpm.crosscat.state import State
from cgpm.utils import config as cu
from cgpm.utils import general as gu
from cgpm.utils import test as tu
# Set up the data generation
cctypes, distargs = cu.parse_distargs(
['normal',
'poisson',
'bernoulli',
'categorical(k=4)',
'lognormal',
'exponential',
'beta_uc',
'geometric',
'vonmises'])
T, Zv, Zc = tu.gen_data_table(
200, [1], [[.25, .25, .5]], cctypes, distargs,
[.95]*len(cctypes), rng=gu.gen_rng(10))
state = State(T.T, cctypes=cctypes, distargs=distargs, rng=gu.gen_rng(312))
state.transition(N=10, progress=1)
def test_crash_simulate_joint(state):
state.simulate(-1, [0, 1, 2, 3, 4, 5, 6, 7, 8], N=10)
def test_crash_logpdf_joint(state):
state.logpdf(-1, {0:1, 1:2, 2:1, 3:3, 4:1, 5:10, 6:.4, 7:2, 8:1.8})
def test_crash_simulate_conditional(state):
state.simulate(-1, [1, 4, 5, 6, 7, 8], evidence={0:1, 2:1, 3:3}, N=10)
def test_crash_logpdf_conditional(state):
state.logpdf(
-1, {1:2, 4:1, 5:10, 6:.4, 7:2, 8:1.8}, evidence={0:1, 2:1, 3:3})
def test_crash_simulate_joint_observed(state):
state.simulate(1, [0, 1, 2, 3, 4, 5, 6, 7, 8], N=10)
def test_crash_logpdf_joint_observed(state):
# XXX DETERMINE ME
state.logpdf(1, {0:1, 1:2, 2:1, 3:3, 4:1, 5:10, 6:.4, 7:2, 8:1.8})
def test_crash_simulate_conditional_observed(state):
try:
state.simulate(1, [1, 4, 5, 6, 7, 8], evidence={0:1, 2:1, 3:3}, N=10)
assert False
except:
pass
def test_crash_logpdf_conditional_observed(state):
try:
state.logpdf(
1, {1:2, 4:1, 5:10, 6:.4, 7:2, 8:1.8}, evidence={0:1, 2:1, 3:3})
assert False
except:
pass
# Plot!
state.plot()
# Run some solid checks on a complex state.
test_crash_simulate_joint(state)
test_crash_logpdf_joint(state)
test_crash_simulate_conditional(state)
test_crash_logpdf_conditional(state)
test_crash_simulate_joint_observed(state)
test_crash_logpdf_joint_observed(state)
test_crash_simulate_conditional_observed(state)
test_crash_logpdf_conditional_observed(state)
| apache-2.0 | Python | |
552b5d97fc9a0298ca43c316aad3d221234b894c | Add fontTools.misc.classifyTools, helpers to classify things into classes | fonttools/fonttools,googlefonts/fonttools | Lib/fontTools/misc/classifyTools.py | Lib/fontTools/misc/classifyTools.py | """ fontTools.misc.classifyTools.py -- tools for classifying things.
"""
from __future__ import print_function, absolute_import
from fontTools.misc.py23 import *
class Classifier:
"""
Main Classifier object, used to classify things into similar sets.
"""
def __init__(self, sorted=True):
self._things = set() # set of all things known so far
self._sets = [] # list of class sets produced so far
self._mapping = {} # map from things to their class set
self._dirty = False
self._sorted = sorted
def add(self, set_of_things):
"""
Add a set to the classifier. Any iterable is accepted.
"""
if not set_of_things:
return;
self._dirty = True
things, sets, mapping = self._things, self._sets, self._mapping
s = set(set_of_things)
intersection = s.intersection(things) # existing things
s.difference_update(intersection) # new things
difference = s
del s
# Add new class for new things
if difference:
things.update(difference)
sets.append(difference)
for thing in difference:
mapping[thing] = difference
del difference
while intersection:
# Take one item and process the old class it belongs to
old_class = mapping[next(iter(intersection))]
old_class_intersection = old_class.intersection(intersection)
# Update old class to remove items from new set
old_class.difference_update(old_class_intersection)
# Remove processed items from todo list
intersection.difference_update(old_class_intersection)
# Add new class for the intersection with old class
sets.append(old_class_intersection)
for thing in old_class_intersection:
mapping[thing] = old_class_intersection
del old_class_intersection
def update(self, list_of_sets):
"""
Add a a list of sets to the classifier. Any iterable of iterables is accepted.
"""
for s in list_of_sets:
self.add(s)
def _process(self):
if not self._dirty:
return
# Do any deferred processing
sets = self._sets
self._sets = [s for s in sets if s]
if self._sorted:
self._sets = sorted(self._sets, key=lambda s: (-len(s), s))
self._dirty = False
# Output methods
def getThings(self):
"""Returns the set of all things known so far.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._things
def getMapping(self):
"""Returns the mapping from things to their class set.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._mapping
def getClasses(self):
"""Returns the list of class sets.
The return value belongs to the Classifier object and should NOT
be modified while the classifier is still in use.
"""
self._process()
return self._sets
def classify(list_of_sets, sorted=True):
"""
Takes a iterable of iterables (list of sets from here on; but any
iterable works.), and returns the smallest list of sets such that
each set, is either a subset, or is disjoint from, each of the input
sets.
In other words, this function classifies all the things present in
any of the input sets, into similar classes, based on which sets
things are a member of.
If sorted=True, return class sets are sorted by decreasing size and
their natural sort order within each class size. Otherwise, class
sets are returned in the order that they were identified, which is
generally not significant.
>>> classify([])
([], {})
>>> classify([[]])
([], {})
>>> classify([[], []])
([], {})
>>> classify([[1]])
([set([1])], {1: set([1])})
>>> classify([[1,2]])
([set([1, 2])], {1: set([1, 2]), 2: set([1, 2])})
>>> classify([[1],[2]])
([set([1]), set([2])], {1: set([1]), 2: set([2])})
>>> classify([[1,2],[2]])
([set([1]), set([2])], {1: set([1]), 2: set([2])})
>>> classify([[1,2],[2,4]])
([set([1]), set([4]), set([2])], {1: set([1]), 2: set([2]), 4: set([4])})
>>> classify([[1,2],[2,4,5]])
([set([4, 5]), set([1]), set([2])], {1: set([1]), 2: set([2]), 4: set([4, 5]), 5: set([4, 5])})
>>> classify([[1,2],[2,4,5]], sorted=False)
([set([1]), set([4, 5]), set([2])], {1: set([1]), 2: set([2]), 4: set([4, 5]), 5: set([4, 5])})
>>> classify([[1,2,9],[2,4,5]], sorted=False)
([set([1, 9]), set([4, 5]), set([2])], {1: set([1, 9]), 2: set([2]), 4: set([4, 5]), 5: set([4, 5]), 9: set([1, 9])})
>>> classify([[1,2,9,15],[2,4,5]], sorted=False)
([set([1, 15, 9]), set([4, 5]), set([2])], {1: set([1, 15, 9]), 2: set([2]), 4: set([4, 5]), 5: set([4, 5]), 9: set([1, 15, 9]), 15: set([1, 15, 9])})
>>> classify([[1,2,9,15],[2,4,5],[15,5]], sorted=False)
([set([1, 9]), set([4]), set([2]), set([5]), set([15])], {1: set([1, 9]), 2: set([2]), 4: set([4]), 5: set([5]), 9: set([1, 9]), 15: set([15])})
"""
classifier = Classifier(sorted=sorted)
classifier.update(list_of_sets)
return classifier.getClasses(), classifier.getMapping()
if __name__ == "__main__":
import doctest
sys.exit(doctest.testmod(optionflags=doctest.ELLIPSIS).failed)
| mit | Python | |
67d44755557347a390ede3a4b5f872dc08b73805 | add tests for weighting angles | RI-imaging/ODTbrain,RI-imaging/ODTbrain,paulmueller/ODTbrain | tests/test_angle_weights.py | tests/test_angle_weights.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Tests backpropagation algorithm
"""
from __future__ import division, print_function
import numpy as np
import os
from os.path import abspath, basename, dirname, join, split, exists
import platform
import sys
import warnings
import zipfile
# Add parent directory to beginning of path variable
DIR = dirname(abspath(__file__))
sys.path = [split(DIR)[0]] + sys.path
import odtbrain
import odtbrain._Back_2D
import odtbrain._util
from common_methods import create_test_sino_2d, get_test_parameter_set, write_results, get_results
def test_angle_offset():
myframe = sys._getframe()
myname = myframe.f_code.co_name
print("running ", myname)
sino, angles = create_test_sino_2d()
parameters = get_test_parameter_set(2)
# reference
r1 = []
for p in parameters:
f1 = odtbrain._Back_2D.backpropagate_2d(sino, angles, weight_angles=False, **p)
r1.append(f1)
# with offset
angles[::2] += 2*np.pi*np.arange(angles[::2].shape[0])
r2 = []
for p in parameters:
f2 = odtbrain._Back_2D.backpropagate_2d(sino, angles, weight_angles=False, **p)
r2.append(f2)
# with offset and weights
r3 = []
for p in parameters:
f3 = odtbrain._Back_2D.backpropagate_2d(sino, angles, weight_angles=True, **p)
r3.append(f3)
assert np.allclose(np.array(r1).flatten().view(float),
np.array(r2).flatten().view(float))
assert np.allclose(np.array(r2).flatten().view(float),
np.array(r3).flatten().view(float))
def test_angle_swap():
myframe = sys._getframe()
myname = myframe.f_code.co_name
print("running ", myname)
sino, angles = create_test_sino_2d()
# remove elements so that we can see that weighting works
angles = angles[:-2]
sino = sino[:-2,:]
parameters = get_test_parameter_set(2)
# reference
r1 = []
for p in parameters:
f1 = odtbrain._Back_2D.backpropagate_2d(sino, angles, weight_angles=True, **p)
r1.append(f1)
# change order of angles
order = np.argsort(angles % .5)
angles = angles[order]
sino = sino[order,:]
r2 = []
for p in parameters:
f2 = odtbrain._Back_2D.backpropagate_2d(sino, angles, weight_angles=True, **p)
r2.append(f2)
assert np.allclose(np.array(r1).flatten().view(float),
np.array(r2).flatten().view(float))
if __name__ == "__main__":
# Run all tests
loc = locals()
for key in list(loc.keys()):
if key.startswith("test_") and hasattr(loc[key], "__call__"):
loc[key]()
| bsd-3-clause | Python | |
594df6d33eaa66acc5d232b9ea3fcbb8917ca26e | Update user tests | fernando24164/flask_api,fernando24164/flask_api | tests/test_user_security.py | tests/test_user_security.py | from unittest import TestCase
from app import create_app, db
from app.api.models import User
class UserModelTestCase(TestCase):
def setUp(self):
self.app = create_app('default')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
self.client = self.app.test_client(use_cookies=True)
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_password(self):
user = User(name='admin', pwd='admin')
self.assertTrue(user.verify_password('admin'))
| mit | Python | |
2f127de7520a0b689bfe5082360eeb53a05d6e2d | Add "repo overview" command. | folpindo/git-repo,baidurom/repo,venus-solar/git-repo,GatorQue/git-repo-flow,linuxdeepin/git-repo,martinjina/git-repo,ediTLJ/git-repo,zbunix/git-repo,GerritCodeReview/git-repo,HenningSchroeder/git-repo,hacker-camp/google_repo,FuangCao/repo,windyan/git-repo,hanchentech/git-repo,FuangCao/git-repo,jingyu/git-repo,ThangBK2009/android-source-browsing.git-repo,sapiippo/git-repo,jcfrank/myrepo,liaog/git-repo,dsiganos/git-repo,slfyusufu/repo,DavidPu/git-repo,opencontrail-ci-admin/git-repo,opensourcechipspark/repo,josn-jys/git-repo,nuclearmistake/repo,linux-knight/repo,gabbayo/git-repo,CyanogenMod/tools_repo,alanbian/git-repo,xianyo/git-repo,SunRain/repo,RuanJG/git-repo,Omnifarious/git-repo,demonyangyue/git-repo,dodocat/git-repo,linuxdeepin/git-repo,xyyangkun/git-repo,ericmckean/git-repo,SaleJumper/android-source-browsing.git-repo,LA-Toth/git-repo,SunRain/repo,hyper123/git-repo,idwanglu2010/git-repo,FlymeOS/repo,aep/repo,kdavis-mozilla/repo-repo,nucked/git-repo,ilansmith/repo,hanw/git-repo,fantasyfly/git-repo,zemug/repo,IbpTeam/repo,vmx/git-repo,masscre/git-repo,hisilicon/git-repo,ilansmith/repo,lewixliu/git-repo,crashkita/git-repo,flingone/git-repo,urras/git-repo,amersons/git-repo,eligoenergy/git-repo,artprogramming/git-repo,ChronoMonochrome/repo,xecle/git-repo,chenyun90323/git-repo,linux-knight/repo,vmx/git-repo,chusiang/git-repo,codetutil/git-repo,weixiaodong/git-repo,crashkita/git-repo,mixedpuppy/git-repo,11NJ/git-repo,hacker-camp/google_repo,lipro-yocto/git-repo,COrtegaflowcorp/git-repo,xxxrac/git-repo,djibi2/git-repo,lewixliu/git-repo,qupai/git-repo,dsiganos/git-repo,FlymeOS/repo,AurelienBallier/git-repo,zodsoft/git-repo,azzurris/git-repo,nuclearmistake/repo,aep/repo,TheQtCompany/git-repo,testbetta/repo-pub,jmollan/git-repo,lshain/repo,todototry/git-repo,weixiaodong/git-repo,chenzilin/git-repo,xin3liang/git-repo,idwanglu2010/git-repo,darrengarvey/git-repo,azzurris/git-repo,hyper123/git-repo,xxxrac/git-repo,chzhong/git-repo,baidurom/repo,jcfrank/myrepo,hackbutty/git-repo,lchiocca/repo,lanniaoershi/git-repo,amersons/git-repo,4455jkjh/repo,lightsofapollo/git-repo,finik/git-repo,ThangBK2009/android-source-browsing.git-repo,todototry/git-repo,Pivosgroup/google-git-repo,biaolv/git-repo,SaleJumper/android-source-browsing.git-repo,yanjiegit/andriod-repo,gbraad/git-repo,Fr4ncky/git-repo,couchbasedeps/git-repo,llg84/google_repo,sapiippo/git-repo,aosp-mirror/tools_repo,FuangCao/git-repo,cubieboard/git-repo,opencontrail-ci-admin/git-repo,jangle789/git-repo,ronan22/repo,mozilla/git-repo,Jokebin/git-repo,rochy2014/repo,RuanJG/git-repo,AurelienBallier/git-repo,wzhy90/git-repo,xecle/git-repo,HenningSchroeder/git-repo,zemug/repo,xyyangkun/git-repo,frogbywyplay/git-repo,couchbasedeps/git-repo,chenyun90323/git-repo,qioixiy/git-repo,venus-solar/git-repo,qingpingguo/git-repo,llg84/google_repo,artprogramming/git-repo,IbpTeam/repo,loungin/git-repo,linux-knight/repo,daimajia/git-repo,jingyu/git-repo,posix4e/git-repo,chusiang/git-repo,DavidPu/git-repo,petemoore/git-repo,finik/git-repo,hisilicon/git-repo,qingpingguo/git-repo,TheQtCompany/git-repo,kdavis-mozilla/repo-repo,hanw/git-repo,jpzhu/git-repo,kangear/git-repo,simbasailor/git-repo,ediTLJ/git-repo,liaog/git-repo,testbetta/repo-pub,mozilla/git-repo,lightsofapollo/git-repo,Pankaj-Sakariya/android-source-browsing.git-repo,gabbayo/git-repo,mixedpuppy/git-repo,duralog/repo,wavecomp/git-repo,Pankaj-Sakariya/android-source-browsing.git-repo,nbp/git-repo,xin3liang/git-repo,nucked/git-repo,slfyusufu/repo,dinpot/git-repo,jmollan/git-repo,testbetta/git-repo-pub,hejq0310/git-repo,nbp/git-repo,hackbutty/git-repo,bhargavkumar040/android-source-browsing.git-repo,petemoore/git-repo,wavecomp/git-repo,demonyangyue/git-repo,zodsoft/git-repo,mer-tools/git-repo,cubieboard/git-repo,jangle789/git-repo,windyan/git-repo,GerritCodeReview/git-repo,sb2008/git-repo,Copypeng/git-repo,alessandro-aglietti/git-repo,luohongzhen/git-repo,lanniaoershi/git-repo,wzhy90/git-repo,qupai/git-repo,aep/repo,11NJ/git-repo,duralog/repo,luohongzhen/git-repo,qioixiy/git-repo,josn-jys/git-repo,zbunix/git-repo,eric011/git-repo,eric011/git-repo,ceejatec/git-repo,Pivosgroup/google-git-repo,testbetta/git-repo-pub,hejq0310/git-repo,ericmckean/git-repo,Copypeng/git-repo,enochcheng/git-repo,opensourcechipspark/repo,lshain/repo,enochcheng/git-repo,ronan22/repo,flingone/git-repo,posix4e/git-repo,rochy2014/repo,derron/git-repo,Omnifarious/git-repo,yanjiegit/andriod-repo,masscre/git-repo,ceejatec/git-repo,derron/git-repo,Fr4ncky/git-repo,4455jkjh/repo,alessandro-aglietti/git-repo,dsiganos/git-repo,dodocat/git-repo,LA-Toth/git-repo,GatorQue/git-repo-flow,bhargavkumar040/android-source-browsing.git-repo,daimajia/git-repo,sb2008/git-repo,xianyo/git-repo,finik/git-repo,codetutil/git-repo,ChronoMonochrome/repo,gbraad/git-repo,djibi2/git-repo,hanchentech/git-repo,mer-tools/git-repo,simbasailor/git-repo,eligoenergy/git-repo,frogbywyplay/git-repo,fantasyfly/git-repo,jpzhu/git-repo,chzhong/git-repo,iAlios/git-repo,CyanogenMod/tools_repo,aosp-mirror/tools_repo,FuangCao/repo,folpindo/git-repo,Omnifarious/git-repo,biaolv/git-repo,kangear/git-repo,iAlios/git-repo,COrtegaflowcorp/git-repo,urras/git-repo,lipro-yocto/git-repo,darrengarvey/git-repo,zbunix/git-repo,Jokebin/git-repo,chenzilin/git-repo,dinpot/git-repo,lchiocca/repo,alanbian/git-repo,cubieboard/git-repo,yanjiegit/andriod-repo,martinjina/git-repo,loungin/git-repo | subcmds/overview.py | subcmds/overview.py | #
# Copyright (C) 2012 The Android Open Source Project
#
# 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 color import Coloring
from command import PagedCommand
class Overview(PagedCommand):
common = True
helpSummary = "Display overview of unmerged project branches"
helpUsage = """
%prog [--current-branch] [<project>...]
"""
helpDescription = """
The '%prog' command is used to display an overview of the projects branches,
and list any local commits that have not yet been merged into the project.
The -b/--current-branch option can be used to restrict the output to only
branches currently checked out in each project. By default, all branches
are displayed.
"""
def _Options(self, p):
p.add_option('-b', '--current-branch',
dest="current_branch", action="store_true",
help="Consider only checked out branches")
def Execute(self, opt, args):
all = []
for project in self.GetProjects(args):
br = [project.GetUploadableBranch(x)
for x in project.GetBranches().keys()]
br = [x for x in br if x]
if opt.current_branch:
br = [x for x in br if x.name == project.CurrentBranch]
all.extend(br)
if not all:
return
class Report(Coloring):
def __init__(self, config):
Coloring.__init__(self, config, 'status')
self.project = self.printer('header', attr='bold')
out = Report(all[0].project.config)
out.project('Projects Overview')
out.nl()
project = None
for branch in all:
if project != branch.project:
project = branch.project
out.nl()
out.project('project %s/' % project.relpath)
out.nl()
commits = branch.commits
date = branch.date
print '%s %-33s (%2d commit%s, %s)' % (
branch.name == project.CurrentBranch and '*' or ' ',
branch.name,
len(commits),
len(commits) != 1 and 's' or ' ',
date)
for commit in commits:
print '%-35s - %s' % ('', commit)
| apache-2.0 | Python | |
9da427f7b1345ba140561a213cb24f857c3f3482 | Add partial spamhandling tests | Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector,ArtOfCode-/SmokeDetector,ArtOfCode-/SmokeDetector,Charcoal-SE/SmokeDetector,NickVolynkin/SmokeDetector | test/test_spamhanding.py | test/test_spamhanding.py | from spamhandling import *
import pytest
@pytest.mark.parametrize("title, body, username, site, match", [
('18669786819 gmail customer service number 1866978-6819 gmail support number', '', '', '', True),
('Is there any http://www.hindawi.com/ template for Cloud-Oriented Data Center Networking?', '', '', '', True),
('', '', 'bagprada', '', True),
('HOW DO YOU SOLVE THIS PROBLEM?', '', '', '', True),
('12 Month Loans quick @ http://www.quick12monthpaydayloans.co.uk/Elimination of collateral pledging', '', '', '', True),
('support for yahoo mail 18669786819 @call for helpline number', '', '', '', True),
('yahoo email tech support 1 866 978 6819 Yahoo Customer Phone Number ,Shortest Wait', '', '', '', True),
('What is the value of MD5 checksums if the MD5 hash itself could potentially also have been manipulated?', '', '', '', False),
('Probability: 6 Dice are rolled. Which is more likely, that you get exactly one 6, or that you get 6 different numbers?', '', '', '', False),
('The Challenge of Controlling a Powerful AI', '', 'Serban Tanasa', '', False),
('Reproducing image of a spiral using TikZ', '', 'Kristoffer Ryhl', '', False),
('What is the proper way to say "queryer"', '', 'jedwards', '', False),
('What\'s a real-world example of "overfitting"?', '', 'user3851283', '', False),
('How to avoid objects when traveling at greater than .75 light speed. or How Not to Go SPLAT?', '', 'bowlturner', '', False),
('Is it unfair to regrade prior work after detecting cheating?', '', 'Village', '', False),
('Inner workings of muscles', '', '', 'fitness.stackexchange.com', False),
('Cannot access http://stackoverflow.com/ with proxy enabled', '', '', 'superuser.com', False),
('kkkkkkkkkkkkkkkkkkkkkkkkkkkk', '<p>bbbbbbbbbbbbbbbbbbbbbb</p>', '', 'stackoverflow.com', True)
])
def test_check_if_spam(title, body, username, site, match):
# We can't check blacklists/whitelists in tests, so these are set to their default values
user_url = ""
post_id = 0
# If we want to test answers separatly, this should be changed
is_answer = False
is_spam = check_if_spam(title, body, username, user_url, site, post_id, is_answer)
print title
assert match == is_spam
| apache-2.0 | Python | |
8979c2122abc6f37b31fe9d4193ef9df350d73f0 | Add bwt implementation | elvinyung/misc,elvinyung/misc | bwt/bwt.py | bwt/bwt.py |
def encode(s):
shifts = []
for i in range(len(s)):
shifts.append(s[i:] + s[:i])
shifts.sort()
encoded = ''.join(shifted[-1] for shifted in shifts)
return encoded, shifts.index(s)
def decode(s, indx):
table = ['' for ch in s]
for _ch in s:
for k in range(len(table)):
table[k] = s[k] + table[k]
table.sort()
return table[indx]
if __name__ == '__main__':
source = input().strip()
encoded = encode(source)
print('encoded:', encoded)
print('decoded:', decode(*encoded))
| mit | Python | |
b81825eb66bd5a9dac6a1e3ff4dfb99e6addd5ac | add ex0 template | zusantunfimmeri/python-exercises | ch3/ex0.py | ch3/ex0.py | #!/usr/bin/env python
#
# To be used as an exercise template for all the rest of the exercises.
#
# Style guide to be used: https://google.github.io/styleguide/pyguide.html
#
def main():
print "Hello world!"
return
if __name__ == '__main__':
main()
| agpl-3.0 | Python | |
9572f256d57bb43cac63cbf0325226d36426eb8d | Add urls file for pods. | praekelt/casepro,rapidpro/casepro,rapidpro/casepro,xkmato/casepro,rapidpro/casepro,praekelt/casepro,xkmato/casepro,praekelt/casepro | casepro/pods/urls.py | casepro/pods/urls.py | from casepro.pods.registry import get_url_patterns
urlpatterns = get_url_patterns()
| bsd-3-clause | Python | |
17831f16aadece921fe2424f305c1c368e12c6e7 | Add user defined operator | nerevu/riko,nerevu/riko | riko/modules/udf.py | riko/modules/udf.py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.udf
~~~~~~~~~~~~~~~~
Provides functions for performing an arbitrary (user-defined) function on stream
items.
Examples:
basic usage::
>>> from riko.modules.udf import pipe
>>>
>>> items = [{'x': x} for x in range(5)]
>>> func = lambda item: {'y': item['x'] + 3}
>>> next(pipe(items, func=func))
{'y': 3}
"""
from . import operator
import pygogo as gogo
logger = gogo.Gogo(__name__, monolog=True).logger
def parser(stream, objconf, tuples, **kwargs):
""" Parses the pipe content
Args:
stream (Iter[dict]): The source. Note: this shares the `tuples`
iterator, so consuming it will consume `tuples` as well.
objconf (obj): the item independent configuration (an Objectify
instance).
tuples (Iter[(dict, obj)]): Iterable of tuples of (item, objconf)
`item` is an element in the source stream and `objconf` is the item
configuration (an Objectify instance). Note: this shares the
`stream` iterator, so consuming it will consume `stream` as well.
kwargs (dict): Keyword arguments.
Returns:
Iter(dict): The output stream
Examples:
>>> from meza.fntools import Objectify
>>> from itertools import repeat
>>>
>>> func = lambda item: {'y': item['x'] + 3}
>>> stream = ({'x': x} for x in range(5))
>>> tuples = zip(stream, repeat(None))
>>> next(parser(stream, None, tuples, func=func))
{'y': 3}
"""
return map(kwargs['func'], stream)
@operator(isasync=True)
def async_pipe(*args, **kwargs):
"""An aggregator that asynchronously returns a specified number of items
from a stream.
Args:
items (Iter[dict]): The source.
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
func (callable): User defined function to apply to each stream item.
Returns:
Deferred: twisted.internet.defer.Deferred truncated stream
Examples:
>>> from riko.bado import react
>>> from riko.bado.mock import FakeReactor
>>>
>>> def run(reactor):
... callback = lambda x: print(next(x))
... func = lambda item: {'y': item['x'] + 3}
... items = ({'x': x} for x in range(5))
... d = async_pipe(items, func=func)
... return d.addCallbacks(callback, logger.error)
>>>
>>> try:
... react(run, _reactor=FakeReactor())
... except SystemExit:
... pass
...
{'y': 3}
"""
return parser(*args, **kwargs)
@operator()
def pipe(*args, **kwargs):
"""An operator that returns a specified number of items from a stream.
Args:
items (Iter[dict]): The source.
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
func (callable): User defined function to apply to each stream item.
Yields:
dict: an item
Examples:
>>> items = [{'x': x} for x in range(5)]
>>> func = lambda item: {'y': item['x'] + 3}
>>> next(pipe(items, func=func))
{'y': 3}
"""
return parser(*args, **kwargs)
| mit | Python | |
b95e5cd706a1cf81e41debae30422345cef3a1ee | Add simple parser to return some activity numbers from our git log. | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/committerparser.py | tests/committerparser.py | #!/usr/bin/python
import sys
import getopt
import re
import email.utils
import datetime
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def parse_date(datestr):
d = email.utils.parsedate(datestr)
return datetime.datetime(d[0],d[1],d[2],d[3],d[4],d[5],d[6])
def parse_gitlog(filename=None):
results = {}
commits = {}
if not filename or filename == '-':
fh = sys.stdin
else:
fh = open(filename, 'r+')
commitcount = 0
for line in fh.readlines():
line = line.rstrip()
if line.startswith('commit '):
new_commit = True
commitcount += 1
continue
if line.startswith('Author:'):
author = re.match('Author:\s+(.*)\s+<(.*)>', line)
if author:
email = author.group(2)
continue
if line.startswith('Date:'):
isodate = re.match('Date:\s+(.*)', line)
d = parse_date(isodate.group(1))
continue
if len(line) < 2 and new_commit:
new_commit = False
key = '{0}-{1}'.format(d.year, str(d.month).zfill(2))
if key not in results:
results[key] = []
if key not in commits:
commits[key] = 0
if email not in results[key]:
results[key].append(email)
commits[key] += commitcount
commitcount = 0
fh.close()
return (results, commits)
def count_results(results, commits):
result_str = ''
print('Date\tContributors\tCommits')
for k in sorted(results.iterkeys()):
result_str += '{0}\t{1}\t{2}'.format(k, len(results[k]), commits[k])
result_str += '\n'
return result_str
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if len(opts) > 0:
if '-h' in opts[0] or '--help' in opts[0]:
print('committerparser.py [- | logfilename]')
print(' : Parse commit log from git and print number of commits and unique committers')
print(' : by month. Accepts a filename or reads from stdin.')
return 0
data, counts = parse_gitlog(filename=args[0])
print count_results(data, counts)
if __name__ == "__main__":
sys.exit(main()) | apache-2.0 | Python | |
666582ff2edf201102e88038e8053908b8020472 | add player data test | jaebradley/nba_data | tests/test_playerData.py | tests/test_playerData.py | from unittest import TestCase
from nba_data.data.player_data import PlayerData
class TestPlayerData(TestCase):
def test_instantiation(self):
player_id = '1234'
name = 'jae'
jersey = 0
team_seasons = list()
self.assertIsNotNone(PlayerData(player_id=player_id, name=name, jersey=jersey, team_seasons=team_seasons))
self.assertRaises(AssertionError, PlayerData, 1, name, jersey, team_seasons)
self.assertRaises(AssertionError, PlayerData, player_id, 1, jersey, team_seasons)
self.assertRaises(AssertionError, PlayerData, player_id, name, '1', team_seasons)
self.assertRaises(AssertionError, PlayerData, player_id, name, jersey, 1)
| mit | Python | |
19bff8fb2141e9e389e4af057c4ea1623a07ac47 | Add serializer test | Callwoola/tinydb,raquel-ucl/tinydb,cagnosolutions/tinydb,msiemens/tinydb,ivankravets/tinydb | tests/test_serializer.py | tests/test_serializer.py | from datetime import datetime
from tinydb import TinyDB, where
from tinydb.middlewares import SerializationMiddleware
from tinydb.serialize import Serializer
from tinydb.storages import MemoryStorage
class DateTimeSerializer(Serializer):
OBJ_CLASS = datetime
FORMAT = '%Y-%m-%dT%H:%M:%S'
def encode(self, obj):
return obj.strftime(self.FORMAT)
def decode(self, s):
return datetime.strptime(s, self.FORMAT)
def test_serializer():
serializer = SerializationMiddleware(MemoryStorage)
serializer.register_serializer(DateTimeSerializer(), 'TinyDate')
db = TinyDB(storage=serializer)
date = datetime(2000, 1, 1, 12, 0, 0)
db.insert({'date': date})
assert db.count(where('date') == date) == 1
| mit | Python | |
3020b2084b24f1e00f0b9fc1d06186b1e697647e | Test long jid passed on CLI | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/unit/utils/args.py | tests/unit/utils/args.py | # -*- coding: utf-8 -*-
# Import Salt Libs
from salt.utils import args
# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.mock import NO_MOCK, NO_MOCK_REASON
from salttesting.helpers import ensure_in_syspath
ensure_in_syspath('../../')
@skipIf(NO_MOCK, NO_MOCK_REASON)
class ArgsTestCase(TestCase):
'''
TestCase for salt.utils.args module
'''
def test_condition_input_string(self):
'''
Test passing a jid on the command line
'''
cmd = args.condition_input(['*', 'foo.bar', 20141020201325675584], None)
self.assertIsInstance(cmd[2], str)
if __name__ == '__main__':
from integration import run_tests
run_tests(ArgsTestCase, needs_daemon=False)
| apache-2.0 | Python | |
8f597e766e9ef8014da4391a7109d9b77daf127e | Add tests for user utilities sum_ and prod_ | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge | tests/user_utils_test.py | tests/user_utils_test.py | """Tests for user utility functions."""
from drudge import Vec, sum_, prod_
from drudge.term import parse_terms
def test_sum_prod_utility():
"""Test the summation and product utility."""
v = Vec('v')
vecs = [v[i] for i in range(3)]
v0, v1, v2 = vecs
# The proxy object cannot be directly compared.
assert parse_terms(sum_(vecs)) == parse_terms(v0 + v1 + v2)
assert parse_terms(prod_(vecs)) == parse_terms(v0 * v1 * v2)
assert sum_([]) == 0
assert prod_([]) == 1
| mit | Python | |
49b3bc23edfb3016228c4f39e4af6e8909eb183f | Create the_supermarket_queue.py | Kunalpod/codewars,Kunalpod/codewars | the_supermarket_queue.py | the_supermarket_queue.py | #Kunal Gautam
#Codewars : @Kunalpod
#Problem name: The Supermarket Queue
#Problem level: 6 kyu
def queue_time(customers, n):
if not customers: return 0
li=customers[:n]
for customer in customers[n:]:
li[li.index(min(li))]+=customer
return max(li)
| mit | Python | |
06c3a417f0270d76a7fcc9e94fdb40f9952b9d12 | Add a login view that automatically starts the oauth2 flow for authenticating using the IdM server | jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud | src/wirecloud/fiware/views.py | src/wirecloud/fiware/views.py | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2013 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud 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.
# Wirecloud 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 Wirecloud. If not, see <http://www.gnu.org/licenses/>.
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
def login(request):
if request.user.is_authenticated():
url = request.GET.get(REDIRECT_FIELD_NAME, '/')
else:
url = reverse('socialauth_begin', kwargs={'backend': 'fiware'}) + '?' + request.GET.urlencode()
return HttpResponseRedirect(url)
| agpl-3.0 | Python | |
ba0ee66177f11fb1c13b00167b04e0ddd23f4e28 | Update bulma | miyakogi/wdom,miyakogi/wdom,miyakogi/wdom | wdom/themes/bulma.py | wdom/themes/bulma.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from wdom.tag import NewTagClass as NewTag
from wdom.tag import *
css_files = [
'//cdnjs.cloudflare.com/ajax/libs/bulma/0.0.20/css/bulma.min.css',
]
js_files = []
headers = []
Button = NewTag('Button', bases=Button, class_='button')
DefaultButton = NewTag('DefaultButton', 'button', Button)
PrimaryButton = NewTag('PrimaryButton', 'button', Button, class_='is-primary')
SuccessButton = NewTag('SuccessButton', 'button', Button, class_='is-success')
InfoButton = NewTag('InfoButton', 'button', Button, class_='is-info')
WarningButton = NewTag('WarningButton', 'button', Button, class_='is-warning')
DangerButton = NewTag('DangerButton', 'button', Button, class_='is-danger')
LinkButton = NewTag('LinkButton', 'button', Button, class_='is-link')
Input = NewTag('Input', 'input', Input, class_='input')
Textarea = NewTag('Textarea', 'textarea', Textarea, class_='textarea')
Select = NewTag('Select', 'select', Select, class_='form-control')
Table = NewTag('Table', 'table', Table, class_='table')
H1 = NewTag('H1', 'h1', H1, class_='title is-1')
H2 = NewTag('H2', 'h2', H2, class_='title is-2')
H3 = NewTag('H3', 'h3', H3, class_='title is-3')
H4 = NewTag('H4', 'h4', H4, class_='title is-4')
H5 = NewTag('H5', 'h5', H5, class_='title is-5')
H6 = NewTag('H6', 'h6', H6, class_='title is-6')
Container = NewTag('Container', 'div', class_='container')
Wrapper = Container
Row = NewTag('Row', 'div', class_='columns')
Col = NewTag('Col', 'div', class_='column')
Col1 = NewTag('Col', 'div', Col, class_='is-1')
Col2 = NewTag('Col', 'div', Col, class_='is-2')
Col3 = NewTag('Col', 'div', Col, class_='is-3')
Col4 = NewTag('Col', 'div', Col, class_='is-4')
Col5 = NewTag('Col', 'div', Col, class_='is-5')
Col6 = NewTag('Col', 'div', Col, class_='is-6')
Col7 = NewTag('Col', 'div', Col, class_='is-7')
Col8 = NewTag('Col', 'div', Col, class_='is-8')
Col9 = NewTag('Col', 'div', Col, class_='is-9')
Col10 = NewTag('Col', 'div', Col, class_='is-10')
Col11 = NewTag('Col', 'div', Col, class_='is-11')
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from wdom.tag import NewTagClass as NewTag
from wdom.tag import *
css_files = [
'//cdnjs.cloudflare.com/ajax/libs/bulma/0.0.20/css/bulma.min.css',
]
js_files = []
headers = []
Button = NewTag('Button', bases=Button, class_='button')
DefaultButton = NewTag('DefaultButton', 'button', Button)
PrimaryButton = NewTag('PrimaryButton', 'button', Button, class_='is-primary')
SuccessButton = NewTag('SuccessButton', 'button', Button, class_='is-success')
InfoButton = NewTag('InfoButton', 'button', Button, class_='is-info')
WarningButton = NewTag('WarningButton', 'button', Button, class_='is-warning')
DangerButton = NewTag('DangerButton', 'button', Button, class_='is-danger')
LinkButton = NewTag('LinkButton', 'button', Button, class_='is-link')
Input = NewTag('Input', 'input', Input, class_='input')
Textarea = NewTag('Textarea', 'textarea', Textarea, class_='textarea')
Select = NewTag('Select', 'select', Select, class_='form-control')
Table = NewTag('Table', 'table', Table, class_='table')
H1 = NewTag('H1', 'h1', H1, class_='title is-1')
H2 = NewTag('H2', 'h2', H2, class_='title is-2')
H3 = NewTag('H3', 'h3', H3, class_='title is-3')
H4 = NewTag('H4', 'h4', H4, class_='title is-4')
H5 = NewTag('H5', 'h5', H5, class_='title is-5')
H6 = NewTag('H6', 'h6', H6, class_='title is-6')
Container = NewTag('Container', 'div', class_='container')
Wrapper = Container
Row = NewTag('Row', 'div', class_='columns')
Col1 = NewTag('Col', 'div', class_='is-1')
Col2 = NewTag('Col', 'div', class_='is-2')
Col3 = NewTag('Col', 'div', class_='is-3')
Col4 = NewTag('Col', 'div', class_='is-4')
Col5 = NewTag('Col', 'div', class_='is-5')
Col6 = NewTag('Col', 'div', class_='is-6')
Col7 = NewTag('Col', 'div', class_='is-7')
Col8 = NewTag('Col', 'div', class_='is-8')
Col9 = NewTag('Col', 'div', class_='is-9')
Col10 = NewTag('Col', 'div', class_='is-10')
Col11 = NewTag('Col', 'div', class_='is-11')
| mit | Python |
07b01296bcbc8c8b9220c93d9014973704d88caa | add script/json/ts-pycurl.py | Zex/Starter,Zex/Starter,Zex/Starter | script/json/ts-pycurl.py | script/json/ts-pycurl.py | #!/usr/bin/env python
#
# ts-pycurl.py
#
# Author: Zex <top_zlynch@yahoo.com>
#
import pycurl
#import json
from os import path, mkdir
from basic import *
from StringIO import StringIO
if not path.isdir(RESPONSE_DIR):
mkdir(RESPONSE_DIR)
def case():
headers = {
#'Content-Type' : 'application/json'
#'Content-Type' : 'text/html',
}
data = {
}
conn = pycurl.Curl()
url = 'https://api.github.com/users/Zex/repos'
connbuf = StringIO()
conn.setopt(conn.URL, url)
conn.setopt(conn.WRITEFUNCTION, connbuf.write)
conn.setopt(conn.HTTPHEADER, [str(x)+':'+str(headers[x]) for x in headers.keys()])
conn.perform()
with open(RESPONSE_DIR+'/rsp_'+url.replace('/','.')+'.json', 'w') as fd:
fd.write('#headers:\n' + connbuf.getvalue() + '\n')
connbuf.close()
try:
case()
except Exception as e:
print e
| mit | Python | |
c51bb87714ade403aeabc9b4b4c62b4ee3a7a8c5 | Add test script for checking to see if scrobbling works on new installs | foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm,foocorp/gnu-fm | scripts/test-scrobble.py | scripts/test-scrobble.py | #!/usr/bin/env python
##### CONFIG #####
SERVER = "turtle.libre.fm"
USER = "testuser"
PASSWORD = "password"
##################
import gobble, datetime
print "Handshaking..."
gs = gobble.GobbleServer(SERVER, USER, PASSWORD, 'tst')
time = datetime.datetime.now() - datetime.timedelta(days=1) # Yesterday
track = gobble.GobbleTrack("Richard Stallman", "Free Software Song", time)
gs.add_track(track)
print "Submitting..."
gs.submit()
print "Done!"
| agpl-3.0 | Python | |
ff1da8b72e0b40d48e6d740bd9eee3fb8f391a58 | add NYU hyperopt search script | ferasha/curfil,ferasha/curfil,ferasha/curfil | scripts/hyperopt/hyperopt_search.py | scripts/hyperopt/hyperopt_search.py | #!/usr/bin/env python
from __future__ import print_function
import sys
import math
from hyperopt import fmin, tpe, hp
from hyperopt.mongoexp import MongoTrials
def get_space():
space = (hp.quniform('numTrees', 1, 10, 1),
hp.quniform('samplesPerImage', 10, 7500, 1),
hp.quniform('featureCount', 10, 7500, 1),
hp.quniform('minSampleCount', 1, 1000, 1),
hp.quniform('maxDepth', 5, 25, 1),
hp.quniform('boxRadius', 1, 127, 1),
hp.quniform('regionSize', 1, 127, 1),
hp.quniform('thresholds', 10, 60, 1),
hp.uniform('histogramBias', 0.0, 0.0),
)
return space
def get_exp(mongodb_url, database, exp_key):
trials = MongoTrials('mongo://%s/%s/jobs' % (mongodb_url, database), exp_key=exp_key)
space = get_space()
return trials, space
if __name__ == "__main__":
if len(sys.argv) < 4:
print("usage: %s <mongodb-url> <database> <experiment>" % sys.argv[0], file=sys.stderr)
sys.exit(1)
mongodb_url, database, exp_key = sys.argv[1:]
trials, space = get_exp(mongodb_url, database, exp_key)
best = fmin(fn=math.sin, space=space, trials=trials, algo=tpe.suggest, max_evals=1000)
print("best: %s" % (repr(best)))
| mit | Python | |
379171e30269cfa219bddb481a9300514941f083 | update header | ct-23/home-assistant,bdfoster/blumate,mikaelboman/home-assistant,pottzer/home-assistant,MartinHjelmare/home-assistant,mikaelboman/home-assistant,w1ll1am23/home-assistant,auduny/home-assistant,SEJeff/home-assistant,maddox/home-assistant,sfam/home-assistant,tchellomello/home-assistant,Zac-HD/home-assistant,mikaelboman/home-assistant,pschmitt/home-assistant,LinuxChristian/home-assistant,MungoRae/home-assistant,g12mcgov/home-assistant,pottzer/home-assistant,persandstrom/home-assistant,adrienbrault/home-assistant,mKeRix/home-assistant,deisi/home-assistant,badele/home-assistant,sfam/home-assistant,emilhetty/home-assistant,shaftoe/home-assistant,philipbl/home-assistant,aequitas/home-assistant,balloob/home-assistant,w1ll1am23/home-assistant,morphis/home-assistant,mezz64/home-assistant,tmm1/home-assistant,robjohnson189/home-assistant,alanbowman/home-assistant,open-homeautomation/home-assistant,eagleamon/home-assistant,devdelay/home-assistant,stefan-jonasson/home-assistant,ewandor/home-assistant,HydrelioxGitHub/home-assistant,nnic/home-assistant,Danielhiversen/home-assistant,florianholzapfel/home-assistant,Zyell/home-assistant,teodoc/home-assistant,open-homeautomation/home-assistant,shaftoe/home-assistant,dmeulen/home-assistant,shaftoe/home-assistant,jawilson/home-assistant,ct-23/home-assistant,rohitranjan1991/home-assistant,home-assistant/home-assistant,srcLurker/home-assistant,betrisey/home-assistant,pschmitt/home-assistant,xifle/home-assistant,jabesq/home-assistant,lukas-hetzenecker/home-assistant,mKeRix/home-assistant,instantchow/home-assistant,mKeRix/home-assistant,qedi-r/home-assistant,theolind/home-assistant,ErykB2000/home-assistant,sanmiguel/home-assistant,tchellomello/home-assistant,CCOSTAN/home-assistant,robjohnson189/home-assistant,aequitas/home-assistant,Teagan42/home-assistant,sfam/home-assistant,soldag/home-assistant,robbiet480/home-assistant,alexmogavero/home-assistant,titilambert/home-assistant,morphis/home-assistant,tboyce021/home-assistant,happyleavesaoc/home-assistant,tinloaf/home-assistant,sffjunkie/home-assistant,tmm1/home-assistant,hexxter/home-assistant,betrisey/home-assistant,nevercast/home-assistant,titilambert/home-assistant,nkgilley/home-assistant,oandrew/home-assistant,soldag/home-assistant,vitorespindola/home-assistant,jaharkes/home-assistant,bdfoster/blumate,Julian/home-assistant,g12mcgov/home-assistant,jaharkes/home-assistant,leppa/home-assistant,miniconfig/home-assistant,aoakeson/home-assistant,dmeulen/home-assistant,LinuxChristian/home-assistant,shaftoe/home-assistant,ct-23/home-assistant,instantchow/home-assistant,jnewland/home-assistant,LinuxChristian/home-assistant,robjohnson189/home-assistant,michaelarnauts/home-assistant,sdague/home-assistant,auduny/home-assistant,jamespcole/home-assistant,HydrelioxGitHub/home-assistant,happyleavesaoc/home-assistant,aoakeson/home-assistant,tomduijf/home-assistant,EricRho/home-assistant,ma314smith/home-assistant,turbokongen/home-assistant,hmronline/home-assistant,ewandor/home-assistant,nugget/home-assistant,JshWright/home-assistant,JshWright/home-assistant,postlund/home-assistant,robbiet480/home-assistant,michaelarnauts/home-assistant,hmronline/home-assistant,maddox/home-assistant,kyvinh/home-assistant,tboyce1/home-assistant,devdelay/home-assistant,stefan-jonasson/home-assistant,aequitas/home-assistant,JshWright/home-assistant,teodoc/home-assistant,instantchow/home-assistant,vitorespindola/home-assistant,Zyell/home-assistant,PetePriority/home-assistant,alexkolar/home-assistant,srcLurker/home-assistant,Zac-HD/home-assistant,Duoxilian/home-assistant,Julian/home-assistant,nnic/home-assistant,justyns/home-assistant,Nzaga/home-assistant,caiuspb/home-assistant,ewandor/home-assistant,balloob/home-assistant,deisi/home-assistant,emilhetty/home-assistant,nugget/home-assistant,keerts/home-assistant,michaelarnauts/home-assistant,bdfoster/blumate,qedi-r/home-assistant,tboyce1/home-assistant,aoakeson/home-assistant,coteyr/home-assistant,theolind/home-assistant,srcLurker/home-assistant,SEJeff/home-assistant,ct-23/home-assistant,teodoc/home-assistant,tomduijf/home-assistant,keerts/home-assistant,home-assistant/home-assistant,happyleavesaoc/home-assistant,deisi/home-assistant,tboyce1/home-assistant,EricRho/home-assistant,xifle/home-assistant,eagleamon/home-assistant,Duoxilian/home-assistant,persandstrom/home-assistant,badele/home-assistant,Smart-Torvy/torvy-home-assistant,FreekingDean/home-assistant,Theb-1/home-assistant,partofthething/home-assistant,florianholzapfel/home-assistant,florianholzapfel/home-assistant,toddeye/home-assistant,dmeulen/home-assistant,leoc/home-assistant,keerts/home-assistant,justyns/home-assistant,leoc/home-assistant,ErykB2000/home-assistant,mahendra-r/home-assistant,oandrew/home-assistant,sanmiguel/home-assistant,mezz64/home-assistant,hexxter/home-assistant,dorant/home-assistant,bdfoster/blumate,alexkolar/home-assistant,nnic/home-assistant,miniconfig/home-assistant,nkgilley/home-assistant,Duoxilian/home-assistant,devdelay/home-assistant,morphis/home-assistant,rohitranjan1991/home-assistant,miniconfig/home-assistant,florianholzapfel/home-assistant,jamespcole/home-assistant,emilhetty/home-assistant,jabesq/home-assistant,varunr047/homefile,coteyr/home-assistant,philipbl/home-assistant,caiuspb/home-assistant,ma314smith/home-assistant,jabesq/home-assistant,Theb-1/home-assistant,nevercast/home-assistant,open-homeautomation/home-assistant,mahendra-r/home-assistant,molobrakos/home-assistant,fbradyirl/home-assistant,auduny/home-assistant,xifle/home-assistant,Cinntax/home-assistant,varunr047/homefile,happyleavesaoc/home-assistant,badele/home-assistant,hexxter/home-assistant,aronsky/home-assistant,keerts/home-assistant,deisi/home-assistant,LinuxChristian/home-assistant,devdelay/home-assistant,tinloaf/home-assistant,philipbl/home-assistant,tomduijf/home-assistant,tinloaf/home-assistant,toddeye/home-assistant,joopert/home-assistant,g12mcgov/home-assistant,GenericStudent/home-assistant,Zac-HD/home-assistant,eagleamon/home-assistant,Teagan42/home-assistant,adrienbrault/home-assistant,kyvinh/home-assistant,jnewland/home-assistant,SEJeff/home-assistant,FreekingDean/home-assistant,balloob/home-assistant,DavidLP/home-assistant,Nzaga/home-assistant,sffjunkie/home-assistant,Duoxilian/home-assistant,betrisey/home-assistant,miniconfig/home-assistant,theolind/home-assistant,GenericStudent/home-assistant,lukas-hetzenecker/home-assistant,alexmogavero/home-assistant,HydrelioxGitHub/home-assistant,leppa/home-assistant,morphis/home-assistant,ma314smith/home-assistant,alexkolar/home-assistant,dorant/home-assistant,alanbowman/home-assistant,pottzer/home-assistant,MungoRae/home-assistant,open-homeautomation/home-assistant,bencmbrook/home-assistant,fbradyirl/home-assistant,caiuspb/home-assistant,DavidLP/home-assistant,joopert/home-assistant,oandrew/home-assistant,rohitranjan1991/home-assistant,Julian/home-assistant,mikaelboman/home-assistant,Danielhiversen/home-assistant,coteyr/home-assistant,PetePriority/home-assistant,luxus/home-assistant,Nzaga/home-assistant,nugget/home-assistant,alanbowman/home-assistant,stefan-jonasson/home-assistant,alexmogavero/home-assistant,ma314smith/home-assistant,PetePriority/home-assistant,varunr047/homefile,emilhetty/home-assistant,jnewland/home-assistant,mikaelboman/home-assistant,jaharkes/home-assistant,sanmiguel/home-assistant,tboyce1/home-assistant,dorant/home-assistant,kennedyshead/home-assistant,Smart-Torvy/torvy-home-assistant,jamespcole/home-assistant,ct-23/home-assistant,varunr047/homefile,Theb-1/home-assistant,deisi/home-assistant,ErykB2000/home-assistant,dmeulen/home-assistant,sffjunkie/home-assistant,varunr047/homefile,eagleamon/home-assistant,jawilson/home-assistant,bdfoster/blumate,sffjunkie/home-assistant,justyns/home-assistant,emilhetty/home-assistant,fbradyirl/home-assistant,MungoRae/home-assistant,nevercast/home-assistant,leoc/home-assistant,betrisey/home-assistant,jaharkes/home-assistant,kennedyshead/home-assistant,CCOSTAN/home-assistant,persandstrom/home-assistant,kyvinh/home-assistant,postlund/home-assistant,Zac-HD/home-assistant,molobrakos/home-assistant,kyvinh/home-assistant,oandrew/home-assistant,MungoRae/home-assistant,sander76/home-assistant,mahendra-r/home-assistant,hmronline/home-assistant,bencmbrook/home-assistant,bencmbrook/home-assistant,stefan-jonasson/home-assistant,srcLurker/home-assistant,Cinntax/home-assistant,DavidLP/home-assistant,MungoRae/home-assistant,hexxter/home-assistant,aronsky/home-assistant,JshWright/home-assistant,Smart-Torvy/torvy-home-assistant,luxus/home-assistant,philipbl/home-assistant,EricRho/home-assistant,Julian/home-assistant,robjohnson189/home-assistant,xifle/home-assistant,luxus/home-assistant,LinuxChristian/home-assistant,Zyell/home-assistant,sdague/home-assistant,partofthething/home-assistant,turbokongen/home-assistant,leoc/home-assistant,CCOSTAN/home-assistant,hmronline/home-assistant,tboyce021/home-assistant,maddox/home-assistant,molobrakos/home-assistant,tmm1/home-assistant,hmronline/home-assistant,sffjunkie/home-assistant,sander76/home-assistant,Smart-Torvy/torvy-home-assistant,mKeRix/home-assistant,alexmogavero/home-assistant,MartinHjelmare/home-assistant,MartinHjelmare/home-assistant,vitorespindola/home-assistant | homeassistant/components/switch/demo.py | homeassistant/components/switch/demo.py | """
homeassistant.components.switch.demo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Demo platform that has two fake switches.
"""
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return demo switches. """
add_devices_callback([
DemoSwitch('Ceiling', STATE_ON),
DemoSwitch('AC', STATE_OFF)
])
class DemoSwitch(ToggleEntity):
""" Provides a demo switch. """
def __init__(self, name, state):
self._name = name or DEVICE_DEFAULT_NAME
self._state = state
@property
def should_poll(self):
""" No polling needed for a demo switch. """
return False
@property
def name(self):
""" Returns the name of the device if any. """
return self._name
@property
def state(self):
""" Returns the state of the device if any. """
return self._state
@property
def is_on(self):
""" True if device is on. """
return self._state == STATE_ON
def turn_on(self, **kwargs):
""" Turn the device on. """
self._state = STATE_ON
def turn_off(self, **kwargs):
""" Turn the device off. """
self._state = STATE_OFF
| """ Demo platform that has two fake switches. """
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.const import STATE_ON, STATE_OFF, DEVICE_DEFAULT_NAME
# pylint: disable=unused-argument
def setup_platform(hass, config, add_devices_callback, discovery_info=None):
""" Find and return demo switches. """
add_devices_callback([
DemoSwitch('Ceiling', STATE_ON),
DemoSwitch('AC', STATE_OFF)
])
class DemoSwitch(ToggleEntity):
""" Provides a demo switch. """
def __init__(self, name, state):
self._name = name or DEVICE_DEFAULT_NAME
self._state = state
@property
def should_poll(self):
""" No polling needed for a demo switch. """
return False
@property
def name(self):
""" Returns the name of the device if any. """
return self._name
@property
def state(self):
""" Returns the state of the device if any. """
return self._state
@property
def is_on(self):
""" True if device is on. """
return self._state == STATE_ON
def turn_on(self, **kwargs):
""" Turn the device on. """
self._state = STATE_ON
def turn_off(self, **kwargs):
""" Turn the device off. """
self._state = STATE_OFF
| mit | Python |
76c4f9b4acbedab7606ddca4c6456db47e68a744 | Add Currency model | jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow | game/currencies/__init__.py | game/currencies/__init__.py | # -*- coding: utf-8 -*-
"""
Enchants
- CurrencyTypes.dbc
"""
from .. import *
class Currency(Model):
def getTooltip(self):
return CurrencyTooltip(self)
class CurrencyTooltip(Tooltip):
def tooltip(self):
self.append("name", self.obj.getName())
self.append("description", self.obj.getDescription(), color=YELLOW)
return self.flush()
class CurrencyProxy(object):
"""
WDBC proxy for currencies
"""
def __init__(self, cls):
from pywow import wdbc
self.__file = wdbc.get("CurrencyTypes.dbc", build=-1)
def get(self, id):
return self.__file[id]
def getDescription(self, row):
return row.description_enus
def getName(self, row):
return row.name_enus
Currency.initProxy(CurrencyProxy)
| cc0-1.0 | Python | |
f2b6d7cb70a0a5b4f1a96657ba66455cdab67b45 | Add search for weird memories | SymbiFlow/prjxray-bram-patch,SymbiFlow/prjxray-bram-patch,SymbiFlow/prjxray-bram-patch | weird.py | weird.py | #
# Author: Brent Nelson
# Created: 18 Dec 2020
# Description:
# Given a directory, will analyze all the MDD files
import glob
import patch_mem
import parseutil.parse_mdd as mddutil
from collections import namedtuple
Mdd = namedtuple('Mdd', 'typ width addrbeg addrend')
def main(dirs, verbose):
d = dict()
for dr in dirs:
fname = dr.split("/")[-1]
if verbose:
print("")
print("Design is in: {}".format(dr))
# Read the MDD data and filter out the ones we want for this memory
mdd = dr + "/mapping.mdd".format(fname)
if verbose:
print("Mdd is: {}".format(mdd))
mdd_data = mddutil.read_mdd(mdd)
for cell in mdd_data:
if not fname in d:
print("Creating entry for " + fname)
d[fname] = []
d[fname].append(Mdd(typ=cell.type, width=cell.width, addrbeg=cell.addr_beg, addrend=cell.addr_end))
print(
" {} {} {} ({}) {}:{} {}.{}".format(
fname,
cell.type,
cell.write_style,
cell.width,
cell.addr_end,
cell.addr_beg,
cell.slice_end,
cell.slice_beg,
)
)
print("")
def printMdd(fname, mdd):
print("fname = {}, mdd = ".format(fname))
for elmt in mdd:
print(" {}".format(elmt))
#for fname, mdd in d.items():
# printMdd(fname, mdd)
# Now check that all widths are the same
print("Checking widths:")
for fname, mdd in d.items():
wid = mdd[0].width
for elmt in mdd:
if wid != elmt.width:
printMdd(fname, mdd)
print("Checking depths:")
for fname, mdd in d.items():
depth = mdd[0].addrend - mdd[0].addrbeg
for elmt in mdd:
if depth != elmt.addrend - elmt.addrbeg:
printMdd(fname, mdd)
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("baseDir")
parser.add_argument("--verbose", action='store_true')
args = parser.parse_args()
print(args.baseDir)
print(args.verbose)
dirs = glob.glob(args.baseDir + "/*")
main(dirs, args.verbose)
| isc | Python | |
c0f71cd818c52bd02bdaff28a1220456bfd4ee5f | Create basecache.py | yangjiePro/cutout,MrZhengliang/cutout,jojoin/cutout | cutout/cache/basecache.py | cutout/cache/basecache.py | # -*- coding: utf-8 -*-
#from itertools import izip
from .posixemulation import _items
class BaseCache(object):
"""Baseclass for the cache systems. All the cache systems implement this
API or a superset of it.
:param default_timeout: the default timeout that is used if no timeout is
specified on :meth:`set`.
"""
def __init__(self, default_timeout=300):
self.default_timeout = default_timeout
def get(self, key):
"""Looks up key in the cache and returns the value for it.
If the key does not exist `None` is returned instead.
:param key: the key to be looked up.
"""
return None
def delete(self, key):
"""Deletes `key` from the cache. If it does not exist in the cache
nothing happens.
:param key: the key to delete.
"""
pass
def get_many(self, *keys):
"""Returns a list of values for the given keys.
For each key a item in the list is created. Example::
foo, bar = cache.get_many("foo", "bar")
If a key can't be looked up `None` is returned for that key
instead.
:param keys: The function accepts multiple keys as positional
arguments.
"""
return map(self.get, keys)
def get_dict(self, *keys):
"""Works like :meth:`get_many` but returns a dict::
d = cache.get_dict("foo", "bar")
foo = d["foo"]
bar = d["bar"]
:param keys: The function accepts multiple keys as positional
arguments.
"""
#return dict(izip(keys, self.get_many(*keys)))
return dict(zip(keys, self.get_many(*keys)))
def set(self, key, value, timeout=None):
"""Adds a new key/value to the cache (overwrites value, if key already
exists in the cache).
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
pass
def add(self, key, value, timeout=None):
"""Works like :meth:`set` but does not overwrite the values of already
existing keys.
:param key: the key to set
:param value: the value for the key
:param timeout: the cache timeout for the key or the default
timeout if not specified.
"""
pass
def set_many(self, mapping, timeout=None):
"""Sets multiple keys and values from a mapping.
:param mapping: a mapping with the keys/values to set.
:param timeout: the cache timeout for the key (if not specified,
it uses the default timeout).
"""
for key, value in _items(mapping):
self.set(key, value, timeout)
def delete_many(self, *keys):
"""Deletes multiple keys at once.
:param keys: The function accepts multiple keys as positional
arguments.
"""
for key in keys:
self.delete(key)
def clear(self):
"""Clears the cache. Keep in mind that not all caches support
completely clearing the cache.
"""
pass
def inc(self, key, delta=1):
"""Increments the value of a key by `delta`. If the key does
not yet exist it is initialized with `delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to add.
"""
self.set(key, (self.get(key) or 0) + delta)
def dec(self, key, delta=1):
"""Decrements the value of a key by `delta`. If the key does
not yet exist it is initialized with `-delta`.
For supporting caches this is an atomic operation.
:param key: the key to increment.
:param delta: the delta to subtract.
"""
self.set(key, (self.get(key) or 0) - delta)
| mit | Python | |
0312a4210d07618755b6ad9caf49b144e7bec58c | add en-gb format tests | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy | babybuddy/tests/formats/tests_en_gb.py | babybuddy/tests/formats/tests_en_gb.py | # -*- coding: utf-8 -*-
import datetime
from django.core.exceptions import ValidationError
from django.forms.fields import DateTimeField
from django.test import TestCase, override_settings, tag
from django.utils.formats import date_format, time_format
from babybuddy.middleware import update_en_gb_date_formats
class GbFormatsTestCase(TestCase):
@override_settings(LANGUAGE_CODE='en-GB')
def test_datetime_input_formats(self):
update_en_gb_date_formats()
field = DateTimeField()
supported_custom_examples = [
'20/01/2020',
'20/01/2020 9:30 AM',
'20/01/2020 9:30:03 AM',
'01/10/2020 11:30 PM',
'01/10/2020 11:30:03 AM',
]
for example in supported_custom_examples:
try:
result = field.to_python(example)
self.assertIsInstance(result, datetime.datetime)
except ValidationError:
self.fail('Format of "{}" not recognized!'.format(example))
with self.assertRaises(ValidationError):
field.to_python('invalid date string!')
@tag('isolate')
@override_settings(LANGUAGE_CODE='en-GB', USE_24_HOUR_TIME_FORMAT=True)
def test_use_24_hour_time_format(self):
update_en_gb_date_formats()
field = DateTimeField()
supported_custom_examples = [
'25/10/2006 2:30:59',
'25/10/2006 2:30',
'25/10/2006 14:30:59',
'25/10/2006 14:30',
]
for example in supported_custom_examples:
try:
result = field.to_python(example)
self.assertIsInstance(result, datetime.datetime)
except ValidationError:
self.fail('Format of "{}" not recognized!'.format(example))
with self.assertRaises(ValidationError):
field.to_python('invalid date string!')
dt = datetime.datetime(year=2011, month=11, day=4, hour=23, minute=5,
second=59)
self.assertEqual(
date_format(dt, 'DATETIME_FORMAT'), '4 November 2011 23:05:59')
dt = datetime.datetime(year=2011, month=11, day=4, hour=2, minute=5,
second=59)
self.assertEqual(
date_format(dt, 'SHORT_DATETIME_FORMAT'), '04/11//2011 2:05:59')
t = datetime.time(hour=16, minute=2, second=25)
self.assertEqual(time_format(t), '16:02:25')
# def test_short_month_day_format(self):
# update_en_gb_date_formats()
# dt = datetime.datetime(year=2021, month=7, day=31, hour=5, minute=5,
# second=5)
# self.assertEqual(date_format(dt, 'SHORT_MONTH_DAY_FORMAT'), '31 Jul')
| bsd-2-clause | Python | |
f14ca27897ade9b4a19aa29b869a845486f67829 | Create audit object class | cpacia/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server,saltduck/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,tyler-smith/OpenBazaar-Server,saltduck/OpenBazaar-Server,OpenBazaar/Network,tyler-smith/OpenBazaar-Server,cpacia/OpenBazaar-Server,OpenBazaar/Network,cpacia/OpenBazaar-Server,OpenBazaar/Network,saltduck/OpenBazaar-Server,OpenBazaar/OpenBazaar-Server | market/audit.py | market/audit.py | __author__ = 'hoffmabc'
from log import Logger
class Audit(object):
"""
A class for handling audit information
"""
def __init__(self, db):
self.db = db
self.log = Logger(system=self)
self.action_ids = {
"GET_PROFILE": 0,
"GET_CONTRACT": 1,
"GET_LISTINGS": 2, # Click Store tab
"GET_FOLLOWING": 3,
"GET_FOLLOWERS": 4,
"GET_RATINGS": 5
}
def record(self, guid, action_id, contract_hash=None):
self.log.info("Recording Audit Event [%s]" % action_id)
if action_id in self.action_ids:
self.db.audit_shopping.set(guid, self.action_ids[action_id], contract_hash)
else:
self.log.error("Could not identify this action id") | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.