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
45444c93a3186b4db6c6a05785756d05d496a351
Copy the helpers before everything else
hawaii-desktop/builder,hawaii-desktop/builder,hawaii-desktop/builder,hawaii-desktop/builder,hawaii-desktop/builder
lib/hawaiibuildbot/archlinux/__init__.py
lib/hawaiibuildbot/archlinux/__init__.py
# # This file is part of Hawaii. # # Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from buildbot.process.factory import BuildFactory from buildbot.steps.shell import ShellCommand from buildbot.steps.source.git import Git from buildbot.plugins import steps from chrootactions import * from repoactions import * class RepositoryFactory(BuildFactory): """ Factory to build a repository of packages for a certain architecture. """ def __init__(self, sources, arch): BuildFactory.__init__(self, sources) # Download the helpers self.addStep(steps.MakeDirectory(name="CreateHelpersDir", dir="helpers")) for helper in ("pkgdepends", "pkgprovides", "pkgversion", "ccm-setup"): self.addStep(steps.FileDownload(name="DownloadHelper " + helper, mastersrc="helpers/archlinux/" + helper, slavedest="../helpers/" + helper, mode=0755)) # Create a directory to hold the packages that have been built self.addStep(steps.MakeDirectory(name="CreateRepositoryDir", dir="repository")) # Create or update the chroot #self.addStep(PrepareChrootAction(arch=arch)) self.addStep(CcmAction(arch=arch, action="u")) # Copy the list of packages to build from slave to master self.addStep(steps.FileUpload("buildinfo.yml", "tmp/buildinfo.yml", name="UploadBuildYaml")) # Scan repository and find packages to build self.addStep(RepositoryScan(channel="ci", arch=arch))
# # This file is part of Hawaii. # # Copyright (C) 2015 Pier Luigi Fiorini <pierluigi.fiorini@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from buildbot.process.factory import BuildFactory from buildbot.steps.shell import ShellCommand from buildbot.steps.source.git import Git from buildbot.plugins import steps from chrootactions import * from repoactions import * class RepositoryFactory(BuildFactory): """ Factory to build a repository of packages for a certain architecture. """ def __init__(self, sources, arch): BuildFactory.__init__(self, sources) # Create a directory to hold the packages that have been built self.addStep(steps.MakeDirectory(name="CreateRepositoryDir", dir="repository")) # Create or update the chroot #self.addStep(PrepareChrootAction(arch=arch)) self.addStep(CcmAction(arch=arch, action="u")) # Download the helpers self.addStep(steps.MakeDirectory(name="CreateHelpersDir", dir="helpers")) for helper in ("pkgdepends", "pkgprovides", "pkgversion", "ccm-setup"): self.addStep(steps.FileDownload(name="DownloadHelper " + helper, mastersrc="helpers/archlinux/" + helper, slavedest="../helpers/" + helper, mode=0755)) # Copy the list of packages to build from slave to master self.addStep(steps.FileUpload("buildinfo.yml", "tmp/buildinfo.yml", name="UploadBuildYaml")) # Scan repository and find packages to build self.addStep(RepositoryScan(channel="ci", arch=arch))
agpl-3.0
Python
275d64b678eaaf193866eced0720838f4817b1f1
modify orm.py
XiaoChengOMG/Practice
www/orm.py
www/orm.py
#!/usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = "" ''' ''' import asyncio,logging logging.basicConfig(level=logging.INFO) import aiomysql def log(sql,args=()): logging.info('SQL: %s' % sql) async def create_pool(loop,**kw): logging.info('create database connection pool...') global _pool _pool = await aiomysql.create_pool( host=kw.get('host','localhost'), port=kw.get('port',3306), user=kw['user'], password=kw['password'], db=kw['db'], charset=kw.get('charset','utf-8'), autocommit=kw.get('autocommit',True), maxsize=kw.get('maxsize',10), minsize=kw.get('minsize',1), loop=loop ) async def select(sql,args,size=None): log(sql,args) global _pool async with _pool.get() as conn: async with conn.cursor(aiomysql.DictCursor) as cur: await cur.execute(sql.replace('?','%s'),args or ()) if size: rs = await cur.fetchmany(size) else: rs = await cur.fetchall() logging.info('rows returned: %s' % len(rs)) return rs
#!/usr/bin/env python3 # -*- coding:utf-8 -*- __author__ = "" ''' ''' import asyncio,logging import aiomysql def log(sql,args=()): logging.info('SQL: %s' % sql) async def create_pool(loop,**kw): logging.info('create database connection pool...') global _pool _pool = await aiomysql.create_pool( host=kw.get('host','localhost'), port=kw.get('port',3306), user=kw['user'], password=kw['password'], db=kw['db'], charset=kw.get('charset','utf-8'), autocommit=kw.get('autocommit',True), maxsize=kw.get('maxsize',10), minsize=kw.get('minsize',1), loop=loop )
apache-2.0
Python
2835ec88db32664ce8fc7b6876a36546063da526
Allow dynamic translation in AngularJS
tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop,tiramiseb/awesomeshop
awesomeshop/views.py
awesomeshop/views.py
# -*- coding: utf8 -*- # Copyright 2015 Sébastien Maccagnoni-Munch # # This file is part of AwesomeShop. # # AwesomeShop 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. # # AwesomeShop 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 eAwesomeShop. If not, see <http://www.gnu.org/licenses/>. from flask import abort, jsonify, redirect, \ render_template as orig_render_template, request from flask_login import current_user from jinja2.exceptions import TemplateNotFound from . import app, get_locale, login_required, admin_required, messages def render_template(template, **context): context['locale'] = get_locale() return orig_render_template(template, **context) @app.route('/') @app.route('/<path:path>') def shop(path=None): return render_template('shop.html') @app.route('/login', methods=['GET','POST']) def login(): return render_template('login.html') @app.route('/messages') def messages_route(): return jsonify(messages.messages()) @app.route('/confirm/<code>') @login_required def confirm_email(code): if code == current_user.confirm_code: current_user.confirm_code = None current_user.save() # XXX Redirect the user to a specific message return redirect('/') @app.route('/part/<partname>') def part(partname): try: return render_template('part/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/shop/<partname>') def shop_part(partname): try: return render_template('shop/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/dashboard') @app.route('/dashboard/') def dashboard(): return render_template('dashboard.html') @app.route('/dashboard/<partname>') @admin_required def dashboard_part(partname): try: return render_template('dashboard/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/api/config') def api_config(): return jsonify( languages=app.config['LANGS'] ) @app.errorhandler(401) def unauthorized(e): return jsonify(error='401', message='Unauthorized'), 401 @app.errorhandler(403) def forbidden(e): return jsonify(error='403', message='Forbidden'), 403 @app.errorhandler(404) def notfound(e): return jsonify(error='404', message='Not Found'), 404 @app.errorhandler(500) def internalservererror(e): return jsonify(error='500', message='Internal Server Error'), 500
# -*- coding: utf8 -*- # Copyright 2015 Sébastien Maccagnoni-Munch # # This file is part of AwesomeShop. # # AwesomeShop 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. # # AwesomeShop 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 eAwesomeShop. If not, see <http://www.gnu.org/licenses/>. from flask import abort, jsonify, redirect, \ render_template as orig_render_template, request from flask_login import current_user from jinja2.exceptions import TemplateNotFound from . import app, get_locale, login_required, admin_required def render_template(template, **context): context['locale'] = get_locale() return orig_render_template(template, **context) @app.route('/') @app.route('/<path:path>') def shop(path=None): return render_template('shop.html') @app.route('/login', methods=['GET','POST']) def login(): return render_template('login.html') @app.route('/confirm/<code>') @login_required def confirm_email(code): if code == current_user.confirm_code: current_user.confirm_code = None current_user.save() # XXX Redirect the user to a specific message return redirect('/') @app.route('/part/<partname>') def part(partname): try: return render_template('part/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/shop/<partname>') def shop_part(partname): try: return render_template('shop/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/dashboard') @app.route('/dashboard/') def dashboard(): return render_template('dashboard.html') @app.route('/dashboard/<partname>') @admin_required def dashboard_part(partname): try: return render_template('dashboard/{}.html'.format(partname)) except TemplateNotFound: abort(404) @app.route('/api/config') def api_config(): return jsonify( languages=app.config['LANGS'] ) @app.errorhandler(401) def unauthorized(e): return jsonify(error='401', message='Unauthorized'), 401 @app.errorhandler(403) def forbidden(e): return jsonify(error='403', message='Forbidden'), 403 @app.errorhandler(404) def notfound(e): return jsonify(error='404', message='Not Found'), 404 @app.errorhandler(500) def internalservererror(e): return jsonify(error='500', message='Internal Server Error'), 500
agpl-3.0
Python
0d1a862cb2745fa15d74a970159f99b6a04ad7d9
Add MXs.
Juniper/contrail-fabric-utils,Juniper/contrail-fabric-utils
fabfile/testbeds/testbed_a6s30.py
fabfile/testbeds/testbed_a6s30.py
from fabric.api import env os_username = 'admin' os_password = 'contrail123' os_tenant_name = 'demo' host1 = 'root@10.84.13.30' ext_routers = [('mx1', '10.84.11.253'), ('mx2', '10.84.11.252')] router_asn = 64512 public_vn_rtgt = 10000 host_build = 'nsheth@10.84.5.31' env.roledefs = { 'all': [host1], 'cfgm': [host1], 'openstack': [host1], 'webui': [host1], 'control': [host1], 'collector': [host1], 'database': [host1], 'compute': [host1], 'build': [host_build], } env.hostnames = { 'all': ['a6s30'] } env.ostypes = { host1:'ubuntu', } env.passwords = { host1: 'c0ntrail123', host_build: 'c0ntrail123', }
from fabric.api import env os_username = 'admin' os_password = 'contrail123' os_tenant_name = 'demo' host1 = 'root@10.84.13.30' ext_routers = [] router_asn = 64512 public_vn_rtgt = 10000 host_build = 'nsheth@10.84.5.31' env.roledefs = { 'all': [host1], 'cfgm': [host1], 'openstack': [host1], 'webui': [host1], 'control': [host1], 'collector': [host1], 'database': [host1], 'compute': [host1], 'build': [host_build], } env.hostnames = { 'all': ['a6s30'] } env.ostypes = { host1:'ubuntu', } env.passwords = { host1: 'c0ntrail123', host_build: 'c0ntrail123', }
apache-2.0
Python
0a5908495afcd9dba729a07d7166f71530d62dee
remove erroneous assert statement
benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus,benedictpaten/cactus
progressive/multiCactusProject.py
progressive/multiCactusProject.py
#!/usr/bin/env python #Copyright (C) 2011 by Glenn Hickey # #Released under the MIT license, see LICENSE.txt """ Basic interface to the multi cactus project xml file. """ import unittest import os import xml.etree.ElementTree as ET from xml.dom import minidom import sys import random import math import copy import filecmp from optparse import OptionParser from cactus.progressive.multiCactusTree import MultiCactusTree from cactus.progressive.experimentWrapper import ExperimentWrapper from sonLib.nxnewick import NXNewick class MultiCactusProject: def __init__(self): self.mcTree = None self.expMap = dict() def readXML(self, path): xmlRoot = ET.parse(path).getroot() treeElem = xmlRoot.find("tree") self.mcTree = MultiCactusTree(NXNewick().parseString(treeElem.text)) self.expMap = dict() cactusPathElemList = xmlRoot.findall("cactus") for cactusPathElem in cactusPathElemList: nameElem = cactusPathElem.attrib["name"] pathElem = cactusPathElem.attrib["experiment_path"] self.expMap[nameElem] = pathElem self.mcTree.assignSubtreeRootNames(self.expMap) def writeXML(self, path): xmlRoot = ET.Element("multi_cactus") treeElem = ET.Element("tree") treeElem.text = NXNewick().writeString(self.mcTree) xmlRoot.append(treeElem) for name, expPath in self.expMap.items(): cactusPathElem = ET.Element("cactus") cactusPathElem.attrib["name"] = name cactusPathElem.attrib["experiment_path"] = expPath xmlRoot.append(cactusPathElem) xmlFile = open(path, "w") xmlString = ET.tostring(xmlRoot) xmlString = minidom.parseString(xmlString).toprettyxml() xmlFile.write(xmlString) xmlFile.close() # find the sequence associated with an event name # by digging out the appropriate experiment file # doesn't work for the rooot!!!! def sequencePath(self, eventName): parentEvent = self.mcTree.getSubtreeRoot(eventName) expPath = self.expMap[parentEvent] expElem = ET.parse(expPath).getroot() exp = ExperimentWrapper(expElem) return exp.getSequence(eventName) if __name__ == '__main__': main()
#!/usr/bin/env python #Copyright (C) 2011 by Glenn Hickey # #Released under the MIT license, see LICENSE.txt """ Basic interface to the multi cactus project xml file. """ import unittest import os import xml.etree.ElementTree as ET from xml.dom import minidom import sys import random import math import copy import filecmp from optparse import OptionParser from cactus.progressive.multiCactusTree import MultiCactusTree from cactus.progressive.experimentWrapper import ExperimentWrapper from sonLib.nxnewick import NXNewick class MultiCactusProject: def __init__(self): self.mcTree = None self.expMap = dict() def readXML(self, path): xmlRoot = ET.parse(path).getroot() treeElem = xmlRoot.find("tree") self.mcTree = MultiCactusTree(NXNewick().parseString(treeElem.text)) self.expMap = dict() cactusPathElemList = xmlRoot.findall("cactus") for cactusPathElem in cactusPathElemList: nameElem = cactusPathElem.attrib["name"] pathElem = cactusPathElem.attrib["experiment_path"] self.expMap[nameElem] = pathElem self.mcTree.assignSubtreeRootNames(self.expMap) def writeXML(self, path): xmlRoot = ET.Element("multi_cactus") treeElem = ET.Element("tree") treeElem.text = NXNewick().writeString(self.mcTree) xmlRoot.append(treeElem) for name, expPath in self.expMap.items(): cactusPathElem = ET.Element("cactus") cactusPathElem.attrib["name"] = name cactusPathElem.attrib["experiment_path"] = expPath xmlRoot.append(cactusPathElem) xmlFile = open(path, "w") xmlString = ET.tostring(xmlRoot) xmlString = minidom.parseString(xmlString).toprettyxml() xmlFile.write(xmlString) xmlFile.close() # find the sequence associated with an event name # by digging out the appropriate experiment file # doesn't work for the rooot!!!! def sequencePath(self, eventName): assert eventName in self.expMap parentEvent = self.mcTree.getSubtreeRoot(eventName) expPath = self.expMap[parentEvent] expElem = ET.parse(expPath).getroot() exp = ExperimentWrapper(expElem) return exp.getSequence(eventName) if __name__ == '__main__': main()
mit
Python
f92eac982dee9d4ea97e36cfda0f1fa19213b9f4
Improve Project Euler problem 092 solution 1 (#5703)
TheAlgorithms/Python
project_euler/problem_092/sol1.py
project_euler/problem_092/sol1.py
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ DIGITS_SQUARED = [digit ** 2 for digit in range(10)] def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a new number. For example, if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: sum_of_digits_squared += DIGITS_SQUARED[number % 10] number //= 10 return sum_of_digits_squared CHAINS = {1: True, 58: False} def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ if number in CHAINS: return CHAINS[number] number_chain = chain(next_number(number)) CHAINS[number] = number_chain return number_chain def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ return sum(1 for i in range(1, number) if not chain(i)) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
""" Project Euler Problem 092: https://projecteuler.net/problem=92 Square digit chains A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before. For example, 44 → 32 → 13 → 10 → 1 → 1 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89 Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89. How many starting numbers below ten million will arrive at 89? """ def next_number(number: int) -> int: """ Returns the next number of the chain by adding the square of each digit to form a neww number. For example if number = 12, next_number() will return 1^2 + 2^2 = 5. Therefore, 5 is the next number of the chain. >>> next_number(44) 32 >>> next_number(10) 1 >>> next_number(32) 13 """ sum_of_digits_squared = 0 while number: sum_of_digits_squared += (number % 10) ** 2 number //= 10 return sum_of_digits_squared def chain(number: int) -> bool: """ The function generates the chain of numbers until the next number is 1 or 89. For example, if starting number is 44, then the function generates the following chain of numbers: 44 → 32 → 13 → 10 → 1 → 1. Once the next number generated is 1 or 89, the function returns whether or not the the next number generated by next_number() is 1. >>> chain(10) True >>> chain(58) False >>> chain(1) True """ while number != 1 and number != 89: number = next_number(number) return number == 1 def solution(number: int = 10000000) -> int: """ The function returns the number of integers that end up being 89 in each chain. The function accepts a range number and the function checks all the values under value number. >>> solution(100) 80 >>> solution(10000000) 8581146 """ return sum(1 for i in range(1, number) if not chain(i)) if __name__ == "__main__": import doctest doctest.testmod() print(f"{solution() = }")
mit
Python
1bc4507234d87b1ed246501165fa1d8138bf5ca6
Fix for pypy compatibility: must super's __init__
jessemyers/cheddar,jessemyers/cheddar
cheddar/exceptions.py
cheddar/exceptions.py
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): super(NotFoundError, self).__init__() self.status_code = status_code
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): self.status_code = status_code
apache-2.0
Python
ac9cd5ff007ee131e97f70c49c763f79f06ebf5a
Include the entire existing environment for integration tests subprocesses
CleanCut/green,CleanCut/green
green/test/test_integration.py
green/test/test_integration.py
import copy import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def test_finalizer(self): """ Test that the finalizer works on Python 3.8+ """ sub_tmpdir = tempfile.mkdtemp(dir=self.tmpdir) for i in range(multiprocessing.cpu_count() * 2): fh = open(os.path.join(sub_tmpdir, f"test_finalizer{i}.py"), "w") fh.write( dedent( f""" import unittest class Pass{i}(unittest.TestCase): def test_pass{i}(self): pass def msg(): print("finalizer worked") """ ) ) fh.close() args = [ sys.executable, "-m", "green.cmdline", "--finalizer=test_finalizer0.msg", "--maxtasksperchild=1", ] pythonpath = str(PurePath(__file__).parent.parent.parent) env = copy.deepcopy(os.environ) env["PYTHONPATH"] = pythonpath output = subprocess.run( args, cwd=sub_tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, timeout=10, ).stdout.decode("utf-8") self.assertIn("finalizer worked", output)
import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def test_finalizer(self): """ Test that the finalizer works on Python 3.8+ """ sub_tmpdir = tempfile.mkdtemp(dir=self.tmpdir) for i in range(multiprocessing.cpu_count() * 2): fh = open(os.path.join(sub_tmpdir, f"test_finalizer{i}.py"), "w") fh.write( dedent( f""" import unittest class Pass{i}(unittest.TestCase): def test_pass{i}(self): pass def msg(): print("finalizer worked") """ ) ) fh.close() args = [ sys.executable, "-m", "green.cmdline", "--finalizer=test_finalizer0.msg", "--maxtasksperchild=1", ] pythonpath = str(PurePath(__file__).parent.parent.parent) output = subprocess.run( args, cwd=sub_tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env={"PYTHONPATH": pythonpath}, timeout=10, ).stdout.decode("utf-8") self.assertIn("finalizer worked", output)
mit
Python
b91974d3e830d97cdb0808dadf8ff5d22b506bdf
Add toString()
lewangbtcc/anti-XSS,lewangbtcc/anti-XSS
lib/var/countpage.py
lib/var/countpage.py
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number pass def setNumber(self, number): self.number = number pass def getNumber(self): return self.number def incNumber(self): self.number += 1 pass def toString(self): return 'number = ' + str(number)
#!/usr/bin/env python ''' Copyright (c) 2016 anti-XSS developers ''' class CountPage(object): number = 0 def __init__(self, number=0): self.number = number def setNumber(self, number): self.number = number def getNumber(self): return self.number def incNumber(self): self.number += 1
mit
Python
46ba8967de7b6f6c714749dd7ff2771f447b9258
fix field allowance
joeyuan19/flaming-bear,joeyuan19/flaming-bear,joeyuan19/flaming-bear,joeyuan19/flaming-bear
PersonalSite/content/models.py
PersonalSite/content/models.py
from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=128,blank=True,null=True,default="") body = models.TextField(blank=True,null=True,default="") preview = models.ImageField(upload_to="img/project_previews/",blank=True,null=True,default=None) rel_date = models.CharField(max_length=128,blank=True,null=True,default="") url = models.URLField(max_length=128,blank=True,null=True,default="") modified = models.DateField(blank=True) def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Project,self).save(*args,**kwargs) class ProjectCategory(models.Model): title = models.CharField(max_length=64) entries = models.ManyToManyField(Project) class Contact(models.Model): pass class Resume(models.Model): title = models.CharField(max_length=128,blank=True,null=True,default="") description = models.TextField(blank=True,null=True,default="") relevent_dates = models.CharField(max_length=128,blank=True,null=True,default="") modified = models.DateTimeField(blank=True) def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Resume,self).save(*args,**kwargs) class ResumeCategory(models.Model): title = models.CharField(max_length=64) entries = models.ManyToManyField(Resume) class Friend(models.Model): name = models.CharField(max_length=64,blank=True,null=True,default="") title = models.CharField(max_length=128,blank=True,null=True,default="") Description = models.CharField(max_length=256,blank=True,null=True,default="") url = models.URLField(max_length=128,blank=True,null=True,default="") modified = models.DateTimeField(editable=False,blank=True) def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Friend,self).save(*args,**kwargs)
from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=128,blank=True,null=True,default="") body = models.TextField(blank=True,null=True,default="") preview = models.ImageField(upload_to="img/project_previews/",blank=True,null=True,default=None) rel_date = models.CharField(max_length=128,blank=True,null=True,default="") url = models.URLField(max_length=128,blank=True,null=True,default="") modified = models.DateField() def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Project,self).save(*args,**kwargs) class ProjectCategory(models.Model): title = models.CharField(max_length=64) entries = models.ManyToManyField(Project) class Contact(models.Model): pass class Resume(models.Model): title = models.CharField(max_length=128,blank=True,null=True,default="") description = models.TextField(blank=True,null=True,default="") relevent_dates = models.CharField(max_length=128,blank=True,null=True,default="") modified = models.DateTimeField() def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Resume,self).save(*args,**kwargs) class ResumeCategory(models.Model): title = models.CharField(max_length=64) entries = models.ManyToManyField(Resume) class Friend(models.Model): name = models.CharField(max_length=64,blank=True,null=True,default="") title = models.CharField(max_length=128,blank=True,null=True,default="") Description = models.CharField(max_length=256,blank=True,null=True,default="") url = models.URLField(max_length=128,blank=True,null=True,default="") modified = models.DateTimeField(editable=False,max_length=128,blank=True,null=True,default="") def save(self,*args,**kwargs): self.modified = datetime.datetime.today() super(Friend,self).save(*args,**kwargs)
apache-2.0
Python
c1abb8ea05c68de7072a34c2f40f1e8c303be0fe
Bump version to 1.0
asfin/electrum,imrehg/electrum,imrehg/electrum,procrasti/electrum,fireduck64/electrum,spesmilo/electrum,cryptapus/electrum,vialectrum/vialectrum,dabura667/electrum,cryptapus/electrum,digitalbitbox/electrum,neocogent/electrum,argentumproject/electrum-arg,procrasti/electrum,wakiyamap/electrum-mona,pooler/electrum-ltc,cryptapus/electrum-myr,spesmilo/electrum,vertcoin/electrum-vtc,asfin/electrum,fyookball/electrum,wakiyamap/electrum-mona,molecular/electrum,cryptapus/electrum-myr,FairCoinTeam/electrum-fair,fujicoin/electrum-fjc,lbryio/lbryum,protonn/Electrum-Cash,digitalbitbox/electrum,molecular/electrum,cryptapus/electrum,FairCoinTeam/electrum-fair,vertcoin/electrum-vtc,vialectrum/vialectrum,vialectrum/vialectrum,aasiutin/electrum,digitalbitbox/electrum,fireduck64/electrum,dashpay/electrum-dash,vertcoin/electrum-vtc,asfin/electrum,digitalbitbox/electrum,pooler/electrum-ltc,romanz/electrum,cryptapus/electrum-myr,aasiutin/electrum,protonn/Electrum-Cash,pknight007/electrum-vtc,fujicoin/electrum-fjc,dashpay/electrum-dash,cryptapus/electrum-uno,pknight007/electrum-vtc,fyookball/electrum,fireduck64/electrum,fireduck64/electrum,imrehg/electrum,aasiutin/electrum,spesmilo/electrum,aasiutin/electrum,pooler/electrum-ltc,molecular/electrum,dashpay/electrum-dash,neocogent/electrum,pooler/electrum-ltc,pknight007/electrum-vtc,procrasti/electrum,kyuupichan/electrum,argentumproject/electrum-arg,argentumproject/electrum-arg,kyuupichan/electrum,spesmilo/electrum,vertcoin/electrum-vtc,wakiyamap/electrum-mona,molecular/electrum,dabura667/electrum,FairCoinTeam/electrum-fair,argentumproject/electrum-arg,neocogent/electrum,dabura667/electrum,wakiyamap/electrum-mona,fyookball/electrum,cryptapus/electrum-uno,cryptapus/electrum-myr,dashpay/electrum-dash,cryptapus/electrum-uno,protonn/Electrum-Cash,romanz/electrum,kyuupichan/electrum,procrasti/electrum,dabura667/electrum,fujicoin/electrum-fjc,protonn/Electrum-Cash,pknight007/electrum-vtc,romanz/electrum,cryptapus/electrum-uno,lbryio/lbryum,imrehg/electrum,FairCoinTeam/electrum-fair
lib/version.py
lib/version.py
ELECTRUM_VERSION = "1.0" SEED_VERSION = 4 # bump this everytime the seed generation is modified TRANSLATION_ID = 28344 # version of the wiki page
ELECTRUM_VERSION = "0.61" SEED_VERSION = 4 # bump this everytime the seed generation is modified TRANSLATION_ID = 28344 # version of the wiki page
mit
Python
ddd8c4d3f913a1f87b68496cca8e1deb10a8ee8e
remove obsolete replacements from synth.py (#37)
googleapis/google-cloud-node,googleapis/google-cloud-node,googleapis/google-cloud-node,googleapis/google-cloud-node
packages/google-cloud-recommender/synth.py
packages/google-cloud-recommender/synth.py
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script is used to synthesize generated parts of this library.""" import synthtool as s import synthtool.gcp as gcp import subprocess import logging logging.basicConfig(level=logging.DEBUG) # Run the gapic generator gapic = gcp.GAPICMicrogenerator() name = 'recommender' versions = ['v1'] for version in versions: library = gapic.typescript_library( name, version, proto_path=f'google/cloud/{name}/{version}', generator_args={ 'grpc-service-config': f'google/cloud/{name}/{version}/{name}_grpc_service_config.json', 'package-name': f'@google-cloud/{name}', 'main-service': 'DataCatalog', # just for webpack.config.js }, extra_proto_files=['google/cloud/common_resources.proto'], ) s.copy(library, excludes=['package.json', 'README.md']) # Copy common templates common_templates = gcp.CommonTemplates() templates = common_templates.node_library(source_location='build/src') s.copy(templates, excludes=[]) # Node.js specific cleanup subprocess.run(['npm', 'install']) subprocess.run(['npm', 'run', 'fix']) subprocess.run(['npx', 'compileProtos', 'src'])
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This script is used to synthesize generated parts of this library.""" import synthtool as s import synthtool.gcp as gcp import subprocess import logging logging.basicConfig(level=logging.DEBUG) # Run the gapic generator gapic = gcp.GAPICMicrogenerator() name = 'recommender' versions = ['v1'] for version in versions: library = gapic.typescript_library( name, version, proto_path=f'google/cloud/{name}/{version}', generator_args={ 'grpc-service-config': f'google/cloud/{name}/{version}/{name}_grpc_service_config.json', 'package-name': f'@google-cloud/{name}', 'main-service': 'DataCatalog', # just for webpack.config.js }, extra_proto_files=['google/cloud/common_resources.proto'], ) s.copy(library, excludes=['package.json', 'README.md']) # Copy common templates common_templates = gcp.CommonTemplates() templates = common_templates.node_library(source_location='build/src') s.copy(templates, excludes=[]) # Fix broken links to cloud.google.com documentation s.replace('src/v1beta1/*.ts', '/data-catalog/docs/', 'https://cloud.google.com/data-catalog/docs/') # Node.js specific cleanup subprocess.run(['npm', 'install']) subprocess.run(['npm', 'run', 'fix']) subprocess.run(['npx', 'compileProtos', 'src'])
apache-2.0
Python
71b5883a6693361facf705f2dc840cdd9ff4c225
format dates more like BibTeX
chbrown/pybtex,andreas-h/pybtex,chbrown/pybtex,andreas-h/pybtex
pybtex/styles/formatting/plain.py
pybtex/styles/formatting/plain.py
# Copyright 2006 Andrey Golovizin # # This file is part of pybtex. # # pybtex is free software; you can redistribute it and/or modify # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # pybtex is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with rdiff-backup; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA from pybtex.utils import try_format, dashify from pybtex.richtext import RichText, Phrase, Tag from pybtex.styles.formatting import FormatterBase, default_phrase class Formatter(FormatterBase): def format_names(self, persons): p = Phrase(sep=', ', sep2 = ' and ', last_sep=', and ') p.extend(person.text for person in persons) def format_date(self, entry): return Phrase(entry.month, entry.year, sep=' ') def format_article(self, e): p = default_phrase(self.format_names(e.authors), e.title) pages = dashify(e.pages) if e.volume: vp = RichText(e.volume, try_format(pages, ':%s')) else: vp = try_format(pages, 'pages %s') p.append(Phrase(Tag('emph', e.journal), vp, self.format_date(e))) return p def format_book(self, e): p = default_phrase() if e.authors: p.append(self.format_names(e.authors)) else: editors = self.format_names(e.editors) if len(e.editors) > 1: word = 'editors' else: word = 'editor' p.append(Phrase(editors, word)) p.append(Tag('emph', e.title)) p.append(Phrase(e.publisher, self.format_date(e), add_period=True)) return p
# Copyright 2006 Andrey Golovizin # # This file is part of pybtex. # # pybtex is free software; you can redistribute it and/or modify # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 2 of the License, or (at your # option) any later version. # # pybtex is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with rdiff-backup; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 # USA from pybtex.utils import try_format, dashify from pybtex.richtext import RichText, Phrase, Tag from pybtex.styles.formatting import FormatterBase, default_phrase class Formatter(FormatterBase): def format_names(self, persons): p = Phrase(sep=', ', sep2 = ' and ', last_sep=', and ') p.extend(person.text for person in persons) return p def format_article(self, e): p = default_phrase(self.format_names(e.authors), e.title) pages = dashify(e.pages) if e.volume: vp = RichText(e.volume, try_format(pages, ':%s')) else: vp = try_format(pages, 'pages %s') p.append(Phrase(Tag('emph', e.journal), vp, e.year)) return p def format_book(self, e): p = default_phrase() if e.authors: p.append(self.format_names(e.authors)) else: editors = self.format_names(e.editors) if len(e.editors) > 1: word = 'editors' else: word = 'editor' p.append(Phrase(editors, word)) p.append(Tag('emph', e.title)) p.append(Phrase(e.publisher, e.year, add_period=True)) return p
mit
Python
016fa58761c1ea42657409bb3f4d6260671d8ea1
Update note_util.py so that it reads the new note offsets
albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com
app/note_util.py
app/note_util.py
import datetime import os import dotenv from getenv import env import markdown2 import pytz root_path = os.path.dirname(os.path.realpath(__file__)) + '/../' dotenv.read_dotenv(os.path.join(root_path, '.env')) # See https://github.com/trentm/python-markdown2/wiki/Extras MARKDOWN_EXTRAS = [ 'code-friendly', 'fenced-code-blocks', 'smarty-pants', 'tables', ] def prune_note_files(note_files): def is_valid_note(note_file): if '~' in note_file: return False if note_file[0] == '.': return False return True files = [note_file for note_file in note_files if is_valid_note(note_file)] return files def get_note_files(): current_directory = os.path.dirname(os.path.realpath(__file__)) notes_directory = os.path.join(current_directory, 'notes') files = os.listdir(notes_directory) files.sort(reverse=True) files = prune_note_files(files) files = [os.path.join(notes_directory, note_file) for note_file in files] return files def get_note_file_data(note_file, timezone): with open(note_file) as note_handle: note = note_handle.readlines() note = [line.strip() for line in note] if len(note) < 4 or not note[4].isdigit(): return None note_parsed = {} note_parsed['title'] = note[0] note_parsed['slug'] = note[2] timestamp = int(note[4]) note_parsed['time'] = datetime.datetime.fromtimestamp( timestamp, timezone) note_parsed['note'] = markdown2.markdown( "\n".join(note[6:]), extras=MARKDOWN_EXTRAS, ) return note_parsed def get_notes(): note_files = get_note_files() timezone = pytz.timezone(env('DISPLAY_TIMEZONE')) notes = [] for note_file in note_files: note_parsed = get_note_file_data(note_file, timezone) if note_parsed: notes.append(note_parsed) return notes def get_note_from_slug(slug): """ Given the slug of a note, reurn the note contents """ notes = get_notes() for note in notes: if note['slug'] == slug: return note return None
import datetime import os import dotenv from getenv import env import markdown2 import pytz root_path = os.path.dirname(os.path.realpath(__file__)) + '/../' dotenv.read_dotenv(os.path.join(root_path, '.env')) # See https://github.com/trentm/python-markdown2/wiki/Extras MARKDOWN_EXTRAS = [ 'code-friendly', 'fenced-code-blocks', 'smarty-pants', 'tables', ] def prune_note_files(note_files): def is_valid_note(note_file): if '~' in note_file: return False if note_file[0] == '.': return False return True files = [note_file for note_file in note_files if is_valid_note(note_file)] return files def get_note_files(): current_directory = os.path.dirname(os.path.realpath(__file__)) notes_directory = os.path.join(current_directory, 'notes') files = os.listdir(notes_directory) files.sort(reverse=True) files = prune_note_files(files) files = [os.path.join(notes_directory, note_file) for note_file in files] return files def get_note_file_data(note_file, timezone): with open(note_file) as note_handle: note = note_handle.readlines() note = [line.strip() for line in note] if len(note) < 4 or not note[2].isdigit(): return None timestamp = int(note[2]) note_parsed = {} note_parsed['title'] = note[0] note_parsed['slug'] = note[1] note_parsed['time'] = datetime.datetime.fromtimestamp( timestamp, timezone) note_parsed['note'] = markdown2.markdown( "\n".join(note[3:]), extras=MARKDOWN_EXTRAS, ) return note_parsed def get_notes(): note_files = get_note_files() timezone = pytz.timezone(env('DISPLAY_TIMEZONE')) notes = [] for note_file in note_files: note_parsed = get_note_file_data(note_file, timezone) if note_parsed: notes.append(note_parsed) return notes def get_note_from_slug(slug): """ Given the slug of a note, reurn the note contents """ notes = get_notes() for note in notes: if note['slug'] == slug: return note return None
mit
Python
117c84bba009aeff166900f5eb70aa640e05beb2
Modify to use casefold
thombashi/typepy
typepy/converter/_bool.py
typepy/converter/_bool.py
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .._common import strip_ansi_escape from .._const import DefaultValue, ParamKey from ..error import TypeConversionError from ._interface import AbstractValueConverter class BoolConverter(AbstractValueConverter): def force_convert(self): if isinstance(self._value, int): return bool(self._value) try: return self.__strict_strtobool(self._value) except ValueError: pass if self._params.get(ParamKey.STRIP_ANSI_ESCAPE, DefaultValue.STRIP_ANSI_ESCAPE): try: return self.__strict_strtobool(strip_ansi_escape(self._value)) except (TypeError, ValueError): pass raise TypeConversionError( "failed to force_convert to bool: type={}".format(type(self._value)) ) @staticmethod def __strict_strtobool(value): if isinstance(value, bool): return value try: lower_text = value.casefold() except AttributeError: raise ValueError("invalid value '{}'".format(str(value))) if lower_text in ["true"]: return True elif lower_text in ["false"]: return False raise ValueError("invalid value '{}'".format(str(value)))
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from .._common import strip_ansi_escape from .._const import DefaultValue, ParamKey from ..error import TypeConversionError from ._interface import AbstractValueConverter class BoolConverter(AbstractValueConverter): def force_convert(self): if isinstance(self._value, int): return bool(self._value) try: return self.__strict_strtobool(self._value) except ValueError: pass if self._params.get(ParamKey.STRIP_ANSI_ESCAPE, DefaultValue.STRIP_ANSI_ESCAPE): try: return self.__strict_strtobool(strip_ansi_escape(self._value)) except (TypeError, ValueError): pass raise TypeConversionError( "failed to force_convert to bool: type={}".format(type(self._value)) ) @staticmethod def __strict_strtobool(value): if isinstance(value, bool): return value try: lower_text = value.lower() except AttributeError: raise ValueError("invalid value '{}'".format(str(value))) if lower_text in ["true"]: return True elif lower_text in ["false"]: return False raise ValueError("invalid value '{}'".format(str(value)))
mit
Python
40777e44e2403d633ecaa4d45b6985be3a5bc907
add version 1.1 (#5461)
skosukhin/spack,matthiasdiener/spack,tmerrick1/spack,matthiasdiener/spack,EmreAtes/spack,TheTimmy/spack,mfherbst/spack,krafczyk/spack,skosukhin/spack,mfherbst/spack,TheTimmy/spack,skosukhin/spack,iulian787/spack,lgarren/spack,LLNL/spack,skosukhin/spack,skosukhin/spack,krafczyk/spack,mfherbst/spack,LLNL/spack,TheTimmy/spack,EmreAtes/spack,lgarren/spack,tmerrick1/spack,EmreAtes/spack,tmerrick1/spack,EmreAtes/spack,matthiasdiener/spack,LLNL/spack,matthiasdiener/spack,iulian787/spack,lgarren/spack,matthiasdiener/spack,TheTimmy/spack,iulian787/spack,tmerrick1/spack,krafczyk/spack,krafczyk/spack,TheTimmy/spack,iulian787/spack,mfherbst/spack,LLNL/spack,tmerrick1/spack,lgarren/spack,LLNL/spack,mfherbst/spack,krafczyk/spack,EmreAtes/spack,iulian787/spack,lgarren/spack
var/spack/repos/builtin/packages/parsplice/package.py
var/spack/repos/builtin/packages/parsplice/package.py
############################################################################## # Copyright (c) 2017, Los Alamos National Security, LLC # Produced at the Los Alamos National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Parsplice(CMakePackage): """ParSplice code implements the Parallel Trajectory Splicing algorithm""" homepage = "https://gitlab.com/exaalt/parsplice" url = "https://gitlab.com/exaalt/parsplice/repository/archive.tar.gz?ref=v1.1" version('1.1', '3a72340d49d731a076e8942f2ae2f4e9') version('develop', git='https://gitlab.com/exaalt/parsplice', branch='master') depends_on("cmake@3.1:", type='build') depends_on("berkeley-db") depends_on("nauty") depends_on("boost") depends_on("mpi") depends_on("eigen@3:") depends_on("lammps+lib@20170901:") def cmake_args(self): options = ['-DBUILD_SHARED_LIBS=ON'] return options
############################################################################## # Copyright (c) 2017, Los Alamos National Security, LLC # Produced at the Los Alamos National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Parsplice(CMakePackage): """ParSplice code implements the Parallel Trajectory Splicing algorithm""" homepage = "https://gitlab.com/exaalt/parsplice" url = "https://gitlab.com/exaalt/parsplice/tags/v1.0" version('develop', git='https://gitlab.com/exaalt/parsplice', branch='master') depends_on("cmake@3.1:", type='build') depends_on("berkeley-db") depends_on("nauty") depends_on("boost") depends_on("mpi") depends_on("eigen@3:") depends_on("lammps+lib@20170901:") def cmake_args(self): options = ['-DBUILD_SHARED_LIBS=ON'] return options
lgpl-2.1
Python
a47ab9c6b216e4926a5cc4564a7db24379354fb4
Add extra version of py-psutil (#15063)
iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack,LLNL/spack,LLNL/spack,iulian787/spack,iulian787/spack
var/spack/repos/builtin/packages/py-psutil/package.py
var/spack/repos/builtin/packages/py-psutil/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPsutil(PythonPackage): """psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python.""" homepage = "https://pypi.python.org/pypi/psutil" url = "https://pypi.io/packages/source/p/psutil/psutil-5.6.3.tar.gz" version('5.6.3', sha256='863a85c1c0a5103a12c05a35e59d336e1d665747e531256e061213e2e90f63f3') version('5.6.2', sha256='828e1c3ca6756c54ac00f1427fdac8b12e21b8a068c3bb9b631a1734cada25ed') version('5.5.1', sha256='72cebfaa422b7978a1d3632b65ff734a34c6b34f4578b68a5c204d633756b810') version('5.4.5', sha256='ebe293be36bb24b95cdefc5131635496e88b17fabbcf1e4bc9b5c01f5e489cfe') version('5.0.1', sha256='9d8b7f8353a2b2eb6eb7271d42ec99d0d264a9338a37be46424d56b4e473b39e') depends_on('python@2.6:2.8,3.4:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-unittest2', when='^python@:2.6', type='test') depends_on('py-mock', when='^python@:2.7', type='test') depends_on('py-ipaddress', when='^python@:3.2', type='test')
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyPsutil(PythonPackage): """psutil is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network) in Python.""" homepage = "https://pypi.python.org/pypi/psutil" url = "https://pypi.io/packages/source/p/psutil/psutil-5.6.3.tar.gz" version('5.6.3', sha256='863a85c1c0a5103a12c05a35e59d336e1d665747e531256e061213e2e90f63f3') version('5.5.1', sha256='72cebfaa422b7978a1d3632b65ff734a34c6b34f4578b68a5c204d633756b810') version('5.4.5', sha256='ebe293be36bb24b95cdefc5131635496e88b17fabbcf1e4bc9b5c01f5e489cfe') version('5.0.1', sha256='9d8b7f8353a2b2eb6eb7271d42ec99d0d264a9338a37be46424d56b4e473b39e') depends_on('python@2.6:2.8,3.4:', type=('build', 'run')) depends_on('py-setuptools', type='build') depends_on('py-unittest2', when='^python@:2.6', type='test') depends_on('py-mock', when='^python@:2.7', type='test') depends_on('py-ipaddress', when='^python@:3.2', type='test')
lgpl-2.1
Python
299ed52e872a2242610cc553ac90764275b05272
Update test_glove2word2vec.py
manasRK/gensim,manasRK/gensim,manasRK/gensim
gensim/test/test_glove2word2vec.py
gensim/test/test_glove2word2vec.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Test for gensim.scripts.glove2word2vec.py.""" import unittest import os import sys import gensim from gensim.utils import check_output class TestGlove2Word2Vec(unittest.TestCase): def setUp(self): self.module_path = os.path.dirname(gensim.__file__) self.datapath = os.path.join(self.module_path, 'test', 'test_data', 'test_glove.txt') # Sample data files are located in the same folder self.output_file = 'sample_word2vec_out.txt' def testConversion(self): output = check_output(['python', '-m', 'gensim.scripts.glove2word2vec', '-i', self.datapath, '-o', self.output_file]) self.assertEqual(output, '')
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2016 Radim Rehurek <radimrehurek@seznam.cz> # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """Test for gensim.scripts.glove2word2vec.py.""" import unittest import os import sys import gensim from gensim.utils import check_output class TestGlove2Word2Vec(unittest.TestCase): def setUp(self): self.module_path = os.path.dirname(gensim.__file__) self.datapath = os.path.join(self.module_path, 'test', 'test_data', 'test_glove.txt') # Sample data files are located in the same folder self.output_file = 'sample_word2vec_out.txt' def testConversion(self): output = check_output(['python', '-m', 'gensim.scripts.glove2word2vec', '-i', self.datapath, '-o', self.output_file]) self.assertEqual(output, b'')
lgpl-2.1
Python
df1e33283485b76c61185a98b5b2c909431c2ae5
Remove white space between print and ()
stackforge/python-monascaclient,sapcc/python-monascaclient,sapcc/python-monascaclient,openstack/python-monascaclient,openstack/python-monascaclient,stackforge/python-monascaclient
client_api_example.py
client_api_example.py
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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. """ An example using monascaclient via the Python API """ from monascaclient import client import monascaclient.exc as exc import time # In order to use the python api directly, you must first obtain an # auth token and identify which endpoint you wish to speak to. endpoint = 'http://192.168.10.4:8070/v2.0' # The api version of monasca-api api_version = '2_0' # Pass in the keystone authentication kwargs to construct a monasca client. # The monasca_client will try to authenticate with keystone one time # when it sees a 401 unauthorized resp, to take care of a stale token. # In this example no token is input, so it will get a 401 when executing the # first metrics.create request, and will authenticate and try again. auth_kwargs = {'username': 'mini-mon', 'password': 'password', 'project_name': 'mini-mon', 'auth_url': 'http://192.168.10.5:35357/v3/'} monasca_client = client.Client(api_version, endpoint, **auth_kwargs) # you can reference the monascaclient.v2_0.shell.py # do_commands for command field initialization. # post a metric dimensions = {'instance_id': '12345', 'service': 'nova'} fields = {} fields['name'] = 'metric1' fields['dimensions'] = dimensions # time in milliseconds fields['timestamp'] = time.time() * 1000 fields['value'] = 222.333 try: resp = monasca_client.metrics.create(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(resp) print('Successfully created metric') # post a metric with a unicode service name dimensions = {'instance_id': '12345', 'service': u'\u76db\u5927'} fields = {} fields['name'] = 'metric1' fields['dimensions'] = dimensions fields['timestamp'] = time.time() * 1000 fields['value'] = 222.333 try: resp = monasca_client.metrics.create(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(resp) print('Successfully created metric') print('Giving the DB time to update...') time.sleep(5) # metric-list name = 'metric1' dimensions = None fields = {} if name: fields['name'] = name if dimensions: fields['dimensions'] = dimensions try: body = monasca_client.metrics.list(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(body)
# Copyright (c) 2014 Hewlett-Packard Development Company, L.P. # # 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. """ An example using monascaclient via the Python API """ from monascaclient import client import monascaclient.exc as exc import time # In order to use the python api directly, you must first obtain an # auth token and identify which endpoint you wish to speak to. endpoint = 'http://192.168.10.4:8070/v2.0' # The api version of monasca-api api_version = '2_0' # Pass in the keystone authentication kwargs to construct a monasca client. # The monasca_client will try to authenticate with keystone one time # when it sees a 401 unauthorized resp, to take care of a stale token. # In this example no token is input, so it will get a 401 when executing the # first metrics.create request, and will authenticate and try again. auth_kwargs = {'username': 'mini-mon', 'password': 'password', 'project_name': 'mini-mon', 'auth_url': 'http://192.168.10.5:35357/v3/'} monasca_client = client.Client(api_version, endpoint, **auth_kwargs) # you can reference the monascaclient.v2_0.shell.py # do_commands for command field initialization. # post a metric dimensions = {'instance_id': '12345', 'service': 'nova'} fields = {} fields['name'] = 'metric1' fields['dimensions'] = dimensions # time in milliseconds fields['timestamp'] = time.time() * 1000 fields['value'] = 222.333 try: resp = monasca_client.metrics.create(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(resp) print('Successfully created metric') # post a metric with a unicode service name dimensions = {'instance_id': '12345', 'service': u'\u76db\u5927'} fields = {} fields['name'] = 'metric1' fields['dimensions'] = dimensions fields['timestamp'] = time.time() * 1000 fields['value'] = 222.333 try: resp = monasca_client.metrics.create(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(resp) print('Successfully created metric') print ('Giving the DB time to update...') time.sleep(5) # metric-list name = 'metric1' dimensions = None fields = {} if name: fields['name'] = name if dimensions: fields['dimensions'] = dimensions try: body = monasca_client.metrics.list(**fields) except exc.HTTPException as he: print('HTTPException code=%s message=%s' % (he.code, he.message)) else: print(body)
apache-2.0
Python
3f877871a9f439be8d0839bfee965dc6462b7b3b
fix class method declaration
mikebranstein/IoT,mikebranstein/IoT
raspberry-pi/led-switch-toggle.py
raspberry-pi/led-switch-toggle.py
import RPi.GPIO as GPIO import time # tell GPIO to use the Pi's board numbering for pins GPIO.setmode(GPIO.BOARD) # simple class that toggles the output value of the outputPin (HIGH/LOW) # by pressing the switch on switchInputPin # # to use, instantiate and call the toggle() method in your loop class SwitchToggler: prevSwitchPressed = False outputPinOn = False def __init__(self, switchInputPin, outputPin): self.switchInputPin = switchInputPin self.outputPin = outputPin GPIO.setup (switchInputPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(outputPin, GPIO.OUT) def toggle(self): curSwitchPressed = not GPIO.input(self.switchInputPin) # do nothing if switch state has not changed if curSwitchPressed == prevSwitchPressed: return self.prevSwitchPressed = curSwitchPressed if curSwitchPressed: if self.outputPinOn: GPIO.output(self.outputPin, GPIO.LOW) self.outputPinOn = False else: GPIO.output(self.outputPin, GPIO.HIGH) self.outputPinOn = True return redLedPin = 22 switchPin = 18 toggler = SwitchToggler(switchPin, redLedPin) # set data direction of LED pin to output def loop(): global toggler toggler.toggle() return #loop until keyboard interrupt try: while True: loop() except KeyboardInterrupt: pass GPIO.cleanup()
import RPi.GPIO as GPIO import time # tell GPIO to use the Pi's board numbering for pins GPIO.setmode(GPIO.BOARD) # simple class that toggles the output value of the outputPin (HIGH/LOW) # by pressing the switch on switchInputPin # # to use, instantiate and call the toggle() method in your loop class SwitchToggler: prevSwitchPressed = False outputPinOn = False def __init__(self, switchInputPin, outputPin): self.switchInputPin = switchInputPin self.outputPin = outputPin GPIO.setup (switchInputPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(outputPin, GPIO.OUT) def toggle(): curSwitchPressed = not GPIO.input(self.switchInputPin) # do nothing if switch state has not changed if curSwitchPressed == prevSwitchPressed: return self.prevSwitchPressed = curSwitchPressed if curSwitchPressed: if self.outputPinOn: GPIO.output(self.outputPin, GPIO.LOW) self.outputPinOn = False else: GPIO.output(self.outputPin, GPIO.HIGH) self.outputPinOn = True return redLedPin = 22 switchPin = 18 toggler = SwitchToggler(switchPin, redLedPin) # set data direction of LED pin to output def loop(): global toggler toggler.toggle() return #loop until keyboard interrupt try: while True: loop() except KeyboardInterrupt: pass GPIO.cleanup()
mit
Python
e40c6076da9f31207b81589082acaca962078107
Fix #2971
vuolter/pyload,vuolter/pyload,vuolter/pyload
module/plugins/crypter/FshareVnFolder.py
module/plugins/crypter/FshareVnFolder.py
# -*- coding: utf-8 -*- import re from ..internal.Crypter import Crypter from ..internal.misc import replace_patterns class FshareVnFolder(Crypter): __name__ = "FshareVnFolder" __type__ = "crypter" __version__ = "0.09" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?fshare\.vn/folder/.+' __config__ = [("activated", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ("folder_per_package", "Default;Yes;No", "Create folder for each package", "Default"), ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10), ("dl_subfolders", "bool", "Download subfolders", False), ("package_subfolder", "bool", "Subfolder as a separate package", False)] __description__ = """Fshare.vn folder decrypter plugin""" __license__ = "GPLv3" __authors__ = [("zoidberg", "zoidberg@mujmail.cz"), ("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")] OFFLINE_PATTERN = r'404</title>' NAME_PATTERN = r'<title>Fshare - (.+?)</title>' LINK_PATTERN = r'<a class="filename" .+? href="(.+?)"' FOLDER_PATTERN = r'<a .*class="filename folder".+?data-id="(.+?)"' URL_REPLACEMENTS = [("http://", "https://")] def enum_folder(self, url): self.data = self.load(url) links = re.findall(self.LINK_PATTERN, self.data) if self.config.get('dl_subfolders'): for _f in re.findall(self.FOLDER_PATTERN, self.data): _u = "https://www.fshare.vn/folder/" + _f if self.config.get('package_subfolder'): links.append(_u) else: links.extend(self.enum_folder(_u)) return links def decrypt(self, pyfile): pyfile.url = replace_patterns(pyfile.url, self.URL_REPLACEMENTS) self.data = self.load(pyfile.url) if re.search(self.OFFLINE_PATTERN, self.data): self.offline() m = re.search(self.NAME_PATTERN, self.data) pack_name = m.group(1) if m is not None else pyfile.package().name links = self.enum_folder(pyfile.url) if links: self.packages = [(pack_name, links, pack_name)]
# -*- coding: utf-8 -*- from ..internal.SimpleCrypter import SimpleCrypter class FshareVnFolder(SimpleCrypter): __name__ = "FshareVnFolder" __type__ = "crypter" __version__ = "0.08" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?fshare\.vn/folder/.+' __config__ = [("activated", "bool", "Activated", True), ("use_premium", "bool", "Use premium account if available", True), ("folder_per_package", "Default;Yes;No", "Create folder for each package", "Default"), ("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)] __description__ = """Fshare.vn folder decrypter plugin""" __license__ = "GPLv3" __authors__ = [("zoidberg", "zoidberg@mujmail.cz"), ("GammaC0de", "nitzo2001[AT]yahoo[DOT]com")] OFFLINE_PATTERN = r'404</title>' LINK_PATTERN = r'<a class="filename" .+? href="(.+?)"' URL_REPLACEMENTS = [("http://", "https://")]
agpl-3.0
Python
c9ad789262f2e75010d0f6690d793a2f7c36f352
Add locked and lock_suggested properties to OfficialDocument
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
ynr/apps/official_documents/models.py
ynr/apps/official_documents/models.py
from __future__ import unicode_literals import os from django.db import models from django.utils.translation import ugettext_lazy as _ from popolo.models import Post from elections.models import Election from django_extensions.db.models import TimeStampedModel from compat import python_2_unicode_compatible DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders" def document_file_name(instance, filename): return os.path.join( "official_documents", str(instance.post_id), filename, ) @python_2_unicode_compatible class OfficialDocument(TimeStampedModel): # TODO FK to post_election and remove the Election and Post FKs NOMINATION_PAPER = 'Nomination paper' DOCUMENT_TYPES = ( (NOMINATION_PAPER, _('Nomination paper'), _('Nomination papers')), ) election = models.ForeignKey(Election) document_type = models.CharField( blank=False, choices=[(d[0], d[1]) for d in DOCUMENT_TYPES], max_length=100) uploaded_file = models.FileField( upload_to=document_file_name, max_length=800) post = models.ForeignKey(Post, blank=True, null=True) post_election = models.ForeignKey('candidates.PostExtraElection', null=False) source_url = models.URLField( help_text=_("The page that links to this document"), max_length=1000, ) def __str__(self): return "{0} ({1})".format( self.post.extra.slug, self.source_url, ) @models.permalink def get_absolute_url(self): return ('uploaded_document_view', (), {'pk': self.pk}) @property def locked(self): """ Is this post election locked? """ return self.post_election.candidates_locked @property def lock_suggested(self): """ Is there a suggested lock for this document? """ return self.post_election.suggestedpostlock_set.exists()
from __future__ import unicode_literals import os from django.db import models from django.utils.translation import ugettext_lazy as _ from popolo.models import Post from elections.models import Election from django_extensions.db.models import TimeStampedModel from compat import python_2_unicode_compatible DOCUMENT_UPLOADERS_GROUP_NAME = "Document Uploaders" def document_file_name(instance, filename): return os.path.join( "official_documents", str(instance.post_id), filename, ) @python_2_unicode_compatible class OfficialDocument(TimeStampedModel): # TODO FK to post_election and remove the Election and Post FKs NOMINATION_PAPER = 'Nomination paper' DOCUMENT_TYPES = ( (NOMINATION_PAPER, _('Nomination paper'), _('Nomination papers')), ) election = models.ForeignKey(Election) document_type = models.CharField( blank=False, choices=[(d[0], d[1]) for d in DOCUMENT_TYPES], max_length=100) uploaded_file = models.FileField( upload_to=document_file_name, max_length=800) post = models.ForeignKey(Post, blank=True, null=True) post_election = models.ForeignKey('candidates.PostExtraElection', null=False) source_url = models.URLField( help_text=_("The page that links to this document"), max_length=1000, ) def __str__(self): return "{0} ({1})".format( self.post.extra.slug, self.source_url, ) @models.permalink def get_absolute_url(self): return ('uploaded_document_view', (), {'pk': self.pk})
agpl-3.0
Python
e863c1b380911d39ebc309fa584dd3c847bc5312
add beta in fabfile
uhuramedia/cookiecutter-django,uhuramedia/cookiecutter-django
{{cookiecutter.repo_name}}/fabfile.py
{{cookiecutter.repo_name}}/fabfile.py
from fabric.api import env, run, local def live(): """Connects to the server.""" env.hosts = ['bankenverband.de'] env.user = 'freshmilk' env.cwd = '/var/www/{{cookiecutter.project_name}}' env.connect_to = '{0}@{1}:{2}'.format(env.user, env.hosts[0], env.cwd) def beta(): """Connects to beta/testing server""" env.hosts = ['beta.{{cookiecutter.domain_name}}'] env.user = 'username' env.cwd = '/var/www/beta.{{cookiecutter.project_name}}' env.connect_to = '{0}@{1}:{2}'.format(env.user, env.hosts[0], env.cwd) def gitpull(tag=None): """Pulls upstream brunch on the server.""" if tag is not None: run('git pull') run('git checkout %s' % tag) else: run('git pull') def collectstatic(): """Collect static files --noinput on server.""" run('{{cookiecutter.repo_name}}/manage.py collectstatic --noinput') def migrate(): """Sync project database on server.""" run('{{cookiecutter.repo_name}}/manage.py migrate') def touch(): """Touch the wsgi file.""" run('touch {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}.wsgi') def update(tag=None): """Runs gitpull, develop, collectstatic, migrate and touch. """ gitpull(tag=tag) collectstatic() migrate() touch() def dump(): run('{{cookiecutter.repo_name}}/manage.py sqldump') def sync_media(): local('rsync -avzh --exclude "CACHE" -e ssh %s/../media/* ../media' % env.connect_to) def sync_dump(): local('rsync -avPhzL -e ssh %s/var/dump.sql.gz var' % env.connect_to) def mirror(): """Runs dump, sync_media, sync_dump and sqlimport.""" dump() sync_media() sync_dump() local('{{cookiecutter.repo_name}}/manage.py sqlimport')
from fabric.api import env, run, local def live(): """Connects to the server.""" env.hosts = ['bankenverband.de'] env.user = 'freshmilk' env.cwd = '/var/www/{{cookiecutter.project_name}}' env.connect_to = '{0}@{1}:{2}'.format(env.user, env.hosts[0], env.cwd) def gitpull(tag=None): """Pulls upstream brunch on the server.""" if tag is not None: run('git pull') run('git checkout %s' % tag) else: run('git pull') def collectstatic(): """Collect static files --noinput on server.""" run('{{cookiecutter.repo_name}}/manage.py collectstatic --noinput') def migrate(): """Sync project database on server.""" run('{{cookiecutter.repo_name}}/manage.py migrate') def touch(): """Touch the wsgi file.""" run('touch {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}.wsgi') def update(tag=None): """Runs gitpull, develop, collectstatic, migrate and touch. """ gitpull(tag=tag) collectstatic() migrate() touch() def dump(): run('{{cookiecutter.repo_name}}/manage.py sqldump') def sync_media(): local('rsync -avzh --exclude "CACHE" -e ssh %s/../media/* ../media' % env.connect_to) def sync_dump(): local('rsync -avPhzL -e ssh %s/var/dump.sql.gz var' % env.connect_to) def mirror(): """Runs dump, sync_media, sync_dump and sqlimport.""" dump() sync_media() sync_dump() local('{{cookiecutter.repo_name}}/manage.py sqlimport')
bsd-3-clause
Python
ede0103939fa25cf04524dfc4d3d1a1430aead82
Update affected content loader tests.
Plexxi/st2,tonybaloney/st2,Itxaka/st2,alfasin/st2,grengojbo/st2,armab/st2,nzlosh/st2,grengojbo/st2,armab/st2,peak6/st2,dennybaa/st2,punalpatel/st2,emedvedev/st2,nzlosh/st2,emedvedev/st2,dennybaa/st2,pinterb/st2,Itxaka/st2,lakshmi-kannan/st2,pixelrebel/st2,peak6/st2,nzlosh/st2,tonybaloney/st2,jtopjian/st2,peak6/st2,punalpatel/st2,tonybaloney/st2,grengojbo/st2,jtopjian/st2,pixelrebel/st2,StackStorm/st2,pixelrebel/st2,pinterb/st2,jtopjian/st2,dennybaa/st2,pinterb/st2,alfasin/st2,punalpatel/st2,StackStorm/st2,nzlosh/st2,lakshmi-kannan/st2,alfasin/st2,Plexxi/st2,StackStorm/st2,emedvedev/st2,Plexxi/st2,StackStorm/st2,lakshmi-kannan/st2,Itxaka/st2,Plexxi/st2,armab/st2
st2common/tests/unit/test_content_loader.py
st2common/tests/unit/test_content_loader.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest2 from st2common.content.loader import ContentPackLoader CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) RESOURCES_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '../resources')) class ContentLoaderTest(unittest2.TestCase): def test_get_sensors(self): packs_base_path = os.path.join(RESOURCES_DIR, 'packs/') loader = ContentPackLoader() pack_sensors = loader.get_content(base_dirs=[packs_base_path], content_type='sensors') self.assertTrue(pack_sensors.get('pack1', None) is not None) def test_get_sensors_pack_missing_sensors(self): loader = ContentPackLoader() fail_pack_path = os.path.join(RESOURCES_DIR, 'packs/pack2') self.assertTrue(os.path.exists(fail_pack_path)) try: loader._get_sensors(fail_pack_path) self.fail('Empty packs must throw exception.') except: pass def test_invalid_content_type(self): packs_base_path = os.path.join(RESOURCES_DIR, 'packs/') loader = ContentPackLoader() try: loader.get_content(base_dirs=[packs_base_path], content_type='stuff') self.fail('Asking for invalid content should have thrown.') except: pass
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest2 from st2common.content.loader import ContentPackLoader CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) RESOURCES_DIR = os.path.abspath(os.path.join(CURRENT_DIR, '../resources')) class ContentLoaderTest(unittest2.TestCase): def test_get_sensors(self): packs_base_path = os.path.join(RESOURCES_DIR, 'packs/') loader = ContentPackLoader() pack_sensors = loader.get_content(base_dir=packs_base_path, content_type='sensors') self.assertTrue(pack_sensors.get('pack1', None) is not None) def test_get_sensors_pack_missing_sensors(self): loader = ContentPackLoader() fail_pack_path = os.path.join(RESOURCES_DIR, 'packs/pack2') self.assertTrue(os.path.exists(fail_pack_path)) try: loader._get_sensors(fail_pack_path) self.fail('Empty packs must throw exception.') except: pass def test_invalid_content_type(self): packs_base_path = os.path.join(RESOURCES_DIR, 'packs/') loader = ContentPackLoader() try: loader.get_content(base_dir=packs_base_path, content_type='stuff') self.fail('Asking for invalid content should have thrown.') except: pass
apache-2.0
Python
0f729d07c6501fe5cb1904ec72264694a5e9023c
Fix some bugs in djbuildhere
hint/django-hint-tools,hint/django-hint-tools
scripts/djbuildhere.py
scripts/djbuildhere.py
#!/usr/bin/env python """ Build """ import glob import os import shutil import sys try: import djtools # this is for testing purposes except ImportError: sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) import djtools # would be good not to overwrite old _djtools_common.py if len(sys.argv) > 1: destdir = sys.argv[1] else: destdir = os.getcwd() for file in glob.glob(djtools.get_skel_dir() + '/*'): shutil.copy(file, destdir)
#!/usr/bin/env python """ Build """ import glob import os import shutil import sys import djtools # would be good not to overwrite old _djtools_common.py if len(sys.argv > 1): destdir = sys.argv[1] else: destdir = os.getcwd() for file in glob(djtools.get_skel_dir() + '/*'): shutil.copy(file, destdir)
bsd-2-clause
Python
923ca5a7083d9833e74a6c5e312c54ff9c2b3209
add docstrings for logger.py
jeremy-miller/life-python
life/logger.py
life/logger.py
"""This module creates a logger for formatted console logging.""" import logging from sys import stdout class LoggerClass(object): """This class creates a logger for formatted console logging.""" @staticmethod def create_logger(log_level=logging.INFO): """This function creates a logger for formatted console logging. Args: log_level (int): The level at which to log. Default is INFO. Returns: The configured logger. """ logger = logging.getLogger('') logger.setLevel(log_level) log_formatter = logging.Formatter("%(asctime)s %(message)s", datefmt='[%d/%b/%Y %H:%M:%S]') console_handler = logging.StreamHandler(stdout) console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) return logger
import logging from sys import stdout class LoggerClass(object): @staticmethod def create_logger(log_level=logging.INFO): logger = logging.getLogger('') logger.setLevel(log_level) log_formatter = logging.Formatter("%(asctime)s %(message)s", datefmt='[%d/%b/%Y %H:%M:%S]') console_handler = logging.StreamHandler(stdout) console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) return logger
mit
Python
f585e7f61a35811cbc85cc39a30ecc6b827ccec0
Add first and last name to userInfo REST endpoint; Addresses #884
RENCI/xDCIShare,FescueFungiShare/hydroshare,RENCI/xDCIShare,RENCI/xDCIShare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,FescueFungiShare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,hydroshare/hydroshare,RENCI/xDCIShare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,hydroshare/hydroshare
hs_core/views/user_rest_api.py
hs_core/views/user_rest_api.py
from rest_framework.views import APIView from rest_framework.response import Response class UserInfo(APIView): def get(self, request): user_info = {"username": request.user.username} if request.user.email: user_info['email'] = request.user.email if request.user.first_name: user_info['first_name'] = request.user.first_name if request.user.last_name: user_info['last_name'] = request.user.last_name return Response(user_info)
from rest_framework.views import APIView from rest_framework.response import Response class UserInfo(APIView): def get(self, request): user_info = {"username": request.user.username} if request.user.email: user_info['email'] = request.user.email return Response(user_info)
bsd-3-clause
Python
d3e4973b8b52ccf1ff78f3780c002e5449622c66
change the length of str to 80 in parse_head.py
shifvb/DarkChina
http_proxy/tools/parse_head.py
http_proxy/tools/parse_head.py
# The MIT License (MIT) # # Copyright shifvb 2015-2016 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import threading from http_proxy.utils import get_time_str from http_proxy.utils import get_pretty_str # # parse http head, print debug message according to verbose level # verbose level 2: # print all brief message and original data # verbose level 1: # print only brief message # verbose level 0: # print nothing # return a tuple of (http_method_str, http_path_str, http_protocol_str) # # example: # if head is str # 'GET http://www.google.com/ HTTP/1.1\r\nHost: www.google.com\r\n\r\n' # then returns tuple # ('GET', 'http://www.google.com/', 'HTTP/1.1') # PATH_LEN = 35 def parse_head(head_str: str, verbose: int): method, path, protocol = head_str.split('\r\n')[0].split(' ') if verbose == 0: # no message pass elif verbose == 1: # brief message only print('[INFO] [{}] {:7} {:35} {}'.format(get_time_str(), method, get_pretty_str(path, PATH_LEN), protocol)) elif verbose == 2: # brief message and original data print('[INFO] [{}] {} {} {}'.format(get_time_str(), method, path, protocol), end=' ') print('[{} in {} running threads]'.format(threading.current_thread().getName(), threading.active_count())) print(head_str) return method, path, protocol def test(): for i in range(10): parse_head('GET http://www.google.com/ HTTP/1.1\r\nHost: www.google.com\r\n\r\n', 2) if __name__ == '__main__': test()
# The MIT License (MIT) # # Copyright shifvb 2015-2016 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import threading from http_proxy.utils import get_time_str from http_proxy.utils import get_pretty_str # # parse http head, print debug message according to verbose level # verbose level 2: # print all brief message and original data # verbose level 1: # print only brief message # verbose level 0: # print nothing # return a tuple of (http_method_str, http_path_str, http_protocol_str) # # example: # if head is str # 'GET http://www.google.com/ HTTP/1.1\r\nHost: www.google.com\r\n\r\n' # then returns tuple # ('GET', 'http://www.google.com/', 'HTTP/1.1') # PATH_LEN = 36 def parse_head(head_str: str, verbose: int): method, path, protocol = head_str.split('\r\n')[0].split(' ') if verbose == 0: # no message pass elif verbose == 1: # brief message only print('[INFO] [{}] {:7} {:36} {}'.format(get_time_str(), method, get_pretty_str(path, PATH_LEN), protocol)) elif verbose == 2: # brief message and original data print('[INFO] [{}] {} {} {}'.format(get_time_str(), method, path, protocol), end=' ') print('[{} in {} running threads]'.format(threading.current_thread().getName(), threading.active_count())) print(head_str) return method, path, protocol def test(): for i in range(10): parse_head('GET http://www.google.com/ HTTP/1.1\r\nHost: www.google.com\r\n\r\n', 2) if __name__ == '__main__': test()
mit
Python
eecf1445d3c14ea3a0b6074eb23b3a18da9715d6
add comment
aurzenligl/prophy,cislaa/prophy,cislaa/prophy,cislaa/prophy,aurzenligl/prophy
jinja/reader.py
jinja/reader.py
import os from xml.dom import minidom #To jest reader to konkretnych xmlwoych plików a nie genertyczny reader class Reader(object): files = [] def __init__(self, xml_dir_path): # czy oby na pewno ma on czytać pliki w momencie konstrukcji? Potem te dane sa w ramie przez cały czas życia tego obiektu a nie tylko wtedy gdy są potrzebne self.tree_files = {} self.xml_dir = xml_dir_path self.__set_files_to_parse() self.__open_files() def __open_files(self): for x in self.files: self.tree_files[x.partition('.')[0]]=self.__open_file(x) def __open_file(self, file): file_dir = os.path.join(self.xml_dir, file) dom_tree = minidom.parse(file_dir) return dom_tree def __set_files_to_parse(self): all_files = os.listdir(self.xml_dir) for f in all_files: # TODO: Think about some error message, now I do not know whether the operation was successful - see the first test if f.endswith('.xml'): self.files.append(f) def return_tree_files(self): return self.tree_files
import os from xml.dom import minidom class Reader(object): files = [] def __init__(self, xml_dir_path): self.tree_files = {} self.xml_dir = xml_dir_path self.__set_files_to_parse() self.__open_files() def __open_files(self): for x in self.files: self.tree_files[x.partition('.')[0]]=self.__open_file(x) def __open_file(self, file): file_dir = os.path.join(self.xml_dir, file) dom_tree = minidom.parse(file_dir) return dom_tree def __set_files_to_parse(self): all_files = os.listdir(self.xml_dir) for f in all_files: # TODO: Think about some error message, now I do not know whether the operation was successful - see the first test if f.endswith('.xml'): self.files.append(f) def return_tree_files(self): return self.tree_files
mit
Python
fb1a991d5840e261462a5378cfc02e43c0606ad8
Add try-catch block to Hausa stemming
berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud
mediacloud/mediawords/languages/ha/__init__.py
mediacloud/mediawords/languages/ha/__init__.py
import hausastemmer from typing import List from mediawords.languages import McLanguageException, SpaceSeparatedWordsMixIn, StopWordsFromFileMixIn from mediawords.languages.en import EnglishLanguage from mediawords.util.perl import decode_object_from_bytes_if_needed from mediawords.util.log import create_logger log = create_logger(__name__) # No non-breaking prefixes in Hausa, so using English class for text / sentence tokenization class HausaLanguage(SpaceSeparatedWordsMixIn, StopWordsFromFileMixIn): """Hausa language support module.""" @staticmethod def language_code() -> str: return "ha" @staticmethod def sample_sentence() -> str: return "a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako" def stem_words(self, words: List[str]) -> List[str]: words = decode_object_from_bytes_if_needed(words) if words is None: raise McLanguageException("Words to stem is None.") stems = [] for word in words: if word is None or len(word) == 0: log.debug("Word is empty or None.") stem = word else: stem = None try: stem = hausastemmer.stem(word) except Exception as ex: # Stemmer fails at certain words log.warning("Unable to stem word '{}': {}".format(word, str(ex))) if stem is None or len(stem) == 0: log.debug("Unable to stem word '%s'" % word) stem = word stems.append(stem) if len(words) != len(stems): log.warning("Stem count is not the same as word count; words: %s; stems: %s" % (str(words), str(stems),)) return stems def split_text_to_sentences(self, text: str) -> List[str]: text = decode_object_from_bytes_if_needed(text) # No non-breaking prefixes in Hausa, so using English file en = EnglishLanguage() return en.split_text_to_sentences(text)
import hausastemmer from typing import List from mediawords.languages import McLanguageException, SpaceSeparatedWordsMixIn, StopWordsFromFileMixIn from mediawords.languages.en import EnglishLanguage from mediawords.util.perl import decode_object_from_bytes_if_needed from mediawords.util.log import create_logger log = create_logger(__name__) # No non-breaking prefixes in Hausa, so using English class for text / sentence tokenization class HausaLanguage(SpaceSeparatedWordsMixIn, StopWordsFromFileMixIn): """Hausa language support module.""" @staticmethod def language_code() -> str: return "ha" @staticmethod def sample_sentence() -> str: return "a cikin a kan sakamako daga sakwannin a kan sakamako daga sakwannin daga ranar zuwa a kan sakamako" def stem_words(self, words: List[str]) -> List[str]: words = decode_object_from_bytes_if_needed(words) if words is None: raise McLanguageException("Words to stem is None.") stems = [] for word in words: if word is None or len(word) == 0: log.debug("Word is empty or None.") stem = word else: stem = hausastemmer.stem(word) if stem is None or len(stem) == 0: log.debug("Unable to stem word '%s'" % word) stem = word stems.append(stem) if len(words) != len(stems): log.warning("Stem count is not the same as word count; words: %s; stems: %s" % (str(words), str(stems),)) return stems def split_text_to_sentences(self, text: str) -> List[str]: text = decode_object_from_bytes_if_needed(text) # No non-breaking prefixes in Hausa, so using English file en = EnglishLanguage() return en.split_text_to_sentences(text)
agpl-3.0
Python
ec108184fec40e200f52b106c88a773f727cec8e
Introduce localizable raise conditions to the iLO power on script Signed-off-by:Javier.Alvarez-Valle@citrix.com
koushikcgit/xcp-networkd,simonjbeaumont/xcp-rrdd,djs55/squeezed,johnelse/xcp-rrdd,sharady/xcp-networkd,robhoes/squeezed,johnelse/xcp-rrdd,djs55/xcp-networkd,koushikcgit/xcp-rrdd,djs55/xcp-rrdd,koushikcgit/xcp-rrdd,djs55/xcp-networkd,sharady/xcp-networkd,djs55/xcp-rrdd,koushikcgit/xcp-networkd,simonjbeaumont/xcp-rrdd,koushikcgit/xcp-rrdd
scripts/poweron/iLO.py
scripts/poweron/iLO.py
import sys,M2Crypto, XenAPI, XenAPIPlugin class ILO_CONNECTION_ERROR(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) class ILO_POWERON_FAILED(Exception): """Base Exception class for all transfer plugin errors.""" def __init__(self, *args): Exception.__init__(self, *args) def getXmlWithLogin(user, password): inputFile=open("/etc/xapi.d/plugins/iLOPowerON.xml",'r') try: result= inputFile.read().replace('user',user).replace('password',password) finally: inputFile.close() return result def iLO(power_on_ip, user, password): xmlWithlogin=getXmlWithLogin(user,password)+'\r\n' ''' Send and receive ''' ctx = M2Crypto.SSL.Context() ctx.set_session_timeout(500) s = M2Crypto.SSL.Connection(ctx) totalmsg='' try: s.connect((power_on_ip,443)) written=s.sendall(xmlWithlogin) msg=s.read() totalmsg=msg while(len(msg)): msg=s.read() totalmsg+=msg except: s.close() raise ILO_CONNECTION_ERROR() '''Check that the server replies with no authentication error''' if len(totalmsg)>0 and totalmsg.find('STATUS="0x000A"')==-1: return str(True) else: raise ILO_POWERON_FAILED() def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print iLO(ip,user,password) if __name__ == "__main__": main()
import sys,M2Crypto def getXmlWithLogin(user, password): inputFile=open("/etc/xapi.d/plugins/iLOPowerON.xml",'r') try: result= inputFile.read().replace('user',user).replace('password',password) finally: inputFile.close() return result def iLO(power_on_ip, user, password): xmlWithlogin=getXmlWithLogin(user,password)+'\r\n' ''' Send and receive ''' ctx = M2Crypto.SSL.Context() ctx.set_session_timeout(500) s = M2Crypto.SSL.Connection(ctx) totalmsg='' try: s.connect((power_on_ip,443)) written=s.sendall(xmlWithlogin) msg=s.read() totalmsg=msg while(len(msg)): msg=s.read() totalmsg+=msg finally: s.close() '''Check that the server replies with no authentication error''' if len(totalmsg)>0 and totalmsg.find('STATUS="0x000A"')==-1: return str(True) else: return str(False) def main(): if len(sys.argv)<3: exit(0) ip=sys.argv[1] user=sys.argv[2] password=sys.argv[3] print iLO(ip,user,password) if __name__ == "__main__": main()
lgpl-2.1
Python
290a1f7a2c6860ec57bdb74b9c97207e93e611f0
Add option to visualize data in reverse
alexlee-gk/visual_dynamics
visualize_data.py
visualize_data.py
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') parser.add_argument('--reverse', action='store_true') args = parser.parse_args() with h5py.File(args.hdf5_fname, 'r') as hdf5_file: dsets = (hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']) if args.reverse: dsets = tuple(dset[()][::-1] for dset in dsets) for image_curr, vel, image_diff in zip(*dsets): image_next = image_curr + image_diff vis_image, done = util.visualize_images_callback(image_curr, image_next, vis_scale=args.vis_scale, delay=0) if done: break cv2.destroyAllWindows() if __name__ == "__main__": main()
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') args = parser.parse_args() with h5py.File(args.hdf5_fname, 'r') as hdf5_file: for image_curr, vel, image_diff in zip(hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']): image_next = image_curr + image_diff vis_image, done = util.visualize_images_callback(image_curr, image_next, vis_scale=args.vis_scale, delay=0) if done: break cv2.destroyAllWindows() if __name__ == "__main__": main()
mit
Python
e214cd39396489c35c36b9e06ba4edb0f426181d
Use a sleep of 0.01s longer than what we're testing for
eriol/circuits,treemo/circuits,eriol/circuits,treemo/circuits,treemo/circuits,nizox/circuits,eriol/circuits
tests/core/test_timers.py
tests/core/test_timers.py
# Module: test_timers # Date: 10th February 2010 # Author: James Mills, prologic at shortcircuit dot net dot au """Timers Tests""" from time import sleep from circuits import Event, Component, Timer class Test(Event): """Test Event""" class App(Component): flag = False def timer(self): self.flag = True app = App() app.start() def test_timer(): timer = Timer(0.1, Test(), "timer") timer.register(app) sleep(0.11) assert app.flag def test_persistentTimer(): timer = Timer(0.1, Test(), "timer", persist=True) timer.register(app) for i in xrange(2): sleep(0.11) assert app.flag app.flag = False timer.unregister()
# Module: test_timers # Date: 10th February 2010 # Author: James Mills, prologic at shortcircuit dot net dot au """Timers Tests""" from time import sleep from circuits import Event, Component, Timer class Test(Event): """Test Event""" class App(Component): flag = False def timer(self): self.flag = True app = App() app.start() def test_timer(): timer = Timer(0.1, Test(), "timer") timer.register(app) sleep(0.1) while app: pass assert app.flag def test_persistentTimer(): timer = Timer(0.1, Test(), "timer", persist=True) timer.register(app) for i in xrange(2): sleep(0.1) while app: pass assert app.flag app.flag = False timer.unregister()
mit
Python
d62588af4e8ee547308d87e95a867581c28e8d03
add example plist
jamesgk/ufo2ft,googlefonts/ufo2ft,jamesgk/ufo2fdk,googlei18n/ufo2ft,moyogo/ufo2ft
tests/featureWriters/featureWriters_test.py
tests/featureWriters/featureWriters_test.py
from __future__ import ( print_function, absolute_import, division, unicode_literals, ) from ufo2ft.featureWriters import ( BaseFeatureWriter, FEATURE_WRITERS_KEY, loadFeatureWriters, loadFeatureWriterFromString, ) try: from plistlib import loads, FMT_XML def readPlistFromString(s): return loads(s, fmt=FMT_XML) except ImportError: from plistlib import readPlistFromString import pytest from ..testSupport import _TempModule TEST_LIB_PLIST = readPlistFromString(""" <dict> <key>com.github.googlei18n.ufo2ft.featureWriters</key> <array> <dict> <key>class</key> <string>KernFeatureWriter</string> <key>options</key> <dict> <key>mode</key> <string>skip</string> </dict> </dict> </array> </dict> """.encode("utf-8")) class FooBarWriter(BaseFeatureWriter): tableTag = "GSUB" def __init__(self, **kwargs): pass def write(self, font, feaFile, compiler=None): return False @pytest.fixture(scope="module", autouse=True) def customWriterModule(): """Make a temporary 'myFeatureWriters' module containing a 'FooBarWriter' class for testing the wruter loading machinery. """ with _TempModule("myFeatureWriters") as temp_module: temp_module.module.__dict__["FooBarWriter"] = FooBarWriter yield VALID_SPEC_LISTS = [ [{"class": "KernFeatureWriter"}], [ {"class": "KernFeatureWriter", "options": {"ignoreMarks": False}}, {"class": "MarkFeatureWriter", "options": {"features": ["mark"]}}, ], [ { "class": "FooBarWriter", "module": "myFeatureWriters", "options": {"a": 1}, } ], TEST_LIB_PLIST[FEATURE_WRITERS_KEY], ] @pytest.mark.parametrize("specList", VALID_SPEC_LISTS) def test_loadFeatureWriters_valid(specList, FontClass): ufo = FontClass() ufo.lib[FEATURE_WRITERS_KEY] = specList for writer in loadFeatureWriters(ufo, ignoreErrors=False): assert writer.tableTag in {"GSUB", "GPOS"} assert callable(writer.write) VALID_SPEC_STRINGS = [ "KernFeatureWriter", "KernFeatureWriter(ignoreMarks=False)", "MarkFeatureWriter(features=['mark'])", "myFeatureWriters::FooBarWriter(a=1)", ] @pytest.mark.parametrize("spec", VALID_SPEC_STRINGS) def test_loadFeatureWriterFromString_valid(spec, FontClass): writer = loadFeatureWriterFromString(spec) assert writer.tableTag in {"GSUB", "GPOS"} assert callable(writer.write)
from __future__ import ( print_function, absolute_import, division, unicode_literals, ) from ufo2ft.featureWriters import ( BaseFeatureWriter, FEATURE_WRITERS_KEY, loadFeatureWriters, loadFeatureWriterFromString, ) import pytest from ..testSupport import _TempModule class FooBarWriter(BaseFeatureWriter): tableTag = "GSUB" def __init__(self, **kwargs): pass def write(self, font, feaFile, compiler=None): return False @pytest.fixture(scope="module", autouse=True) def customWriterModule(): """Make a temporary 'myFeatureWriters' module containing a 'FooBarWriter' class for testing the wruter loading machinery. """ with _TempModule("myFeatureWriters") as temp_module: temp_module.module.__dict__["FooBarWriter"] = FooBarWriter yield VALID_SPEC_LISTS = [ [{"class": "KernFeatureWriter"}], [ {"class": "KernFeatureWriter", "options": {"ignoreMarks": False}}, {"class": "MarkFeatureWriter", "options": {"features": ["mark"]}}, ], [ { "class": "FooBarWriter", "module": "myFeatureWriters", "options": {"a": 1}, } ], ] @pytest.mark.parametrize("specList", VALID_SPEC_LISTS) def test_loadFeatureWriters_valid(specList, FontClass): ufo = FontClass() ufo.lib[FEATURE_WRITERS_KEY] = specList for writer in loadFeatureWriters(ufo, ignoreErrors=False): assert writer.tableTag in {"GSUB", "GPOS"} assert callable(writer.write) VALID_SPEC_STRINGS = [ "KernFeatureWriter", "KernFeatureWriter(ignoreMarks=False)", "MarkFeatureWriter(features=['mark'])", "myFeatureWriters::FooBarWriter(a=1)", ] @pytest.mark.parametrize("spec", VALID_SPEC_STRINGS) def test_loadFeatureWriterFromString_valid(spec, FontClass): writer = loadFeatureWriterFromString(spec) assert writer.tableTag in {"GSUB", "GPOS"} assert callable(writer.write)
mit
Python
bf6d6cdaf946af7ce8d1aa6831e7da9b47fef54f
Put import back on top
incuna/django-user-deletion
user_deletion/managers.py
user_deletion/managers.py
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
from dateutil.relativedelta import relativedelta from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
bsd-2-clause
Python
8d0e16041a24f4526ac35aaad1c2f16e601236b1
simplify import for ViewItem
TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera,TheImagingSource/tiscamera
tools/tcam-capture/tcam_capture/ViewItem.py
tools/tcam-capture/tcam_capture/ViewItem.py
# Copyright 2018 The Imaging Source Europe GmbH # # 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 PyQt5.QtWidgets import (QGraphicsPixmapItem) from PyQt5.QtGui import QColor class ViewItem(QGraphicsPixmapItem): """ Derived class enables mouse tracking for color under mouse retrieval """ def __init__(self, parent=None): super(ViewItem, self).__init__(parent) self.setAcceptHoverEvents(True) self.mouse_over = False # flag if mouse is over our widget self.mouse_position_x = -1 self.mouse_position_y = -1 def hoverEnterEvent(self, event): self.mouse_over = True def hoverLeaveEvent(self, event): self.mouse_over = False def hoverMoveEvent(self, event): mouse_position = event.pos() self.mouse_position_x = mouse_position.x() self.mouse_position_y = mouse_position.y() super().hoverMoveEvent(event) def get_resolution(self): return self.pixmap().size() def get_mouse_color(self): if self.mouse_over: if(self.mouse_position_x <= self.pixmap().width() and self.mouse_position_y <= self.pixmap().height()): return QColor(self.pixmap().toImage().pixel(self.mouse_position_x, self.mouse_position_y)) else: self.mouse_position_x = -1 self.mouse_position_y = -1 return QColor(0, 0, 0)
# Copyright 2018 The Imaging Source Europe GmbH # # 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 PyQt5 import QtGui, QtWidgets from PyQt5.QtWidgets import (QAction, QMenu, QGraphicsView, QGraphicsItem, QGraphicsScene, QGraphicsPixmapItem) from PyQt5.QtCore import QObject, pyqtSignal, Qt, QEvent, QSizeF class ViewItem(QtWidgets.QGraphicsPixmapItem): """Derived class enables mouse tracking for color under mouse retrieval""" def __init__(self, parent=None): super(ViewItem, self).__init__(parent) self.setAcceptHoverEvents(True) self.mouse_over = False # flag if mouse is over our widget self.mouse_position_x = -1 self.mouse_position_y = -1 def hoverEnterEvent(self, event): self.mouse_over = True def hoverLeaveEvent(self, event): self.mouse_over = False def hoverMoveEvent(self, event): mouse_position = event.pos() self.mouse_position_x = mouse_position.x() self.mouse_position_y = mouse_position.y() super().hoverMoveEvent(event) def get_resolution(self): return self.pixmap().size() def get_mouse_color(self): if self.mouse_over: if(self.mouse_position_x <= self.pixmap().width() and self.mouse_position_y <= self.pixmap().height()): return QtGui.QColor(self.pixmap().toImage().pixel(self.mouse_position_x, self.mouse_position_y)) else: self.mouse_position_x = -1 self.mouse_position_y = -1 return QtGui.QColor(0, 0, 0)
apache-2.0
Python
3d8d6f906f8adcf60a8e91f2962f2756789581a7
update test_mesh_expand.py for pytest
vlukes/sfepy,vlukes/sfepy,rc/sfepy,sfepy/sfepy,vlukes/sfepy,rc/sfepy,rc/sfepy,sfepy/sfepy,BubuLK/sfepy,BubuLK/sfepy,sfepy/sfepy,BubuLK/sfepy
tests/test_mesh_expand.py
tests/test_mesh_expand.py
def test_mesh_expand(): import numpy as nm from sfepy.mesh.mesh_tools import expand2d from sfepy.discrete.fem.mesh import Mesh from sfepy import data_dir mesh2d = Mesh.from_file(data_dir + '/meshes/2d/square_quad.mesh') mesh3d_ref = Mesh.from_file(data_dir +\ '/meshes/3d/cube_medium_hexa.mesh') mesh3d_gen = expand2d(mesh2d, 0.1, 10) mesh3d_gen.coors[:,2] += -0.5 d0 = nm.sort(nm.linalg.norm(mesh3d_ref.coors, axis=1)) d1 = nm.sort(nm.linalg.norm(mesh3d_gen.coors, axis=1)) ok = nm.linalg.norm(d0 - d1) < 1e-6 assert ok
from __future__ import absolute_import from sfepy.base.testing import TestCommon class Test(TestCommon): @staticmethod def from_conf(conf, options): test = Test(conf=conf, options=options) return test def test_mesh_expand(self): import numpy as nm from sfepy.mesh.mesh_tools import expand2d from sfepy.discrete.fem.mesh import Mesh from sfepy import data_dir mesh2d = Mesh.from_file(data_dir + '/meshes/2d/square_quad.mesh') mesh3d_ref = Mesh.from_file(data_dir +\ '/meshes/3d/cube_medium_hexa.mesh') mesh3d_gen = expand2d(mesh2d, 0.1, 10) mesh3d_gen.coors[:,2] += -0.5 d0 = nm.sort(nm.linalg.norm(mesh3d_ref.coors, axis=1)) d1 = nm.sort(nm.linalg.norm(mesh3d_gen.coors, axis=1)) if nm.linalg.norm(d0 - d1) < 1e-6: return True else: return False return True
bsd-3-clause
Python
287389927050c6cc32cab0d572ad8c9931fe922e
Remove some optional middleware from the testsuite
matthiask/django-admin-ordering,matthiask/django-admin-ordering
tests/testapp/settings.py
tests/testapp/settings.py
import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.messages', 'testapp', 'admin_ordering', ] MEDIA_ROOT = '/media/' STATIC_URL = '/static/' BASEDIR = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(BASEDIR, 'media/') STATIC_ROOT = os.path.join(BASEDIR, 'static/') SECRET_KEY = 'supersikret' LOGIN_REDIRECT_URL = '/?login=1' ROOT_URLCONF = 'testapp.urls' LANGUAGES = (('en', 'English'), ('de', 'German')) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE_CLASSES = MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ] # Do not warn about MIDDLEWARE_CLASSES SILENCED_SYSTEM_CHECKS = ['1_10.W001']
import os DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.staticfiles', 'django.contrib.messages', 'testapp', 'admin_ordering', ] MEDIA_ROOT = '/media/' STATIC_URL = '/static/' BASEDIR = os.path.dirname(__file__) MEDIA_ROOT = os.path.join(BASEDIR, 'media/') STATIC_ROOT = os.path.join(BASEDIR, 'static/') SECRET_KEY = 'supersikret' LOGIN_REDIRECT_URL = '/?login=1' ROOT_URLCONF = 'testapp.urls' LANGUAGES = (('en', 'English'), ('de', 'German')) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MIDDLEWARE_CLASSES = MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # Do not warn about MIDDLEWARE_CLASSES SILENCED_SYSTEM_CHECKS = ['1_10.W001']
bsd-3-clause
Python
32ae4df3ace7c7f44ed9f7c55d144c43e55f2c4b
Fix build for third_party/qcms when SSE is diabled.
patrickm/chromium.src,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,rogerwang/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,hujiajie/pa-chromium,robclark/chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,keishi/chromium,hujiajie/pa-chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,robclark/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,keishi/chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,patrickm/chromium.src,dednal/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,keishi/chromium,robclark/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,jaruba/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,timopulkkinen/BubbleFish,patrickm/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,Chilledheart/chromium,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,robclark/chromium,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,ltilve/chromium,dednal/chromium.src,jaruba/chromium.src,jaruba/chromium.src,anirudhSK/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,patrickm/chromium.src,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,keishi/chromium,anirudhSK/chromium,littlstar/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,patrickm/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,hujiajie/pa-chromium,Jonekee/chromium.src,keishi/chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,rogerwang/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,zcbenz/cefode-chromium,robclark/chromium,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,patrickm/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,M4sse/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,rogerwang/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,markYoungH/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,rogerwang/chromium,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,robclark/chromium,rogerwang/chromium,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,Chilledheart/chromium,rogerwang/chromium,mogoweb/chromium-crosswalk,anirudhSK/chromium,keishi/chromium,dushu1203/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,dednal/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,keishi/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,bright-sparks/chromium-spacewalk,rogerwang/chromium,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,dednal/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,ltilve/chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,rogerwang/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,keishi/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,littlstar/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,robclark/chromium,pozdnyakov/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk
third_party/qcms/qcms.gyp
third_party/qcms/qcms.gyp
# Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'qcms', 'product_name': 'qcms', 'type': '<(library)', 'sources': [ 'qcms.h', 'qcmsint.h', 'qcmstypes.h', 'iccread.c', 'transform-sse1.c', 'transform-sse2.c', 'transform.c', ], 'direct_dependent_settings': { 'include_dirs': [ '.', ], }, 'conditions': [ ['OS=="linux" and (branding=="Chrome" or disable_sse2==1)', { 'sources/': [ ['exclude', 'transform-sse1.c'], ['exclude', 'transform-sse2.c'], ], },], ], }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
# Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'qcms', 'product_name': 'qcms', 'type': '<(library)', 'sources': [ 'qcms.h', 'qcmsint.h', 'qcmstypes.h', 'iccread.c', 'transform-sse1.c', 'transform-sse2.c', 'transform.c', ], 'direct_dependent_settings': { 'include_dirs': [ '.', ], }, }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
bsd-3-clause
Python
88e56a74e85f46290966cd881d2a84b08f9c975e
Fix children bug
adrianliaw/PyCuber
pycuber/ext/solvers/cfop/f2l.py
pycuber/ext/solvers/cfop/f2l.py
""" Module for solving Rubik's Cube F2L. """ from ....cube import * from ....algorithm import * from ....util import a_star_search class F2LPairSolver(object): """ F2LPairSolver() => Solver for solving an F2L pair. """ def __init__(self, cube=None, pair=None): self.cube = cube self.pair = pair def feed(self, cube, pair): """ Feed Cube to the solver. """ self.cube = cube self.pair = pair def get_pair(self): """ Get the F2L pair (corner, edge). """ colours = ( self.cube[self.pair[0]].colour, self.cube[self.pair[1]].colour, self.cube["D"].colour ) result_corner = self.cube.children.copy() for c in colours[:2]: result_corner &= self.cube.has_colour(c) result_edge = result_corner & self.cube.select_type("edge") result_corner &= self.cube.has_colour(colours[2]) return (list(result_corner)[0], list(result_edge)[0])
""" Module for solving Rubik's Cube F2L. """ from ....cube import * from ....algorithm import * from ....util import a_star_search class F2LPairSolver(object): """ F2LPairSolver() => Solver for solving an F2L pair. """ def __init__(self, cube=None, pair=None): self.cube = cube self.pair = pair def feed(self, cube, pair): """ Feed Cube to the solver. """ self.cube = cube self.pair = pair def get_pair(self): """ Get the F2L pair (corner, edge). """ colours = ( self.cube[self.pair[0]].colour, self.cube[self.pair[1]].colour, self.cube["D"].colour ) result_corner = self.cube.children for c in colours[:2]: result_corner &= self.cube.has_colour(c) result_edge = result_corner & self.cube.select_type("edge") result_corner &= self.cube.has_colour(colours[2]) return (list(result_corner)[0], list(result_edge)[0])
mit
Python
6a767780253ef981e78b00bb9937e9aaa0f9d1b8
Add sleep after nickserv identify
Motoko11/MotoBot
motobot/core_plugins/network_handlers.py
motobot/core_plugins/network_handlers.py
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.identified = False sleep(1) @hook('NOTICE') def handle_identification(bot, context, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) bot.identified = True @hook('002') def handle_nickserv_identification(bot, context, message): """ At server welcome message 004 identify to nickserv and join channels. """ if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) sleep(1) @hook('ERROR') def handle_error(bot, context, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.identified = False sleep(1) @hook('NOTICE') def handle_identification(bot, context, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) bot.identified = True @hook('002') def handle_nickserv_identification(bot, context, message): """ At server welcome message 004 identify to nickserv and join channels. """ if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) @hook('ERROR') def handle_error(bot, context, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
mit
Python
68832a3638029713b59f8a462b96e797ce754c72
Add docstrings to Singleton methods
shaunstanislaus/pyexperiment,duerrp/pyexperiment,shaunstanislaus/pyexperiment,shaunstanislaus/pyexperiment,DeercoderResearch/pyexperiment,DeercoderResearch/pyexperiment,duerrp/pyexperiment,shaunstanislaus/pyexperiment,DeercoderResearch/pyexperiment,kinverarity1/pyexperiment,kinverarity1/pyexperiment,DeercoderResearch/pyexperiment,kinverarity1/pyexperiment,duerrp/pyexperiment,kinverarity1/pyexperiment
pyexperiment/utils/Singleton.py
pyexperiment/utils/Singleton.py
"""Implements a singleton base-class (as in tornado.ioloop.IOLoop.instance()) Written by Peter Duerr (inspired by tornado's implementation) """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import threading class Singleton(object): """Singleton base-class (or mixin) """ __singleton_lock = threading.Lock() __singleton_instance = None @classmethod def get_instance(cls): """Get the singleton instance """ if not cls.__singleton_instance: with cls.__singleton_lock: if not cls.__singleton_instance: cls.__singleton_instance = cls() return cls.__singleton_instance @classmethod def reset_instance(cls): """Reset the singleton """ if cls.__singleton_instance: with cls.__singleton_lock: if cls.__singleton_instance: cls.__singleton_instance = None class SingletonIndirector(object): """Creates a class that mimics the Singleton lazily This avoids calling obj.get_instance().attribute too often """ def __init__(self, singleton): """Initializer """ self.singleton = singleton def __getattr__(self, attr): """Call __getattr__ on the singleton instance """ return getattr(self.singleton.get_instance(), attr) def __repr__(self): """Call __repr__ on the singleton instance """ return repr(self.singleton.get_instance()) def __getitem__(self, *args): """Call __getitem__ on the singleton instance """ return self.singleton.get_instance().__getitem__(*args)
"""Implements a singleton base-class (as in tornado.ioloop.IOLoop.instance()) Written by Peter Duerr (inspired by tornado's implementation) """ from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import import threading class Singleton(object): """Singleton base-class (or mixin) """ __singleton_lock = threading.Lock() __singleton_instance = None @classmethod def get_instance(cls): if not cls.__singleton_instance: with cls.__singleton_lock: if not cls.__singleton_instance: cls.__singleton_instance = cls() return cls.__singleton_instance @classmethod def reset_instance(cls): if cls.__singleton_instance: with cls.__singleton_lock: if cls.__singleton_instance: cls.__singleton_instance = None class SingletonIndirector(object): """Creates a class that mimics the Singleton lazily This avoids calling obj.get_instance().attribute too often """ def __init__(self, singleton): """Initializer """ self.singleton = singleton def __getattr__(self, attr): """Call __getattr__ on the singleton instance """ return getattr(self.singleton.get_instance(), attr) def __repr__(self): """Call __repr__ on the singleton instance """ return repr(self.singleton.get_instance()) def __getitem__(self, *args): """Call __getitem__ on the singleton instance """ return self.singleton.get_instance().__getitem__(*args)
mit
Python
1a9122d59be0c351b14c174a60880c2e927e6168
Fix failing host name test and add wildcard tests
fyookball/electrum,fyookball/electrum,fyookball/electrum
lib/tests/test_interface.py
lib/tests/test_interface.py
import unittest from .. import interface class TestInterface(unittest.TestCase): def test_match_host_name(self): self.assertTrue(interface._match_hostname('asd.fgh.com', 'asd.fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', 'asd.zxc.com')) self.assertTrue(interface._match_hostname('asd.fgh.com', '*.fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', '*fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', '*.zxc.com')) def test_check_host_name(self): i = interface.TcpConnection(server=':1:', queue=None, config_path=None) self.assertFalse(i.check_host_name(None, None)) self.assertFalse(i.check_host_name( peercert={'subjectAltName': []}, name='')) self.assertTrue(i.check_host_name( peercert={'subjectAltName': (('DNS', 'foo.bar.com'),)}, name='foo.bar.com')) self.assertTrue(i.check_host_name( peercert={'subjectAltName': (('DNS', '*.bar.com'),)}, name='foo.bar.com')) self.assertFalse(i.check_host_name( peercert={'subjectAltName': (('DNS', '*.bar.com'),)}, name='sub.foo.bar.com')) self.assertTrue(i.check_host_name( peercert={'subject': ((('commonName', 'foo.bar.com'),),)}, name='foo.bar.com')) self.assertTrue(i.check_host_name( peercert={'subject': ((('commonName', '*.bar.com'),),)}, name='foo.bar.com')) self.assertFalse(i.check_host_name( peercert={'subject': ((('commonName', '*.bar.com'),),)}, name='sub.foo.bar.com'))
import unittest from .. import interface class TestInterface(unittest.TestCase): def test_match_host_name(self): self.assertTrue(interface._match_hostname('asd.fgh.com', 'asd.fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', 'asd.zxc.com')) self.assertTrue(interface._match_hostname('asd.fgh.com', '*.fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', '*fgh.com')) self.assertFalse(interface._match_hostname('asd.fgh.com', '*.zxc.com')) def test_check_host_name(self): i = interface.TcpConnection(server=':1:', queue=None, config_path=None) self.assertFalse(i.check_host_name(None, None)) self.assertFalse(i.check_host_name( peercert={'subjectAltName': []}, name='')) self.assertTrue(i.check_host_name( peercert={'subjectAltName': [('DNS', 'foo.bar.com')]}, name='foo.bar.com')) self.assertTrue(i.check_host_name( peercert={'subject': [('commonName', 'foo.bar.com')]}, name='foo.bar.com'))
mit
Python
d7d16f5c154b1c135e4eede78338022307bc720d
Fix bug in zhengzhou jiesuan parameter
happy6666/stockStrategies,happy6666/stockStrategies
options/script/zzjiesuan_parameter.py
options/script/zzjiesuan_parameter.py
#!/usr/bin/python # coding: utf-8 import sys import urllib2 import time from datetime import datetime from bs4 import BeautifulSoup TODAY=datetime.today().strftime('%Y%m%d') IMPORTANT='20101008' def getDataOnDate(ts): t=0; alldata=[] while True: time.sleep(3) try: if ts>=IMPORTANT: print 'http://www.czce.com.cn/portal/DFSStaticFiles/Future/%s/%s/FutureDataClearParams.htm?'%(ts[:4],ts) url=urllib2.urlopen(urllib2.Request('http://www.czce.com.cn/portal/DFSStaticFiles/Future/%s/%s/FutureDataClearParams.htm'%(ts[:4],ts))) else: print 'http://www.czce.com.cn/portal/exchange/%s/dataclearparams/%s.htm'%(ts[:4],ts) url=urllib2.urlopen('http://www.czce.com.cn/portal/exchange/%s/dataclearparams/%s.htm'%(ts[:4],ts)) data=url.read() soup=BeautifulSoup(data,from_encoding='utf-8') return soup for i,prod in enumerate(soup.find('table').find('table').find_all('tr')): #skip first name line if i>0: tmplist=[('%s'%(col.text)).encode('utf8') for col in prod.find_all('td')] if len(tmplist)<9: tmplist.append('None') tmplist.append('None') tmplist.append('None') tmplist.append(ts) tmplist.append(TODAY) alldata.append(tmplist) return alldata except urllib2.HTTPError as e: print '%s->Data not exist on date:%s'%(e.code,ts) return None except Exception as e: print 'Error on date:%s\n%s'%(ts,e) t+=60 time.sleep(t) if __name__=='__main__': with file(sys.argv[2],'a') as output: alldata=getDataOnDate(sys.argv[1]) if alldata is not None and len(alldata)>0: for prod in alldata: output.write('\001'.join(prod)) output.write('\n') output.flush()
#!/usr/bin/python # coding: utf-8 import sys import urllib2 import time from datetime import datetime from bs4 import BeautifulSoup TODAY=datetime.today().strftime('%Y%m%d') IMPORTANT='20101008' def getDataOnDate(ts): t=0; alldata=[] while True: time.sleep(3) try: if ts>=IMPORTANT: print 'http://www.czce.com.cn/portal/DFSStaticFiles/Future/%s/%s/FutureDataClearParams.htm'%(ts[:4],ts) url=urllib2.urlopen('http://www.czce.com.cn/portal/DFSStaticFiles/Future/%s/%s/FutureDataClearParams.htm'%(ts[:4],ts)) else: print 'http://www.czce.com.cn/portal/exchange/%s/dataclearparams/%s.htm'%(ts[:4],ts) url=urllib2.urlopen('http://www.czce.com.cn/portal/exchange/%s/dataclearparams/%s.htm'%(ts[:4],ts)) data=url.read() soup=BeautifulSoup(data,from_encoding='utf-8') for i,prod in enumerate(soup.find('table').find('table').find_all('tr')): #skip first name line if i>0: tmplist=[('%s'%(col.text)).encode('utf8') for col in prod.find_all('td')] if len(tmplist)<9: tmplist.append('None') tmplist.append('None') tmplist.append('None') tmplist.append(ts) tmplist.append(TODAY) alldata.append(tmplist) return alldata except urllib2.HTTPError as e: print '%s->Data not exist on date:%s'%(e.code,ts) return None except Exception as e: print 'Error on date:%s\n%s'%(ts,e) t+=60 time.sleep(t) if __name__=='__main__': with file(sys.argv[2],'a') as output: alldata=getDataOnDate(sys.argv[1]) if alldata is not None and len(alldata)>0: for prod in alldata: output.write('\001'.join(prod)) output.write('\n') output.flush()
apache-2.0
Python
832951d57a76d106db485c9a3469870713759ba5
Fix ID of previous migration in comment
stackforge/blazar,ChameleonCloud/blazar,openstack/blazar,stackforge/blazar,openstack/blazar,ChameleonCloud/blazar
blazar/db/migration/alembic_migrations/versions/e069c014356d_add_floatingip.py
blazar/db/migration/alembic_migrations/versions/e069c014356d_add_floatingip.py
# Copyright 2019 OpenStack Foundation. # # 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. """add-floatingip Revision ID: e069c014356d Revises: 9593f3656974 Create Date: 2019-01-10 10:15:47.874521 """ # revision identifiers, used by Alembic. revision = 'e069c014356d' down_revision = '9593f3656974' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('floatingips', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('floating_network_id', sa.String(length=255), nullable=False), sa.Column('subnet_id', sa.String(length=255), nullable=False), sa.Column('floating_ip_address', sa.String(length=255), nullable=False), sa.Column('reservable', sa.Boolean(), server_default=sa.text(u'true'), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('subnet_id', 'floating_ip_address')) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('floatingips') # ### end Alembic commands ###
# Copyright 2019 OpenStack Foundation. # # 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. """add-floatingip Revision ID: e069c014356d Revises: 35b314cd39ee Create Date: 2019-01-10 10:15:47.874521 """ # revision identifiers, used by Alembic. revision = 'e069c014356d' down_revision = '9593f3656974' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('floatingips', sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.Column('id', sa.String(length=36), nullable=False), sa.Column('floating_network_id', sa.String(length=255), nullable=False), sa.Column('subnet_id', sa.String(length=255), nullable=False), sa.Column('floating_ip_address', sa.String(length=255), nullable=False), sa.Column('reservable', sa.Boolean(), server_default=sa.text(u'true'), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('subnet_id', 'floating_ip_address')) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('floatingips') # ### end Alembic commands ###
apache-2.0
Python
c2d3c2c471dfb504626509a34256eb2d9898cfa2
Fix to use get_serializer_class method instead of serializer_class
alanjds/drf-nested-routers
rest_framework_nested/viewsets.py
rest_framework_nested/viewsets.py
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() serializer_class = self.get_serializer_class() if hasattr(serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
apache-2.0
Python
c6790535ea1e49ec65c4926f997db746d9b0833b
use common board mode
wuan/klimalogger
klimalogger/sensor/sht1x_sensor.py
klimalogger/sensor/sht1x_sensor.py
# -*- coding: utf8 -*- from injector import singleton, inject try: import configparser except ImportError: import configparser as configparser from sht1x.Sht1x import Sht1x as SHT1x @singleton class Sensor: name = "SHT1x" @inject def __init__(self, config_parser: configparser.ConfigParser): data_pin = int(config_parser.get('sht1x_sensor', 'data_pin')) sck_pin = int(config_parser.get('sht1x_sensor', 'sck_pin')) self.sht1x = SHT1x(dataPin=data_pin, sckPin=sck_pin, gpioMode=SHT1x.GPIO_BCM) def measure(self, data_builder): (temperature, humidity) = self.sht1x.read_temperature_C_and_humidity() if temperature > -40.0: print("valid values") try: dew_point = self.sht1x.calculate_dew_point(temperature, humidity) dew_point = round(dew_point, 2) except ValueError: dew_point = None temperature = round(temperature, 2) humidity = round(humidity, 2) else: temperature = None humidity = None dew_point = None data_builder.add(self.name, "temperature", "°C", temperature) if dew_point: data_builder.add(self.name, "dew point", "°C", dew_point, True) data_builder.add(self.name, "relative humidity", "%", humidity)
# -*- coding: utf8 -*- from injector import singleton, inject try: import configparser except ImportError: import configparser as configparser from sht1x.Sht1x import Sht1x as SHT1x @singleton class Sensor: name = "SHT1x" @inject def __init__(self, config_parser: configparser.ConfigParser): data_pin = int(config_parser.get('sht1x_sensor', 'data_pin')) sck_pin = int(config_parser.get('sht1x_sensor', 'sck_pin')) self.sht1x = SHT1x(dataPin=data_pin, sckPin=sck_pin, gpioMode=SHT1x.GPIO_BOARD) def measure(self, data_builder): (temperature, humidity) = self.sht1x.read_temperature_C_and_humidity() if temperature > -40.0: print("valid values") try: dew_point = self.sht1x.calculate_dew_point(temperature, humidity) dew_point = round(dew_point, 2) except ValueError: dew_point = None temperature = round(temperature, 2) humidity = round(humidity, 2) else: temperature = None humidity = None dew_point = None data_builder.add(self.name, "temperature", "°C", temperature) if dew_point: data_builder.add(self.name, "dew point", "°C", dew_point, True) data_builder.add(self.name, "relative humidity", "%", humidity)
apache-2.0
Python
3b7328dd7d9d235bf32b3cfb836b49e50b70be77
Allow for non-ascii characters in password_hash
dailymuse/oz,dailymuse/oz,dailymuse/oz
oz/plugins/redis_sessions/__init__.py
oz/plugins/redis_sessions/__init__.py
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(os.urandom(length))[length:] def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.app.settings["session_salt"] salted_password = "".join([unicode(password_salt), password]) return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(os.urandom(length))[length:] def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.app.settings["session_salt"] return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
bsd-3-clause
Python
d514558e6f229abbd34392bf34235db8ebf1b0d9
allow local users too
biviosoftware/salt-conf,radiasoft/salt-conf,biviosoftware/salt-conf,radiasoft/salt-conf
srv/salt/jupyterhub/jupyterhub_config.py
srv/salt/jupyterhub/jupyterhub_config.py
c.Authenticator.admin_users = {'{{ pillar.jupyterhub.admin_user }}',} c.JupyterHub.confirm_no_ssl = True c.JupyterHub.ip = '0.0.0.0' c.JupyterHub.cookie_secret_file = '{{ zz.guest_cookie }}' c.JupyterHub.proxy_auth_token = '{{ pillar.jupyterhub.proxy_auth_token }}' # Allow both local and GitHub users; Useful for bootstrap c.JupyterHub.authenticator_class = 'oauthenticator.LocalGitHubOAuthenticator' c.GitHubOAuthenticator.oauth_callback_url = 'https://jupyter.radiasoft.org/hub/oauth_callback' c.GitHubOAuthenticator.client_id = '{{ pillar.jupyterhub.github_client_id }}' c.GitHubOAuthenticator.client_secret = '{{ pillar.jupyterhub.github_client_secret }}'
c.Authenticator.admin_users = {'{{ pillar.jupyterhub.admin_user }}',} c.JupyterHub.confirm_no_ssl = True c.JupyterHub.ip = '0.0.0.0' c.JupyterHub.cookie_secret_file = '{{ zz.guest_cookie }}' c.JupyterHub.proxy_auth_token = '{{ pillar.jupyterhub.proxy_auth_token }}' c.JupyterHub.authenticator_class = 'oauthenticator.GitHubOAuthenticator' c.GitHubOAuthenticator.oauth_callback_url = 'https://jupyter.radiasoft.org/hub/oauth_callback' c.GitHubOAuthenticator.client_id = '{{ pillar.jupyterhub.github_client_id }}' c.GitHubOAuthenticator.client_secret = '{{ pillar.jupyterhub.github_client_secret }}'
apache-2.0
Python
e01c990aa095b28cd72be14917fec4e8e5253729
support specifying custom runner file name
userzimmermann/robotframework-python3,userzimmermann/robotframework-python3,userzimmermann/robotframework-python3,userzimmermann/robotframework-python3,userzimmermann/robotframework-python3
atest/genrunner.py
atest/genrunner.py
#!/usr/bin/env python """Script to generate atest runners based on plain text data files. Usage: %s testdata/path/data.txt [robot/path/runner.txt] """ from os.path import abspath, basename, dirname, exists, join, splitext import os import sys if len(sys.argv) not in [2, 3] or not all(a.endswith('.txt') for a in sys.argv[1:]): print __doc__ % basename(sys.argv[0]) sys.exit(1) INPATH = abspath(sys.argv[1]) if len(sys.argv) == 2: OUTPATH = INPATH.replace(join('atest', 'testdata'), join('atest', 'robot')) else: OUTPATH = sys.argv[2] if not exists(dirname(OUTPATH)): os.mkdir(dirname(OUTPATH)) with open(INPATH) as input: TESTS = [] process = False for line in input.readlines(): line = line.rstrip() if line.startswith('*'): name = line.replace('*', '').replace(' ', '').upper() process = name in ('TESTCASE', 'TESTCASES') elif process and line and line[0] != ' ': TESTS.append(line.split(' ')[0]) with open(OUTPATH, 'wb') as output: path = INPATH.split(join('atest', 'testdata'))[1][1:].replace(os.sep, '/') output.write("""\ *** Settings *** Suite Setup Run Tests ${EMPTY} %(path)s Force Tags regression pybot jybot Resource atest_resource.txt *** Test Cases *** """ % locals()) for test in TESTS: output.write(test + '\n Check Test Case ${TESTNAME}\n') if test is not TESTS[-1]: output.write('\n') print OUTPATH
#!/usr/bin/env python """Script to generate atest runners based on plain text data files. Usage: %s path/to/data.txt """ from __future__ import with_statement from os.path import abspath, basename, dirname, exists, join, splitext import os import sys if len(sys.argv) != 2 or splitext(sys.argv[1])[1] != '.txt': print __doc__ % basename(sys.argv[0]) sys.exit(1) INPATH = abspath(sys.argv[1]) OUTPATH = INPATH.replace(join('atest', 'testdata'), join('atest', 'robot')) if not exists(dirname(OUTPATH)): os.mkdir(dirname(OUTPATH)) with open(INPATH) as input: TESTS = [] process = False for line in input.readlines(): line = line.rstrip() if line.startswith('*'): name = line.replace('*', '').replace(' ', '').upper() process = name in ('TESTCASE', 'TESTCASES') elif process and line and line[0] != ' ': TESTS.append(line.split(' ')[0]) with open(OUTPATH, 'wb') as output: path = INPATH.split(join('atest', 'testdata'))[1][1:].replace(os.sep, '/') output.write("""\ *** Settings *** Suite Setup Run Tests ${EMPTY} %(path)s Force Tags regression pybot jybot Resource atest_resource.txt *** Test Cases *** """ % locals()) for test in TESTS: output.write(test + '\n Check Test Case ${TESTNAME}\n') if test is not TESTS[-1]: output.write('\n') print OUTPATH
apache-2.0
Python
d4a4fd7fd5565276dabd7990721210bf9df6dd42
fix busy cursor nesting
pbmanis/acq4,acq4/acq4,pbmanis/acq4,campagnola/acq4,acq4/acq4,campagnola/acq4,campagnola/acq4,pbmanis/acq4,meganbkratz/acq4,campagnola/acq4,acq4/acq4,meganbkratz/acq4,meganbkratz/acq4,pbmanis/acq4,meganbkratz/acq4,acq4/acq4
pyqtgraph/widgets/BusyCursor.py
pyqtgraph/widgets/BusyCursor.py
from ..Qt import QtGui, QtCore __all__ = ['BusyCursor'] class BusyCursor(object): """Class for displaying a busy mouse cursor during long operations. Usage:: with pyqtgraph.BusyCursor(): doLongOperation() May be nested. """ active = [] def __enter__(self): QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) BusyCursor.active.append(self) def __exit__(self, *args): if self._active: BusyCursor.active.pop(-1) QtGui.QApplication.restoreOverrideCursor()
from ..Qt import QtGui, QtCore __all__ = ['BusyCursor'] class BusyCursor(object): """Class for displaying a busy mouse cursor during long operations. Usage:: with pyqtgraph.BusyCursor(): doLongOperation() May be nested. """ active = [] def __enter__(self): QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) BusyCursor.active.append(self) def __exit__(self, *args): BusyCursor.active.pop(-1) if len(BusyCursor.active) == 0: QtGui.QApplication.restoreOverrideCursor()
mit
Python
3c06788eef9ddfa8cc628c1d7c628073ec7fd50b
Set APK size limit to 5 MB. (#1523)
mozilla-mobile/focus-android,liuche/focus-android,liuche/focus-android,pocmo/focus-android,mozilla-mobile/focus-android,mastizada/focus-android,pocmo/focus-android,liuche/focus-android,ekager/focus-android,Benestar/focus-android,ekager/focus-android,pocmo/focus-android,Benestar/focus-android,mastizada/focus-android,ekager/focus-android,jonalmeida/focus-android,mozilla-mobile/focus-android,mozilla-mobile/focus-android,mastizada/focus-android,Benestar/focus-android,pocmo/focus-android,jonalmeida/focus-android,liuche/focus-android,mozilla-mobile/focus-android,ekager/focus-android,jonalmeida/focus-android,mastizada/focus-android,pocmo/focus-android,Benestar/focus-android,pocmo/focus-android,ekager/focus-android,mozilla-mobile/focus-android,mastizada/focus-android,ekager/focus-android,jonalmeida/focus-android,jonalmeida/focus-android,liuche/focus-android,jonalmeida/focus-android,Benestar/focus-android,liuche/focus-android
tools/metrics/apk_size.py
tools/metrics/apk_size.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Check APK file size for limit from os import path, listdir, stat from sys import exit SIZE_LIMIT = 5242880 PATH = path.join(path.dirname(path.abspath(__file__)), '../../app/build/outputs/apk/') files = [] try: files = [f for f in listdir(PATH) if path.isfile(path.join(PATH, f)) and f.endswith('.apk') and "release" in f] except OSError as e: if e.errno == 2: print("Directory is missing, build apk first!") exit(1) print("Unknown error: {err}".format(err=str(e))) exit(2) for apk_file in files: file_size = stat(path.join(PATH, apk_file)).st_size if file_size > SIZE_LIMIT: print(" * [TOOBIG] {filename} ({filesize} > {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT )) exit(27) print(" * [OKAY] {filename} ({filesize} <= {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT ))
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Check APK file size for limit from os import path, listdir, stat from sys import exit SIZE_LIMIT = 4500000 PATH = path.join(path.dirname(path.abspath(__file__)), '../../app/build/outputs/apk/') files = [] try: files = [f for f in listdir(PATH) if path.isfile(path.join(PATH, f)) and f.endswith('.apk') and "release" in f] except OSError as e: if e.errno == 2: print("Directory is missing, build apk first!") exit(1) print("Unknown error: {err}".format(err=str(e))) exit(2) for apk_file in files: file_size = stat(path.join(PATH, apk_file)).st_size if file_size > SIZE_LIMIT: print(" * [TOOBIG] {filename} ({filesize} > {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT )) exit(27) print(" * [OKAY] {filename} ({filesize} <= {sizelimit})".format( filename=apk_file, filesize=file_size, sizelimit=SIZE_LIMIT ))
mpl-2.0
Python
06e703290640ed6326bf70e172c25be92799591f
Exclude extmod/vfs_fat_fileio.py test.
selste/micropython,chrisdearman/micropython,pfalcon/micropython,dmazzella/micropython,deshipu/micropython,TDAbboud/micropython,dxxb/micropython,SHA2017-badge/micropython-esp32,MrSurly/micropython,tralamazza/micropython,blazewicz/micropython,kerneltask/micropython,henriknelson/micropython,trezor/micropython,Timmenem/micropython,jmarcelino/pycom-micropython,tobbad/micropython,torwag/micropython,adafruit/micropython,cwyark/micropython,adafruit/circuitpython,SHA2017-badge/micropython-esp32,MrSurly/micropython,MrSurly/micropython,toolmacher/micropython,kerneltask/micropython,chrisdearman/micropython,alex-robbins/micropython,PappaPeppar/micropython,chrisdearman/micropython,PappaPeppar/micropython,TDAbboud/micropython,hiway/micropython,Peetz0r/micropython-esp32,AriZuu/micropython,alex-march/micropython,hiway/micropython,matthewelse/micropython,SHA2017-badge/micropython-esp32,MrSurly/micropython-esp32,jmarcelino/pycom-micropython,hiway/micropython,HenrikSolver/micropython,bvernoux/micropython,henriknelson/micropython,hosaka/micropython,selste/micropython,jmarcelino/pycom-micropython,TDAbboud/micropython,cwyark/micropython,alex-robbins/micropython,Peetz0r/micropython-esp32,dxxb/micropython,SHA2017-badge/micropython-esp32,tralamazza/micropython,swegener/micropython,hosaka/micropython,blazewicz/micropython,pramasoul/micropython,MrSurly/micropython,Peetz0r/micropython-esp32,micropython/micropython-esp32,blazewicz/micropython,alex-robbins/micropython,henriknelson/micropython,pfalcon/micropython,puuu/micropython,henriknelson/micropython,PappaPeppar/micropython,toolmacher/micropython,tralamazza/micropython,infinnovation/micropython,dxxb/micropython,deshipu/micropython,tuc-osg/micropython,torwag/micropython,swegener/micropython,torwag/micropython,pramasoul/micropython,adafruit/micropython,selste/micropython,matthewelse/micropython,HenrikSolver/micropython,hosaka/micropython,matthewelse/micropython,oopy/micropython,pfalcon/micropython,blazewicz/micropython,adafruit/circuitpython,ryannathans/micropython,puuu/micropython,infinnovation/micropython,bvernoux/micropython,oopy/micropython,ryannathans/micropython,tobbad/micropython,dmazzella/micropython,AriZuu/micropython,hiway/micropython,HenrikSolver/micropython,tralamazza/micropython,pramasoul/micropython,blazewicz/micropython,adafruit/micropython,pozetroninc/micropython,lowRISC/micropython,hosaka/micropython,micropython/micropython-esp32,TDAbboud/micropython,adafruit/micropython,oopy/micropython,pfalcon/micropython,micropython/micropython-esp32,pfalcon/micropython,hiway/micropython,matthewelse/micropython,tuc-osg/micropython,lowRISC/micropython,pozetroninc/micropython,pozetroninc/micropython,jmarcelino/pycom-micropython,swegener/micropython,mhoffma/micropython,SHA2017-badge/micropython-esp32,bvernoux/micropython,alex-robbins/micropython,swegener/micropython,lowRISC/micropython,matthewelse/micropython,matthewelse/micropython,toolmacher/micropython,adafruit/circuitpython,swegener/micropython,Peetz0r/micropython-esp32,trezor/micropython,tuc-osg/micropython,pramasoul/micropython,kerneltask/micropython,chrisdearman/micropython,infinnovation/micropython,deshipu/micropython,trezor/micropython,tuc-osg/micropython,bvernoux/micropython,kerneltask/micropython,dxxb/micropython,HenrikSolver/micropython,alex-march/micropython,dmazzella/micropython,toolmacher/micropython,MrSurly/micropython-esp32,kerneltask/micropython,ryannathans/micropython,lowRISC/micropython,micropython/micropython-esp32,alex-march/micropython,selste/micropython,oopy/micropython,pozetroninc/micropython,mhoffma/micropython,tobbad/micropython,tobbad/micropython,Timmenem/micropython,puuu/micropython,tobbad/micropython,mhoffma/micropython,oopy/micropython,infinnovation/micropython,AriZuu/micropython,AriZuu/micropython,ryannathans/micropython,selste/micropython,ryannathans/micropython,mhoffma/micropython,alex-march/micropython,tuc-osg/micropython,puuu/micropython,MrSurly/micropython-esp32,deshipu/micropython,lowRISC/micropython,hosaka/micropython,torwag/micropython,infinnovation/micropython,chrisdearman/micropython,alex-march/micropython,cwyark/micropython,Timmenem/micropython,adafruit/circuitpython,trezor/micropython,cwyark/micropython,dmazzella/micropython,MrSurly/micropython,adafruit/circuitpython,pozetroninc/micropython,dxxb/micropython,mhoffma/micropython,Timmenem/micropython,pramasoul/micropython,cwyark/micropython,TDAbboud/micropython,HenrikSolver/micropython,micropython/micropython-esp32,torwag/micropython,alex-robbins/micropython,puuu/micropython,PappaPeppar/micropython,MrSurly/micropython-esp32,toolmacher/micropython,deshipu/micropython,Timmenem/micropython,MrSurly/micropython-esp32,adafruit/micropython,Peetz0r/micropython-esp32,jmarcelino/pycom-micropython,trezor/micropython,AriZuu/micropython,PappaPeppar/micropython,bvernoux/micropython,henriknelson/micropython,adafruit/circuitpython
tools/tinytest-codegen.py
tools/tinytest-codegen.py
#! /usr/bin/env python3 import os, sys from glob import glob from re import sub def escape(s): lookup = { '\0': '\\0', '\t': '\\t', '\n': '\\n\"\n\"', '\r': '\\r', '\\': '\\\\', '\"': '\\\"', } return "\"\"\n\"{}\"".format(''.join([lookup[x] if x in lookup else x for x in s])) def chew_filename(t): return { 'func': "test_{}_fn".format(sub(r'/|\.|-', '_', t)), 'desc': t.split('/')[1] } def script_to_map(t): r = { 'name': chew_filename(t)['func'] } with open(t) as f: r['script'] = escape(''.join(f.readlines())) return r test_function = ( "void {name}(void* data) {{\n" " const char * pystr = {script};\n" " do_str(pystr);\n" "}}" ) testcase_struct = ( "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" ) testcase_member = ( " {{ \"{desc}\", {func}, TT_ENABLED_, 0, 0 }}," ) testgroup_struct = ( "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" ) testgroup_member = ( " {{ \"{name}/\", {name}_tests }}," ) ## XXX: may be we could have `--without <groups>` argument... # currently these tests are selected because they pass on qemu-arm test_dirs = ('basics', 'micropython', 'extmod', 'inlineasm') # 'float', 'import', 'io', 'misc') exclude_tests = ( 'inlineasm/asmfpaddsub.py', 'inlineasm/asmfpcmp.py', 'inlineasm/asmfpldrstr.py', 'inlineasm/asmfpmuldiv.py', 'inlineasm/asmfpsqrt.py', 'extmod/time_ms_us.py', 'extmod/ujson_dumps_float.py', 'extmod/ujson_loads_float.py', 'extmod/uctypes_native_float.py', 'extmod/uctypes_le_float.py', 'extmod/machine_pinbase.py', 'extmod/machine_pulse.py', 'extmod/vfs_fat_ramdisk.py', 'extmod/vfs_fat_fileio.py', ) output = [] for group in test_dirs: tests = [test for test in glob('{}/*.py'.format(group)) if test not in exclude_tests] output.extend([test_function.format(**script_to_map(test)) for test in tests]) testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests] output.append(testcase_struct.format(name=group, body='\n'.join(testcase_members))) testgroup_members = [testgroup_member.format(name=group) for group in test_dirs] output.append(testgroup_struct.format(body='\n'.join(testgroup_members))) ## XXX: may be we could have `--output <filename>` argument... print('\n\n'.join(output))
#! /usr/bin/env python3 import os, sys from glob import glob from re import sub def escape(s): lookup = { '\0': '\\0', '\t': '\\t', '\n': '\\n\"\n\"', '\r': '\\r', '\\': '\\\\', '\"': '\\\"', } return "\"\"\n\"{}\"".format(''.join([lookup[x] if x in lookup else x for x in s])) def chew_filename(t): return { 'func': "test_{}_fn".format(sub(r'/|\.|-', '_', t)), 'desc': t.split('/')[1] } def script_to_map(t): r = { 'name': chew_filename(t)['func'] } with open(t) as f: r['script'] = escape(''.join(f.readlines())) return r test_function = ( "void {name}(void* data) {{\n" " const char * pystr = {script};\n" " do_str(pystr);\n" "}}" ) testcase_struct = ( "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" ) testcase_member = ( " {{ \"{desc}\", {func}, TT_ENABLED_, 0, 0 }}," ) testgroup_struct = ( "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" ) testgroup_member = ( " {{ \"{name}/\", {name}_tests }}," ) ## XXX: may be we could have `--without <groups>` argument... # currently these tests are selected because they pass on qemu-arm test_dirs = ('basics', 'micropython', 'extmod', 'inlineasm') # 'float', 'import', 'io', 'misc') exclude_tests = ( 'inlineasm/asmfpaddsub.py', 'inlineasm/asmfpcmp.py', 'inlineasm/asmfpldrstr.py', 'inlineasm/asmfpmuldiv.py', 'inlineasm/asmfpsqrt.py', 'extmod/time_ms_us.py', 'extmod/ujson_dumps_float.py', 'extmod/ujson_loads_float.py', 'extmod/uctypes_native_float.py', 'extmod/uctypes_le_float.py', 'extmod/machine_pinbase.py', 'extmod/machine_pulse.py', 'extmod/vfs_fat_ramdisk.py', ) output = [] for group in test_dirs: tests = [test for test in glob('{}/*.py'.format(group)) if test not in exclude_tests] output.extend([test_function.format(**script_to_map(test)) for test in tests]) testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests] output.append(testcase_struct.format(name=group, body='\n'.join(testcase_members))) testgroup_members = [testgroup_member.format(name=group) for group in test_dirs] output.append(testgroup_struct.format(body='\n'.join(testgroup_members))) ## XXX: may be we could have `--output <filename>` argument... print('\n\n'.join(output))
mit
Python
19c97e2d109a0ceaaf2a7ed38a16d621e9b7535d
Fix help print for modules.
S2R2/viper,cwtaylor/viper,kevthehermit/viper,Beercow/viper,MeteorAdminz/viper,cwtaylor/viper,kevthehermit/viper,Beercow/viper,MeteorAdminz/viper,S2R2/viper,Beercow/viper
viper/common/abstracts.py
viper/common/abstracts.py
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message = message.strip() + '\n' self.level = level.strip() def __str__(self): return '{}: {}'.format(self.level, self.message) def get(self): return self.level, self.message class ArgumentParser(argparse.ArgumentParser): def print_usage(self): raise ArgumentErrorCallback(self.format_usage()) def print_help(self): raise ArgumentErrorCallback(self.format_help()) def error(self, message): raise ArgumentErrorCallback(message, 'error') def exit(self, status, message=None): if message is not None: raise ArgumentErrorCallback(message) class Module(object): cmd = '' description = '' command_line = [] args = None authors = [] output = [] def __init__(self): self.parser = ArgumentParser(prog=self.cmd, description=self.description) def set_commandline(self, command): self.command_line = command def log(self, event_type, event_data): self.output.append(dict( type=event_type, data=event_data )) if event_type == 'table': print(out.table(event_data['header'], event_data['rows'])) elif event_type: getattr(out, 'print_{0}'.format(event_type))(event_data) else: print(event_data) def usage(self): self.log('', self.parser.format_usage()) def help(self): self.log('', self.parser.format_help()) def run(self): try: self.args = self.parser.parse_args(self.command_line) except ArgumentErrorCallback as e: self.log(*e.get())
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message = message.strip() + '\n' self.level = level.strip() def __str__(self): return '{}: {}'.format(self.level, self.message) def get(self): return self.level, self.message class ArgumentParser(argparse.ArgumentParser): def print_usage(self): raise ArgumentErrorCallback(self.format_usage()) def print_help(self): raise ArgumentErrorCallback(self.format_help()) def error(self, message): raise ArgumentErrorCallback(message, 'error') def exit(self, status, message=None): if message is not None: raise ArgumentErrorCallback(message) class Module(object): cmd = '' description = '' command_line = [] args = None authors = [] output = [] def __init__(self): self.parser = ArgumentParser(prog=self.cmd, description=self.description) def set_commandline(self, command): self.command_line = command def log(self, event_type, event_data): self.output.append(dict( type=event_type, data=event_data )) if event_type == 'table': print out.table(event_data['header'], event_data['rows']) else: getattr(out, 'print_{0}'.format(event_type))(event_data) def usage(self): self.log('', self.parser.format_usage()) def help(self): self.log('', self.parser.format_help()) def run(self): try: self.args = self.parser.parse_args(self.command_line) except ArgumentErrorCallback as e: self.log(*e.get())
bsd-3-clause
Python
5516fdee86fe0ffcd34381985ebe798f9fbda1af
Fix incorrect check for `self.log`
h01ger/voctomix,h01ger/voctomix,voc/voctomix,voc/voctomix
voctogui/lib/uibuilder.py
voctogui/lib/uibuilder.py
import gi import logging from gi.repository import Gtk, Gst class UiBuilder(object): def __init__(self, uifile): if not hasattr(self, 'log'): self.log = logging.getLogger('UiBuilder') self.uifile = uifile self.builder = Gtk.Builder() self.builder.add_from_file(self.uifile) def find_widget_recursive(self, widget, name): widget = self._find_widget_recursive(widget, name) if not widget: self.log.error( 'could find required widget "%s" by ID inside the parent %s', name, str(widget) ) raise Exception('Widget not found in parent') return widget def _find_widget_recursive(self, widget, name): if Gtk.Buildable.get_name(widget) == name: return widget if hasattr(widget, 'get_children'): for child in widget.get_children(): widget = self._find_widget_recursive(child, name) if widget: return widget return None def get_check_widget(self, widget_id, clone=False): if clone: builder = Gtk.Builder() builder.add_from_file(self.uifile) else: builder = self.builder self.log.debug('loading widget "%s" from the .ui-File', widget_id) widget = builder.get_object(widget_id) if not widget: self.log.error( 'could not load required widget "%s" from the .ui-File', widget_id ) raise Exception('Widget not found in .ui-File') return widget
import gi import logging from gi.repository import Gtk, Gst class UiBuilder(object): def __init__(self, uifile): if not self.log: self.log = logging.getLogger('UiBuilder') self.uifile = uifile self.builder = Gtk.Builder() self.builder.add_from_file(self.uifile) def find_widget_recursive(self, widget, name): widget = self._find_widget_recursive(widget, name) if not widget: self.log.error( 'could find required widget "%s" by ID inside the parent %s', name, str(widget) ) raise Exception('Widget not found in parent') return widget def _find_widget_recursive(self, widget, name): if Gtk.Buildable.get_name(widget) == name: return widget if hasattr(widget, 'get_children'): for child in widget.get_children(): widget = self._find_widget_recursive(child, name) if widget: return widget return None def get_check_widget(self, widget_id, clone=False): if clone: builder = Gtk.Builder() builder.add_from_file(self.uifile) else: builder = self.builder self.log.debug('loading widget "%s" from the .ui-File', widget_id) widget = builder.get_object(widget_id) if not widget: self.log.error( 'could not load required widget "%s" from the .ui-File', widget_id ) raise Exception('Widget not found in .ui-File') return widget
mit
Python
aaab0505fe1547a01a096d5612597f74f9534b29
Send credentials only when they are provided
citrix-openstack-build/python-saharaclient,citrix-openstack-build/python-saharaclient,openstack/python-saharaclient,citrix-openstack-build/python-saharaclient
savannaclient/api/data_sources.py
savannaclient/api/data_sources.py
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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 savannaclient.api import base class DataSources(base.Resource): resource_name = 'DataSource' class DataSourceManager(base.ResourceManager): resource_class = DataSources def create(self, name, description, data_source_type, url, credential_user=None, credential_pass=None): data = { 'name': name, 'description': description, 'type': data_source_type, 'url': url, 'credentials': {} } self._copy_if_defined(data['credentials'], user=credential_user, password=credential_pass) return self._create('/data-sources', data, 'data_source') def list(self): return self._list('/data-sources', 'data_sources') def get(self, data_source_id): return self._get('/data-sources/%s' % data_source_id, 'data_source') def delete(self, data_source_id): self._delete('/data-sources/%s' % data_source_id)
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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 savannaclient.api import base class DataSources(base.Resource): resource_name = 'DataSource' class DataSourceManager(base.ResourceManager): resource_class = DataSources def create(self, name, description, data_source_type, url, credential_user, credential_pass): data = { 'name': name, 'description': description, 'type': data_source_type, 'url': url, 'credentials': {'user': credential_user, 'password': credential_pass} } return self._create('/data-sources', data, 'data_source') def list(self): return self._list('/data-sources', 'data_sources') def get(self, data_source_id): return self._get('/data-sources/%s' % data_source_id, 'data_source') def delete(self, data_source_id): self._delete('/data-sources/%s' % data_source_id)
apache-2.0
Python
b1eafae0b56abc652f884cec78a885669ab78986
Update class name
jalama/drupdates
drupdates/tests/behavioral/test_multiple_working_directories_multiple_sites.py
drupdates/tests/behavioral/test_multiple_working_directories_multiple_sites.py
""" Test running Drupdates on multiple repos, multiple working Directories. """ """ note: The second working directory will have it's own settings file. """ from drupdates.tests.behavioral.behavioral_utils import BehavioralUtils from drupdates.tests import Setup class TestMultipleWorkingDirectoriesOneCustomSettings(object): """ Test multiple repos, multiple working directories. """ @classmethod def setup_class(cls): """ Setup test class. """ utils = BehavioralUtils() utils.build(__file__) def __init__(self): base = Setup() self.test_directory = base.test_dir @staticmethod def test_repo_built(): """ Test to ensure both repos built successfully. """ count = BehavioralUtils.count_repos_updated('builds') # If 1 repo Siteupdates in report repo built successfully in builds dir. assert count == 1 @staticmethod def test_second_repo_built(): """ Test to ensure both repos built successfully. """ count = BehavioralUtils.count_repos_updated('builds/test') # If 1 repo Siteupdates in report repo built successfully in builds/test. assert count == 1 @staticmethod def test_frst_repo_updated(): """ Test to ensure the repo was updated. """ status = "The following updates were applied" report_status = BehavioralUtils.check_repo_updated('drupal', 'builds') assert report_status == status @staticmethod def test_second_repo_updated(): """ Test to ensure the second repo was updated. """ status = "The following updates were applied" report_status = BehavioralUtils.check_repo_updated('dmake', 'builds/test') assert report_status == status
""" Test running Drupdates on multiple repos, multiple working Directories. """ """ note: The second working directory will have it's own settings file. """ from drupdates.tests.behavioral.behavioral_utils import BehavioralUtils from drupdates.tests import Setup class TestMultipleWorkingDirectoriesMultipleSites(object): """ Test multiple repos, multiple working directories. """ @classmethod def setup_class(cls): """ Setup test class. """ utils = BehavioralUtils() utils.build(__file__) def __init__(self): base = Setup() self.test_directory = base.test_dir @staticmethod def test_repo_built(): """ Test to ensure both repos built successfully. """ count = BehavioralUtils.count_repos_updated('builds') # If 1 repo Siteupdates in report repo built successfully in builds dir. assert count == 1 @staticmethod def test_second_repo_built(): """ Test to ensure both repos built successfully. """ count = BehavioralUtils.count_repos_updated('builds/test') # If 1 repo Siteupdates in report repo built successfully in builds/test. assert count == 1 @staticmethod def test_frst_repo_updated(): """ Test to ensure the repo was updated. """ status = "The following updates were applied" report_status = BehavioralUtils.check_repo_updated('drupal', 'builds') assert report_status == status @staticmethod def test_second_repo_updated(): """ Test to ensure the second repo was updated. """ status = "The following updates were applied" report_status = BehavioralUtils.check_repo_updated('dmake', 'builds/test') assert report_status == status
mit
Python
780b25b724991ccfca20f649d0e4902cb94c4885
Use static JSONEncoders (#7)
matrix-org/python-canonicaljson
canonicaljson.py
canonicaljson.py
# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # Copyright 2018 New Vector Ltd # # 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. # using simplejson rather than regular json gives approximately a 25% # performance improvement (as measured on python 2.7.12/simplejson 3.13.2) import simplejson as json from frozendict import frozendict __version__ = '1.0.0' def _default(obj): if type(obj) is frozendict: return dict(obj) raise TypeError('Object of type %s is not JSON serializable' % obj.__class__.__name__) _canonical_encoder = json.JSONEncoder( ensure_ascii=False, separators=(',', ':'), sort_keys=True, default=_default, ) _pretty_encoder = json.JSONEncoder( ensure_ascii=True, indent=4, sort_keys=True, default=_default, ) def encode_canonical_json(json_object): """Encodes the shortest UTF-8 JSON encoding with dictionary keys lexicographically sorted by unicode code point. Args: json_object (dict): The JSON object to encode. Returns: bytes encoding the JSON object""" s = _canonical_encoder.encode(json_object) return s.encode("UTF-8") def encode_pretty_printed_json(json_object): """Encodes the JSON object dict as human readable ascii bytes.""" return _pretty_encoder.encode(json_object).encode("ascii")
# -*- coding: utf-8 -*- # Copyright 2014 OpenMarket Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import simplejson as json from frozendict import frozendict __version__ = '1.0.0' def encode_canonical_json(json_object): """Encodes the shortest UTF-8 JSON encoding with dictionary keys lexicographically sorted by unicode code point. Args: json_object (dict): The JSON object to encode. Returns: bytes encoding the JSON object""" return json.dumps( json_object, ensure_ascii=False, separators=(',', ':'), sort_keys=True, cls=FrozenEncoder ).encode("UTF-8") def encode_pretty_printed_json(json_object): """Encodes the JSON object dict as human readable ascii bytes.""" return json.dumps( json_object, ensure_ascii=True, indent=4, sort_keys=True, cls=FrozenEncoder ).encode("ascii") class FrozenEncoder(json.JSONEncoder): def default(self, obj): if type(obj) is frozendict: return dict(obj) return json.JSONEncoder.default(self, obj)
apache-2.0
Python
442f21bfde16f72d4480fa7fd9dea2eac741a857
Include analysis detail view URL in message
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
src/analyses/views.py
src/analyses/views.py
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _( 'You just created a %(analysis_type)s analysis! ' 'View its detail <a href="%(analysis_detail_url)s">here</a>.' ) % { 'analysis_type': self.analysis_type, 'analysis_detail_url': self.object.get_absolute_url(), }, extra_tags='safe', ) return response
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _('You just created a %(analysis_type)s analysis!') % { 'analysis_type': self.analysis_type } ) return response
mit
Python
9283c745e510add1748c579020e87fa18459ee6f
Fix (hide) blacklist integrity error
tyler274/Recruitment-App,tyler274/Recruitment-App,tyler274/Recruitment-App
recruit_app/blacklist/models.py
recruit_app/blacklist/models.py
# -*- coding: utf-8 -*- from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from flask import current_app import requests import datetime as dt class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] name = Column(db.Unicode, nullable=True) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) ip_address = Column(db.Unicode) creator_id = ReferenceCol('users', nullable=True) creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') def __repr__(self): return '<' + self.name + ': ' + self.notes + '>' # A cache table and wrapper for the GSF blacklist class BlacklistGSF(TimeMixin, Model): __tablename__ = 'blacklist_gsf' status = Column(db.Unicode) character_id = ReferenceCol('characters', pk_name='character_id', primary_key=True) character = relationship('EveCharacter', foreign_keys=[character_id], backref='blacklist_gsf') @staticmethod def getStatus(character): try: entry = BlacklistGSF.query.filter_by(character_id=character.character_id).one() except: # No entry, create a new one entry = BlacklistGSF() entry.character_id = character.character_id entry.status = u'UNKNOWN' if entry.last_update_time is None or (dt.datetime.utcnow() - entry.last_update_time).total_seconds() > 86400: # 1 day cache try: url = current_app.config['GSF_BLACKLIST_URL'] + character.character_name r = requests.post(url) entry.status = str(r.json()[0]['output']) entry.last_update_time = dt.datetime.utcnow() except: # Will except on NONE for URL or connection issues. Just keep status as UNKNOWN pass try: entry.save() except: # It's possible that multiple people are viewing the same new app at the same time, causing multiple threads to make the same cache object, # which throws an IntegrityError. In that case just ignore the error, this is just a cache anyway. pass return entry.status def __repr__(self): return '<BlacklistCacheEntry' + ': ' + self.character_id + '>'
# -*- coding: utf-8 -*- from recruit_app.database import Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin from flask import current_app import requests import datetime as dt class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' # __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes', 'ip_address'] name = Column(db.Unicode, nullable=True) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) ip_address = Column(db.Unicode) creator_id = ReferenceCol('users', nullable=True) creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') def __repr__(self): return '<' + self.name + ': ' + self.notes + '>' # A cache table and wrapper for the GSF blacklist class BlacklistGSF(TimeMixin, Model): __tablename__ = 'blacklist_gsf' status = Column(db.Unicode) character_id = ReferenceCol('characters', pk_name='character_id', primary_key=True) character = relationship('EveCharacter', foreign_keys=[character_id], backref='blacklist_gsf') @staticmethod def getStatus(character): try: entry = BlacklistGSF.query.filter_by(character_id=character.character_id).one() except: # No entry, create a new one entry = BlacklistGSF() entry.character_id = character.character_id entry.status = u'UNKNOWN' if entry.last_update_time is None or (dt.datetime.utcnow() - entry.last_update_time).total_seconds() > 86400: # 1 day cache try: url = current_app.config['GSF_BLACKLIST_URL'] + character.character_name r = requests.post(url) entry.status = str(r.json()[0]['output']) entry.last_update_time = dt.datetime.utcnow() except: # Will except on NONE for URL or connection issues. Just keep status as UNKNOWN pass entry.save() return entry.status def __repr__(self): return '<BlacklistCacheEntry' + ': ' + self.character_id + '>'
bsd-3-clause
Python
6356cc557e392d3d28886e2d930aa7faa8bb0ac7
switch to repr
tyler274/Recruitment-App,tyler274/Recruitment-App,tyler274/Recruitment-App
recruit_app/blacklist/models.py
recruit_app/blacklist/models.py
# -*- coding: utf-8 -*- from recruit_app.extensions import bcrypt from recruit_app.database import ( Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin, ) import flask_whooshalchemy as whooshalchemy from sqlalchemy_searchable import make_searchable from sqlalchemy_utils.types import TSVectorType, ScalarListType from sqlalchemy_searchable import SearchQueryMixin from flask_sqlalchemy import BaseQuery from sqlalchemy.dialects import postgresql make_searchable() class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes'] name = Column(db.Unicode, nullable=False) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) creator_id = ReferenceCol('users', nullable=True) creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') def __repr__(self): return '<' + self.name + '>' # @property # def creator_name(self): # return self.creator.auth_info[0].main_character.character_name
# -*- coding: utf-8 -*- from recruit_app.extensions import bcrypt from recruit_app.database import ( Column, db, Model, ReferenceCol, relationship, SurrogatePK, TimeMixin, ) import flask_whooshalchemy as whooshalchemy from sqlalchemy_searchable import make_searchable from sqlalchemy_utils.types import TSVectorType, ScalarListType from sqlalchemy_searchable import SearchQueryMixin from flask_sqlalchemy import BaseQuery from sqlalchemy.dialects import postgresql make_searchable() class BlacklistCharacter(SurrogatePK, TimeMixin, Model): __tablename__ = 'blacklist_character' __searchable__ = ['name', 'main_name', 'corporation', 'alliance', 'notes'] name = Column(db.Unicode, nullable=False) main_name = Column(db.Unicode, nullable=True) corporation = Column(db.Unicode) alliance = Column(db.Unicode) notes = Column(db.Unicode) creator_id = ReferenceCol('users', nullable=True) creator = relationship('User', foreign_keys=[creator_id], backref='blacklist_character_entries') def __str__(self): return '<' + self.name + '>' # @property # def creator_name(self): # return self.creator.auth_info[0].main_character.character_name
bsd-3-clause
Python
d07530e309936f686c0d05eb9df257e5c89e16c7
Update submission
davidgasquez/kaggle-airbnb
scripts/one_vs_rest_classifier.py
scripts/one_vs_rest_classifier.py
#!/usr/bin/env python import pandas as pd import numpy as np import datetime from sklearn.preprocessing import LabelEncoder from sklearn.multiclass import OneVsRestClassifier from xgboost.sklearn import XGBClassifier def generate_submission(y_pred, test_users_ids, label_encoder): ids = [] cts = [] for i in range(len(test_users_ids)): idx = test_users_ids[i] ids += [idx] * 5 sorted_countries = np.argsort(y_pred[i])[::-1] cts += label_encoder.inverse_transform(sorted_countries)[:5].tolist() sub = pd.DataFrame(np.column_stack((ids, cts)), columns=['id', 'country']) return sub def main(): path = '../datasets/processed/' train_users = pd.read_csv(path + 'train_users.csv') test_users = pd.read_csv(path + 'test_users.csv') y_train = train_users['country_destination'] train_users.drop('country_destination', axis=1, inplace=True) train_users.drop('id', axis=1, inplace=True) x_train = train_users.values test_users_ids = test_users['id'] test_users.drop('id', axis=1, inplace=True) x_test = test_users.values label_encoder = LabelEncoder() encoded_y_train = label_encoder.fit_transform(y_train) xgb = XGBClassifier( max_depth=6, learning_rate=0.2, n_estimators=45, gamma=0, min_child_weight=1, max_delta_step=0, subsample=0.6, colsample_bytree=0.6, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, seed=42 ) one_vs_rest = OneVsRestClassifier(xgb, n_jobs=-1) one_vs_rest.fit(x_train, encoded_y_train) print 'Train score:', one_vs_rest.score(x_train, encoded_y_train) y_pred = one_vs_rest.predict_proba(x_test) submission = generate_submission(y_pred, test_users_ids, label_encoder) date = datetime.datetime.now().strftime("%m-%d-%H:%M:%S") name = __file__.split('.')[0] + '_' + str(date) + '.csv' submission.to_csv('../datasets/submissions/' + name, index=False) if __name__ == '__main__': main()
#!/usr/bin/env python import pandas as pd import numpy as np import datetime from sklearn.preprocessing import LabelEncoder from sklearn.multiclass import OneVsRestClassifier from xgboost.sklearn import XGBClassifier def generate_submission(y_pred, test_users_ids, label_encoder): ids = [] cts = [] for i in range(len(test_users_ids)): idx = test_users_ids[i] ids += [idx] * 5 sorted_countries = np.argsort(y_pred[i])[::-1] cts += label_encoder.inverse_transform(sorted_countries)[:5].tolist() sub = pd.DataFrame(np.column_stack((ids, cts)), columns=['id', 'country']) return sub def main(): path = '../datasets/processed/' train_users = pd.read_csv(path + 'processed_train_users.csv') test_users = pd.read_csv(path + 'processed_test_users.csv') y_train = train_users['country_destination'] train_users.drop('country_destination', axis=1, inplace=True) train_users.drop('id', axis=1, inplace=True) x_train = train_users.values test_users_ids = test_users['id'] test_users.drop('id', axis=1, inplace=True) x_test = test_users.values label_encoder = LabelEncoder() encoded_y_train = label_encoder.fit_transform(y_train) xgb = XGBClassifier( max_depth=6, learning_rate=0.2, n_estimators=45, gamma=0, min_child_weight=1, max_delta_step=0, subsample=0.6, colsample_bytree=0.6, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, seed=42 ) one_vs_rest = OneVsRestClassifier(xgb, n_jobs=-1) one_vs_rest.fit(x_train, encoded_y_train) print 'Train score:', one_vs_rest.score(x_train, encoded_y_train) y_pred = one_vs_rest.predict_proba(x_test) submission = generate_submission(y_pred, test_users_ids, label_encoder) date = datetime.datetime.now().strftime("%m-%d_%H:%M") name = __file__ + '_' + str(date) + '.csv' submission.to_csv(name, index=False) if __name__ == '__main__': main()
mit
Python
2bc95d90db15160f9c4869c03f9dadb6cd8d56fa
Add another proxy server example string
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "example2": "158.69.138.8:1080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
mit
Python
c0d3922b38a12e9de4bbca0935b7089e8156cf5c
Update three-words.py
Pouf/CodingCompetition,Pouf/CodingCompetition
CheckiO/three-words.py
CheckiO/three-words.py
def checkio(words): return '111' in ''.join('1' if w.isalpha() else '0' for w in words.split()) # alt from re import findall, I def checkio(words): return bool(findall('([a-z]+ +){2,}[a-z]+', words, flags=I))
def checkio(words): return '111' in ''.join('1' if w.isalpha() else '0' for w in words.split())
mit
Python
a54ebe90f03406ab5c5587d9d63b01c5d9890863
Update A.py
Pouf/CodingCompetition,Pouf/CodingCompetition
Google-Code-Jam/2016-1B/A.py
Google-Code-Jam/2016-1B/A.py
import os import sys script = __file__ script_path = os.path.dirname(script) script_file = os.path.basename(script)[0] files = [f for f in os.listdir(script_path) if script_file in f and '.in' in f] if '{}-large'.format(script_file) in str(files): size = 'large' elif '{}-small'.format(script_file) in str(files): size = 'small' elif '{}-test'.format(script_file) in str(files): size = 'test' else: print('{}-test not found'.format(script_file)) sys.exit() latest = sorted(f for f in files if size in f)[-1][:-3] f = '{}/{}'.format(script_path, latest) i = open(f + '.in', 'r') o = open(f + '.out', 'w') print(f) T = int(i.readline()) # https://code.google.com/codejam/contest/11254486/dashboard # Problem A. Getting the Digits for x in range(T): y = '' S = i.readline().rstrip() def gotcha(s, num): for l in num: s = s.replace(l, '', 1) return s, str(["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"].index(num)) while 'Z' in S: S, z = gotcha(S, 'ZERO') y += z while 'W' in S: S, z = gotcha(S, 'TWO') y += z while 'U' in S: S, z = gotcha(S, 'FOUR') y += z while 'X' in S: S, z = gotcha(S, 'SIX') y += z while 'G' in S: S, z = gotcha(S, 'EIGHT') y += z while 'F' in S: S, z = gotcha(S, 'FIVE') y += z while 'H' in S: S, z = gotcha(S, 'THREE') y += z while 'O' in S: S, z = gotcha(S, 'ONE') y += z while 'S' in S: S, z = gotcha(S, 'SEVEN') y += z while 'I' in S: S, z = gotcha(S, 'NINE') y += z y = ''.join(sorted(y)) o.write('{}Case #{}: {}'.format(['', '\n'][x > 0], x + 1, y)) i.close() o.close()
import os import sys script = __file__ scriptPath = os.path.dirname(script) scriptFile = os.path.basename(script)[0] files = [f for f in os.listdir(scriptPath) if scriptFile in f and '.in' in f] if '{}-large'.format(scriptFile) in str(files): size = 'large' elif '{}-small'.format(scriptFile) in str(files): size = 'small' elif '{}-test'.format(scriptFile) in str(files): size = 'test' else: print('{}-test not found'.format(scriptFile)) sys.exit() latest = sorted(f for f in files if size in f)[-1][:-3] f = '{}/{}'.format(scriptPath, latest) i = open(f + '.in', 'r') o = open(f + '.out', 'w') print(f) T = int(i.readline()) # https://code.google.com/codejam/contest/11254486/dashboard # Problem A. Getting the Digits for x in range(T): y = '' S = i.readline().rstrip() def gotcha(s, num): for l in num: s = s.replace(l, '', 1) return s, str(["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"].index(num)) while 'Z' in S: S, z = gotcha(S, 'ZERO') y += z while 'W' in S: S, z = gotcha(S, 'TWO') y += z while 'U' in S: S, z = gotcha(S, 'FOUR') y += z while 'X' in S: S, z = gotcha(S, 'SIX') y += z while 'G' in S: S, z = gotcha(S, 'EIGHT') y += z while 'F' in S: S, z = gotcha(S, 'FIVE') y += z while 'H' in S: S, z = gotcha(S, 'THREE') y += z while 'O' in S: S, z = gotcha(S, 'ONE') y += z while 'S' in S: S, z = gotcha(S, 'SEVEN') y += z while 'I' in S: S, z = gotcha(S, 'NINE') y += z y = ''.join(sorted(y)) o.write('{}Case #{}: {}'.format(['', '\n'][x > 0], x + 1, y)) i.close() o.close()
mit
Python
f825f2378f9546bb415282635955e31075a1405e
remove print statements
jdodds/feather
feather/dispatcher.py
feather/dispatcher.py
from collections import defaultdict from multiprocessing import Queue class Dispatcher(object): """Recieve messages from Plugins and send them to the Plugins that listen for them. """ def __init__(self): """Create our set of listeners, communication Queue, and empty set of plugins. """ self.listeners = defaultdict(set) self.plugins = set() self.messages = Queue() def register(self, plugin): """Add the plugin to our set of listeners for each message that it listens to, tell it to use our messages Queue for communication, and start it up. """ for listener in plugin.listeners: self.listeners[listener].add(plugin) self.plugins.add(plugin) plugin.set_messenger(self.messages) plugin.start() def start(self): """Send 'APP_START' to any plugins that listen for it, and loop around waiting for messages and sending them to their listening plugins until it's time to shutdown. """ self.recieve('APP_START') self.alive = True while self.alive: message, payload = self.messages.get() if message == 'APP_STOP': for plugin in self.plugins: plugin.recieve('SHUTDOWN') self.alive = False else: self.recieve(message, payload) def recieve(self, message, payload=None): for listener in self.listeners[message]: listener.recieve(message, payload)
from collections import defaultdict from multiprocessing import Queue class Dispatcher(object): """Recieve messages from Plugins and send them to the Plugins that listen for them. """ def __init__(self): """Create our set of listeners, communication Queue, and empty set of plugins. """ self.listeners = defaultdict(set) self.plugins = set() self.messages = Queue() def register(self, plugin): """Add the plugin to our set of listeners for each message that it listens to, tell it to use our messages Queue for communication, and start it up. """ for listener in plugin.listeners: self.listeners[listener].add(plugin) self.plugins.add(plugin) plugin.set_messenger(self.messages) plugin.start() def start(self): """Send 'APP_START' to any plugins that listen for it, and loop around waiting for messages and sending them to their listening plugins until it's time to shutdown. """ self.recieve('APP_START') self.alive = True while self.alive: message, payload = self.messages.get() if message == 'APP_STOP': for plugin in self.plugins: print 'shutting down %s' % plugin plugin.recieve('SHUTDOWN') self.alive = False else: self.recieve(message, payload) def recieve(self, message, payload=None): print 'got %s %s' % (message, payload) print 'have %d listeners to send to' % len(self.listeners[message]) for listener in self.listeners[message]: print 'sending to %s' % listener listener.recieve(message, payload)
bsd-3-clause
Python
e2af3ff1f28db11ee05e471a6f14f5a04244a69a
bump to next dev version
ocefpaf/ulmo,nathanhilbert/ulmo,cameronbracken/ulmo,nathanhilbert/ulmo,cameronbracken/ulmo,ocefpaf/ulmo
ulmo/version.py
ulmo/version.py
# set version number __version__ = '0.7.2-dev'
# set version number __version__ = '0.7.1'
bsd-3-clause
Python
34256a3a7a5e56e6ebf74fa86861a176d6bf02cd
Update hsi_evaluate.py
JiJingYu/tensorflow-exercise
HSI_evaluate/hsi_evaluate.py
HSI_evaluate/hsi_evaluate.py
import numpy as np from numpy.linalg import norm from skimage.measure import compare_psnr, compare_ssim, compare_mse def psnr(x_true, x_pred): """ :param x_true: 高光谱图像:格式:(H, W, C) :param x_pred: 高光谱图像:格式:(H, W, C) :return: 计算原始高光谱数据与重构高光谱数据的均方误差 References ---------- .. [1] https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio """ n_bands = x_true.shape[2] p = [compare_psnr(x_true[:, :, k], x_pred[:, :, k], dynamic_range=np.max(x_true[:, :, k])) for k in range(n_bands)] return np.mean(p) def sam(x_true, x_pred): """ :param x_true: 高光谱图像:格式:(H, W, C) :param x_pred: 高光谱图像:格式:(H, W, C) :return: 计算原始高光谱数据与重构高光谱数据的光谱角相似度 """ assert x_true.ndim ==3 and x_true.shape == x_pred.shape sam_rad = np.zeros(x_pred.shape[0, 1]) for x in range(x_true.shape[0]): for y in range(x_true.shape[1]): tmp_pred = x_pred[x, y].ravel() tmp_true = x_true[x, y].ravel() sam_rad[x, y] = np.arccos(tmp_pred / (norm(tmp_pred) * tmp_true / norm(tmp_true))) sam_deg = sam_rad.mean() * 180 / np.pi return sam_deg def ssim(x_true,x_pred): """ :param x_true: 高光谱图像:格式:(H, W, C) :param x_pred: 高光谱图像:格式:(H, W, C) :return: 计算原始高光谱数据与重构高光谱数据的结构相似度 """ SSIM = compare_ssim(X=x_true, Y=x_pred, multichannel=True) return SSIM
import numpy as np from numpy.linalg import norm from skimage.measure import compare_psnr, compare_ssim, compare_mse def psnr(x_true, x_pred): """ :param x_true: :param x_pred: :return: References ---------- .. [1] https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio """ n_bands = x_true.shape[2] p = [compare_psnr(x_true[:, :, k], x_pred[:, :, k], dynamic_range=np.max(x_true[:, :, k])) for k in range(n_bands)] return np.mean(p) def sam(x_true, x_pred): """ :param x_true: 高光谱图像:格式:(H, W, C) :param x_pred: 高光谱图像:格式:(H, W, C) :return: 计算原始高光谱数据与重构高光谱数据之间的光谱角相似度 """ assert x_true.ndim ==3 and x_true.shape == x_pred.shape sam_rad = np.zeros(x_pred.shape[0, 1]) for x in range(x_true.shape[0]): for y in range(x_true.shape[1]): tmp_pred = x_pred[x, y].ravel() tmp_true = x_true[x, y].ravel() sam_rad[x, y] = np.arccos(tmp_pred / (norm(tmp_pred) * tmp_true / norm(tmp_true))) sam_deg = sam_rad.mean() * 180 / np.pi return sam_deg def ssim(x_true,x_pred): """ :param x_true: 高光谱图像:格式:(H, W, C) :param x_pred: 高光谱图像:格式:(H, W, C) :return: 计算原始高光谱数据与重构高光谱数据之间的结构相似度 """ SSIM = compare_ssim(X=x_true, Y=x_pred, multichannel=True) return SSIM
apache-2.0
Python
12e68786488daf1a1d60681ed9800f9951cdd618
Create handler object, add write functionality
SentientCNC/Sentient-CNC
store_data.py
store_data.py
from google.cloud import datastore import datetime class data_handler(): """ Object designed to handle storage of incoming sensor data. Args: project_id: string Project ID per Google Cloud's project ID (see Cloud Console) sensor_node: string Identifier for sensor gateway. This is used as a primary key for storing data entries (so data can be viewed per device) """ def __init__(self, project_id='sentientcnc-1', sensor_node='CNCmill_001'): # Creates an authorized service object to make authenticated # requests to Google Cloud API using the API's client libraries. self.client = datastore.Client(project_id) self.device = self.client.key(sensor_node) def write(self, sensor_data, timestamp=None): """ writes the sensor data to the cloud storage Args: sensor_data: dict dictionary of sensor nodes as keys and data as parameters timestamp: string timestamp of when the data was recorded """ # Create key for timestamp if not timestamp: data_snapshot = self.client.key(self.sensor_node, datetime.datetime) else: data_snapshot = self.client.key(self.sensor_node, timestamp) entry = datastore.Entity(data_snapshot) entry.update(sensor_data) client.put(entry) with client.transaction(): def add_task(client, description): key = client.key('Task') task = datastore.entity(key, exclude_from_indexes=['description']) task.update({ 'created': datetime.datetime.utcnow(), 'description': description, 'done': False }) client.put(task return task.key def mark_done(client, task_id): with client.transaction(): key = client.key('Task', task_id) task = client.get(key) if not task: raise ValueError( 'Task {} does not exist'.format(task_id)) task['done'] = True client.put(task) def delete_task(client, task_id): ''' deletes a task entity, using the task entity's key ''' key = client.key('Task', task_id) client.delete(key) def list_tasks(client): query = client.query(kind='Task') query.order = ['created'] return list(query.fetch())
from google.cloud import datastore import datetime class data_writer(): def __init__(self, project_id='sentientcnc-1'): self.project = datastore.Client(project_id) pass def create_client(project_id): ''' Creates an authorized service object to make authenticated requests to Google Cloud API using the API's client libraries input: Google Cloud project ID output: client object ''' return datastore.Client(project_id) def add_task(client, description): key = client.key('Task') task = datastore.Entity(key, exclude_from_indexes=['description']) task.update({ 'created': datetime.datetime.utcnow(), 'description': description, 'done': False }) client.put(task) return task.key def mark_done(client, task_id): with client.transaction(): key = client.key('Task', task_id) task = client.get(key) if not task: raise ValueError( 'Task {} does not exist'.format(task_id)) task['done'] = True client.put(task) def delete_task(client, task_id): ''' deletes a task entity, using the task entity's key ''' key = client.key('Task', task_id) client.delete(key) def list_tasks(client): query = client.query(kind='Task') query.order = ['created'] return list(query.fetch())
apache-2.0
Python
1a15a08abd7c7b5313402be4574ca6811044fd75
Fix HardwareDevice constructor to provide 'description' argument
Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server
launch_control/models/hw_device.py
launch_control/models/hw_device.py
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU) >>> cpu.desc = "800MHz OMAP3 Processor" >>> cpu.attributes['machine'] = 'arm' >>> cpu.attributes['mhz'] = 800 >>> cpu.attributes['vendor'] = 'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'desc', 'attributes') def __init__(self, device_type, description, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU) >>> cpu.desc = "800MHz OMAP3 Processor" >>> cpu.attributes['machine'] = 'arm' >>> cpu.attributes['mhz'] = 800 >>> cpu.attributes['vendor'] = 'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'desc', 'attributes') def __init__(self, device_type, desc, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
agpl-3.0
Python
f20c62b663cb35cb60e26884000d47e8c9b712a3
Include thread name in log output
netsec-ethz/scion,dmpiergiacomo/scion,netsec-ethz/scion,dmpiergiacomo/scion,klausman/scion,Oncilla/scion,dmpiergiacomo/scion,Oncilla/scion,Oncilla/scion,FR4NK-W/osourced-scion,FR4NK-W/osourced-scion,FR4NK-W/osourced-scion,dmpiergiacomo/scion,klausman/scion,klausman/scion,klausman/scion,Oncilla/scion,dmpiergiacomo/scion,dmpiergiacomo/scion,FR4NK-W/osourced-scion,FR4NK-W/osourced-scion,netsec-ethz/scion,klausman/scion,netsec-ethz/scion
lib/log.py
lib/log.py
# Copyright 2015 ETH Zurich # # 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. """ :mod:`log` --- Logging utilites =============================== """ import logging import traceback # This file should not include other SCION libraries, to prevent cirular import # errors. class _StreamErrorHandler(logging.StreamHandler): """ A logging StreamHandler that will exit the application if there's a logging exception. We don't try to use the normal logging system at this point because we don't know if that's working at all. If it is (e.g. when the exception is a formatting error), when we re-raise the exception, it'll get handled by the normal process. """ def handleError(self, record): self.stream.write("Exception in logging module:\n") for line in traceback.format_exc().split("\n"): self.stream.write(line+"\n") self.flush() raise def init_logging(level=logging.DEBUG): """ Configure logging for components (servers, routers, gateways). """ logging.basicConfig(level=level, handlers=[_StreamErrorHandler()], format='%(asctime)s [%(levelname)s]\t' '(%(threadName)s) %(message)s') def log_exception(msg, *args, level=logging.CRITICAL, **kwargs): """ Properly format an exception before logging """ logging.log(level, msg, *args, **kwargs) for line in traceback.format_exc().split("\n"): logging.log(level, line)
# Copyright 2015 ETH Zurich # # 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. """ :mod:`log` --- Logging utilites =============================== """ import logging import traceback # This file should not include other SCION libraries, to prevent cirular import # errors. class _StreamErrorHandler(logging.StreamHandler): """ A logging StreamHandler that will exit the application if there's a logging exception. We don't try to use the normal logging system at this point because we don't know if that's working at all. If it is (e.g. when the exception is a formatting error), when we re-raise the exception, it'll get handled by the normal process. """ def handleError(self, record): self.stream.write("Exception in logging module:\n") for line in traceback.format_exc().split("\n"): self.stream.write(line+"\n") self.flush() raise def init_logging(level=logging.DEBUG): """ Configure logging for components (servers, routers, gateways). """ logging.basicConfig(level=level, handlers=[_StreamErrorHandler()], format='%(asctime)s [%(levelname)s]\t%(message)s') def log_exception(msg, *args, level=logging.CRITICAL, **kwargs): """ Properly format an exception before logging """ logging.log(level, msg, *args, **kwargs) for line in traceback.format_exc().split("\n"): logging.log(level, line)
apache-2.0
Python
f4c66c87683587145f06fd332609152faa62ea00
Fix filters config loading
dmrib/trackingtermites
trackingtermites/utils.py
trackingtermites/utils.py
"""Utilitary shared functions.""" boolean_parameters = ['show_labels', 'highlight_collisions', 'show_bounding_box', 'show_frame_info', 'show_d_lines', 'show_trails'] tuple_parameters = ['video_source_size', 'arena_size'] integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size', 'termite_radius'] list_parameters = ['filters'] def read_config_file(config_path): """Read input file and creates parameters dictionary. Args: config_path (str): path to configuration file. Returns: parameters (dict): loaded parameters. """ parameters = {} with open(config_path, mode='r', encoding='utf-8') as input_file: for line in input_file: if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ': param, value = line.strip().split(' ') if param in tuple_parameters: width, height = value.strip().split(',') parameters[param] = tuple([int(width), int(height)]) elif param in list_parameters: values = [] for field in value.strip().split(','): if field != 'None': values.append(field) parameters[param] = values elif param in integer_parameters: parameters[param] = int(value) elif param in boolean_parameters: if value.lower() == 'true': parameters[param] = True else: parameters[param] = False else: parameters[param] = value return parameters
"""Utilitary shared functions.""" boolean_parameters = ['show_labels', 'highlight_collisions', 'show_bounding_box', 'show_frame_info', 'show_d_lines', 'show_trails'] tuple_parameters = ['video_source_size', 'arena_size'] integer_parameters = ['n_termites', 'box_size', 'scale', 'trail_size', 'termite_radius'] list_parameters = ['filters'] def read_config_file(config_path): """Read input file and creates parameters dictionary. Args: config_path (str): path to configuration file. Returns: parameters (dict): loaded parameters. """ parameters = {} with open(config_path, mode='r', encoding='utf-8') as input_file: for line in input_file: if not line[0] == '\n' and not line[0] == '#' and not line[0] == ' ': param, value = line.strip().split(' ') if param in tuple_parameters: width, height = value.strip().split(',') parameters[param] = tuple([int(width), int(height)]) elif param in list_parameters: values = [] for field in value.strip().split(','): if field != 'None': filters.append(field) parameters[param] = values elif param in integer_parameters: parameters[param] = int(value) elif param in boolean_parameters: if value.lower() == 'true': parameters[param] = True else: parameters[param] = False else: parameters[param] = value return parameters
mit
Python
2b487bfe85d87dda6e7e89fd8f950d708db9fe52
Revert Essentia from build test
Kaggle/docker-python,Kaggle/docker-python
test_build.py
test_build.py
# This script should run without errors whenever we update the # kaggle/python container. It checks that all our most popular packages can # be loaded and used without errors. import numpy as np print("Numpy imported ok") print("Your lucky number is: " + str(np.random.randint(100))) import pandas as pd print("Pandas imported ok") from sklearn import datasets print("sklearn imported ok") iris = datasets.load_iris() X, y = iris.data, iris.target from sklearn.ensemble import RandomForestClassifier rf1 = RandomForestClassifier() rf1.fit(X,y) print("sklearn RandomForestClassifier: ok") from xgboost import XGBClassifier xgb1 = XGBClassifier(n_estimators=3) xgb1.fit(X[0:70],y[0:70]) print("xgboost XGBClassifier: ok") import matplotlib.pyplot as plt plt.plot(np.linspace(0,1,50), np.random.rand(50)) plt.savefig("plot1.png") print("matplotlib.pyplot ok") from mpl_toolkits.basemap import Basemap print("Basemap ok") import plotly.plotly as py import plotly.graph_objs as go print("plotly ok") from ggplot import * print("ggplot ok") import theano print("Theano ok") from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.optimizers import SGD print("keras ok") import nltk from nltk.stem import WordNetLemmatizer print("nltk ok") import tensorflow as tf hello = tf.constant('TensorFlow ok') sess = tf.Session() print(sess.run(hello)) import cv2 img = cv2.imread('plot1.png',0) print("OpenCV ok")
# This script should run without errors whenever we update the # kaggle/python container. It checks that all our most popular packages can # be loaded and used without errors. import numpy as np print("Numpy imported ok") print("Your lucky number is: " + str(np.random.randint(100))) import pandas as pd print("Pandas imported ok") from sklearn import datasets print("sklearn imported ok") iris = datasets.load_iris() X, y = iris.data, iris.target from sklearn.ensemble import RandomForestClassifier rf1 = RandomForestClassifier() rf1.fit(X,y) print("sklearn RandomForestClassifier: ok") from xgboost import XGBClassifier xgb1 = XGBClassifier(n_estimators=3) xgb1.fit(X[0:70],y[0:70]) print("xgboost XGBClassifier: ok") import matplotlib.pyplot as plt plt.plot(np.linspace(0,1,50), np.random.rand(50)) plt.savefig("plot1.png") print("matplotlib.pyplot ok") from mpl_toolkits.basemap import Basemap print("Basemap ok") import plotly.plotly as py import plotly.graph_objs as go print("plotly ok") from ggplot import * print("ggplot ok") import theano print("Theano ok") from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from keras.optimizers import SGD print("keras ok") import nltk from nltk.stem import WordNetLemmatizer print("nltk ok") import tensorflow as tf hello = tf.constant('TensorFlow ok') sess = tf.Session() print(sess.run(hello)) import cv2 img = cv2.imread('plot1.png',0) print("OpenCV ok") import essentia print("Essentia ok")
apache-2.0
Python
b956f5d8c4c9329d4fae448358b5d3169939fcfb
Fix when packages not exist
clchiou/garage,clchiou/garage,clchiou/garage,clchiou/garage
shipyard/rules/java/java/build.py
shipyard/rules/java/java/build.py
"""Set up Java runtime environment.""" from pathlib import Path from foreman import define_parameter, rule from garage import scripts from templates import common (define_parameter.path_typed('jre') .with_doc('Path to JRE.') .with_default(Path('/usr/local/lib/java/jre'))) (define_parameter.path_typed('packages') .with_doc('Path to directory of Java packages') .with_default(Path('/usr/local/lib/java/packages'))) # Copy source (because all Java projects are under one Gradle root # project and thus we don't copy Java projects individually). common.define_copy_src(src_relpath='java', dst_relpath='java') @rule @rule.depend('//base:build') @rule.depend('//host/gradle:install') @rule.depend('//host/java:install') @rule.depend('copy_src') def build(parameters): """Prepare Java development environment.""" # Prepare build environment. drydock_src = parameters['//base:drydock'] / 'java' if not (drydock_src / 'gradlew').exists(): with scripts.directory(drydock_src): # Create gradle wrapper. scripts.execute(['gradle', 'wrapper']) # Download the gradle of version pinned in build.gradle. scripts.execute(['./gradlew', '--version']) # Copy JRE to /usr/local/lib. with scripts.using_sudo(): jre = parameters['jre'] scripts.mkdir(jre) # Appending '/' to src is an rsync trick. src = parameters['//host/java:jdk'] / 'jre' scripts.rsync(['%s/' % src], jre) @rule @rule.depend('build') @rule.reverse_depend('//base:tapeout') def tapeout(parameters): """Tape-out Java. NOTE: All Java package's `tapeout` rules should reverse depend on this rule. """ with scripts.using_sudo(): rootfs = parameters['//base:drydock/rootfs'] srcs = [parameters['jre']] packages = parameters['packages'] if packages.exists(): srcs.append(packages) scripts.rsync(srcs, rootfs, relative=True)
"""Set up Java runtime environment.""" from pathlib import Path from foreman import define_parameter, rule from garage import scripts from templates import common (define_parameter.path_typed('jre') .with_doc('Path to JRE.') .with_default(Path('/usr/local/lib/java/jre'))) (define_parameter.path_typed('packages') .with_doc('Path to directory of Java packages') .with_default(Path('/usr/local/lib/java/packages'))) # Copy source (because all Java projects are under one Gradle root # project and thus we don't copy Java projects individually). common.define_copy_src(src_relpath='java', dst_relpath='java') @rule @rule.depend('//base:build') @rule.depend('//host/gradle:install') @rule.depend('//host/java:install') @rule.depend('copy_src') def build(parameters): """Prepare Java development environment.""" # Prepare build environment. drydock_src = parameters['//base:drydock'] / 'java' if not (drydock_src / 'gradlew').exists(): with scripts.directory(drydock_src): # Create gradle wrapper. scripts.execute(['gradle', 'wrapper']) # Download the gradle of version pinned in build.gradle. scripts.execute(['./gradlew', '--version']) # Copy JRE to /usr/local/lib. with scripts.using_sudo(): jre = parameters['jre'] scripts.mkdir(jre) # Appending '/' to src is an rsync trick. src = parameters['//host/java:jdk'] / 'jre' scripts.rsync(['%s/' % src], jre) @rule @rule.depend('build') @rule.reverse_depend('//base:tapeout') def tapeout(parameters): """Tape-out Java. NOTE: All Java package's `tapeout` rules should reverse depend on this rule. """ with scripts.using_sudo(): rootfs = parameters['//base:drydock/rootfs'] jre = parameters['jre'] packages = parameters['packages'] scripts.rsync([jre, packages], rootfs, relative=True)
mit
Python
3983d7a205766526364c64158f10c0d931190d93
Use update
davidfischer/readthedocs.org,davidfischer/readthedocs.org,safwanrahman/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,davidfischer/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org,safwanrahman/readthedocs.org
readthedocs/projects/migrations/0025_show-version-warning-existing-projects.py
readthedocs/projects/migrations/0025_show-version-warning-existing-projects.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 19:25 from __future__ import unicode_literals from django.db import migrations def show_version_warning_to_existing_projects(apps, schema_editor): Project = apps.get_model('projects', 'Project') Project.objects.all().update(show_version_warning=True) class Migration(migrations.Migration): dependencies = [ ('projects', '0024_add-show-version-warning'), ] operations = [ migrations.RunPython(show_version_warning_to_existing_projects), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-05-07 19:25 from __future__ import unicode_literals from django.db import migrations def show_version_warning_to_existing_projects(apps, schema_editor): Project = apps.get_model('projects', 'Project') for project in Project.objects.all(): project.show_version_warning = True project.save() class Migration(migrations.Migration): dependencies = [ ('projects', '0024_add-show-version-warning'), ] operations = [ migrations.RunPython(show_version_warning_to_existing_projects), ]
mit
Python
e4d818072e72492df6275c1ca43d06165c113a49
Implement size method
funkybob/django-webdav-storage
webdav_storage/backend.py
webdav_storage/backend.py
from django.conf import settings from django.core.files.storage import Storage import requests from urlparse import urljoin try: from cStringIO import StringIO except ImportError: from StringIO import StringIO WEBDAV_ROOT = settings.WEBDAV_ROOT WEBDAV_PULIC = getattr(settings, 'WEBDAV_PUBLIC', WEBDAV_ROOT) class WebDavStorage(Storage): @cached_property def session(self): return requests.Session() def _build_url(self, name, external=False): """ Return the full URL for accessing the name. """ return urljoin(WEBDAV_PUBLIC if external else WEBDAV_ROOT, name) def _open(self, name, mode='rb'): """ Retrieves the specified file from storage. """ resp = self.session.get(self._build_url(name)) assert resp.status_code == 200 return StringIO(resp.content) def _save(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object or any python file-like object, ready to be read from the beginning. """ resp = self.session.put(self._build_url(name), content) def delete(self, name): """ Deletes the specified file from the storage system. """ resp = self.session.delete(self._build_url(name)) def exists(self, name): """ Returns True if a file referened by the given name already exists in the storage system, or False if the name is available for a new file. """ resp = self.session.head(self._build_url(name)) return resp.status_code != 404 def listdir(self, path): """ Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. """ resp = self.session.get(self._build_path(path)) # XXX? def size(self, name): """ Returns the total size, in bytes, of the file specified by name. """ resp = self.session.head(self._build_url(name)) return int(resp['content-lenght']) def url(self, name): """ Returns an absolute URL where the file's contents can be accessed directly by a Web browser. """ return self._build_url(name, external=True)
from django.conf import settings from django.core.files.storage import Storage import requests from urlparse import urljoin try: from cStringIO import StringIO except ImportError: from StringIO import StringIO WEBDAV_ROOT = settings.WEBDAV_ROOT WEBDAV_PULIC = getattr(settings, 'WEBDAV_PUBLIC', WEBDAV_ROOT) class WebDavStorage(Storage): @cached_property def session(self): return requests.Session() def _build_url(self, name, external=False): """ Return the full URL for accessing the name. """ return urljoin(WEBDAV_PUBLIC if external else WEBDAV_ROOT, name) def _open(self, name, mode='rb'): """ Retrieves the specified file from storage. """ resp = self.session.get(self._build_url(name)) assert resp.status_code == 200 return StringIO(resp.content) def _save(self, name, content): """ Saves new content to the file specified by name. The content should be a proper File object or any python file-like object, ready to be read from the beginning. """ resp = self.session.put(self._build_url(name), content) def delete(self, name): """ Deletes the specified file from the storage system. """ resp = self.session.delete(self._build_url(name)) def exists(self, name): """ Returns True if a file referened by the given name already exists in the storage system, or False if the name is available for a new file. """ resp = self.session.head(self._build_url(name)) return resp.status_code != 404 def listdir(self, path): """ Lists the contents of the specified path, returning a 2-tuple of lists; the first item being directories, the second item being files. """ resp = self.session.get(self._build_path(path)) # XXX? def size(self, name): """ Returns the total size, in bytes, of the file specified by name. """ def url(self, name): """ Returns an absolute URL where the file's contents can be accessed directly by a Web browser. """ return self._build_url(name, external=True)
bsd-2-clause
Python
3c9504efecf0f5e14a3922e0f33f812851837bc7
Add test to handle errors from extract_topics
NewAcropolis/api,NewAcropolis/api,NewAcropolis/api
tests/app/na_celery/test_upload_tasks.py
tests/app/na_celery/test_upload_tasks.py
from app.models import MAGAZINE from app.na_celery.upload_tasks import upload_magazine from tests.db import create_email class WhenUploadingMagazinePdfs: def it_uploads_a_magazine_pdf_and_sends_email(self, db_session, mocker, sample_magazine, sample_user): mocker.patch('app.na_celery.upload_tasks.Storage') mocker.patch('app.na_celery.upload_tasks.base64') mocker.patch('app.na_celery.upload_tasks.extract_topics', return_value='Philosophy: Meaning of Life And Death') mock_send_email = mocker.patch('app.na_celery.upload_tasks.send_smtp_email') upload_magazine(sample_magazine.id, 'pdf data') assert mock_send_email.called def it_uploads_a_magazine_pdf_and_reuses_email(self, app, db_session, mocker, sample_magazine, sample_user): mocker.patch('app.na_celery.upload_tasks.Storage') mocker.patch('app.na_celery.upload_tasks.base64') mocker.patch('app.na_celery.upload_tasks.extract_topics', return_value='Philosophy: Meaning of Life And Death') mock_send_email = mocker.patch('app.na_celery.upload_tasks.send_smtp_email', return_value=200) email = create_email(magazine_id=sample_magazine.id, email_type=MAGAZINE) upload_magazine(sample_magazine.id, 'pdf data') assert mock_send_email.called assert '<div>Please review this email: {}/emails/{}</div>'.format( app.config['FRONTEND_ADMIN_URL'], str(email.id)) in mock_send_email.call_args[0][2] def it_logs_errors(self, app, db_session, mocker, sample_magazine, sample_uuid): mocker.patch('app.na_celery.upload_tasks.dao_get_magazine_by_id') mock_logger = mocker.patch('app.na_celery.upload_tasks.current_app.logger.error') upload_magazine(sample_uuid, 'pdf data') assert mock_logger.called assert 'Task error uploading magazine' in mock_logger.call_args[0][0] def it_handles_error_from_extract_topics(self, app, db_session, mocker, sample_magazine, sample_user): mocker.patch('app.na_celery.upload_tasks.extract_topics', side_effect=Exception('Unknown')) mocker.patch('app.na_celery.upload_tasks.Storage') mocker.patch('app.na_celery.upload_tasks.base64') mock_logger = mocker.patch('app.na_celery.upload_tasks.current_app.logger.error') mock_send_email = mocker.patch('app.na_celery.upload_tasks.send_smtp_email', return_value=200) email = create_email(magazine_id=sample_magazine.id, email_type=MAGAZINE) upload_magazine(sample_magazine.id, 'pdf data') assert mock_logger.called assert 'Error extracting topics:' in mock_logger.call_args[0][0] assert mock_send_email.called assert '<div>Please review this email: {}/emails/{}</div>'.format( app.config['FRONTEND_ADMIN_URL'], str(email.id)) in mock_send_email.call_args[0][2]
from app.models import MAGAZINE from app.na_celery.upload_tasks import upload_magazine from tests.db import create_email class WhenUploadingMagazinePdfs: def it_uploads_a_magazine_pdf_and_sends_email(self, db_session, mocker, sample_magazine, sample_user): mocker.patch('app.na_celery.upload_tasks.Storage') mocker.patch('app.na_celery.upload_tasks.base64') mocker.patch('app.na_celery.upload_tasks.extract_topics', return_value='Philosophy: Meaning of Life And Death') mock_send_email = mocker.patch('app.na_celery.upload_tasks.send_smtp_email') upload_magazine(sample_magazine.id, 'pdf data') assert mock_send_email.called def it_uploads_a_magazine_pdf_and_reuses_email(self, app, db_session, mocker, sample_magazine, sample_user): mocker.patch('app.na_celery.upload_tasks.Storage') mocker.patch('app.na_celery.upload_tasks.base64') mocker.patch('app.na_celery.upload_tasks.extract_topics', return_value='Philosophy: Meaning of Life And Death') mock_send_email = mocker.patch('app.na_celery.upload_tasks.send_smtp_email', return_value=200) email = create_email(magazine_id=sample_magazine.id, email_type=MAGAZINE) upload_magazine(sample_magazine.id, 'pdf data') assert mock_send_email.called assert '<div>Please review this email: {}/emails/{}</div>'.format( app.config['FRONTEND_ADMIN_URL'], str(email.id)) in mock_send_email.call_args[0][2] def it_logs_errors(self, app, db_session, mocker, sample_magazine, sample_uuid): mocker.patch('app.na_celery.upload_tasks.dao_get_magazine_by_id') mock_logger = mocker.patch('app.na_celery.upload_tasks.current_app.logger.error') upload_magazine(sample_uuid, 'pdf data') assert mock_logger.called assert 'Task error uploading magazine' in mock_logger.call_args[0][0]
mit
Python
674a19c3d78829135a39dda34e468413bd72364b
Add description of work todo (so I don't forget).
agbrooks/ghetto-sonar
mlsmath/mls.py
mlsmath/mls.py
from polynomial import * from modtwo import * """ mls defines make_mls, which creates a maximum length sequence from a given degree. The top of the file contains some parsing functions to read the generator polynomial definitions. """ GENERATOR_FILE = "generators.text" def _strip_after_pound(string): """ Treat "#" as a comment character and remove everything after. """ msg = "" for char in string: if char != "#": msg = msg + char else: return msg return msg def _to_integers(lst): """ Coerce all members of a list to integers. """ return list(map(int, lst)) def _powers_to_terms(pwrs): """ Converts lists containing which terms have a coefficient of 1 to the actual terms themselves. """ terms = [] for pwr in pwrs: terms.append(Term(pwr, 1)) return terms def _parse_polynomials(filepath): """ Populate a list of polynomials from a filepath. """ try: f = open(filepath) except FileNotFoundError: raise Warning("Unable to find generator definition " + filepath) poly_strs = f.readlines() polynomials = map(_parse_polynomial, poly_strs) # Reject any failures. good_polynomials = [p for p in polynomials if p is not None] return list(good_polynomials) def _parse_polynomial(string): """ Convert a string describing a polynomial (see generators.text) to a MTPoly. On fail returns None. """ p = _strip_after_pound(string).split() if len(p) is 0: return None try: p = _to_integers(p) except ValueError: return None return MTPolynomial(_powers_to_terms(p)) # Note the null polynomial at the beginning. This makes _generators[degree] valid. _generators = [MTPolynomial([])] + _parse_polynomials(GENERATOR_FILE) def make_mls(degree): """ Create a maximum length sequence of a given degree. """ if degree > len(_generators): raise ValueError("Degree can be, at most, 30.") if degree < 1: raise ValueError("Degrees less than one are meaningless for MLSes.") generator = generators[degree] # Very wrong -- correct approach is to convert to an LFSR and then eval. return list(map(generator.evaluate, list(range(2**degree + 1))))
from polynomial import * from modtwo import * """ mls defines make_mls, which creates a maximum length sequence from a given degree. The top of the file contains some parsing functions to read the generator polynomial definitions. """ GENERATOR_FILE = "generators.text" def _strip_after_pound(string): """ Treat "#" as a comment character and remove everything after. """ msg = "" for char in string: if char != "#": msg = msg + char else: return msg return msg def _to_integers(lst): """ Coerce all members of a list to integers. """ return list(map(int, lst)) def _powers_to_terms(pwrs): """ Converts lists containing which terms have a coefficient of 1 to the actual terms themselves. """ terms = [] for pwr in pwrs: terms.append(Term(pwr, 1)) return terms def _parse_polynomials(filepath): """ Populate a list of polynomials from a filepath. """ try: f = open(filepath) except FileNotFoundError: raise Warning("Unable to find generator definition " + filepath) poly_strs = f.readlines() polynomials = map(_parse_polynomial, poly_strs) # Reject any failures. good_polynomials = [p for p in polynomials if p is not None] return list(good_polynomials) def _parse_polynomial(string): """ Convert a string describing a polynomial (see generators.text) to a MTPoly. On fail returns None. """ p = _strip_after_pound(string).split() if len(p) is 0: return None try: p = _to_integers(p) except ValueError: return None return MTPolynomial(_powers_to_terms(p)) # Note the null polynomial at the beginning. This makes _generators[degree] valid. _generators = [MTPolynomial([])] + _parse_polynomials(GENERATOR_FILE) # TODO: Test this. def make_mls(degree): """ Create a maximum length sequence of a given degree. """ if degree > len(_generators): raise ValueError("Degree can be, at most, 30.") if degree < 1: raise ValueError("Degrees less than one are meaningless for MLSes.") generator = generators[degree] return list(map(generator.evaluate, list(range(2**degree + 1))))
mit
Python
9c668a12a021ed0e3698699cd36506f10a0fa486
add coreview: user.json_list
abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core
abilian/web/coreviews/users.py
abilian/web/coreviews/users.py
# coding=utf-8 """ """ from __future__ import absolute_import import hashlib from sqlalchemy.sql.expression import or_, func from flask import Blueprint, make_response, request, g, Response from werkzeug.exceptions import NotFound from abilian.core.models.subjects import User from abilian.web import url_for from abilian.web.views import JSONModelSearch bp = Blueprint('users', __name__, url_prefix='/users') @bp.url_value_preprocessor def get_user(endpoint, values): try: user_id = values.pop('user_id') user = User.query.get(user_id) if user: values['user'] = user else: raise NotFound() except KeyError: # this endpoint is not looking for a specific user pass @bp.route('/<int:user_id>/photo') def photo(user): if not user.photo: raise NotFound() data = user.photo self_photo = (user.id == g.user.id) if self_photo: # special case: for its own photo user has an etag, so that on change photo # is immediatly reloaded from server. # # FIXME: there should be a photo_digest field on user object acc = hashlib.md5(data) etag = acc.hexdigest() if request.if_none_match and etag in request.if_none_match: return Response(status=304) r = make_response(data) r.headers['content-type'] = 'image/jpeg' if not self_photo: r.headers.add('Cache-Control', 'public, max-age=600') else: # user always checks its own mugshot is up-to-date, in order to avoid seeing # old one immediatly after having uploaded of a new picture. r.headers.add('Cache-Control', 'private, must-revalidate') r.set_etag(etag) return r # JSON search class UserJsonListing(JSONModelSearch): """ """ Model = User minimum_input_length = 0 def filter(self, query, q, **kwargs): if q: query = query.filter( or_(func.lower(User.first_name).like(q + "%"), func.lower(User.last_name).like(q + "%")) ) return query def order_by(self, query): return query.order_by(func.lower(User.last_name), func.lower(User.first_name)) def get_item(self, obj): d = super(UserJsonListing, self).get_item(obj) d['email'] = obj.email d['can_login'] = obj.can_login d['photo'] = url_for('users.photo', user_id=obj.id) return d bp.route('/json/')(UserJsonListing.as_view('json_list'))
# coding=utf-8 """ """ from __future__ import absolute_import import hashlib from flask import Blueprint, make_response, request, g, Response from werkzeug.exceptions import NotFound from abilian.core.models.subjects import User bp = Blueprint('users', __name__, url_prefix='/users') @bp.url_value_preprocessor def get_user(endpoint, values): try: user_id = values.pop('user_id') user = User.query.get(user_id) if user: values['user'] = user else: raise NotFound() except KeyError: # this endpoint is not looking for a specific user pass @bp.route('/<int:user_id>/photo') def photo(user): if not user.photo: raise NotFound() data = user.photo self_photo = (user.id == g.user.id) if self_photo: # special case: for its own photo user has an etag, so that on change photo # is immediatly reloaded from server. # # FIXME: there should be a photo_digest field on user object acc = hashlib.md5(data) etag = acc.hexdigest() if request.if_none_match and etag in request.if_none_match: return Response(status=304) r = make_response(data) r.headers['content-type'] = 'image/jpeg' if not self_photo: r.headers.add('Cache-Control', 'public, max-age=600') else: # user always checks its own mugshot is up-to-date, in order to avoid seeing # old one immediatly after having uploaded of a new picture. r.headers.add('Cache-Control', 'private, must-revalidate') r.set_etag(etag) return r
lgpl-2.1
Python
f1fab0dbb25104213359c8da5aacb1bbed290a6b
Call match() instead of copying its body
nvbn/thefuck,SimenB/thefuck,Clpsplug/thefuck,scorphus/thefuck,SimenB/thefuck,nvbn/thefuck,scorphus/thefuck,Clpsplug/thefuck
thefuck/rules/git_flag_after_filename.py
thefuck/rules/git_flag_after_filename.py
import re from thefuck.specific.git import git_support error_pattern = "fatal: bad flag '(.*?)' used after filename" @git_support def match(command): return re.search(error_pattern, command.output) @git_support def get_new_command(command): command_parts = command.script_parts[:] # find the bad flag bad_flag = match(command).group(1) bad_flag_index = command_parts.index(bad_flag) # find the filename for index in reversed(range(bad_flag_index)): if command_parts[index][0] != '-': filename_index = index break # swap them command_parts[bad_flag_index], command_parts[filename_index] = \ command_parts[filename_index], command_parts[bad_flag_index] # noqa: E122 return u' '.join(command_parts)
import re from thefuck.specific.git import git_support error_pattern = "fatal: bad flag '(.*?)' used after filename" @git_support def match(command): return re.search(error_pattern, command.output) @git_support def get_new_command(command): command_parts = command.script_parts[:] # find the bad flag bad_flag = re.search(error_pattern, command.output).group(1) bad_flag_index = command_parts.index(bad_flag) # find the filename for index in reversed(range(bad_flag_index)): if command_parts[index][0] != '-': filename_index = index break # swap them command_parts[bad_flag_index], command_parts[filename_index] = \ command_parts[filename_index], command_parts[bad_flag_index] # noqa: E122 return u' '.join(command_parts)
mit
Python
c9b5998372b99140b0c9032af0ba6590d68ad6d6
Bump version to 0.10.3
botify-labs/simpleflow,botify-labs/simpleflow
simpleflow/__init__.py
simpleflow/__init__.py
# -*- coding: utf-8 -*- import logging.config from .activity import Activity # NOQA from .workflow import Workflow # NOQA from . import settings __version__ = '0.10.3' __author__ = 'Greg Leclercq' __license__ = "MIT" logging.config.dictConfig(settings.base.load()['LOGGING'])
# -*- coding: utf-8 -*- import logging.config from .activity import Activity # NOQA from .workflow import Workflow # NOQA from . import settings __version__ = '0.10.2' __author__ = 'Greg Leclercq' __license__ = "MIT" logging.config.dictConfig(settings.base.load()['LOGGING'])
mit
Python
e82c6f691a66efd6b7db3ef5db696e8d745b5d18
reduce space
alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl,alphatwirl/alphatwirl
alphatwirl/roottree/inspect.py
alphatwirl/roottree/inspect.py
# Tai Sakuma <tai.sakuma@gmail.com> ##__________________________________________________________________|| def is_ROOT_null_pointer(tobject): try: tobject.GetName() return False except ReferenceError: return True ##__________________________________________________________________|| def inspect_tree(tree): ret = { } ret['leaves'] = [inspect_leaf(leaf) for leaf in tree.GetListOfLeaves()] return ret ##__________________________________________________________________|| def inspect_leaf(leaf): ret = { } ret.update(inspect_leaf_definition(leaf)) ret.update(inspect_leaf_size(leaf)) return ret ##__________________________________________________________________|| def inspect_leaf_definition(leaf): leafcount = leaf.GetLeafCount() isArray = not is_ROOT_null_pointer(leafcount) ret = { } ret['name'] = leaf.GetName() ret['type'] = leaf.GetTypeName() ret['isarray'] = '1' if isArray else '0' ret['countname'] = leafcount.GetName() if isArray else None ret['title'] = leaf.GetBranch().GetTitle() return ret ##__________________________________________________________________|| def inspect_leaf_size(leaf): ret = { } zipbytes = leaf.GetBranch().GetZipBytes()/1024.0/1024.0 # MB totalsize = leaf.GetBranch().GetTotalSize()/1024.0/1024.0 # MB ret['size'] = zipbytes ret['uncompressed_size'] = totalsize ret['compression_factor'] = totalsize/zipbytes if zipbytes > 0 else 0 return ret ##__________________________________________________________________||
# Tai Sakuma <tai.sakuma@gmail.com> ##__________________________________________________________________|| def is_ROOT_null_pointer(tobject): try: tobject.GetName() return False except ReferenceError: return True ##__________________________________________________________________|| def inspect_tree(tree): ret = { } ret['leaves'] = [inspect_leaf(leaf) for leaf in tree.GetListOfLeaves()] return ret ##__________________________________________________________________|| def inspect_leaf(leaf): ret = { } ret.update(inspect_leaf_definition(leaf)) ret.update(inspect_leaf_size(leaf)) return ret ##__________________________________________________________________|| def inspect_leaf_definition(leaf): leafcount = leaf.GetLeafCount() isArray = not is_ROOT_null_pointer(leafcount) ret = { } ret['name'] = leaf.GetName() ret['type'] = leaf.GetTypeName() ret['isarray'] = '1' if isArray else '0' ret['countname'] = leafcount.GetName() if isArray else None ret['title'] = leaf.GetBranch().GetTitle() return ret ##__________________________________________________________________|| def inspect_leaf_size(leaf): ret = { } zipbytes = leaf.GetBranch().GetZipBytes()/1024.0/1024.0 # MB totalsize = leaf.GetBranch().GetTotalSize()/1024.0/1024.0 # MB ret['size'] = zipbytes ret['uncompressed_size'] = totalsize ret['compression_factor'] = totalsize/zipbytes if zipbytes > 0 else 0 return ret ##__________________________________________________________________||
bsd-3-clause
Python
77c15b91325e43c7c28d83c8b97130b31facd2ea
Update post and add put method for User api endpoint.
rivalrockets/benchmarks.rivalrockets.com,rivalrockets/rivalrockets-api
app/api_1_0/resources/users.py
app/api_1_0/resources/users.py
from flask import g from flask_restful import Resource, reqparse, fields, marshal_with from .authentication import auth from .machines import machine_fields from ... import db from ...models import User, Machine # flask_restful fields usage: # note that the 'Url' field type takes the 'endpoint' for the arg user_fields = { 'username': fields.String, 'uri': fields.Url('.user', absolute=True), 'last_seen': fields.DateTime(dt_format='rfc822'), 'machines': fields.List(fields.Nested(machine_fields)) } # List of users class UserListAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, location='json') self.reqparse.add_argument('password', type=str, required=True, location='json') super(UserListAPI, self).__init__() @marshal_with(user_fields, envelope='users') def get(self): return User.query.outerjoin(User.machines).all() @marshal_with(user_fields, envelope='user') def post(self): args = self.reqparse.parse_args() user = User(username=args['username']) user.hash_password(args['password']) db.session.add(user) db.session.commit() return user, 201 # New user API class class UserAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=False, location='json') self.reqparse.add_argument('password', type=str, required=True, location='json') super(UserAPI, self).__init__() @marshal_with(user_fields, envelope='user') def get(self, id): return User.query.get_or_404(id) @auth.login_required @marshal_with(user_fields, envelope='user') def put(self, id): user = User.query.get_or_404(id) # only currently logged in user allowed to change their username or password if g.user.id == id: # as seen in other places, loop through all the supplied args to apply # the difference is that we're watching out for the password args = self.reqparse.parse_args() for k, v in args.items(): if v is not None and k != "password": setattr(user, k, v) elif v is not None and k == "password": user.hash_password(v) db.session.commit() return user, 201 else: return 403
from flask_restful import Resource, reqparse, fields, marshal_with from ... import db from ...models import User # flask_restful fields usage: # note that the 'Url' field type takes the 'endpoint' for the arg user_fields = { 'username': fields.String, 'uri': fields.Url('.user', absolute=True) } # List of users class UserListAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, location='json') self.reqparse.add_argument('password', type=str, required=True, location='json') super(UserListAPI, self).__init__() @marshal_with(user_fields, envelope='users') def get(self): return User.query.all() # New user API class class UserAPI(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('username', type=str, required=True, location='json') self.reqparse.add_argument('password', type=str, required=True, location='json') super(UserAPI, self).__init__() @marshal_with(user_fields, envelope='user') def get(self, id): return User.query.get_or_404(id) @marshal_with(user_fields, envelope='user') def post(self): args = self.reqparse.parse_args() user = User(username=args['username']) user.hash_password(args['password']) db.session.add(user) db.session.commit() return user, 201
mit
Python
e02c4a9b39a11af0dad6312abcd20855744d5344
update Ashford import script for parl.2017-06-08 (closes #946)
DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations
polling_stations/apps/data_collection/management/commands/import_ashford.py
polling_stations/apps/data_collection/management/commands/import_ashford.py
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = 'E07000105' addresses_name = 'parl.2017-06-08/Version 1/Ashford Democracy_Club__08June2017.tsv' stations_name = 'parl.2017-06-08/Version 1/Ashford Democracy_Club__08June2017.tsv' elections = ['parl.2017-06-08'] csv_delimiter = '\t'
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = 'E07000105' addresses_name = 'Ashford_Democracy_Club__04May2017.CSV' stations_name = 'Ashford_Democracy_Club__04May2017.CSV' elections = [ 'local.kent.2017-05-04', 'parl.2017-06-08' ]
bsd-3-clause
Python
5f70996680418c4c5b35ecf88a1bf3bb3b718c1f
Bump max API to 2. #485 #486
mfeit-internet2/pscheduler-dev,perfsonar/pscheduler,mfeit-internet2/pscheduler-dev,perfsonar/pscheduler,perfsonar/pscheduler,perfsonar/pscheduler
pscheduler-server/pscheduler-server/api-server/pschedulerapiserver/admin.py
pscheduler-server/pscheduler-server/api-server/pschedulerapiserver/admin.py
# # Administrative Information # import datetime import pscheduler import pytz import socket import tzlocal from pschedulerapiserver import application from .access import * from .args import arg_integer from .dbcursor import dbcursor_query from .response import * from .util import * from .log import log @application.route("/", methods=['GET']) def root(): return ok_json("This is the pScheduler API server on %s (%s)." % (server_netloc(), pscheduler.api_this_host())) max_api = 2 @application.route("/api", methods=['GET']) def api(): return ok_json(max_api) @application.before_request def before_req(): log.debug("REQUEST: %s %s", request.method, request.url) try: version = arg_integer("api") if version is None: version = 1 if version > max_api: return not_implemented( "No API above %s is supported" % (max_api)) except ValueError: return bad_request("Invalid API value.") # All went well. return None @application.errorhandler(Exception) def exception_handler(ex): log.exception() return error("Internal problem; see system logs.") @application.route("/exception", methods=['GET']) def exception(): """Throw an exception""" # Allow only from localhost if not request.remote_addr in ['127.0.0.1', '::1']: return not_allowed() raise Exception("Forced exception.") @application.route("/hostname", methods=['GET']) def hostname(): """Return the hosts's name""" return ok_json(pscheduler.api_this_host()) @application.route("/schedule-horizon", methods=['GET']) def schedule_horizon(): """Get the length of the server's scheduling horizon""" try: cursor = dbcursor_query( "SELECT schedule_horizon FROM configurables", onerow=True) except Exception as ex: log.exception() return error(str(ex)) return ok_json(pscheduler.timedelta_as_iso8601(cursor.fetchone()[0])) @application.route("/clock", methods=['GET']) def time(): """Return clock-related information""" try: return ok_json(pscheduler.clock_state()) except Exception as ex: return error("Unable to fetch clock state: " + str(ex))
# # Administrative Information # import datetime import pscheduler import pytz import socket import tzlocal from pschedulerapiserver import application from .access import * from .args import arg_integer from .dbcursor import dbcursor_query from .response import * from .util import * from .log import log @application.route("/", methods=['GET']) def root(): return ok_json("This is the pScheduler API server on %s (%s)." % (server_netloc(), pscheduler.api_this_host())) max_api = 1 @application.route("/api", methods=['GET']) def api(): return ok_json(max_api) @application.before_request def before_req(): log.debug("REQUEST: %s %s", request.method, request.url) try: version = arg_integer("api") if version is None: version = 1 if version > max_api: return not_implemented( "No API above %s is supported" % (max_api)) except ValueError: return bad_request("Invalid API value.") # All went well. return None @application.errorhandler(Exception) def exception_handler(ex): log.exception() return error("Internal problem; see system logs.") @application.route("/exception", methods=['GET']) def exception(): """Throw an exception""" # Allow only from localhost if not request.remote_addr in ['127.0.0.1', '::1']: return not_allowed() raise Exception("Forced exception.") @application.route("/hostname", methods=['GET']) def hostname(): """Return the hosts's name""" return ok_json(pscheduler.api_this_host()) @application.route("/schedule-horizon", methods=['GET']) def schedule_horizon(): """Get the length of the server's scheduling horizon""" try: cursor = dbcursor_query( "SELECT schedule_horizon FROM configurables", onerow=True) except Exception as ex: log.exception() return error(str(ex)) return ok_json(pscheduler.timedelta_as_iso8601(cursor.fetchone()[0])) @application.route("/clock", methods=['GET']) def time(): """Return clock-related information""" try: return ok_json(pscheduler.clock_state()) except Exception as ex: return error("Unable to fetch clock state: " + str(ex))
apache-2.0
Python
a412c1c9ec32fc75e69981f2420c77ebf04bd9be
Make benchmark callable from profile / cProfile module
googlei18n/cu2qu,googlefonts/cu2qu,googlefonts/fonttools,fonttools/fonttools
Lib/cu2qu/benchmark.py
Lib/cu2qu/benchmark.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 __future__ import print_function, division, absolute_import import random import timeit MAX_ERR = 5 SETUP_CODE = ''' from cu2qu import %s from cu2qu.benchmark import setup_%s args = setup_%s() ''' def generate_curve(): return [ tuple(float(random.randint(0, 2048)) for coord in range(2)) for point in range(4)] def setup_curve_to_quadratic(): return generate_curve(), MAX_ERR def setup_curves_to_quadratic(): num_curves = 3 return ( [generate_curve() for curve in range(num_curves)], [MAX_ERR] * num_curves) def run_test(name): print('%s:' % name) results = timeit.repeat( '%s(*args)' % name, setup=(SETUP_CODE % (name, name, name)), repeat=1000, number=1) print('min: %dus' % (min(results) * 1000000.)) print('avg: %dus' % (sum(results) / len(results) * 1000000.)) print() def main(): run_test('curve_to_quadratic') run_test('curves_to_quadratic') if __name__ == '__main__': random.seed(1) main()
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or 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 __future__ import print_function, division, absolute_import import random import timeit MAX_ERR = 5 SETUP_CODE = ''' from cu2qu import %s from __main__ import setup_%s args = setup_%s() ''' def generate_curve(): return [ tuple(float(random.randint(0, 2048)) for coord in range(2)) for point in range(4)] def setup_curve_to_quadratic(): return generate_curve(), MAX_ERR def setup_curves_to_quadratic(): num_curves = 3 return ( [generate_curve() for curve in range(num_curves)], [MAX_ERR] * num_curves) def run_test(name): print('%s:' % name) results = timeit.repeat( '%s(*args)' % name, setup=(SETUP_CODE % (name, name, name)), repeat=1000, number=1) print('min: %dus' % (min(results) * 1000000.)) print('avg: %dus' % (sum(results) / len(results) * 1000000.)) print() def main(): run_test('curve_to_quadratic') run_test('curves_to_quadratic') if __name__ == '__main__': random.seed(1) main()
apache-2.0
Python
778393cfd2d186f9fe771218da9e42ad1eda109b
support for sharding builds
kim42083/webm.libvpx,jdm/libvpx,mbebenita/aom,felipebetancur/libvpx,shacklettbp/aom,VTCSecureLLC/libvpx,abwiz0086/webm.libvpx,ittiamvpx/libvpx,ittiamvpx/libvpx-1,gshORTON/webm.libvpx,turbulenz/libvpx,webmproject/libvpx,matanbs/webm.libvpx,liqianggao/libvpx,luctrudeau/aom,shareefalis/libvpx,jdm/libvpx,felipebetancur/libvpx,kim42083/webm.libvpx,shacklettbp/aom,lyx2014/libvpx_c,jdm/libvpx,iniwf/webm.libvpx,Acidburn0zzz/webm.libvpx,Laknot/libvpx,vasilvv/esvp8,Distrotech/libvpx,kalli123/webm.libvpx,jmvalin/aom,Topopiccione/libvpx,mwgoldsmith/vpx,felipebetancur/libvpx,n4t/libvpx,turbulenz/libvpx,n4t/libvpx,Suvarna1488/webm.libvpx,kleopatra999/webm.libvpx,Laknot/libvpx,thdav/aom,Suvarna1488/webm.libvpx,stewnorriss/libvpx,charup/https---github.com-webmproject-libvpx-,shacklettbp/aom,webmproject/libvpx,GrokImageCompression/aom,running770/libvpx,mbebenita/aom,kleopatra999/webm.libvpx,running770/libvpx,ittiamvpx/libvpx,ittiamvpx/libvpx-1,mwgoldsmith/libvpx,pcwalton/libvpx,matanbs/webm.libvpx,shacklettbp/aom,Acidburn0zzz/webm.libvpx,shyamalschandra/libvpx,matanbs/vp982,Acidburn0zzz/webm.libvpx,charup/https---github.com-webmproject-libvpx-,mwgoldsmith/libvpx,stewnorriss/libvpx,zofuthan/libvpx,stewnorriss/libvpx,shyamalschandra/libvpx,matanbs/webm.libvpx,jmvalin/aom,pcwalton/libvpx,turbulenz/libvpx,luctrudeau/aom,ittiamvpx/libvpx-1,reimaginemedia/webm.libvpx,jdm/libvpx,Maria1099/webm.libvpx,Suvarna1488/webm.libvpx,cinema6/libvpx,ittiamvpx/libvpx-1,shareefalis/libvpx,goodleixiao/vpx,Topopiccione/libvpx,zofuthan/libvpx,Suvarna1488/webm.libvpx,turbulenz/libvpx,jacklicn/webm.libvpx,iniwf/webm.libvpx,Acidburn0zzz/webm.libvpx,lyx2014/libvpx_c,WebRTC-Labs/libvpx,abwiz0086/webm.libvpx,GrokImageCompression/aom,webmproject/libvpx,turbulenz/libvpx,GrokImageCompression/aom,altogother/webm.libvpx,matanbs/vp982,mbebenita/aom,thdav/aom,GrokImageCompression/aom,shacklettbp/aom,jacklicn/webm.libvpx,luctrudeau/aom,mbebenita/aom,sanyaade-teachings/libvpx,kalli123/webm.libvpx,gshORTON/webm.libvpx,luctrudeau/aom,turbulenz/libvpx,GrokImageCompression/aom,openpeer/libvpx_new,Maria1099/webm.libvpx,charup/https---github.com-webmproject-libvpx-,abwiz0086/webm.libvpx,iniwf/webm.libvpx,ittiamvpx/libvpx,pcwalton/libvpx,smarter/aom,vasilvv/esvp8,kim42083/webm.libvpx,lyx2014/libvpx_c,gshORTON/webm.libvpx,shyamalschandra/libvpx,running770/libvpx,goodleixiao/vpx,kleopatra999/webm.libvpx,VTCSecureLLC/libvpx,matanbs/webm.libvpx,abwiz0086/webm.libvpx,matanbs/webm.libvpx,WebRTC-Labs/libvpx,sanyaade-teachings/libvpx,kim42083/webm.libvpx,running770/libvpx,lyx2014/libvpx_c,mbebenita/aom,jacklicn/webm.libvpx,liqianggao/libvpx,luctrudeau/aom,thdav/aom,pcwalton/libvpx,WebRTC-Labs/libvpx,luctrudeau/aom,reimaginemedia/webm.libvpx,hsueceumd/test_hui,openpeer/libvpx_new,webmproject/libvpx,smarter/aom,ittiamvpx/libvpx,abwiz0086/webm.libvpx,altogother/webm.libvpx,liqianggao/libvpx,openpeer/libvpx_new,kalli123/webm.libvpx,shareefalis/libvpx,cinema6/libvpx,sanyaade-teachings/libvpx,jmvalin/aom,goodleixiao/vpx,running770/libvpx,smarter/aom,jmvalin/aom,kleopatra999/webm.libvpx,mwgoldsmith/vpx,gshORTON/webm.libvpx,mbebenita/aom,reimaginemedia/webm.libvpx,mwgoldsmith/vpx,jacklicn/webm.libvpx,kalli123/webm.libvpx,iniwf/webm.libvpx,VTCSecureLLC/libvpx,Maria1099/webm.libvpx,matanbs/webm.libvpx,Maria1099/webm.libvpx,stewnorriss/libvpx,sanyaade-teachings/libvpx,Distrotech/libvpx,webmproject/libvpx,Topopiccione/libvpx,ShiftMediaProject/libvpx,Laknot/libvpx,shyamalschandra/libvpx,altogother/webm.libvpx,turbulenz/libvpx,matanbs/vp982,n4t/libvpx,charup/https---github.com-webmproject-libvpx-,iniwf/webm.libvpx,kim42083/webm.libvpx,mbebenita/aom,reimaginemedia/webm.libvpx,VTCSecureLLC/libvpx,Distrotech/libvpx,shyamalschandra/libvpx,Topopiccione/libvpx,Suvarna1488/webm.libvpx,webmproject/libvpx,n4t/libvpx,Laknot/libvpx,ittiamvpx/libvpx-1,shareefalis/libvpx,Topopiccione/libvpx,hsueceumd/test_hui,cinema6/libvpx,zofuthan/libvpx,Topopiccione/libvpx,matanbs/vp982,charup/https---github.com-webmproject-libvpx-,smarter/aom,Acidburn0zzz/webm.libvpx,sanyaade-teachings/libvpx,lyx2014/libvpx_c,Acidburn0zzz/webm.libvpx,goodleixiao/vpx,vasilvv/esvp8,jacklicn/webm.libvpx,zofuthan/libvpx,hsueceumd/test_hui,felipebetancur/libvpx,thdav/aom,goodleixiao/vpx,zofuthan/libvpx,thdav/aom,VTCSecureLLC/libvpx,vasilvv/esvp8,felipebetancur/libvpx,gshORTON/webm.libvpx,mbebenita/aom,zofuthan/libvpx,shareefalis/libvpx,kleopatra999/webm.libvpx,charup/https---github.com-webmproject-libvpx-,kim42083/webm.libvpx,lyx2014/libvpx_c,vasilvv/esvp8,hsueceumd/test_hui,WebRTC-Labs/libvpx,iniwf/webm.libvpx,liqianggao/libvpx,mwgoldsmith/libvpx,turbulenz/libvpx,felipebetancur/libvpx,kalli123/webm.libvpx,n4t/libvpx,gshORTON/webm.libvpx,reimaginemedia/webm.libvpx,Suvarna1488/webm.libvpx,pcwalton/libvpx,ShiftMediaProject/libvpx,pcwalton/libvpx,jdm/libvpx,ittiamvpx/libvpx,smarter/aom,thdav/aom,jdm/libvpx,ShiftMediaProject/libvpx,jacklicn/webm.libvpx,matanbs/vp982,stewnorriss/libvpx,hsueceumd/test_hui,stewnorriss/libvpx,cinema6/libvpx,reimaginemedia/webm.libvpx,vasilvv/esvp8,WebRTC-Labs/libvpx,Laknot/libvpx,matanbs/vp982,ShiftMediaProject/libvpx,Laknot/libvpx,mwgoldsmith/vpx,turbulenz/libvpx,kleopatra999/webm.libvpx,mbebenita/aom,altogother/webm.libvpx,cinema6/libvpx,GrokImageCompression/aom,shyamalschandra/libvpx,running770/libvpx,ittiamvpx/libvpx,Distrotech/libvpx,liqianggao/libvpx,shacklettbp/aom,kalli123/webm.libvpx,openpeer/libvpx_new,Maria1099/webm.libvpx,ShiftMediaProject/libvpx,cinema6/libvpx,altogother/webm.libvpx,mwgoldsmith/libvpx,jmvalin/aom,Maria1099/webm.libvpx,altogother/webm.libvpx,shareefalis/libvpx,ittiamvpx/libvpx-1,smarter/aom,cinema6/libvpx,goodleixiao/vpx,VTCSecureLLC/libvpx,abwiz0086/webm.libvpx,liqianggao/libvpx,Distrotech/libvpx,vasilvv/esvp8,hsueceumd/test_hui,openpeer/libvpx_new,mwgoldsmith/libvpx,mwgoldsmith/vpx,Distrotech/libvpx,mwgoldsmith/libvpx,mwgoldsmith/vpx,openpeer/libvpx_new,matanbs/vp982,jmvalin/aom
all_builds.py
all_builds.py
#!/usr/bin/python import getopt import subprocess import sys LONG_OPTIONS = ["shard=", "shards="] BASE_COMMAND = "./configure --enable-internal-stats --enable-experimental" def RunCommand(command): run = subprocess.Popen(command, shell=True) output = run.communicate() if run.returncode: print "Non-zero return code: " + str(run.returncode) + " => exiting!" sys.exit(1) def list_of_experiments(): experiments = [] configure_file = open("configure") list_start = False for line in configure_file.read().split("\n"): if line == 'EXPERIMENT_LIST="': list_start = True elif line == '"': list_start = False elif list_start: currently_broken = ["csm"] experiment = line[4:] if experiment not in currently_broken: experiments.append(experiment) return experiments def main(argv): # Parse arguments options = {"--shard": 0, "--shards": 1} o, _ = getopt.getopt(argv[1:], None, LONG_OPTIONS) options.update(o) # Shard experiment list shard = int(options["--shard"]) shards = int(options["--shards"]) experiments = list_of_experiments() configs = [BASE_COMMAND] configs += ["%s --enable-%s" % (BASE_COMMAND, e) for e in experiments] my_configs = zip(configs, range(len(configs))) my_configs = filter(lambda x: x[1] % shards == shard, my_configs) my_configs = [e[0] for e in my_configs] # Run configs for this shard for config in my_configs: test_build(config) def test_build(configure_command): print "\033[34m\033[47mTesting %s\033[0m" % (configure_command) RunCommand(configure_command) RunCommand("make clean") RunCommand("make") if __name__ == "__main__": main(sys.argv)
#!/usr/bin/python import subprocess import sys def RunCommand(command): run = subprocess.Popen(command, shell=True) output = run.communicate() if run.returncode: print "Non-zero return code: " + str(run.returncode) + " => exiting!" sys.exit(1) def list_of_experiments(): experiments = [] configure_file = open("configure") list_start = False for line in configure_file.read().split("\n"): if line == 'EXPERIMENT_LIST="': list_start = True elif line == '"': list_start = False elif list_start: currently_broken = ["csm"] experiment = line[4:] if experiment not in currently_broken: experiments.append(experiment) return experiments def main(): base_command = "./configure --enable-internal-stats" test_build(base_command) for experiment_name in list_of_experiments(): test_build("%s --enable-experimental --enable-%s" % (base_command, experiment_name)) def test_build(configure_command): print "\033[34m\033[47mTesting %s\033[0m" % (configure_command) RunCommand(configure_command) RunCommand("make clean") RunCommand("make") if __name__ == "__main__": main()
bsd-2-clause
Python
8976837f144bcc46ce3b0ae1f2a0ba3a75604d18
Fix __init__.py
kowito/bluesnap-python,justyoyo/bluesnap-python,kowito/bluesnap-python,justyoyo/bluesnap-python
bluesnap/__init__.py
bluesnap/__init__.py
from __future__ import absolute_import __all__ = ['constants', 'client', 'exceptions', 'models', 'resources', 'version'] from . import constants, client, exceptions, models, resources, version
from __future__ import absolute_import
mit
Python
8fff587b9fd7e2cd0ca4d45e869345cbfb248045
Add encryption properties to Workspace
7digital/troposphere,dmm92/troposphere,horacio3/troposphere,ikben/troposphere,alonsodomin/troposphere,pas256/troposphere,cloudtools/troposphere,dmm92/troposphere,ikben/troposphere,Yipit/troposphere,cloudtools/troposphere,johnctitus/troposphere,amosshapira/troposphere,johnctitus/troposphere,pas256/troposphere,alonsodomin/troposphere,7digital/troposphere,craigbruce/troposphere,horacio3/troposphere
troposphere/workspaces.py
troposphere/workspaces.py
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), 'RootVolumeEncryptionEnabled': (boolean, False), 'UserVolumeEncryptionEnabled': (boolean, False), 'VolumeEncryptionKey': (basestring, False), }
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), }
bsd-2-clause
Python
b4e106271f96b083644b27d313ad80c240fcb0a5
Add agency chain to Booking
gadventures/gapipy
gapipy/resources/booking/booking.py
gapipy/resources/booking/booking.py
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agent', 'Agent'), ('agency', 'Agency'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
mit
Python
893f5c5b33c833a5b497caa69f72af2285f5b81c
Bump version
dimagi/loveseat
loveseat/__init__.py
loveseat/__init__.py
__author__ = 'Dimagi' __version__ = '0.0.6' __licence__ = 'MIT'
__author__ = 'Dimagi' __version__ = '0.0.5' __licence__ = 'MIT'
mit
Python
e01426579813507880d7a415b3f9f11cd3dceb2c
Add error to possible results
ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec
benchexec/tools/infer.py
benchexec/tools/infer.py
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.tools.template from collections.abc import Mapping import benchexec.result as result class Tool(benchexec.tools.template.BaseTool2): """ Tool info for Infer with a wrapper for usage in the SVCOMP. URL: https://fbinfer.com/ """ REQUIRED_PATHS = ["."] def executable(self, tool_locator): return tool_locator.find_executable("infer-sv.py") def version(self, executable): return self._version_from_tool(executable) def name(self): return "infer-sv" def cmdline(self, executable, options, task, rlimits): cmd = [executable, "--program"] + list(task.input_files) if task.property_file: cmd += ["--property", task.property_file] if isinstance(task.options, Mapping) and "data_model" in task.options: cmd += ["--datamodel", task.options["data_model"]] return cmd def determine_result(self, run): run_result = run.output[-1].split(":", maxsplit=2)[-1] if run_result == "true": return result.RESULT_TRUE_PROP if run_result == "false": return result.RESULT_FALSE_PROP if run_result == "error": return result.RESULT_ERROR return result.RESULT_UNKNOWN
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 import benchexec.tools.template from collections.abc import Mapping import benchexec.result as result class Tool(benchexec.tools.template.BaseTool2): """ Tool info for Infer with a wrapper for usage in the SVCOMP. URL: https://fbinfer.com/ """ REQUIRED_PATHS = ["."] def executable(self, tool_locator): return tool_locator.find_executable("infer-sv.py") def version(self, executable): return self._version_from_tool(executable) def name(self): return "infer-sv" def cmdline(self, executable, options, task, rlimits): cmd = [executable, "--program"] + list(task.input_files) if task.property_file: cmd += ["--property", task.property_file] if isinstance(task.options, Mapping) and "data_model" in task.options: cmd += ["--datamodel", task.options["data_model"]] return cmd def determine_result(self, run): run_result = run.output[-1].split(":", maxsplit=2)[-1] if run_result == "true": return result.RESULT_TRUE_PROP if run_result == "false": return result.RESULT_FALSE_PROP return result.RESULT_UNKNOWN
apache-2.0
Python
4702b1d3ee912676f4bd8ca0032f368573c81210
add sorting to benchmark
numerai/submission-criteria,numerai/submission-criteria
benchmark_originality.py
benchmark_originality.py
import time import statistics import os import numpy as np import randomstate as rnd from multiprocessing import Pool from originality import original N_RUNS = 50 def gen_submission(predictions=45000, users=1000): # numpy's RandomSeed don't play well with multiprocessing; randomstate is a drop-in replacement return rnd.normal(loc=0.5, scale=0.1, size=(predictions, users)) def check_original(new_submission, other_submissions): t0 = time.time() n_predictions = new_submission.shape[0] sorted_submission = np.sort(new_submission.reshape(n_predictions,)) for i in range(other_submissions.shape[1]): original(sorted_submission, other_submissions[:, i]) t1 = time.time() return (t1 - t0) * 1000 def run_benchmark(): # try to use half the available cores to avoid shaky medians per run caused by cpu usage from other processes pool_size = os.cpu_count() or 1 if pool_size > 1: pool_size = pool_size//2 new_submission = gen_submission(users=1) other_submissions = gen_submission(users=1000) with Pool(pool_size) as pool: times = pool.starmap(check_original, [(new_submission, other_submissions) for _ in range(N_RUNS)]) print('ran method %s times' % len(times)) print('median: %.2fms' % statistics.median(times)) print('mean: %.2fms' % statistics.mean(times)) print('stdev: %.2f' % statistics.stdev(times)) if __name__ == '__main__': run_benchmark()
import time import statistics import os import randomstate as rnd from multiprocessing import Pool from originality import original N_RUNS = 50 def gen_submission(predictions=45000, users=1000): # numpy's RandomSeed don't play well with multiprocessing; randomstate is a drop-in replacement return rnd.normal(loc=0.5, scale=0.1, size=(predictions, users)) def check_original(new_submission, other_submissions): t0 = time.time() n_predictions = new_submission.shape[0] for i in range(other_submissions.shape[1]): original(new_submission.reshape(n_predictions,), other_submissions[:, i]) t1 = time.time() return (t1 - t0) * 1000 def run_benchmark(): # try to use half the available cores to avoid shaky medians per run caused by cpu usage from other processes pool_size = os.cpu_count() or 1 if pool_size > 1: pool_size = pool_size//2 new_submission = gen_submission(users=1) other_submissions = gen_submission(users=1000) with Pool(pool_size) as pool: times = pool.starmap(check_original, [(new_submission, other_submissions) for _ in range(N_RUNS)]) print('ran method %s times' % len(times)) print('median: %.2fms' % statistics.median(times)) print('mean: %.2fms' % statistics.mean(times)) print('stdev: %.2f' % statistics.stdev(times)) if __name__ == '__main__': run_benchmark()
apache-2.0
Python
57db503feed5321cfa6635c86629d3f0c9fc276d
Fix python 3 support
alexmojaki/flower,getupcloud/flower,ChinaQuants/flower,pj/flower,asmodehn/flower,tellapart/flower,pj/flower,asmodehn/flower,pygeek/flower,pygeek/flower,allengaller/flower,pj/flower,Lingling7/flower,marrybird/flower,getupcloud/flower,raphaelmerx/flower,lucius-feng/flower,asmodehn/flower,barseghyanartur/flower,barseghyanartur/flower,ChinaQuants/flower,marrybird/flower,ucb-bar/bar-crawl-web,allengaller/flower,jzhou77/flower,Lingling7/flower,alexmojaki/flower,alexmojaki/flower,lucius-feng/flower,tellapart/flower,marrybird/flower,ChinaQuants/flower,barseghyanartur/flower,Lingling7/flower,jzhou77/flower,getupcloud/flower,tellapart/flower,allengaller/flower,ucb-bar/bar-crawl-web,pygeek/flower,jzhou77/flower,ucb-bar/bar-crawl-web,raphaelmerx/flower,lucius-feng/flower,raphaelmerx/flower
flower/views/tasks.py
flower/views/tasks.py
from __future__ import absolute_import import copy try: from itertools import imap except ImportError: imap = map import celery from tornado import web from ..views import BaseHandler from ..utils.tasks import iter_tasks, get_task_by_id class TaskView(BaseHandler): @web.authenticated def get(self, task_id): task = get_task_by_id(self.application, task_id) if task is None: raise web.HTTPError(404, "Unknown task '%s'" % task_id) self.render("task.html", task=task) class TasksView(BaseHandler): @web.authenticated def get(self): app = self.application limit = self.get_argument('limit', default=None, type=int) worker = self.get_argument('worker', None) type = self.get_argument('type', None) state = self.get_argument('state', None) worker = worker if worker != 'All' else None type = type if type != 'All' else None state = state if state != 'All' else None tasks = iter_tasks(app, limit=limit, type=type, worker=worker, state=state) tasks = imap(self.format_task, tasks) workers = app.events.state.workers seen_task_types = app.events.state.task_types() time = 'natural-time' if app.natural_time else 'time' self.render("tasks.html", tasks=tasks, task_types=seen_task_types, all_states=celery.states.ALL_STATES, workers=workers, limit=limit, worker=worker, type=type, state=state, time=time) def format_task(self, args): uuid, task = args custom_format_task = self.application.format_task if custom_format_task: task = custom_format_task(copy.copy(task)) return uuid, task
from __future__ import absolute_import import copy from itertools import imap import celery from tornado import web from ..views import BaseHandler from ..utils.tasks import iter_tasks, get_task_by_id class TaskView(BaseHandler): @web.authenticated def get(self, task_id): task = get_task_by_id(self.application, task_id) if task is None: raise web.HTTPError(404, "Unknown task '%s'" % task_id) self.render("task.html", task=task) class TasksView(BaseHandler): @web.authenticated def get(self): app = self.application limit = self.get_argument('limit', default=None, type=int) worker = self.get_argument('worker', None) type = self.get_argument('type', None) state = self.get_argument('state', None) worker = worker if worker != 'All' else None type = type if type != 'All' else None state = state if state != 'All' else None tasks = iter_tasks(app, limit=limit, type=type, worker=worker, state=state) tasks = imap(self.format_task, tasks) workers = app.events.state.workers seen_task_types = app.events.state.task_types() time = 'natural-time' if app.natural_time else 'time' self.render("tasks.html", tasks=tasks, task_types=seen_task_types, all_states=celery.states.ALL_STATES, workers=workers, limit=limit, worker=worker, type=type, state=state, time=time) def format_task(self, args): uuid, task = args custom_format_task = self.application.format_task if custom_format_task: task = custom_format_task(copy.copy(task)) return uuid, task
bsd-3-clause
Python
2767e954c160682aed5e0dd46b7430ac0825a2a7
Clean geometry of access level before returning
OpenChemistry/mongochemserver
girder/molecules/server/geometry.py
girder/molecules/server/geometry.py
from girder.api.describe import Description, autoDescribeRoute from girder.api import access from girder.api.rest import Resource from girder.api.rest import RestException from girder.api.rest import getCurrentUser from girder.constants import AccessType from girder.constants import TokenScope from .models.geometry import Geometry as GeometryModel class Geometry(Resource): def __init__(self): super(Geometry, self).__init__() self.resourceName = 'geometry' self.route('GET', (), self.find_geometries) self.route('POST', (), self.create) self.route('DELETE', (':id',), self.delete) self._model = GeometryModel() def _clean(self, doc): if 'access' in doc: del doc['access'] return doc @access.public @autoDescribeRoute( Description('Find geometries of a given molecule.') .param('moleculeId', 'The id of the parent molecule.') ) def find_geometries(self, params): user = getCurrentUser() moleculeId = params['moleculeId'] geometries = self._model.find_geometries(moleculeId) # Filter based upon access level. return [self._clean(self._model.filter(x, user)) for x in geometries] @access.user(scope=TokenScope.DATA_WRITE) @autoDescribeRoute( Description('Create a geometry.') .param('moleculeId', 'The id of the parent molecule.') .jsonParam('cjson', 'The chemical json of the geometry.') ) def create(self, params): self.requireParams(['moleculeId', 'cjson'], params) user = getCurrentUser() moleculeId = params['moleculeId'] cjson = params['cjson'] return self._clean(self._model.create(user, moleculeId, cjson, 'user', user['_id'])) @access.user(scope=TokenScope.DATA_WRITE) @autoDescribeRoute( Description('Delete a geometry.') .param('id', 'The id of the geometry to be deleted.') .errorResponse('Geometry not found.', 404) ) def delete(self, id): user = self.getCurrentUser() geometry = GeometryModel().load(id, user=user, level=AccessType.WRITE) if not geometry: raise RestException('Geometry not found.', code=404) return GeometryModel().remove(geometry)
from girder.api.describe import Description, autoDescribeRoute from girder.api import access from girder.api.rest import Resource from girder.api.rest import RestException from girder.api.rest import getCurrentUser from girder.constants import AccessType from girder.constants import TokenScope from .models.geometry import Geometry as GeometryModel class Geometry(Resource): def __init__(self): super(Geometry, self).__init__() self.resourceName = 'geometry' self.route('GET', (), self.find_geometries) self.route('POST', (), self.create) self.route('DELETE', (':id',), self.delete) self._model = GeometryModel() @access.public @autoDescribeRoute( Description('Find geometries of a given molecule.') .param('moleculeId', 'The id of the parent molecule.') ) def find_geometries(self, params): user = getCurrentUser() moleculeId = params['moleculeId'] geometries = self._model.find_geometries(moleculeId) # Filter based upon access level. return [self._model.filter(x, user) for x in geometries] @access.user(scope=TokenScope.DATA_WRITE) @autoDescribeRoute( Description('Create a geometry.') .param('moleculeId', 'The id of the parent molecule.') .jsonParam('cjson', 'The chemical json of the geometry.') ) def create(self, params): self.requireParams(['moleculeId', 'cjson'], params) user = getCurrentUser() moleculeId = params['moleculeId'] cjson = params['cjson'] return self._model.create(moleculeId, cjson, 'user', user['_id']) @access.user(scope=TokenScope.DATA_WRITE) @autoDescribeRoute( Description('Delete a geometry.') .param('id', 'The id of the geometry to be deleted.') .errorResponse('Geometry not found.', 404) ) def delete(self, id): user = self.getCurrentUser() geometry = GeometryModel().load(id, user=user, level=AccessType.WRITE) if not geometry: raise RestException('Geometry not found.', code=404) return GeometryModel().remove(geometry)
bsd-3-clause
Python
81a905e4626cbcaf887813fddea686f9ae61ce6f
Fix version number
adamchainz/freezegun,spulec/freezegun,Sun77789/freezegun,Affirm/freezegun
freezegun/__init__.py
freezegun/__init__.py
# -*- coding: utf-8 -*- """ freezegun ~~~~~~~~ :copyright: (c) 2012 by Steve Pulec. """ __title__ = 'freezegun' __version__ = '0.1.17' __author__ = 'Steve Pulec' __license__ = 'Apache License 2.0' __copyright__ = 'Copyright 2012 Steve Pulec' from .api import freeze_time __all__ = ["freeze_time"]
# -*- coding: utf-8 -*- """ freezegun ~~~~~~~~ :copyright: (c) 2012 by Steve Pulec. """ __title__ = 'freezegun' __version__ = '0.1.16' __author__ = 'Steve Pulec' __license__ = 'Apache License 2.0' __copyright__ = 'Copyright 2012 Steve Pulec' from .api import freeze_time __all__ = ["freeze_time"]
apache-2.0
Python
b9b1374f6c4076cb2444f45333c203124668f970
Add test to improve coverage
jni/skan
skan/test/test_draw.py
skan/test/test_draw.py
""" Basic testing of the draw module. This just ensures the functions don't crash. Testing plotting is hard. ;) """ import os import numpy as np from skimage import io, morphology import matplotlib.pyplot as plt from matplotlib.figure import Figure import pytest from skan import pre, draw, csr rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') @pytest.fixture def test_image(): image = io.imread(os.path.join(datadir, 'skeleton.tif')) return image @pytest.fixture def test_thresholded(test_image): thresholded = pre.threshold(test_image, sigma=2, radius=31, offset=0.075) return thresholded @pytest.fixture def test_skeleton(test_thresholded): skeleton = morphology.skeletonize(test_thresholded) return skeleton @pytest.fixture def test_stats(test_skeleton): stats = csr.summarise(test_skeleton) return stats def test_overlay_skeleton(test_image, test_skeleton): draw.overlay_skeleton_2d(test_image, test_skeleton) draw.overlay_skeleton_2d(test_image, test_skeleton, image_cmap='viridis') def test_overlay_euclidean_skeleton(test_image, test_stats): draw.overlay_euclidean_skeleton_2d(test_image, test_stats) draw.overlay_euclidean_skeleton_2d(test_image, test_stats, skeleton_color_source='branch-distance') def test_pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats): draw.pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats) def test_pipeline_plot_existing_fig(test_image, test_thresholded, test_skeleton, test_stats): fig = Figure() draw.pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats, figure=fig) fig, axes = plt.subplots(2, 2, sharex=True, sharey=True) draw.pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats, figure=fig, axes=np.ravel(axes))
""" Basic testing of the draw module. This just ensures the functions don't crash. Testing plotting is hard. ;) """ import os from skimage import io, morphology import pytest from skan import pre, draw, csr rundir = os.path.abspath(os.path.dirname(__file__)) datadir = os.path.join(rundir, 'data') @pytest.fixture def test_image(): image = io.imread(os.path.join(datadir, 'skeleton.tif')) return image @pytest.fixture def test_thresholded(test_image): thresholded = pre.threshold(test_image, sigma=2, radius=31, offset=0.075) return thresholded @pytest.fixture def test_skeleton(test_thresholded): skeleton = morphology.skeletonize(test_thresholded) return skeleton @pytest.fixture def test_stats(test_skeleton): stats = csr.summarise(test_skeleton) return stats def test_overlay_skeleton(test_image, test_skeleton): draw.overlay_skeleton_2d(test_image, test_skeleton) draw.overlay_skeleton_2d(test_image, test_skeleton, image_cmap='viridis') def test_overlay_euclidean_skeleton(test_image, test_stats): draw.overlay_euclidean_skeleton_2d(test_image, test_stats) draw.overlay_euclidean_skeleton_2d(test_image, test_stats, skeleton_color_source='branch-distance') def test_pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats): draw.pipeline_plot(test_image, test_thresholded, test_skeleton, test_stats)
bsd-3-clause
Python
04398c4f91e5ceae83d4efec46f918949129867e
add timer
poweredbygrow/backup_gitlab.com
backup_gitlab.py
backup_gitlab.py
#!/usr/bin/env python3 import os import requests import shutil import subprocess import sys import time import conf def clean(dir_to_clean): if os.path.isdir(dir_to_clean): shutil.rmtree(dir_to_clean) def run(cmd): print("running", ' '.join(cmd)) subprocess.check_call(cmd) def get_projects(): params = {'private_token': conf.private_token, 'membership': 'yes', 'per_page': 100} r = requests.get('https://gitlab.com/api/v4/projects', params=params) projects = r.json() os.makedirs(conf.backup_dir, exist_ok=True) os.chdir(conf.backup_dir) return projects def mirror_git_repo(http_url, repo_dir): try: run(['git', 'clone', '--mirror', http_url]) except KeyboardInterrupt: clean(repo_dir) sys.exit(1) except Exception: clean(repo_dir) def update_git_repo(repo_dir): try: old_dir = os.getcwd() os.chdir(repo_dir) run(['git', 'remote', 'update']) finally: os.chdir(old_dir) def backup_gitlab(): start = time.time() for project in get_projects(): print('*'*80) web_url = project['web_url'] print(web_url) http_url = project['ssh_url_to_repo'] # Remove the entire url except the last part which is # what the mirrored directory will be called repo_dir = http_url.split('/')[-1] if os.path.isdir(repo_dir): update_git_repo(repo_dir) else: mirror_git_repo(http_url, repo_dir) end = time.time() print('took: ', end-start, 's') def main(): backup_gitlab() if __name__ == '__main__': main()
#!/usr/bin/env python3 import os import requests import shutil import subprocess import sys import conf def clean(dir_to_clean): if os.path.isdir(dir_to_clean): shutil.rmtree(dir_to_clean) def run(cmd): print("running", ' '.join(cmd)) subprocess.check_call(cmd) def get_projects(): params = {'private_token': conf.private_token, 'membership': 'yes', 'per_page': 100} r = requests.get('https://gitlab.com/api/v4/projects', params=params) projects = r.json() os.makedirs(conf.backup_dir, exist_ok=True) os.chdir(conf.backup_dir) return projects def mirror_git_repo(http_url, repo_dir): try: run(['git', 'clone', '--mirror', http_url]) except KeyboardInterrupt: clean(repo_dir) sys.exit(1) except Exception: clean(repo_dir) def update_git_repo(repo_dir): try: old_dir = os.getcwd() os.chdir(repo_dir) run(['git', 'remote', 'update']) finally: os.chdir(old_dir) def backup_gitlab(): for project in get_projects(): print('*'*80) web_url = project['web_url'] print(web_url) http_url = project['ssh_url_to_repo'] # Remove the entire url except the last part which is # what the mirrored directory will be called repo_dir = http_url.split('/')[-1] if os.path.isdir(repo_dir): update_git_repo(repo_dir) else: mirror_git_repo(http_url, repo_dir) def main(): backup_gitlab() if __name__ == '__main__': main()
apache-2.0
Python
9a60a053ae59b255817839be75b7f3481839ce3e
Update cron
Soaring-Outliers/news_graph,Soaring-Outliers/news_graph,Soaring-Outliers/news_graph,Soaring-Outliers/news_graph
graph/management/commands/filldb.py
graph/management/commands/filldb.py
from django.core.management.base import BaseCommand, CommandError from graph.models import Website class Command(BaseCommand): help = 'Fill database by retrieving articles and concepts' def handle(self, *args, **options): for website in Website.objects.all(): print(website.name) website.download_rss_articles()
from django.core.management.base import BaseCommand, CommandError from graph.models import Website class Command(BaseCommand): help = 'Fill database by retrieving articles and concepts' def handle(self, *args, **options): for website in Website.objects.all(): website.download_rss_articles()
mit
Python
ed1172479388c302356af093f6dd855cab61f914
Update hipchat.py
ViaSat/graphite-beacon,gcochard/graphite-beacon,ViaSat/graphite-beacon,ViaSat/graphite-beacon,gcochard/graphite-beacon,gcochard/graphite-beacon
graphite_beacon/handlers/hipchat.py
graphite_beacon/handlers/hipchat.py
import json from tornado import gen, httpclient as hc from . import AbstractHandler, LOGGER class HipChatHandler(AbstractHandler): name = 'hipchat' # Default options defaults = { 'url': 'https://api.hipchat.com', 'room': None, 'key': None, } colors = { 'critical': 'red', 'warning': 'yellow', 'normal': 'green', } def init_handler(self): self.room = self.options.get('room') self.key = self.options.get('key') assert self.room, 'Hipchat room is not defined.' assert self.key, 'Hipchat key is not defined.' self.client = hc.AsyncHTTPClient() @gen.coroutine def notify(self, level, *args, **kwargs): LOGGER.debug("Handler (%s) %s", self.name, level) data = { 'message': self.get_short(level, *args, **kwargs).decode('UTF-8'), 'notify': True, 'color': self.colors.get(level, 'gray'), 'message_format': 'text', } yield self.client.fetch('{url}/v2/room/{room}/notification?auth_token={token}'.format( url=self.options.get('url'), room=self.room, token=self.key), headers={'Content-Type': 'application/json'}, method='POST', body=json.dumps(data))
import json from tornado import gen, httpclient as hc from . import AbstractHandler, LOGGER class HipChatHandler(AbstractHandler): name = 'hipchat' # Default options defaults = { 'url': 'https://api.hipchat.com', 'room': None, 'key': None, } colors = { 'critical': 'red', 'warning': 'yellow', 'normal': 'green', } def init_handler(self): self.room = self.options.get('room') self.key = self.options.get('key') assert self.room, 'Hipchat room is not defined.' assert self.key, 'Hipchat key is not defined.' self.client = hc.AsyncHTTPClient() @gen.coroutine def notify(self, level, *args, **kwargs): LOGGER.debug("Handler (%s) %s", self.name, level) data = { 'message': self.get_short(level, *args, **kwargs).decode('UTF-8'), 'notify': True, 'color': self.colors.get(level, 'gray'), 'message_format': 'text', } yield self.client.fetch('{url}/v2/room/{room}/notification?auth_token={token}'.format( url=self.options.url, room=self.room, token=self.key), headers={'Content-Type': 'application/json'}, method='POST', body=json.dumps(data))
mit
Python