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 |
|---|---|---|---|---|---|---|---|---|
nwjs/chromium.src | third_party/mako/mako/ast.py | Python | bsd-3-clause | 6,789 | 0 | # mako/ast.py
# Copyright 2006-2020 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST nodes"""
import re
from mako import compat
from mako import exceptions
from mako import pyparser
class PythonCode(object):
"""represents information about a string containing Python code"""
def __init__(self, code, **exception_kwargs):
self.code = code
# represents all identifiers which are assigned to at some point in
# the code
self.declared_identifiers = set()
# represents all identifiers which are referenced before their
# assignment, if any
self.undeclared_identifiers = set()
# note that an identifier can be in both the undeclared and declared
# lists.
# using AST to parse instead of using code.co_varnames,
# code.co_names has several advantages:
# - we can locate an identifier as "undeclared" even if
# its declared later in the same block of code
# - AST is less likely to break with version changes
# (for example, the behavior of co_names changed a little bit
# in python version 2.5)
if isinstance(code, compat.string_types):
expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
else:
expr = code
f = pyparser.FindIdentifiers(self, **exception_kwargs)
f.visit(expr)
class ArgumentList(object):
"""parses a fragment of code as a comma-separated list of expressions"""
def __init__(self, code, **exception_kwargs):
self.codeargs = []
self.args = []
self.declared_identifiers = set()
self.undeclared_identifiers = set()
if isinstance(code, compat.string_types):
if re.match(r"\S", code) and not re.match(r",\s*$", code):
# if theres text and no trailing comma, insure its parsed
# as a tuple by adding a trailing comma
code += ","
expr = pyparser.parse(code, "exec", **exception_kwargs)
else:
expr = code
f = pyparser.FindTuple(self, PythonCode, **exception_kwargs)
f.visit(expr)
class PythonFragment(PythonCode):
"""extends PythonCode to provide identifier lookups in partial control
statements
e.g.::
for x in 5:
elif y==9:
except (MyException, e):
"""
def __init__(self, code, **exception_kwargs):
m = re.match(r"^(\w+)(?:\s+(.*?))?:\s*(#|$)", code.strip(), re.S)
if not m:
raise exceptions.CompileException(
"Fragment '%s' is not a partial control statement" % code,
**exception_kwargs
)
if m.group(3):
code = code[: m.start(3)]
(keyword, expr) = m.group(1, 2)
if keyword in ["for", "if", "while"]:
code = code + "pass"
elif keyword == "try":
code = code + "pass\nexcept:pass"
elif keyword == "elif" or keyword == "else":
code = "if False:pass\n" + code + "pass"
elif keyword == "except":
code = "try:pass\n" + code + "pass"
elif keyword == "with":
code = code + "pass"
else:
raise exceptions.CompileException(
"Unsupported control keyword: '%s'" % keyword,
**exception_kwargs
)
super(PythonFragment, self).__init__(code, **exception_kwargs)
class FunctionDecl(object):
"""function declaration"""
def __init__(self, code, allow_kwargs=True, **exception_kwargs):
self.code = code
expr = pyparser.parse(code, "exec", **exception_kwargs)
f = pyparser.ParseFunc(self, **exception_kwargs)
f.visit(expr)
if not hasattr(self, "funcname"):
raise exceptions.CompileException(
"Code '%s' is not a function declaration" % code,
**exception_kwargs
)
if not allow_kwargs and self.kwargs:
raise exceptions.CompileException(
"'**%s' keyword argument not allowed here"
% self.kwargnames[- | 1],
**exception_kwargs
)
def get_argument_expressions(self, as_call=False):
"""Return the argument declarati | ons of this FunctionDecl as a printable
list.
By default the return value is appropriate for writing in a ``def``;
set `as_call` to true to build arguments to be passed to the function
instead (assuming locals with the same names as the arguments exist).
"""
namedecls = []
# Build in reverse order, since defaults and slurpy args come last
argnames = self.argnames[::-1]
kwargnames = self.kwargnames[::-1]
defaults = self.defaults[::-1]
kwdefaults = self.kwdefaults[::-1]
# Named arguments
if self.kwargs:
namedecls.append("**" + kwargnames.pop(0))
for name in kwargnames:
# Keyword-only arguments must always be used by name, so even if
# this is a call, print out `foo=foo`
if as_call:
namedecls.append("%s=%s" % (name, name))
elif kwdefaults:
default = kwdefaults.pop(0)
if default is None:
# The AST always gives kwargs a default, since you can do
# `def foo(*, a=1, b, c=3)`
namedecls.append(name)
else:
namedecls.append(
"%s=%s"
% (name, pyparser.ExpressionGenerator(default).value())
)
else:
namedecls.append(name)
# Positional arguments
if self.varargs:
namedecls.append("*" + argnames.pop(0))
for name in argnames:
if as_call or not defaults:
namedecls.append(name)
else:
default = defaults.pop(0)
namedecls.append(
"%s=%s"
% (name, pyparser.ExpressionGenerator(default).value())
)
namedecls.reverse()
return namedecls
@property
def allargnames(self):
return tuple(self.argnames) + tuple(self.kwargnames)
class FunctionArgs(FunctionDecl):
"""the argument portion of a function declaration"""
def __init__(self, code, **kwargs):
super(FunctionArgs, self).__init__(
"def ANON(%s):pass" % code, **kwargs
)
|
MrZigler/UnderdogMilitia | charactors.py | Python | gpl-3.0 | 628 | 0.025478 |
import random
class Livingbeing():
def __init__(self, name, health, armor, mindset, emotion, skills, inventory):
self.name = name
self.health = he | alth
self.armor = armor
self.mindset = mindset
self.emotion = emotion
self.skills = skills
self.inventory = inventory
self | .hunger = random.randrange(1, 5)
self.thirst = 0
def takeDamage(self, dmgAmount):
if dmgAmount > self.armor:
self.health = self.health - (dmgAmount - self.armor)
quit()
|
lukas-hetzenecker/home-assistant | tests/components/api/test_init.py | Python | apache-2.0 | 18,138 | 0.001103 | """The tests for the Home Assistant API component."""
# pylint: disable=protected-access
import json
from unittest.mock import patch
from aiohttp import web
import pytest
import voluptuous as vol
from homeassistant import const
from homeassistant.bootstrap import DATA_LOGGING
import homeassistant.core as ha
from homeassistant.setup import async_setup_component
from tests.common import async_mock_service
@pytest.fixture
def mock_api_client(hass, hass_client):
"""Start the Home Assistant HTTP component and return admin API client."""
hass.loop.run_until_complete(async_setup_component(hass, "api", {}))
return hass.loop.run_until_complete(hass_client())
async def test_api_list_state_entities(hass, mock_api_client):
"""Test if the debug interface allows us to list state entities."""
hass.states.async_set("test.entity", "hello")
resp = await mock_api_client.get(const.URL_API_STATES)
assert resp.status == 200
json = await resp.json()
remote_data = [ha.State.from_dict(item) for item in json]
assert remote_data == hass.states.async_all()
async def test_api_get_state(hass, mock_api_client):
"""Test if the debug interface allows us to get a state."""
hass.states.async_set("hello.world", "nice", {"attr": 1})
resp = await mock_api_client.get("/api/states/hello.world")
assert resp.status == 200
json = await resp.json()
data = ha.State.from_dict(json)
state = hass.states.get("hello.world")
assert data.state == state.state
assert data.last_changed == state.last_changed
assert data.attributes == state.attributes
async def test_api_get_non_existing_state(hass, mock_api_client):
"""Test if the debug interface allows us to get a state."""
resp = await mock_api_client.get("/api/states/does_not_exist")
assert resp.status == const.HTTP_NOT_FOUND
async def test_api_state_change(hass, mock_api_client):
"""Test if we can change the state of an entity that exists."""
hass.states.async_set("test.test", "not_to_be_set")
await mock_api_client.post(
"/api/states/test.test", json={"state": "debug_state_change2"}
)
assert hass.states.get("test.test").state == "debug_state_change2"
# pylint: disable=invalid-name
async def test_api_state_change_of_non_existing_entity(hass, mock_api_client):
"""Test if changing a state of a non existing entity is possible."""
new_state = "debug_state_change"
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={"state": new_state}
)
assert resp.status == 201
assert hass.states.get( | "test_entity.that_does_not_exist").state == new_state
# pylint: disable=invalid-name
async def test_api_state_change_with_bad_data(hass, mock_api_client):
"""Test i | f API sends appropriate error if we omit state."""
resp = await mock_api_client.post(
"/api/states/test_entity.that_does_not_exist", json={}
)
assert resp.status == 400
# pylint: disable=invalid-name
async def test_api_state_change_to_zero_value(hass, mock_api_client):
"""Test if changing a state to a zero value is possible."""
resp = await mock_api_client.post(
"/api/states/test_entity.with_zero_state", json={"state": 0}
)
assert resp.status == 201
resp = await mock_api_client.post(
"/api/states/test_entity.with_zero_state", json={"state": 0.0}
)
assert resp.status == 200
# pylint: disable=invalid-name
async def test_api_state_change_push(hass, mock_api_client):
"""Test if we can push a change the state of an entity."""
hass.states.async_set("test.test", "not_to_be_set")
events = []
@ha.callback
def event_listener(event):
"""Track events."""
events.append(event)
hass.bus.async_listen(const.EVENT_STATE_CHANGED, event_listener)
await mock_api_client.post("/api/states/test.test", json={"state": "not_to_be_set"})
await hass.async_block_till_done()
assert len(events) == 0
await mock_api_client.post(
"/api/states/test.test", json={"state": "not_to_be_set", "force_update": True}
)
await hass.async_block_till_done()
assert len(events) == 1
# pylint: disable=invalid-name
async def test_api_fire_event_with_no_data(hass, mock_api_client):
"""Test if the API allows us to fire an event."""
test_value = []
@ha.callback
def listener(event):
"""Record that our event got called."""
test_value.append(1)
hass.bus.async_listen_once("test.event_no_data", listener)
await mock_api_client.post("/api/events/test.event_no_data")
await hass.async_block_till_done()
assert len(test_value) == 1
# pylint: disable=invalid-name
async def test_api_fire_event_with_data(hass, mock_api_client):
"""Test if the API allows us to fire an event."""
test_value = []
@ha.callback
def listener(event):
"""Record that our event got called.
Also test if our data came through.
"""
if "test" in event.data:
test_value.append(1)
hass.bus.async_listen_once("test_event_with_data", listener)
await mock_api_client.post("/api/events/test_event_with_data", json={"test": 1})
await hass.async_block_till_done()
assert len(test_value) == 1
# pylint: disable=invalid-name
async def test_api_fire_event_with_invalid_json(hass, mock_api_client):
"""Test if the API allows us to fire an event."""
test_value = []
@ha.callback
def listener(event):
"""Record that our event got called."""
test_value.append(1)
hass.bus.async_listen_once("test_event_bad_data", listener)
resp = await mock_api_client.post(
"/api/events/test_event_bad_data", data=json.dumps("not an object")
)
await hass.async_block_till_done()
assert resp.status == 400
assert len(test_value) == 0
# Try now with valid but unusable JSON
resp = await mock_api_client.post(
"/api/events/test_event_bad_data", data=json.dumps([1, 2, 3])
)
await hass.async_block_till_done()
assert resp.status == 400
assert len(test_value) == 0
async def test_api_get_config(hass, mock_api_client):
"""Test the return of the configuration."""
resp = await mock_api_client.get(const.URL_API_CONFIG)
result = await resp.json()
if "components" in result:
result["components"] = set(result["components"])
if "whitelist_external_dirs" in result:
result["whitelist_external_dirs"] = set(result["whitelist_external_dirs"])
if "allowlist_external_dirs" in result:
result["allowlist_external_dirs"] = set(result["allowlist_external_dirs"])
if "allowlist_external_urls" in result:
result["allowlist_external_urls"] = set(result["allowlist_external_urls"])
assert hass.config.as_dict() == result
async def test_api_get_components(hass, mock_api_client):
"""Test the return of the components."""
resp = await mock_api_client.get(const.URL_API_COMPONENTS)
result = await resp.json()
assert set(result) == hass.config.components
async def test_api_get_event_listeners(hass, mock_api_client):
"""Test if we can get the list of events being listened for."""
resp = await mock_api_client.get(const.URL_API_EVENTS)
data = await resp.json()
local = hass.bus.async_listeners()
for event in data:
assert local.pop(event["event"]) == event["listener_count"]
assert len(local) == 0
async def test_api_get_services(hass, mock_api_client):
"""Test if we can get a dict describing current services."""
resp = await mock_api_client.get(const.URL_API_SERVICES)
data = await resp.json()
local_services = hass.services.async_services()
for serv_domain in data:
local = local_services.pop(serv_domain["domain"])
assert serv_domain["services"] == local
async def test_api_call_service_no_data(hass, mock_api_client):
"""Test if the API allows us to call a service."""
test_value = []
@ha.callback
def listener(service_call):
"""Record that our service got called."""
test_value.append(1)
hass. |
ToonTownInfiniteRepo/ToontownInfinite | otp/friends/AvatarFriendsManager.py | Python | mit | 4,080 | 0.001471 | from direct.distributed.DistributedObjectGlobal import DistributedObjectGlobal
from direct.directnotify.DirectNotifyGlobal import directNotif | y
from otp.uberdog.RejectCode import RejectCode
from otp.otpbase import OTPGlobals
from otp.otpbase import OTPLocalizer
class AvatarFriendsManager(DistributedObjectGlobal):
notify = directNotify | .newCategory('AvatarFriendsManager')
def __init__(self, cr):
DistributedObjectGlobal.__init__(self, cr)
self.reset()
def reset(self):
self.avatarFriendsList = set()
self.avatarId2Info = {}
self.invitedAvatarsList = []
self.ignoredAvatarList = []
def addIgnore(self, avId):
if avId not in self.ignoredAvatarList:
self.ignoredAvatarList.append(avId)
base.cr.centralLogger.writeClientEvent('ignoring %s' % (avId,))
messenger.send('AvatarIgnoreChange')
def removeIgnore(self, avId):
if avId in self.ignoredAvatarList:
self.ignoredAvatarList.remove(avId)
base.cr.centralLogger.writeClientEvent('stopped ignoring %s' % (avId,))
messenger.send('AvatarIgnoreChange')
def checkIgnored(self, avId):
return avId and avId in self.ignoredAvatarList
def sendRequestInvite(self, avId):
self.notify.debugCall()
self.sendUpdate('requestInvite', [avId])
self.invitedAvatarsList.append(avId)
def sendRequestRemove(self, avId):
self.notify.debugCall()
self.sendUpdate('requestRemove', [avId])
if avId in self.invitedAvatarsList:
self.invitedAvatarsList.remove(avId)
def friendConsidering(self, avId):
self.notify.debugCall()
messenger.send(OTPGlobals.AvatarFriendConsideringEvent, [1, avId])
def invitationFrom(self, avId, avatarName):
self.notify.debugCall()
messenger.send(OTPGlobals.AvatarFriendInvitationEvent, [avId, avatarName])
def retractInvite(self, avId):
self.notify.debugCall()
messenger.send(OTPGlobals.AvatarFriendRetractInviteEvent, [avId])
if avId in self.invitedAvatarsList:
self.invitedAvatarsList.remove(avId)
def rejectInvite(self, avId, reason):
self.notify.debugCall()
messenger.send(OTPGlobals.AvatarFriendRejectInviteEvent, [avId, reason])
if avId in self.invitedAvatarsList:
self.invitedAvatarsList.remove(avId)
def rejectRemove(self, avId, reason):
self.notify.debugCall()
messenger.send(OTPGlobals.AvatarFriendRejectRemoveEvent, [avId, reason])
def updateAvatarFriend(self, avId, info):
if hasattr(info, 'avatarId') and not info.avatarId and avId:
info.avatarId = avId
if avId not in self.avatarFriendsList:
self.avatarFriendsList.add(avId)
self.avatarId2Info[avId] = info
messenger.send(OTPGlobals.AvatarFriendAddEvent, [avId, info])
if self.avatarId2Info[avId].onlineYesNo != info.onlineYesNo:
base.talkAssistant.receiveFriendUpdate(avId, info.getName(), info.onlineYesNo)
self.avatarId2Info[avId] = info
messenger.send(OTPGlobals.AvatarFriendUpdateEvent, [avId, info])
if avId in self.invitedAvatarsList:
self.invitedAvatarsList.remove(avId)
messenger.send(OTPGlobals.AvatarNewFriendAddEvent, [avId])
def removeAvatarFriend(self, avId):
self.avatarFriendsList.remove(avId)
self.avatarId2Info.pop(avId, None)
messenger.send(OTPGlobals.AvatarFriendRemoveEvent, [avId])
return
def setFriends(self, avatarIds):
self.notify.debugCall()
def isFriend(self, avId):
return self.isAvatarFriend(avId)
def isAvatarFriend(self, avId):
return avId in self.avatarFriendsList
def getFriendInfo(self, avId):
return self.avatarId2Info.get(avId)
def countTrueFriends(self):
count = 0
for id in self.avatarId2Info:
if self.avatarId2Info[id].openChatFriendshipYesNo:
count += 1
return count
|
potolock/proverca | test/test_add_group.py | Python | apache-2.0 | 690 | 0.017391 |
from model.group import Group
import pytest
def test_add_group(app, db, json_grou | ps):
group = json_groups
with pytest.allure.step('Given a group list'):
old_groups = db.get_group_list()
with pytest.allure.step('When I add a group %s to the list' % group):
app.group.create(group)
#assert len (old_groups) + 1 == app.group.count()
with pytes | t.allure.step('Then the new group list is equal to the old list with the added group'):
new_groups = db.get_group_list()
old_groups.append(group)
assert sorted (old_groups, key=Group.id_or_max ) == sorted (new_groups, key=Group.id_or_max)
|
oakeyc/azure-cli-shell | azclishell/az_completer.py | Python | mit | 14,854 | 0.001548 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals
from prompt_toolkit.completion import Completer, Completion
import azclishell.configuration
from azclishell.argfinder import ArgsFinder
from azclishell.command_tree import in_tree
from azclishell.layout import get_scope
from azclishell.util import parse_quotes
from azure.cli.core.parser import AzCliCommandParser
from azure.cli.core.util import CLIError
SELECT_SYMBOL = azclishell.configuration.SELECT_SYMBOL
def dynamic_param_ | logic(text):
""" validates parameter values for dynamic completion """
is_param = False
started_param = False
prefix = ""
param = ""
txtspt = text.split()
if txtspt:
param = txtspt[-1]
if param.startswith("-"):
is_param = True
elif len(txtspt) > 2 and txtspt[-2]\
and txtspt[-2].startswith('-'):
is_param = True
| param = txtspt[-2]
started_param = True
prefix = txtspt[-1]
return is_param, started_param, prefix, param
def reformat_cmd(text):
""" reformat the text to be stripped of noise """
# remove az if there
text = text.replace('az', '')
# disregard defaulting symbols
if text and SELECT_SYMBOL['scope'] == text[0:2]:
text = text.replace(SELECT_SYMBOL['scope'], "")
if get_scope():
text = get_scope() + ' ' + text
return text
def gen_dyn_completion(comp, started_param, prefix, text):
""" how to validate and generate completion for dynamic params """
if len(comp.split()) > 1:
completion = '\"' + comp + '\"'
else:
completion = comp
if started_param:
if comp.lower().startswith(prefix.lower()) and comp not in text.split():
yield Completion(completion, -len(prefix))
else:
yield Completion(completion, -len(prefix))
def sort_completions(gen):
""" sorts the completions """
def _get_weight(val):
""" weights the completions with required things first the lexicographically"""
priority = ''
if val.display_meta and val.display_meta.startswith('[REQUIRED]'):
priority = ' ' # a space has the lowest ordinance
return priority + val.text
return sorted(list(gen), key=_get_weight)
# pylint: disable=too-many-instance-attributes
class AzCompleter(Completer):
""" Completes Azure CLI commands """
def __init__(self, commands, global_params=True):
# dictionary of command to descriptions
self.command_description = commands.descrip
# from a command to a list of parameters
self.command_parameters = commands.command_param
# a list of all the possible parameters
self.completable_param = commands.completable_param
# the command tree
self.command_tree = commands.command_tree
# a dictionary of parameter (which is command + " " + parameter name)
# to a description of what it does
self.param_description = commands.param_descript
# a dictionary of command to examples of how to use it
self.command_examples = commands.command_example
# a dictionary of which parameters mean the same thing
self.same_param_doubles = commands.same_param_doubles or {}
self._is_command = True
self.branch = self.command_tree
self.curr_command = ""
self.global_param = commands.global_param if global_params else []
self.output_choices = commands.output_choices if global_params else []
self.output_options = commands.output_options if global_params else []
self.global_param_descriptions = commands.global_param_descriptions if global_params else []
self.global_parser = AzCliCommandParser(add_help=False)
self.global_parser.add_argument_group('global', 'Global Arguments')
self.parser = AzCliCommandParser(parents=[self.global_parser])
from azclishell._dump_commands import CMD_TABLE
self.cmdtab = CMD_TABLE
self.parser.load_command_table(CMD_TABLE)
self.argsfinder = ArgsFinder(self.parser)
def validate_completion(self, param, words, text_before_cursor, double=True):
""" validates that a param should be completed """
return param.lower().startswith(words.lower()) and param.lower() != words.lower() and\
param not in text_before_cursor.split() and not \
text_before_cursor[-1].isspace() and\
(not (double and param in self.same_param_doubles) or
self.same_param_doubles[param] not in text_before_cursor.split())
def get_completions(self, document, complete_event):
text = document.text_before_cursor
self.branch = self.command_tree
self.curr_command = ''
self._is_command = True
text = reformat_cmd(text)
if text.split():
for comp in sort_completions(self.gen_cmd_and_param_completions(text)):
yield comp
for cmd in sort_completions(self.gen_cmd_completions(text)):
yield cmd
for val in sort_completions(self.gen_dynamic_completions(text)):
yield val
for param in sort_completions(self.gen_global_param_completions(text)):
yield param
def gen_enum_completions(self, arg_name, text, started_param, prefix):
""" generates dynamic enumeration completions """
try: # if enum completion
for choice in self.cmdtab[
self.curr_command].arguments[arg_name].choices:
if started_param:
if choice.lower().startswith(prefix.lower())\
and choice not in text.split():
yield Completion(choice, -len(prefix))
else:
yield Completion(choice, -len(prefix))
except TypeError: # there is no choices option
pass
def get_arg_name(self, is_param, param):
""" gets the argument name used in the command table for a parameter """
if self.curr_command in self.cmdtab and is_param:
for arg in self.cmdtab[self.curr_command].arguments:
for name in self.cmdtab[self.curr_command].arguments[arg].options_list:
if name == param:
return arg
# pylint: disable=too-many-branches
def gen_dynamic_completions(self, text):
""" generates the dynamic values, like the names of resource groups """
try: # pylint: disable=too-many-nested-blocks
is_param, started_param, prefix, param = dynamic_param_logic(text)
# command table specific name
arg_name = self.get_arg_name(is_param, param)
if arg_name and ((text.split()[-1].startswith('-') and text[-1].isspace()) or
text.split()[-2].startswith('-')):
for comp in self.gen_enum_completions(arg_name, text, started_param, prefix):
yield comp
parse_args = self.argsfinder.get_parsed_args(
parse_quotes(text, quotes=False))
# there are 3 formats for completers the cli uses
# this try catches which format it is
if self.cmdtab[self.curr_command].arguments[arg_name].completer:
try:
for comp in self.cmdtab[self.curr_command].arguments[arg_name].completer(
parsed_args=parse_args):
for comp in gen_dyn_completion(
comp, started_param, prefix, text):
yield comp
except TypeError:
try:
for comp in self. |
iradicek/clara | tests/utils.py | Python | gpl-3.0 | 498 | 0.006024 | import os
dir_path = os.path.dirname(os.path.realpath(__file__))
def get_full_data_filename(f, reldir='data'):
| """
Gets the full path to the data file `f`.
"""
return os.path.join(dir_path, reldir, f)
def parse_file(fname, parser):
"""
Parses the file `fname` using the parser `parser` and returns the resulting model.
"""
with open(fname, encoding="utf-8") as f:
code = f.read()
model = parser.parse_code(code)
model.src = fname
return model | |
rpm-software-management/dnf | dnf/transaction_sr.py | Python | gpl-2.0 | 24,701 | 0.003603 | # Copyright (C) 2020 Red Hat, Inc.
#
# 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 Library 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 __future__ import absolute | _import
from __future__ import print_function
from __future__ import unicode_literals
import libdnf
import hawkey
from dnf.i18n import _
import dnf.exceptions
import json
VERSION_MAJOR = 0
VERSION_MINOR = 0
VERSION = "%s.%s" % (VERSION_MAJOR, VERSION_MINOR)
"""
The version of the stored transaction.
MAJOR version denotes backwards incompatible changes (old dnf won't work with
new transaction JSON).
MINOR version denotes extending the format without breaking backwards
compatibility (old dnf can work with new transaction JSON). Forwards
compatibility needs to be handled by being able to process the old format as
well as the new one.
"""
class TransactionError(dnf.exceptions.Error):
def __init__(self, msg):
super(TransactionError, self).__init__(msg)
class TransactionReplayError(dnf.exceptions.Error):
def __init__(self, filename, errors):
"""
:param filename: The name of the transaction file being replayed
:param errors: a list of error classes or a string with an error description
"""
# store args in case someone wants to read them from a caught exception
self.filename = filename
if isinstance(errors, (list, tuple)):
self.errors = errors
else:
self.errors = [errors]
if filename:
msg = _('The following problems occurred while replaying the transaction from file "{filename}":').format(filename=filename)
else:
msg = _('The following problems occurred while running a transaction:')
for error in self.errors:
msg += "\n " + str(error)
super(TransactionReplayError, self).__init__(msg)
class IncompatibleTransactionVersionError(TransactionReplayError):
def __init__(self, filename, msg):
super(IncompatibleTransactionVersionError, self).__init__(filename, msg)
def _check_version(version, filename):
major, minor = version.split('.')
try:
major = int(major)
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid major version "{major}", number expected.').format(major=major)
)
try:
int(minor) # minor is unused, just check it's a number
except ValueError as e:
raise TransactionReplayError(
filename,
_('Invalid minor version "{minor}", number expected.').format(minor=minor)
)
if major != VERSION_MAJOR:
raise IncompatibleTransactionVersionError(
filename,
_('Incompatible major version "{major}", supported major version is "{major_supp}".')
.format(major=major, major_supp=VERSION_MAJOR)
)
def serialize_transaction(transaction):
"""
Serializes a transaction to a data structure that is equivalent to the stored JSON format.
:param transaction: the transaction to serialize (an instance of dnf.db.history.TransactionWrapper)
"""
data = {
"version": VERSION,
}
rpms = []
groups = []
environments = []
if transaction is None:
return data
for tsi in transaction.packages():
if tsi.is_package():
rpms.append({
"action": tsi.action_name,
"nevra": tsi.nevra,
"reason": libdnf.transaction.TransactionItemReasonToString(tsi.reason),
"repo_id": tsi.from_repo
})
elif tsi.is_group():
group = tsi.get_group()
group_data = {
"action": tsi.action_name,
"id": group.getGroupId(),
"packages": [],
"package_types": libdnf.transaction.compsPackageTypeToString(group.getPackageTypes())
}
for pkg in group.getPackages():
group_data["packages"].append({
"name": pkg.getName(),
"installed": pkg.getInstalled(),
"package_type": libdnf.transaction.compsPackageTypeToString(pkg.getPackageType())
})
groups.append(group_data)
elif tsi.is_environment():
env = tsi.get_environment()
env_data = {
"action": tsi.action_name,
"id": env.getEnvironmentId(),
"groups": [],
"package_types": libdnf.transaction.compsPackageTypeToString(env.getPackageTypes())
}
for grp in env.getGroups():
env_data["groups"].append({
"id": grp.getGroupId(),
"installed": grp.getInstalled(),
"group_type": libdnf.transaction.compsPackageTypeToString(grp.getGroupType())
})
environments.append(env_data)
if rpms:
data["rpms"] = rpms
if groups:
data["groups"] = groups
if environments:
data["environments"] = environments
return data
class TransactionReplay(object):
"""
A class that encapsulates replaying a transaction. The transaction data are
loaded and stored when the class is initialized. The transaction is run by
calling the `run()` method, after the transaction is created (but before it is
performed), the `post_transaction()` method needs to be called to verify no
extra packages were pulled in and also to fix the reasons.
"""
def __init__(
self,
base,
filename="",
data=None,
ignore_extras=False,
ignore_installed=False,
skip_unavailable=False
):
"""
:param base: the dnf base
:param filename: the filename to load the transaction from (conflicts with the 'data' argument)
:param data: the dictionary to load the transaction from (conflicts with the 'filename' argument)
:param ignore_extras: whether to ignore extra package pulled into the transaction
:param ignore_installed: whether to ignore installed versions of packages
:param skip_unavailable: whether to skip transaction packages that aren't available
"""
self._base = base
self._filename = filename
self._ignore_installed = ignore_installed
self._ignore_extras = ignore_extras
self._skip_unavailable = skip_unavailable
if not self._base.conf.strict:
self._skip_unavailable = True
self._nevra_cache = set()
self._nevra_reason_cache = {}
self._warnings = []
if filename and data:
raise ValueError(_("Conflicting TransactionReplay arguments have been specified: filename, data"))
elif filename:
self._load_from_file(filename)
else:
self._load_from_data(data)
def _load_from_file(self, fn):
self._filename = fn
with open(fn, "r") as f:
try:
replay_data = json.load(f)
except json.decoder.JSONDecodeError as e:
raise TransactionReplayError(fn, str(e) + ".")
try:
self._load_from_data(replay_data)
except TransactionError as e:
raise TransactionReplayError(fn, e)
def _load_from_data(self, data):
self._replay_data = data
self._verify_toplevel_json(self._replay_data)
self._rpms = self._replay_data.get("rpms", [])
self._assert_type(self |
Debian/openjfx | modules/web/src/main/native/Tools/QueueStatusServer/handlers/releasepatch.py | Python | gpl-2.0 | 2,670 | 0.000749 | # Copyright (C) 2013 Google 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 Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGL | IGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILI | TY OF SUCH DAMAGE.
from google.appengine.ext import webapp, db
from google.appengine.ext.webapp import template
from handlers.updatebase import UpdateBase
from loggers.recordpatchevent import RecordPatchEvent
from model.attachment import Attachment
from model.queues import Queue
class ReleasePatch(UpdateBase):
def get(self):
self.response.out.write(template.render("templates/releasepatch.html", None))
def post(self):
queue_name = self.request.get("queue_name")
# FIXME: This queue lookup should be shared between handlers.
queue = Queue.queue_with_name(queue_name)
if not queue:
self.error(404)
return
attachment_id = self._int_from_request("attachment_id")
attachment = Attachment(attachment_id)
last_status = attachment.status_for_queue(queue)
# Ideally we should use a transaction for the calls to
# WorkItems and ActiveWorkItems.
queue.work_items().remove_work_item(attachment_id)
RecordPatchEvent.stopped(attachment_id, queue_name, last_status.message)
queue.active_work_items().expire_item(attachment_id)
|
grueni75/GeoDiscoverer | Source/Platform/Target/Android/core/src/main/jni/gdal-3.2.1/swig/python/samples/get_soundg.py | Python | gpl-3.0 | 3,997 | 0.00025 | #!/usr/bin/env python3
###############################################################################
# $Id: get_soundg.py 428d6fbc987332afb0ba6c7b6913390f7386e864 2020-01-17 22:19:28 +0100 Even Rouault $
#
# Project: OGR Python samples
# Purpose: Extract SOUNDGings from an S-57 dataset, and write them to
# Shapefile format, creating one feature for each sounding, and
# adding the elevation as an attribute for easier use.
# Author: Frank Warmerdam, warmerdam@pobox.com
#
###############################################################################
# Copyright (c) 2003, Frank Warmerdam <warmerdam@pobox.com>
#
# 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 sys
from osgeo import ogr
#############################################################################
def Usage():
print('Usage: get_soundg.py <s57file> <shapefile>')
print('')
sys.exit(1)
#############################################################################
# Argument processing.
if len(sys.argv) != 3:
Usage()
s57filename = sys.argv[1]
shpfilename = sys.argv[2]
# -
# Open the S57 file, and find the SOUNDG layer.
ds = ogr.Open(s57filename)
src_soundg = ds.GetLayerByName('SOUNDG')
# -
# Create the output shapefile.
shp_driver = ogr.GetDriverByName('ESRI Shapefile')
shp_driver.DeleteDataSource(shpfilename)
shp_ds = shp_driver.CreateDataSource(shpfilename)
shp_layer = shp_ds.CreateLayer('out', geom_type=ogr.wkbPoint25D)
src_defn = src_soundg.GetLayerDefn()
field_count = src_defn.GetFieldCount()
# -
# Copy the SOUNDG schema, and add an ELEV field.
out_mapping = []
for fld_index in range(field_count):
src_fd = src_defn.GetFieldDefn(fld_index)
fd = ogr.FieldDefn(src_fd.GetName(), src_fd.GetType())
fd.SetWidth(src_fd.GetWidth())
fd.SetPrecision(src_fd.GetPrecision())
if shp_layer.CreateField(fd) != 0:
out_mapping.append(-1)
else:
out_mapping.append(shp_layer.GetLayerDefn().GetFieldCount() - 1)
fd = ogr.FieldDefn('ELEV', ogr.OFTReal)
fd.SetWidth(12)
fd.SetPrecision(4)
shp_layer.CreateField(fd)
#############################################################################
# Process all SOUNDG features.
feat = src_soundg.GetNextFeature()
while feat is not None:
multi_geom = feat.GetGeometryRef()
for iPnt in range(multi_geom.GetGeometryCount()):
pnt = multi_geom.GetGeometryRef(iPnt)
feat2 = ogr.Feature(feature_def=shp_layer.GetLayerDefn())
for fld_index in range(field_count):
feat2.SetField(out_mapping[fld_index], feat.GetField(fld_index))
feat2.SetField('ELEV', pnt.GetZ(0))
feat2.SetGeometry(pnt)
shp_layer.CreateFeature(feat2)
feat2.Destroy()
feat.Destroy()
feat = src_soundg.GetNextFeature()
#############################################################################
# Cleanup
shp_ds.Destroy()
ds.Destroy()
|
mm22dl/MeinKPS | uploader.py | Python | gpl-3.0 | 3,745 | 0.005874 | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Title: uploader
Author: David Leclerc
Version: 0.1
Date: 01.07.2017
License: GNU General Public License, Version 3
(http://www.gnu.org/licenses/gpl.html)
Overview: This is a script that uploads all reports to a server.
Notes: ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# LIBRARIES
import os
import pysftp
# USER LIBRARIES
import logger
import errors
import path
import reporter
# Define instances
Logger = logger.Logger("uploader")
# CLASSES
class Uploader(object):
def __init__(self):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INIT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Define report
self.report = reporter.getSFTPReport()
def upload(self, sftp, path, ext = None):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UPLOAD
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Get all files from path
files = os.listdir(path)
# Get inside path
os.chdir(path)
# Upload files
for f in files:
# If file
if os.path.isfile(f):
# Verify extension
if "." + ext != os.path.splitext(f)[1]:
# Skip file
continue
# Info
Logger.debug("Uploading: '" + os.getcwd() + "/" + f + "'")
# Upload file
sftp.put(f, preserve_mtime = True)
# If directory
elif os.path.isdir(f):
# If directory does not exist
if f not in sftp.listdir():
# Info
Logger.debug("Making directory: '" + f + "'")
# Make directory
sftp.mkdir(f)
# Move in directory
sftp.cwd(f)
# Upload files in directory
self.upload(sftp, f, ext)
# Get back to original directory on server
sftp.cwd("..")
# Locally as well
os.chdir("..")
def run(self):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
RUN
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Test if report is empty before proceding
if not self.report.isValid():
raise errors.InvalidSFTPReport
# Disable host key checking (FIXME)
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
# Instanciate an FTP object
sftp = pysftp.Connection(
host = self.report.get(["Host"]),
username = self.report.get(["Username"]),
private_key = path.REPORTS.path + self.report.get(["Key"]),
cnopts = cnopts)
# Move to directory
sftp.cwd(self.report.get(["Path"]))
# Upload files
self.upload(sftp, path.EXPORTS.path, "json")
# Close SFTP connection
sftp.close()
def main():
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~
MAIN
~~~~~~~~~~~~~~~~~~~~ | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Define uploader
uploader = Uploader()
# Run it
uploader.run()
# Run this when script is called from terminal
if __name__ == "__main__":
main() |
philchristensen/modu | src/twisted/plugins/modu_web.py | Python | mit | 1,455 | 0.029553 | # | modu
# Copyright (c) 2006-2010 Phil Christensen
# http://modu.bubblehouse.org
#
#
# See LICENSE for details
"""
Twisted plugin to launch a modu web application container.
"""
from zope.interface import implements
from twisted.py | thon import usage
from twisted.plugin import IPlugin
from twisted.application import internet, service
from twisted.internet import reactor
from twisted.web import server, resource, wsgi
from modu.web import app
from modu.persist import dbapi
import os
class Options(usage.Options):
"""
Implement usage parsing for the modu-web plugin.
"""
optParameters = [["port", "p", 8888, "Port to use for web server.", int],
['interface', 'i', '', 'Interface to listen on.'],
['logfile', 'l', None, 'Path to access log.']
]
optFlags = [["debug-db", "d", "Turn on dbapi debugging."]
]
class ModuServiceMaker(object):
"""
Create a modu web service with twisted.web.
"""
implements(service.IServiceMaker, IPlugin)
tapname = "modu-web"
description = "Run a modu application server."
options = Options
def makeService(self, config):
"""
Instantiate the service.
"""
dbapi.debug = config['debug-db']
wsgi_rsrc = wsgi.WSGIResource(reactor, reactor.getThreadPool(), app.handler)
site = server.Site(wsgi_rsrc, logPath=config['logfile'])
web_service = internet.TCPServer(config['port'], site, interface=config['interface'])
return web_service
serviceMaker = ModuServiceMaker() |
PapenfussLab/Srtools | bin/old/filterMaqMapview.py | Python | artistic-2.0 | 1,020 | 0.027451 | #!/usr/bin/env python
"""
filterMapview.py <input mapview file> <output filename>
Author: Tony Papenfuss
Date: Mon Jun 16 14:31:42 EST 2008
"""
import os, sys
from useful import progressMessage
iFilename = sys.argv[1]
oFilename = sys.argv[2]
mQ_cutoff = 40
nSeqs = 280000000
oFile = open(oFilename, 'w')
headers = ['name','chrom','start','strand','mQ','numTied','score','numZeroMismatches']
format = '\t'.join(['%s','%s','%i','%s','%i','%i','%i','%i'])
print >> oFile, '\t'.join(headers)
for i,line in enumerate(open(iFilename)):
tokens = line.strip().split('\t')
mQ = int(tokens[7])
if mQ>=mQ_cutoff:
name = tokens[0]
chrom = tokens[1]
start = int(token | s[2])
strand = tokens[3]
numTied = int(tokens[10])
score = int(tokens[11])
numZeroMismat | ches = int(tokens[12])
print >> oFile, format % (name,chrom,start,strand,mQ,numTied,score,numZeroMismatches)
if (i % 1000)==0: progressMessage('# maq hits %s', i, nSeqs)
oFile.close()
|
polyaxon/polyaxon | traceml/traceml/artifacts/__init__.py | Python | apache-2.0 | 727 | 0 | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 traceml.artifacts.kinds import V1ArtifactKind
from traceml.artifacts.schemas import RunArtifactSchema, V1RunArtifact
|
demonshreder/pirate | pirate/urls.py | Python | apache-2.0 | 2,735 | 0.007313 | """pirate URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
import files.views
import user.views
urlpatterns = [
#Admin Site
#url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS
url(r'^boss/', include(admin.site.urls),name='boss'),
#Home & Captain
url(r'^$', files.views.index, name='home'),
url(r'^review$', files.views.review, name ='review'),
url(r'^captain$', files.views.captain, name='captain'),
#Text pages
url(r'^policy$', us | er.views.policy, name='policy'),
url(r'^about$', user.views.about, name='about'),
#Files
url(r'^upload$', files.views.upload, name='upload'),
url(r'^search$', files.views.search, name='search'),
url(r | '^file_delete$', files.views.file_delete, name='file_delete'),
url(r'^file_delete_all$', files.views.file_delete_all, name='file_delete_all'),
url(r'^file_update$', files.views.file_update, name='file_update'),
#Communities
url(r'^comm/(?P<name>[a-z0-9A-Z \.\,\_\-\$\~\'\@\!\#\%\^\&\*]+)$', user.views.comm, name='comm'),
url(r'^comm_add$', user.views.comm_add, name='comm_add'),
url(r'^comm_join$', user.views.comm_join, name='comm_join'),
#Friends
url(r'^friend_add$', user.views.friend_add, name='friend_add'),
url(r'^friend_accept$', user.views.friend_accept, name='friend_accept'),
#User*(\([a-zA-Z]+\).+)
url(r'^user/(?P<username>[a-z0-9A-Z \.\,\_\-\$\~\'\@\!\#\%\^\&\*]+)$', user.views.user, name='user'),
url(r'^login$', user.views.login, name='login'),
url(r'^register$', user.views.register, name='register'),
url(r'^logout$', user.views.logout, name='logout'),
url(r'^profile$', user.views.profile, name='profile'),
url(r'^profile_update$', user.views.profile_update, name='profile_update'),
url(r'^account_reset_passwowrd$', files.views.index, name='account_reset_password'),
#Testing
url(r'^test$', files.views.test, name ='test'),
url(r'^test2$', user.views.test2, name ='test2'),
#Autocomplete
url(r'^autocomplete/search/(?P<query>[\\?\\=a-z0-9 ]+)$', files.views.auto_search, name='auto_search'),
] |
Huyuwei/tvm | python/tvm/relay/op/image/image.py | Python | apache-2.0 | 2,130 | 0.000939 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Image operations."""
from __future__ import absolute_import as _abs
from . import _make
def resize(data,
size,
layout="NCHW",
method="bilinear",
| align_corners=True,
out_dtype=None):
"""Image resize operator.
This operator takes data as input and does 2D scaling to the given scale factor.
In the default case, where the data_layout is `NCHW`
with data of shape (n, c, h, w)
out will have a shape (n, c, size[0], | size[1])
method indicates the algorithm to be used while calculating ghe out value
and method can be one of ("bilinear", "nearest_neighbor", "bicubic")
Parameters
----------
data : relay.Expr
The input data to the operator.
size: Tuple of Expr
The out size to which the image will be resized.
layout : str, optional
Layout of the input.
method : str, optional
Scale method to used [nearest_neighbor, bilinear, bicubic].
align_corners : int, optional
Should be true to preserve the values at the corner pixels
out_dtype : str, optional
Type to return. If left None returns the same type as input.
Returns
-------
result: relay.Expr
The resized result.
"""
return _make.resize(data, size, layout, method, align_corners, out_dtype)
|
sparkslabs/kamaelia_ | Sketches/JL/Sequencer/__init__.py | Python | apache-2.0 | 23 | 0.043478 | ## Seq | uencer init | file
|
jjdmol/LOFAR | SAS/ResourceAssignment/SystemStatusService/SSDBrpc.py | Python | gpl-3.0 | 2,363 | 0.005501 | #!/usr/bin/python
from lofar.messaging.RPC import RPC, RPCException, RPCWrapper
import logging
import sys
logger = logging.getLogger(__name__)
from lofar.sas.systemstatus.service.config import DEFAULT_SSDB_BUSNAME
from lofar.sas.systemstatus.service.config import DEFAULT_SSDB_SERVICENAME
class SSDBRPC(RPCWrapper):
def __init__(self,
busname=DEFAULT_SSDB_BUSNAME,
servicename=DEFAULT_SSDB_SERVICENAME,
broker=None):
super(SSDBRPC, self).__init__(busname, servicename, broker)
def getstatenames(self):
return self.rpc('GetStateNames')
def getactivegroupnames(self):
return self.rpc('GetActiveGroupNames')
def gethostsforgid(self,gid):
return self.rpc('GetHostForGID', gid=gid)
def counthostsforgroups(self,groups,states):
return self.rpc('CountHostsForGroups', groups=groups, states=states)
def listall(self):
return self.rpc('ListAll')
def countactivehosts(self):
return self.rpc('CountActiveHosts')
def getArchivingStatus(self,*args,**kwargs):
return self.rpc('GetArchivingStatus')
# test code for all methods
if __name__ == '__main__':
import pprint
with SSDBRPC(broker='10.149.96.22') as ssdb:
print '\n | ------------------'
print 'getstatenames'
states = ssdb.getstatenames()
pprint.pprint(states)
print '\n------------------'
print 'getactivegroupnames'
groups = ssdb.getactivegroupnames()
pprint.pprint(ssdb.getactivegroupnames())
for gid, groupname in groups.items():
print '\n------------------'
print 'gethostsforgid'
pprint.pprint(ssdb.gethostsforgid(gid))
for gid, groupname in groups.items(): |
for sid, statename in states.items():
print '\n------------------'
print 'counthostsforgroups'
pprint.pprint(ssdb.counthostsforgroups({gid:groupname}, {sid:statename}))
print '\n------------------'
print 'listall'
pprint.pprint(ssdb.listall())
print '\n------------------'
print 'countactivehosts'
pprint.pprint(ssdb.countactivehosts())
print '\n------------------'
print 'getArchivingStatus'
pprint.pprint(ssdb.getArchivingStatus())
|
pirata-cat/agora-ciudadana | agora_site/accounts/forms.py | Python | agpl-3.0 | 24,702 | 0.003481 | # Copyright (C) 2012 Eduardo Robles Elvira <edulix AT wadobo DOT com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import random
import os
import json
import hashlib
from django.contrib import messages
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.shortcuts import get_object_or_404
from django.template.loader import render_to_string
| from django.contrib.auth import authenticate, login
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth import forms as auth_forms
from django.contrib.sites.models import Site
from django import forms as django_forms
from django.utils import transla | tion
from django.core.mail import EmailMultiAlternatives, EmailMessage, send_mass_mail
from django.utils import simplejson as json
from django.utils import timezone
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Hidden, Layout, Fieldset
from userena import forms as userena_forms
from userena import settings as userena_settings
from userena.models import UserenaSignup
from actstream.actions import follow
from actstream.signals import action
from agora_site.misc.utils import (geolocate_ip, get_base_email_context,
JSONFormField, import_member)
from agora_site.agora_core.forms.election import LoginAndVoteForm
from agora_site.agora_core.models.election import Election
from captcha.fields import CaptchaField
class AccountSignupForm(userena_forms.SignupForm):
def __init__(self, *args, **kwargs):
super(AccountSignupForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.fields.insert(0, 'first_name', django_forms.CharField(label=_("Nombre y DOS APELLIDOS"), required=True, max_length=140))
self.fields.insert(5, 'tos', django_forms.BooleanField(required=True,
label=_(' I accept the <a href="/misc/page/terms-of-service" target="_blank">Terms of Service</a> and <a href="/misc/page/privacy-policy" target="_blank">Privacy Policy</a>.')))
# if using fnmt, we require user/pass registration to give a way to
# verify their identity
if settings.AGORA_REQUEST_SCANNED_ID_ON_REGISTER:
self.fields.insert(0, 'scanned_id', django_forms.FileField(label=_("DNI escaneado"), required=True, help_text=u"Adjunta tu DNI escaneado para poder verificar tu identidad (formato pdf o imagen, max. 1MB)"))
self.helper.form_enctype = 'multipart/form-data'
self.add_extra_fields()
self.helper.form_id = 'register-form'
self.helper.form_action = 'userena_signup'
self.helper.add_input(Submit('submit', _('Sign up'), css_class='btn btn-success btn-large'))
self.helper.add_input(Hidden('type', 'register'))
def handle_uploaded_file(self, f):
file_name = "%s_%s%s" % (self.cleaned_data['username'],
hashlib.md5(self.cleaned_data['username'] + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest(),
os.path.splitext(f.name)[1])
file_path = os.path.join(settings.MEDIA_ROOT, 'dnis', file_name)
with open(file_path, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def add_extra_fields(self):
for element in settings.AGORA_REGISTER_EXTRA_FIELDS:
validators = []
field_name = element['field_name']
label = element['label']
help_text = element.get('help_text', '')
position = element.get('position', len(self.fields))
if "validator" in element:
validators = [import_member(element['validator'])]
self.fields.insert(position, field_name, django_forms.CharField(
label=label,
required=True,
help_text=help_text,
validators=validators
))
def save_extra(self, new_user):
'''
Save the data from extra fields
'''
profile = new_user.get_profile()
if not isinstance(profile.extra, dict):
profile.extra = dict()
for element in settings.AGORA_REGISTER_EXTRA_FIELDS:
fname = element['field_name']
profile.extra[fname] = self.cleaned_data[fname]
profile.save()
def save(self):
if settings.AGORA_REQUEST_SCANNED_ID_ON_REGISTER:
self.handle_uploaded_file(self.request.FILES['scanned_id'])
new_user = super(AccountSignupForm, self).saveWithFirstName(auto_join_secret=True)
signup_object = new_user.save()
self.save_extra(new_user)
return new_user
class SignupAndVoteForm(userena_forms.SignupForm):
existing_user = None
def __init__(self, request, *args, **kwargs):
self.request = request
super(SignupAndVoteForm, self).__init__(*args, **kwargs)
self.fields.insert(0, 'first_name', django_forms.CharField(label=_("Nombre y DOS APELLIDOS"), required=True, max_length=140))
self.add_extra_fields()
# if using fnmt, we require user/pass registration to give a way to
# verify their identity
if settings.AGORA_REQUEST_SCANNED_ID_ON_REGISTER:
self.fields.insert(0, 'scanned_id', django_forms.FileField(label=_("DNI escaneado"), required=True, help_text=u"Adjunta tu DNI escaneado para poder verificar tu identidad (formato pdf o imagen, max. 1MB)"))
def add_extra_fields(self):
for element in settings.AGORA_REGISTER_EXTRA_FIELDS:
validators = []
field_name = element['field_name']
label = element['label']
help_text = element.get('help_text', '')
position = element.get('position', len(self.fields))
if "validator" in element:
validators = [import_member(element['validator'])]
self.fields.insert(position, field_name, django_forms.CharField(
label=label,
required=True,
help_text=help_text,
validators=validators
))
def clean_username(self):
"""
Validate that the username is alphanumeric and is not already in use.
Also validates that the username is not listed in
``USERENA_FORBIDDEN_USERNAMES`` list.
"""
try:
user = User.objects.get(username=self.cleaned_data['username'])
except User.DoesNotExist:
pass
else:
self.existing_user = user
if self.cleaned_data['username'].lower() in userena_settings.USERENA_FORBIDDEN_USERNAMES:
raise forms.ValidationError(_('This username is not allowed.'))
return self.cleaned_data['username']
def clean_email(self):
""" Validate that the e-mail address is unique. """
user = User.objects.filter(email__iexact=self.cleaned_data['email'])
if user:
self.existing_user = user[0]
return self.cleaned_data['email']
def handle_uploaded_file(self, f):
file_name = "%s_%s%s" % (self.cleaned_data['username'],
hashlib.md5(self.cleaned_data['username'] + settings.AGORA_API_AUTO_ACTIVATION_SECRET).hexdigest(),
os.path.splitext(f.name)[1])
file_path = os.path.join(settings.MEDIA_ROOT, 'dnis', file_name)
with open(file_path, 'wb+') as destination:
|
Javid-Izadfar/TaOonja | taOonja/game/models.py | Python | mit | 444 | 0.006757 | import os
from django.db import models
from django import forms
class Location(models.Model):
name = models.CharField(max_length=250)
local_name = mode | ls.CharField(max_length=250)
visited = models.BooleanField(default=False)
coordinates = models.CharField(ma | x_length=250)
detail = models.TextField()
img = models.ImageField(upload_to = "media/", blank=True, null=True)
def __str__(self):
return self.name
|
pombredanne/Octopus | octopus/backends/docker.py | Python | gpl-3.0 | 4,587 | 0.000218 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2014-2015 Bitergia
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# Authors:
# Santiago Dueñas <sduenas@bitergia.com>
#
import datetime
import urlparse
import requests
from octopus.backends import Backend
from octopus.model import Platform, Project, Repository, RepositoryLog
DOCKER_OWNER_PATH = '/u/'
DOCKER_REPOSITORY_PATH = '/r/'
DOCKER_API_REPOSITORIES = '/v2/repositories/'
HEADERS = {'User-Agent': 'Octopus/0.0.1'}
class DockerRegistry(Backend):
def __init__(self, session, url, owner):
super(DockerRegistry, self).__init__('docker')
self.session = session
self.base_url = url
self.owner = owner
@classmethod
def set_arguments_subparser(cls, parser):
subparser = parser.add_parser('docker', help='Docker registry backend')
# Positional arguments
subparser.add_argument('url',
help='Docker registry url')
subparser.add_argument('owner',
help='Owner of the repositories on Docker Hub')
def fetch(self):
platform = Platform.as_unique(self.session, url=self.base_url)
if not platform.id:
platform.type = 'docker'
| platform = self._fetch(self.owner, platform)
| return platform
def _fetch(self, owner, platform):
project = self._fetch_project(owner, platform)
platform.projects.append(project)
return platform
def _fetch_project(self, owner, platform):
url = urlparse.urljoin(self.base_url, DOCKER_OWNER_PATH)
url = urlparse.urljoin(url, owner)
try:
r = requests.get(url, headers=HEADERS)
r.raise_for_status()
except requests.exceptions.HTTPError, e:
msg = "Docker - owner %s. Error: %s" % (owner, str(e))
raise Exception(msg)
project = Project().as_unique(self.session, url=url,
platform=platform)
if not project.id:
project.name = owner
repositories = self._fetch_repositories(owner)
for repo in repositories:
project.repositories.append(repo)
return project
def _fetch_repositories(self, owner):
page = 1
fetching = True
repositories = []
while fetching:
json_data = self._fetch_repositories_json(owner, page)
page += 1
for raw_repo in json_data['results']:
repo = self._parse_repository_json(owner, raw_repo)
repositories.append(repo)
if not json_data['next']:
fetching = False
return repositories
def _fetch_repositories_json(self, owner, page=1):
url = urlparse.urljoin(self.base_url, DOCKER_API_REPOSITORIES)
url = urlparse.urljoin(url, owner)
params = {'page' : page}
try:
r = requests.get(url, headers=HEADERS, params=params)
r.raise_for_status()
except requests.exceptions.HTTPError, e:
msg = "Docker - repositories %s. Error: %s" \
% (owner, str(e))
raise Exception(msg)
return r.json()
def _parse_repository_json(self, owner, raw_repo):
name = raw_repo['name']
url = urlparse.urljoin(self.base_url, DOCKER_REPOSITORY_PATH)
url = urlparse.urljoin(url, owner + '/' + name)
repo = Repository().as_unique(self.session, url=url)
if not repo.id:
repo.name = name
repo.type = 'docker'
repo.starred = int(raw_repo['star_count'])
repo.pulls = int(raw_repo['pull_count'])
repo_log = RepositoryLog(date=datetime.datetime.now(),
starred=repo.starred,
pulls=repo.pulls)
repo.log.append(repo_log)
return repo
|
wbsoft/frescobaldi | frescobaldi_app/documentstructure.py | Python | gpl-2.0 | 3,353 | 0.003579 | # This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2013 - 2014 by Wilbert Berendsen
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
# See http://www.gnu.org/licenses/ for more information.
"""
Maintains an overview of the structure of a Document.
"""
import re
from PyQt5.QtCore import QSettings
import app
import plugin
default_outline_patterns = [
r"(?P<title>\\(score|book|bookpart))\b",
r"^\\(paper|layout|header)\b",
r"\\(new|context)\s+[A-Z]\w+",
r"(?P<title>BEGIN[^\n]*)[ \t]*$",
r"^[a-zA-Z]+\s*=",
r"^<<",
r"^\{",
r"^\\relative([ \t]+\w+[',]*)?",
r"\b(?P<alert>(FIXME|HACK|XXX+)\b\W*\w+)",
]
# cache the outline regexp
_outline_re = None
def outline_re():
"""Return the expression to look for document outline items."""
global _outline_re
if _outline_re is None:
_outline_re = create_outline_re()
return _outline_re
def _reset_outline_re():
global _outline_re
_outline_re = None
app.settingsChanged.connect(_reset_outline_re, -999)
def create_outline_re():
"""Create and return the expression to look for document outline items."""
try:
rx = QSettings().value("documentstructure/outline_patterns",
default_outline_patterns, str)
except TypeError:
rx = []
# suffix duplicate named groups with a number
groups = {}
new_rx = []
for e in rx:
try:
c = re.compile(e)
except re.error:
continue
if c.groupindex:
for name in c.groupindex:
if name in groups:
groups[name] += 1
new_name = name + format(groups[name])
e = e.replace("(?P<{0}>".format(name), "(?P<{0}> | ".format(new_name))
else:
groups[name] = 0
new_rx.append(e)
rx = '|'.join(new_rx)
return re.compile(rx, re.MULTILINE | re.UNICODE)
class DocumentStructure(plugin.DocumentPlugin):
def __init__(self, document):
| self._outline = None
def invalidate(self):
"""Called when the document changes or the settings are changed."""
self._outline = None
app.settingsChanged.disconnect(self.invalidate)
self.document().contentsChanged.disconnect(self.invalidate)
def outline(self):
"""Return the document outline as a series of match objects."""
if self._outline is None:
self._outline = list(outline_re().finditer(self.document().toPlainText()))
self.document().contentsChanged.connect(self.invalidate)
app.settingsChanged.connect(self.invalidate, -999)
return self._outline
|
kramer314/1d-vd-test | convergence-tests/cleanup.py | Python | mit | 229 | 0 | import os |
input_dir = "./convergence_inputs/"
output_dir = "./convergence | _outputs/"
print("Removing input files")
os.system("rm -rf " + input_dir)
print("Removing output directories / files")
os.system("rm -rf " + output_dir)
|
Jgarcia-IAS/SAT | openerp/addons-extra/odoo-pruebas/odoo-server/addons/stock_landed_costs/stock_landed_costs.py | Python | agpl-3.0 | 19,099 | 0.004189 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
from openerp.exceptions import Warning
from openerp.tools import float_compare
from openerp.tools.translate import _
import product
class stock_landed_cost(osv.osv):
_name = 'stock.landed.cost'
_description = 'Stock Landed Cost'
_inherit = 'mail.thread'
_track = {
'state': {
'stock_landed_costs.mt_stock_landed_cost_open': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'done',
},
}
def _total_amount(self, cr, uid, ids, name, args, context=None):
result = {}
for cost in self.browse(cr, uid, ids, context=context):
total = 0.0
for line in cost.cost_lines:
total += line.price_unit
result[cost.id] = total
return result
def _get_cost_line(self, cr, uid, ids, context=None):
cost_to_recompute = []
for line in self.pool.get('stock.landed.cost.lines').browse(cr, uid, ids, context=context):
cost_to_recompute.append(line.cost_id.id)
return cost_to_recompute
def get_valuation_lines(self, cr, uid, ids, picking_ids=None, context=None):
picking_obj = self.pool.get('stock.picking')
lines = []
if not picking_ids:
return lines
for picking in picking_obj.browse(cr, uid, picking_ids):
for move in picking.move_lines:
#it doesn't make sense to make a landed cost for a product that isn't set as being valuated in real time at real cost
#if move.product_id.valuation != 'real_time' or move.product_id.cost_method != 'real':
# continue
total_cost = 0.0
total_qty = move.product_qty
weight = move.product_id and move.product_id.weight * move.product_qty
volume = move.product_id and move.product_id.volume * move.product_qty
for quant in move.quant_ids:
total_cost += quant.cost
vals = dict(product_id=move.product_id.id, move_id=move.id, quantity=move.product_uom_qty, former_cost=total_cost * total_qty, weight=weight, volume=volume)
lines.append(vals)
if not lines:
raise osv.except_osv(_('Error!'), _('The selected picking does not contain any move that would be impacted by landed costs. Landed costs are only possible for products configured in real time valuation with real price costing method. Please make sure it is the case, or you selected the correct picking'))
return lines
_columns = {
'name': fields.char('Name', track_visibility='always', readonly=True, copy=False),
'date': fields.date('Date', required=True, states={'done': [('readonly', True)]}, track_visibility='onchange', copy=False),
'picking_ids': fields.many2many('stock.picking', string='Pickings', states={'done': [('readonly', True)]}, copy=False),
'cost_lines': fields.one2many('stock.landed.cost.lines', 'cost_id', 'Cost Lines', states={'done': [('readonly', True)]}, copy=True),
'valuation_adjustment_lines': fields.one2many('stock.valuation.adjustment.lines', 'cost_id', 'Valuation Adjustments', states={'done': [('readonly', True)]}),
'description': fields.text('Item Description', states={'done': [('readonly', True)]}),
'amount_total': fields.function(_total_amount, type='float', string='Total', digits_compute=dp.get_precision('Account'),
store={
'stock.landed.cost': (lambda self, cr, uid, ids, c={}: ids, ['cost_lines'], 20),
'stock.landed.cost.lines': (_get_cost_line, ['price_unit', 'quantity', 'cost_id'], 20),
}, track_visibility='always'
),
'state': fields.selection([('draft', 'Draft'), ('done', 'Posted'), ('cancel', 'Cancelled')], 'State', readonly=True, track_visibility='onchange', copy=False),
'account_move_id': fields.many2one('account.move', 'Journal Entry', readonly=True, copy=False),
'account_journal_id': fields.many2one('account.journal', 'Account Journal', required=True, states={'done': [('readonly', True)]}),
}
_defaults = {
'name': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'stock.landed.cost'),
'state': 'draft',
'date': fields.date.context_today,
}
def _create_accounting_entries(self, cr, uid, line, move_id, qty_out, context=None):
product_obj = self.pool.get('product.template')
cost_product = line.cost_line_id and line.cost_line_id.product_id
if not cost_product:
return False
accounts = product_obj.get_product_accounts(cr, uid, line.product_id.product_tmpl_id.id, context=context)
debit_account_id = accounts['property_stock_valuation_account_id']
already_out_account_id = accounts['stock_account_output']
credit_account_id = line.cost_line_id.account_id.id or cost_product.property_account_expense.id or cost_product.categ_id.property_account_expense_categ.id
if not credit_account_id:
raise osv.except_osv(_('Error!'), _('Please configure Stock Expense Account for product: %s.') % (cost_product.name))
return self._create_account_move_line(cr, uid, line, move_id, credit_account_id, debit_account_id, qty_out, already_out_account_id, context=context)
def _create_account_move_line(self, cr, uid, line, move_id, credit_account_id, debit_account_id, qty_out, already_out_account_id, context=None):
"""
Generate the account.move.line values to track the landed cost.
Afterwards, for the goods that are already out of stock, we should create the out moves
"""
aml_obj = self.pool.get('account.move.line')
base_line = {
'name': line.name,
'move_id': move_id,
'product_id': line.product_id.id,
'quantity': line.quantity,
}
debit_line = dict(base_line, account_id=debit_account_id)
credit_line = dict(base_line, account_id=credit_account_id)
diff = line.additional_landed_cost
if diff > 0:
debit_line['debit'] = diff
credit_line['credit'] = diff
else:
# negative cost, reverse the entry
debit_line['credit'] = -diff
credit_line['debit'] = -diff
aml_obj.create(cr, uid, debit_line, context=context)
aml_obj.create(cr, uid, credit_line, context=context)
| #Create a | ccount move lines for quants already out of stock
if qty_out > 0:
debit_line = dict(debit_line,
name=(line.name + ": " + str(qty_out) + _(' already out')),
quantity=qty_out)
credit_line = dict(credit_line,
name=(line.name + ": " + str(qty_out) + _(' already out')),
quantity=qty_out)
diff = diff * qty_out / line.quantity
if diff > 0:
debit_line['debit'] = diff
credit_line['credit'] = diff
else:
# n |
mm10ws/ImPy | ImAdd.py | Python | gpl-3.0 | 1,485 | 0.002694 | __author__ = 'Mayur M'
import ImgIO
def add(image1, image2): # add two images together
if image1.width == image2.width and image1.height == image2.height:
return_red = []
return_green = []
return_blue = []
for i in range(0, len(image1.red)):
tmp_r = ima | ge1.red[i] + | image2.red[i] # adding the RGB values
tmp_g = image1.green[i] + image2.green[i]
tmp_b = image1.blue[i] + image2.blue[i]
if 0 <= tmp_r <= 255:
return_red.append(tmp_r)
else:
return_red.append(tmp_r % 255) # loop values around if saturation
if 0 <= tmp_g <= 255:
return_green.append(tmp_g)
else:
return_green.append(tmp_g % 255) # loop values around if saturation
if 0 <= tmp_b <= 255:
return_blue.append(tmp_b)
else:
return_blue.append(tmp_b % 255) # loop values around if saturation
return return_red, return_green, return_blue
else:
print "Error: image dimensions do not match!"
def main(): # test case
print('start!!!!!')
ima = ImgIO.ImgIO()
imb = ImgIO.ImgIO()
ima.read_image("y.jpg")
imb.read_image("test1.png")
add_r, add_g, add_b = add(ima, imb)
imc = ImgIO.ImgIO()
imc.read_list(add_r, add_g, add_b, "final1.png", ima.width, ima.height)
imc.write_image("final1.png")
if __name__ == '__main__':
main() |
fdibaldassarre/mload | src/Utils/Browser.py | Python | gpl-3.0 | 1,525 | 0.019016 | #!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('WebKit2', '4.0')
from gi.repository import Gtk
from gi.repository import WebKit2 as WebKit
from src.Utils import Browser
COOKIES_TEXT = 0
COOKIES_SQLITE = 1
class MLBrowser():
def __init__(self):
self.window = Gtk.Window()
self.view = WebKit.WebView()
self._interfaceInit()
self.close_condition = lambda title : True
self.close_callback | = lambda _ : True
self.view.connect('load_changed', self.onLoadChanged)
def _interfaceInit(self):
scroll = Gtk.ScrolledWindow()
scroll.add_with_viewport(self.view)
self.window.add(scroll)
def saveCookiesTo(self, s | avepath):
context = self.view.get_context()
cookie_manager = context.get_cookie_manager()
storage = WebKit.CookiePersistentStorage(COOKIES_TEXT)
cookie_manager.set_persistent_storage(savepath, storage)
def show(self):
self.window.show_all()
def close(self):
self.close_callback(self)
self.window.close()
def load(self, url):
self.view.load_uri(url)
def getUserAgent(self):
settings = self.view.get_settings()
return settings.get_user_agent()
def setCloseCondition(self, func):
self.close_condition = func
def setCloseCallback(self, func):
self.close_callback = func
def onLoadChanged(self, *args, **kwargs):
title = self.view.get_title()
if self.close_condition(title):
self.close()
def start():
browser = MLBrowser()
return browser
|
pattarapol-iamngamsup/projecteuler_python | problem_041.py | Python | gpl-3.0 | 1,724 | 0.034803 | """ Copyright 2014, March 21
Written by Pattarapol (Cheer) Iamngamsup
E-mail: IAM.PATTARAPOL@GMAIL.COM
Pandigital prime
Problem 41
We shall say that an n-digit number is pandigital
if it makes use of all the digits 1 to n exactly once.
For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
"""
#################################################
# Importing libraries & modules
import datetime
from MyMathSolver import MyMathSolver
#################################################
# Global variables
#################################################
# Functions
#################################################
# Classes
#################################################
# Main function
def main():
largestPanDigitalPrimeNumber = 2
for digitNumber in xrange( 1, 10 ):
for panDigitalNumber in MyMathSolver.getPanDigitalNumbersList( digitNumber ):
if MyMathSolver.isPrimeNumber( panDigitalNumber ):
largestPanDigitalPrimeNumber = panDigitalNumber
print( 'answer = {0}'.format( largestPanDigitalPrimeNumber ) )
#################################################
# Main execution
if __name__ == '__main__':
# get starting date t | ime
startingDateTime = datetime.datetime.utcnow()
|
print( 'startingDateTime = {0} UTC'.format( startingDateTime ) )
# call main function
main()
# get ending date time
endingdateTime = datetime.datetime.utcnow()
print( 'endingdateTime = {0} UTC'.format( endingdateTime ) )
# compute delta date time
deltaDateTime = endingdateTime - startingDateTime
print( 'deltaDateTime = {0}'.format( deltaDateTime ) )
|
debalance/hp | hp/conversejs/views.py | Python | gpl-3.0 | 878 | 0.006834 | # -*- coding: utf-8 -*-
#
# This file is part of the jabber.at homepage (https://github.com/jabber-at/hp).
#
# This project 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 project 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 PARTI | CULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with django-xmpp-account.
# If | not, see <http://www.gnu.org/licenses/>.
from django.views.generic.base import TemplateView
class ConverseJsView(TemplateView):
template_name = 'conversejs/main.html'
|
saurabh6790/frappe | frappe/tests/test_exporter_fixtures.py | Python | mit | 8,665 | 0.030467 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import frappe.defaults
from frappe.core.doctype.data_import.data_import import export_csv
import unittest
import os
class TestDataImportFixtures(unittest.TestCase):
def setUp(self):
pass
#start test for Client Script
def test_Custom_Script_fixture_simple(self):
fixture = "Client Script"
path = frappe.scrub(fixture) + "_original_style.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_simple_name_equal_default(self):
fixture = ["Client Script", {"name":["Item"]}]
path = frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_simple_name_equal(self):
fixture = ["Client Script", {"name":["Item"],"op":"="}]
path = frappe.scrub(fixture[0]) + "_simple_name_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_simple_name_not_equal(self):
fixture = ["Client Script", {"name":["Item"],"op":"!="}]
path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
#without [] around the name...
def test_Custom_Script_fixture_simple_name_at_least_equal(self):
fixture = ["Client Script", {"name":"Item-Cli"}]
path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_multi_name_equal(self):
fixture = ["Client Script", {"name":["Item", "Customer"],"op":"="}]
path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_multi_name_not_equal(self):
fixture = ["Client Script", {"name":["Item", "Customer"],"op":"!="}]
path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_empty_object(self):
fixture = ["Client Script", {}]
path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_just_list(self):
fixture = ["Client Script"]
path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
# Client Script regular expression
def test_Custom_Script_fixture_rex_no_flags(self):
fixture = ["Client Script", {"name":r"^[i|A]"}]
path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Script_fixture_rex_with_flags(self):
fixture = ["Client Script", {"name":r"^[i|A]", "flags":"L,M"}]
path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
#start test for Custom Field
def test_Custom_Field_fixture_simple(self):
fixture = "Custom Field"
path = frappe.scrub(fixture) + "_original_style.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_simple_name_equal_default(self):
fixture = ["Custom Field", {"name":["Item-vat"]}]
path = fra | ppe.scrub(fixture[0]) + "_simple_name_equal_default.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_simple_name_equal(self):
fixture = ["Custom Field", {"name":["Item-vat"],"op":"="}]
path = frappe.scrub(fixture[0]) + "_simple_name_equal.c | sv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_simple_name_not_equal(self):
fixture = ["Custom Field", {"name":["Item-vat"],"op":"!="}]
path = frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
#without [] around the name...
def test_Custom_Field_fixture_simple_name_at_least_equal(self):
fixture = ["Custom Field", {"name":"Item-va"}]
path = frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_multi_name_equal(self):
fixture = ["Custom Field", {"name":["Item-vat", "Bin-vat"],"op":"="}]
path = frappe.scrub(fixture[0]) + "_multi_name_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_multi_name_not_equal(self):
fixture = ["Custom Field", {"name":["Item-vat", "Bin-vat"],"op":"!="}]
path = frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_empty_object(self):
fixture = ["Custom Field", {}]
path = frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_just_list(self):
fixture = ["Custom Field"]
path = frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
# Custom Field regular expression
def test_Custom_Field_fixture_rex_no_flags(self):
fixture = ["Custom Field", {"name":r"^[r|L]"}]
path = frappe.scrub(fixture[0]) + "_rex_no_flags.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Custom_Field_fixture_rex_with_flags(self):
fixture = ["Custom Field", {"name":r"^[i|A]", "flags":"L,M"}]
path = frappe.scrub(fixture[0]) + "_rex_with_flags.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
#start test for Doctype
def test_Doctype_fixture_simple(self):
fixture = "ToDo"
path = "Doctype_" + frappe.scrub(fixture) + "_original_style_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_fixture_simple_name_equal_default(self):
fixture = ["ToDo", {"name":["TDI00000008"]}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal_default.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_fixture_simple_name_equal(self):
fixture = ["ToDo", {"name":["TDI00000002"],"op":"="}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_simple_name_not_equal(self):
fixture = ["ToDo", {"name":["TDI00000002"],"op":"!="}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
#without [] around the name...
def test_Doctype_fixture_simple_name_at_least_equal(self):
fixture = ["ToDo", {"name":"TDI"}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_simple_name_at_least_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_multi_name_equal(self):
fixture = ["ToDo", {"name":["TDI00000002", "TDI00000008"],"op":"="}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_multi_name_not_equal(self):
fixture = ["ToDo", {"name":["TDI00000002", "TDI00000008"],"op":"!="}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_multi_name_not_equal.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_fixture_empty_object(self):
fixture = ["ToDo", {}]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_empty_object_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
def test_Doctype_fixture_just_list(self):
fixture = ["ToDo"]
path = "Doctype_" + frappe.scrub(fixture[0]) + "_just_list_should_be_all.csv"
export_csv(fixture, path)
self.assertTrue(True)
os.remove(path)
# Doctype regular expression
def test_Docty |
locaweb/netl2api | netl2api/l2api/hp/flex10res.py | Python | apache-2.0 | 1,378 | 0.002177 | #!/usr/bin/python
# -*- coding: utf-8; -*-
#
# 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.
#
# @author: Eduardo S. Scarpellini
# @author: Luiz Ozaki
__copyright__ = "Copyright 2012, Locaweb IDC"
import re
__all__ = ["RE_SH_VERSION", "RE_SH_DOMAIN", "RE_SH_INTERCONN_MAC",
"RE_SH_UPLINKPORT_status", "RE_SH_UPLINKPORT_duplex"]
# show version
RE_SH_VERSION = re.compile(r"(?P<sys_name>.+ | )\sManagement CLI.+\r\nBuild:\s+(?P<build>.+)\r\n")
# show domain
RE_SH_DOMAIN = re.compile(r"Domain Name\s+:\s+(.+)\r\n")
# show interconnect-mac-table encX:ID
RE_SH_INTERCONN_MAC = re.compile(r"^d(\d+)\s+((?:[a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2})\s")
| RE_SH_UPLINKPORT_status = re.compile(r"^Linked(?:\ \((Active|Standby)\))?", re.IGNORECASE)
RE_SH_UPLINKPORT_duplex = re.compile(r"\((\d+[KMG]b)/(.+)\)$", re.IGNORECASE)
|
HPNetworking/HP-Intelligent-Management-Center | build/lib/pyhpeimc/plat/device.py | Python | apache-2.0 | 23,430 | 0.004609 | #!/usr/bin/env python3
# author: @netmanchris
# This section imports required libraries
import json
import requests
HEADERS = {'Accept': 'application/json', 'Content-Type':
'application/json', 'Accept-encoding': 'application/json'}
#auth = None
"""
This section contains functions which operate at the system level
"""
def get_system_vendors(auth, url):
"""Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each dictionary represents a single vendor
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> vendors = get_system_vendors(auth.creds, auth.url)
>>> assert type(vendors) is list
>>> assert 'name' in vendors[0]
"""
get_system_vendors_url = '/imcrs/plat/res/vendor?start=0&size=10000&orderBy=id&desc=false&total=false'
f_url = url + get_system_vendors_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=HEADERS)
# r.status_code
try:
if r.status_code == 200:
system_vendors = (json.loads(r.text))
return system_vendors['deviceVendor']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
def get_system_category(auth, url):
"""Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each dictionary represents a single device category
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> categories = get_system_category(auth.creds, auth.url)
>>> assert type(categories) is list
>>> assert 'name' in categories[0]
"""
get_system_category_url = '/imcrs/plat/res/category?start=0&size=10000&orderBy=id&desc=false&total=false'
f_url = url + get_system_category_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=HEADERS)
# r.status_code
try:
if r.status_code == 200:
system_category = (json.loads(r.text))
return system_category['deviceCategory']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
def get_system_device_models(auth, url):
"""Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each dictionary represents a single device model
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> device_models = get_system_device_models(auth.creds, auth.url)
>>> assert type(device_models) is list
>>> assert 'virtualDeviceName' in device_models[0]
"""
get_system_device_model_url = '/imcrs/plat/res/model?start=0&size=10000&orderBy=id&desc=false&total=false'
f_url = url + get_system_device_model_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=HEADERS)
# r.status_code
try:
if r.status_code == 200:
system_device_model = (json.loads(r.text))
return system_device_model['deviceModel']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
def get_system_series(auth, url):
"""Takes string no input to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each dictionary represents a single device series
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> series = get_system_series(auth.creds, auth.url)
>>> assert type(series) is list
>>> assert 'name' in series[0]
"""
get_system_series_url = '/imcrs/plat/res/series?managedOnly=false&start=0&size=10000&orderBy=id&desc=false&total=false'
f_url = url + get_system_series_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=HEADERS)
# r.status_code
try:
if r.status_code == 200:
system_series = (json.loads(r.text))
return system_series['deviceSeries']
excep | t requests.exceptio | ns.RequestException as e:
return "Error:\n" + str(e) + " get_dev_series: An Error has occured"
"""
This section contains functions which operate at the device level.
"""
def get_all_devs(auth, url, network_address= None):
"""Takes string input of IP address to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param network_address= str IPv4 Network Address
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.')
>>> assert type(dev_list) is list
>>> assert 'sysName' in dev_list[0]
"""
if network_address != None:
get_all_devs_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \
str(network_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false"
else:
get_all_devs_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&start=0&size=1000&orderBy=id&desc=false&total=false&exact=false"
f_url = url + get_all_devs_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=HEADERS)
# r.status_code
try:
if r.status_code == 200:
dev_details = (json.loads(r.text))
if len(dev_details) == 0:
print("Device not found")
return "Device not found"
else:
return dev_details['device']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_dev_details: An Error has occured"
def get_dev_details(ip_address, auth, url):
"""Takes string input of IP address to issue RESTUL call to HP IMC\n
:param ip_address: string object of dotted decimal notation of IPv4 address
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url)
>>> assert type(dev_1) is dict
>>> assert 'sysName' in dev_1
>>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url)
Device not found
>>> assert type(dev_2) is str
|
reellz/django-statify | statify/views.py | Python | bsd-3-clause | 12,635 | 0.00372 | # -*- coding: utf-8 -*-
#
import ftplib
import os
import re
import shutil
import tarfile
import time
from pathlib import Path
from subprocess import call
from socket import gaierror
import paramiko
from paramiko.ssh_exception import SSHException, AuthenticationException
import requests
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.template import RequestContext
from django.urls import reverse
from django.utils.translation import ugettext as _
from django.core.management import call_command
import statify.settings as statify_settings
from statify.forms import DeployForm
from statify.models import DeploymentHost, ExternalURL, Release, DeploymentTypes, AuthTypes
CURRENT_SITE = Site.objects.get_current()
@login_required()
def make_release(request):
timestamp = '%s' % (time.time())
htdocs = 'htdocs.%s.tar.gz' % (timestamp)
upload_path = statify_settings.STATIFY_UPLOAD_PATH
absolute_path = os.path.join(settings.MEDIA_ROOT, statify_settings.STATIFY_UPLOAD_PATH)
external_url_list = ExternalURL.objects.filter(is_valid=True)
# If htdocs already exists, remove
if os.path.isdir(settings.MEDUSA_DEPLOY_DIR):
shutil.rmtree(settings.MEDUSA_DEPLOY_DIR, ignore_errors=True)
os.makedirs(settings.MEDUSA_DEPLOY_DIR)
else:
os.makedirs(settings.MEDUSA_DEPLOY_DIR)
version_file = open(os.path.join(settings.MEDUSA_DEPLOY_DIR, 'version.txt'), 'w')
version_file.write(str(timestamp))
version_file.close()
# Call command to run medusa and statify all registered urls
call([
'python',
'manage.py',
'staticsitegen',
statify_settings.STATIFY_BUILD_SETTINGS
])
# Create files from external urls
for external_url in external_url_list:
path = os.path.join(settings.MEDUSA_DEPLOY_DIR, '/'.join(external_url.path[1:].split('/')[:-1]))
filepath = os.path.join(settings.MEDUSA_DEPLOY_DIR, external_url.path[1:])
# If path does not exists, create it
if not os.path.isdir(path):
os.makedirs(path)
# If file extists, remove it (need to be sure the file is clean)
if os.path.exists(filepath):
os.remove(filepath)
# Make request and get content
r = requests.get(external_url.url)
content = r.content
# Write content to file and save
filename = open(filepath, 'w+')
filename.write(content)
filename.close()
# Copy root files to builded htdocs
if os.path.isdir(statify_settings.STATIFY_ROOT_FILES):
files = os.listdir(statify_settings.STATIFY_ROOT_FILES)
for file in files:
filepath = os.path.join(statify_settings.STATIFY_ROOT_FILES, file)
shutil.copy(filepath, settings.MEDUSA_DEPLOY_DIR)
# Copy static files to builded htdocs
if not statify_settings.STATIFY_IGNORE_STATIC:
shutil.copytree(
os.path.join(statify_settings.STATIFY_PROJECT_DIR, 'static'),
os.path.join(settings.MEDUSA_DEPLOY_DIR, 'static'),
ignore=shutil.ignore_patterns(*statify_settings.STATIFY_EXCLUDED_STATIC),
dirs_exist_ok=True,
)
# Copy media files to builded htdocs
if not statify_settings.STATIFY_IGNORE_MEDIA:
shutil.copytree(
os.path.join(settings.STATIFY_PROJECT_DIR, 'media'),
os.path.join(settings.MEDUSA_DEPLOY_DIR, 'media'),
ignore=shutil.ignore_patterns('statify'),
dirs_exist_ok=True,
)
# Create tar.gz from htdocs and move it to media folder
dirlist = os.listdir(settings.MEDUSA_DEPLOY_DIR)
archive = tarfile.open(htdocs, 'w:gz')
for obj in dirlist:
path = os.path.join(settings.MEDUSA_DEPLOY_DIR, obj)
archive.add(path, arcname=obj)
archive.close()
if not os.path.isdir(absolute_path):
os.makedirs(absolute_path)
shutil.move(os.path.join(settings.STATIFY_PROJECT_DIR, htdocs), os.path.join(absolute_path, htdocs))
# Remove htdocs and tmp dir
shutil.rmtree(settings.MEDUSA_DEPLOY_DIR, ignore_errors=True,)
# shutil.rmtree(os.path.join(settings.MEDIA_ROOT, 'tmp'))
# Save new release object
release = Release(user=request.user, timestamp=timestamp)
release.archive = u'%s%s' % (upload_path, htdocs)
release.save()
messages.success(request, _('Release %s has been created successfully.') % (release.date_created))
return HttpResponseRedirect(reverse('admin:statify_release_change', args=(release.pk,)))
@login_required()
def deploy_select_release(request, release_id):
if request.POST:
form = DeployForm(request.POST)
if form.is_valid():
form.cleaned_data
host = request.POST['deploymenthost']
return HttpResponseRedirect(u'/admin/statify/release/%s/deploy/%s/' % (release_id, host))
else:
form = DeployForm()
return render(
request=requ | est,
template_name = 'admin/statify/release/deploy_form.html',
context = {
'form': form,
'release_id': release_id
}
)
@login_required()
def deploy_release(request, release_id, deploymenthost_id):
release = get_object_or_404(R | elease, pk=release_id)
deploymenthost = get_object_or_404(DeploymentHost, pk=deploymenthost_id)
archive = os.path.join(settings.MEDIA_ROOT, u'%s' % release.archive)
directory = deploymenthost.path.split('/')[-1]
tmp_path = os.path.join(settings.MEDUSA_DEPLOY_DIR, '..', 'deploy', release.timestamp)
if not os.path.isdir(tmp_path):
os.makedirs(tmp_path)
else:
shutil.rmtree(tmp_path, ignore_errors=True)
os.makedirs(tmp_path)
call(['tar', 'xfz', archive, '-C', tmp_path])
# Replace hostnames
path_of_tmp_path = Path(tmp_path)
html_files = [item for item in path_of_tmp_path.glob('**/*.html') if item.is_file()]
xml_files = [item for item in path_of_tmp_path.glob('**/*.xml') if item.is_file()]
json_files = [item for item in path_of_tmp_path.glob('**/*.json') if item.is_file()]
css_files = [item for item in path_of_tmp_path.glob('**/*.css') if item.is_file()]
txt_files = [item for item in path_of_tmp_path.glob('**/*.txt') if item.is_file()]
all_files = html_files + xml_files + json_files + css_files + txt_files
for file in all_files:
fin = open(file, "rt")
data = fin.read()
data = re.sub(r'(http|https):\/\/({})'.format(CURRENT_SITE.domain), '{}://{}'.format(deploymenthost.target_scheme, deploymenthost.target_domain), data)
data = re.sub(r'{}'.format(CURRENT_SITE.domain), deploymenthost.target_domain, data)
fin.close()
fin = open(file, "wt")
fin.write(data)
fin.close()
# Local deployment
if deploymenthost.type == DeploymentTypes.LOCAL:
if not os.path.isdir(deploymenthost.path):
os.makedirs(deploymenthost.path)
else:
shutil.rmtree(deploymenthost.path, ignore_errors=True)
os.makedirs(deploymenthost.path)
files = os.listdir(tmp_path)
for file in files:
shutil.move(os.path.join(tmp_path, file), deploymenthost.path)
# FTP deployment
elif deploymenthost.type == DeploymentTypes.FTP:
# Check if host is available
try:
ftp = ftplib.FTP(deploymenthost.host)
except:
messages.error(request,
_('Deployment host "%s" is not available.') % (deploymenthost.host))
return HttpResponseRedirect(u'/admin/statify/release/%s/deploy/select/' % (release.id))
try:
ftp.login(deploymenthost.user, deploymenthost.password)
except:
messages.error(request,
_('Your login information to %s is not correct.') % (deploymenthost.host))
return HttpResponseRedirect(u'/admin/statify/release/%s/deploy/select/' % (release.id))
# Check if dir |
nbkr/blog3 | blogthree/util.py | Python | gpl-2.0 | 3,541 | 0.001977 | import os
import math
from datetime import datetime
def indexGenerator(articleList, paths, env, language, folder='',
article_per_page=3, future=False):
filenumber = 0
count = 0
# Counting the actual number of articles we are going to publish
# we have to do this in advance, otherwise we might miscount the
# number of index pages we have.
numarticles = 0
for i in articleList:
if i.date > datetime.now() and not future:
continue
else:
numarticles += 1
articles = []
meta = {}
meta['language'] = language
for i in articleList:
if i.date > datetime.now() and not future:
continue
url = '{}/{}.html'.format(language, i.slug)
articles.append({'title': i.content.getTitle(language=language).
decode('utf8'),
'content': i.content.getText(language=language).
decode('utf8'),
'date': i.date,
'url': url})
count += 1
if count % article_per_page == 0 or count == numarticles:
formatedfilenumber = str(filenumber)
if filenumber == 0:
formatedfilenumber = ''
indexfile = os.path.join(
paths['output'],
'{}index{}.html'.format(folder, | formatedfilenumber))
numpages = int(math.ceil(numarticles / float(article_per_page)))
pagenumber = filenumber + 1
prev = ''
if filenumber == 1:
prev = 'index.html'
if filenumber > 1:
prev = 'i | ndex{}.html'.format(filenumber - 1)
nxt = ''
if pagenumber < numpages:
nxt = 'index{}.html'.format(filenumber + 1)
if not os.path.exists(os.path.join(paths['output'], folder)):
os.makedirs(os.path.join(paths['output'], folder))
# Writing content
t = env.get_template('index.html')
f = open(indexfile, 'wb')
f.write(t.render(articles=articles,
numpages=numpages,
prev=prev,
nxt=nxt,
meta=meta,
pagenumber=pagenumber
).encode('utf-8'))
f.close()
filenumber += 1
articles = []
def feedGenerator(articleList, paths, env, language, folder='', future=False):
articles = []
meta = {}
meta['language'] = language
meta['url'] = '{}atom.xml'.format(folder)
for i in articleList:
if i.date > datetime.now() and not future:
continue
url = None
url = '{}/{}.html'.format(language, i.slug)
articles.append({'title': i.content.getTitle(language=language).
decode('utf8'),
'content': i.content.getText(language=language).
decode('utf8'),
'date': i.date,
'url': url})
if not os.path.exists(os.path.join(paths['output'], folder)):
os.makedirs(os.path.join(paths['output'], folder))
t = env.get_template('atom.xml')
f = open(os.path.join(paths['output'], folder, 'atom.xml'), 'wb')
f.write(t.render(articles=articles, meta=meta).encode('utf-8'))
f.close()
|
jackzhao-mj/ok | server/tests/integration/test_api_course.py | Python | apache-2.0 | 1,100 | 0.02 | #!/usr/bin/env python
# encoding: utf-8
#pylint: disable=no-member, no-init, too-many-public-methods
#pylint: disable=attribute-defined-outside-init
# This disable is because the tests need to be name such that
# you can understand what the test is doing from the method name.
#pylint: disable=missing-docstring
"""
tests.py
"""
import datetime
from test_base import APIBaseTestCase, unittest, api #pylint: disable=relative-import
from test_base import make_fake_assignment, make_fake_course, make_fake_backup, make_fake_submission, make_fake_finalsubmission #pylint: disable=relative-import
from google.appengine.ext import ndb
from app import models, constants, | utils
from ddt import ddt, data, unpack
from app.exceptions import *
from integration.test_api_base import APITest
class CourseAPITest(APITest, APIBaseTestCase):
model = models.Course
name = 'course'
num = 1
access_token = 'dummy_admin'
def get_basic_instance(self, mutate=True):
name = 'testcourse'
if mutate:
name += str(self.num)
self.num += 1
rval = m | ake_fake_course(self.user)
rval.name = name
return rval |
wildchildyn/autism-website | yanni_env/lib/python3.6/site-packages/sqlalchemy/dialects/mssql/__init__.py | Python | gpl-3.0 | 1,081 | 0.000925 | # mssql/__ini | t__.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy.dialects.mssql import base, pyodbc, adodbapi, \
pymssql, zxjdbc, mxodbc
base.dialect = pyodbc.dialect
from sqlalchemy.dialects.mssql.base import \
INTEGER, BIGINT, SMALLINT, TINYINT, VA | RCHAR, NVARCHAR, CHAR, \
NCHAR, TEXT, NTEXT, DECIMAL, NUMERIC, FLOAT, DATETIME,\
DATETIME2, DATETIMEOFFSET, DATE, TIME, SMALLDATETIME, \
BINARY, VARBINARY, BIT, REAL, IMAGE, TIMESTAMP,\
MONEY, SMALLMONEY, UNIQUEIDENTIFIER, SQL_VARIANT, dialect
__all__ = (
'INTEGER', 'BIGINT', 'SMALLINT', 'TINYINT', 'VARCHAR', 'NVARCHAR', 'CHAR',
'NCHAR', 'TEXT', 'NTEXT', 'DECIMAL', 'NUMERIC', 'FLOAT', 'DATETIME',
'DATETIME2', 'DATETIMEOFFSET', 'DATE', 'TIME', 'SMALLDATETIME',
'BINARY', 'VARBINARY', 'BIT', 'REAL', 'IMAGE', 'TIMESTAMP',
'MONEY', 'SMALLMONEY', 'UNIQUEIDENTIFIER', 'SQL_VARIANT', 'dialect'
)
|
dzamie/weasyl | weasyl/test/test_collection.py | Python | apache-2.0 | 1,760 | 0.000568 | import unittest
import pytest
from libweasyl import ratings
from weasyl.error import WeasylError
from weasyl.test import db_utils
from weasyl import collection
@pytest.mark.usefixtures('db')
class CollectionsTestCase(unittest.TestCase):
def setUp(self):
self.creator = db_utils.create_user()
self.collector = db_utils.create_user()
self.s = db_utils.create_submission(self.creator)
def offer(self):
collection.offer(self.creator, self.s, self.collector)
def count_collections(self, pending, ra | ting=ratings.GENERAL.code):
return len(collection.select_manage(self.collector, rating, 10, pending))
def test_offer_and_accept(self):
self.offer()
self.assertEqual(1, self.count_collections(True))
collection.pending_accept(self.col | lector, [(self.s, self.collector)])
self.assertEqual(1, self.count_collections(False))
def test_offer_with_errors(self):
self.assertRaises(WeasylError, collection.offer,
db_utils.create_user(), self.s, self.collector)
def test_offer_and_reject(self):
self.offer()
self.assertEqual(1, self.count_collections(True))
collection.pending_reject(self.collector, [(self.s, self.collector)])
self.assertEqual(0, self.count_collections(False))
self.assertEqual(0, self.count_collections(True))
def test_offer_accept_and_remove(self):
self.offer()
self.assertEqual(1, self.count_collections(True))
collection.pending_accept(self.collector, [(self.s, self.collector)])
collection.remove(self.collector, [self.s])
self.assertEqual(0, self.count_collections(False))
self.assertEqual(0, self.count_collections(True))
|
singulared/aiohttp | aiohttp/http.py | Python | apache-2.0 | 1,163 | 0 | from .http_exceptions import HttpProcessingError
from .http_message import (RESPONSES, SERVER_SOFTWARE, HttpMessage,
HttpVersion, HttpVersion10, HttpVersion11,
PayloadWriter, Request, Response)
from .http_parser import (HttpParser, HttpRequestParser, HttpResponseParser,
RawReq | uestMessage, RawResponseMessage)
from .http_websocket import (WS_CLOSED_MESSAGE, WS_CLOSING_MESSAGE, WS_KEY,
WebSocketError, WebSocketReader, WebSocketWriter,
WSCloseCode, WSMessage, WSMsgType, do_handshake)
__all | __ = (
'HttpProcessingError',
# .http_message
'RESPONSES', 'SERVER_SOFTWARE',
'HttpMessage', 'Request', 'Response', 'PayloadWriter',
'HttpVersion', 'HttpVersion10', 'HttpVersion11',
# .http_parser
'HttpParser', 'HttpRequestParser', 'HttpResponseParser',
'RawRequestMessage', 'RawResponseMessage',
# .http_websocket
'WS_CLOSED_MESSAGE', 'WS_CLOSING_MESSAGE', 'WS_KEY',
'WebSocketReader', 'WebSocketWriter', 'do_handshake',
'WSMessage', 'WebSocketError', 'WSMsgType', 'WSCloseCode',
)
|
PARINetwork/pari | article/views.py | Python | bsd-3-clause | 8,919 | 0.001345 | import calendar
from bs4 import BeautifulSoup
from django.views.generic import ListView
from django.views.generic.detail import DetailView
from django.conf import settings
from django.http import Http404
from django.core.cache import caches
from django.contrib.contenttypes.models import ContentType
from wagtail.core.models import Page
from article.models import Article
from author.models import Author
from core.utils import get_translations_for_page, filter_by_language
from album.models import Album
from face.models import Face
from resources.models import Resource
from core.mixins import Page1Redirector
class ArticleDetail(DetailView):
template_name = "article/article.html"
model = Article
def get_object(self, queryset=None):
obj = super(ArticleDetail, self).get_object(queryset)
if self.request.user.is_staff or self.request.GET.get("preview"):
obj = obj.get_latest_revision_as_page()
return obj
if not obj.live:
raise Http404
return obj
def get_context_data(self, **kwargs):
context = super(ArticleDetail, self).get_context_data(**kwargs)
translations = get_translations_for_page(context['object'])
context['translations'] = translations
arc = ContentType.objects.get_for_model(Article)
alc = ContentType.objects.get_for_model(Album)
fac = ContentType.objects.get_for_model(Face)
rec = ContentType.objects.get_for_model(Resource)
context['new_list'] = Page.objects.live()\
.filter(content_type__in=[
arc, alc, fac, rec
])\
.order_by('-first_published_at')[:4]
context['MAP_KEY'] = settings.GOOGLE_MAP_KEY
context['current_page'] = 'article-detail'
context['beginning_authors_with_role'] = self.object.beginning_authors_with_role()
context['end_authors_with_role'] = self.object.end_authors_with_role()
return context
def render_to_response(self, context, **kwargs):
response = super(ArticleDetail, self).render_to_response(context, **kwargs)
if self.request.user.is_staff or self.request.GET.get("preview"):
return response
cache = caches['default']
if cache.get(context['object'].get_absolute_url()):
return cache.get(context['object'].get_absolute_url())
content = response.rendered_content
bs = BeautifulSoup(content, "html5lib")
imgs = bs.find("div", class_="article-content").find_all("img")
for img in imgs:
if not img.attrs:
continue
ns_attrs = img.attrs
ns_img = bs.new_tag("img", **ns_attrs)
img.insert_before(ns_img)
ns_img.wrap(bs.new_tag("noscript"))
if img.attrs.get("class") and "lazyload" in img.attrs["class"]:
continue
img.attrs["class"] = img.attrs.get("class", []) + ["lazyload"]
if img.attrs.get("src"):
img.attrs["data-src"] = img.attrs.get("src")
if img.attrs.get("srcset"):
img.attrs["data-srcset"] = img.attrs.get("srcset")
img.attrs.pop("srcset", "")
gray_gif = "data:image/gif;base64,R0lGODlhAQABAIAAAMLCwgAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="
img.attrs["src"] = gray_gif
content = bs.decode('utf-8','ignore')
response.content = content
cache.set(context['object'].get_absolute_url(), response)
return response
class ArchiveDetail(Page1Redirector, ListView):
context_object_name = "articles"
model = Article
template_name = 'article/archive_article_list.html'
paginate_by = 12
def get_queryset(self):
year = self.kwargs['year']
month = self.kwargs['month']
qs = Article.objects.live().filter(first_published_at__year=year,
first_published_at__month=month).order_by('-first_published_at')
qs, = filter_by_language(self.request, qs)
return qs
def get_context_data(self, **kwargs):
context = super(ArchiveDetail, self).get_context_data(**kwargs)
context['year'] = self.kwargs["year"]
context['month'] = self.kwargs["month"]
context['month_as_name'] = calendar.month_name[int(context["month"])]
context['title'] = "{0} {1}".format(context['month_as_name'], context["year"])
context['LANGAUAGES'] = settings.LANGUAGES
context['current_page'] = 'archive-detail'
return context
class AuthorArticleList(Page1Redirector, ListView):
context_object_name = "articles"
paginate_by = 12
template_name = "article/author_article_list.html"
def get_queryset(self):
live_articles_by_author = Article.objects.live().filter(
authors__author__slug=self.kwargs["slug"]
)
qs = live_articles_by_author.order_by("-first_published_at")
qs, = filter_by_language(self.request, qs)
return qs
def get_context_data(self, **kwargs):
context = super(AuthorArticleList, self).get_context_data(**kwargs)
try:
author = Author.objects.get(slug=self.kwargs["slug"])
except Author.DoesNotExist:
raise Http404
context["authors"] = [author]
context["title"] = "All stories by %s" %(author.name)
context["articles"] = context["page_obj"]
context['LANGUAGES'] = settings.LANGUAGES
context['current_page'] = 'author-detail'
return context
class ArticleList(Page1Redirector, ListView):
context_object_name = "articles"
model = Article
paginate_by = 12
template_name = 'article/archive_article_list.html'
def get_queryset(self):
url_name = self.request.resolver_match.url_name
if url_name == "author-detail":
live_articles_by_author = Article.objects.live().filter(
authors__author__slug=self.kwargs["slug"]
)
qs = live_articles_by_author.order_by("-first_published_at")
else:
qs = super(ArticleList, self).get_queryset().filter(live=True)
if self.request.GET.get("lang"):
qs = qs.filter(language=self.request.GET["lang"])
return qs
def get_context_data(self, **kwargs):
context = super(ArticleList, self).get_context_data(**kwargs)
current_page_type = self.kwargs['filter']
url_name = self.request.resolver_match.url_name
context['title'] = "All articles"
if url_name == "author-detail":
try:
context["author"] = Author.objects.get(slug=self.kwargs["slug"])
except Author.DoesNotExist:
raise Http404
context["title"] = context["author"].name
context["articles"] = context["page_obj"]
context['LANGUAGES'] = settings.LANGUAGES
context['current_page'] = current_page_type
return context
cla | ss GalleryArticleList(P | age1Redirector, ListView):
context_object_name = "articles"
model = Article
paginate_by = 12
template_name = 'includes/gallery_article_list.html'
def get_queryset(self):
url_name = self.request.resolver_match.url_name
if url_name == "author-detail":
live_articles_by_author = Article.objects.live().filter(
authors__slug=self.kwargs["slug"]
)
qs = live_articles_by_author.order_by("-first_published_at")
else:
qs = super(GalleryArticleList, self).get_queryset()
if self.request.GET.get("lang"):
qs = qs.filter(language=self.request.GET["lang"])
return qs
def get_context_data(self, **kwargs):
context = super(GalleryArticleList, self).get_context_data(**kwargs)
url_name = self.request.resolver_match.url_name
context['title'] = "All articles"
if url_name == "author-detail":
try:
context["author"] = Author.objects.get(slug=self.kwargs[" |
sleepinghungry/wwif | students/parker/practice 3.py | Python | mit | 766 | 0.050914 | Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
RESTART: Z:\Coding Cla | sses\Python Text Adventures\wwif\students\parker\practice 2.py
I will spell the word "one"
o
n
e
>>>
RESTART: Z:\Coding Classes\Python Text Adventures\wwif\students\parker\practice 2.py
I will spell the word "one"
one
>>>
RESTART: Z:\Coding | Classes\Python Text Adventures\wwif\students\parker\practice 2.py
what is your name?parker
6
>>> semi
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
semi
NameError: name 'semi' is not defined
>>>
RESTART: Z:\Coding Classes\Python Text Adventures\wwif\students\parker\practice 2.py
Your name?
|
soulmachine/scikit-learn | examples/cluster/plot_kmeans_digits.py | Python | bsd-3-clause | 4,526 | 0.001989 | """
===========================================================
A demo of K-Means clustering on the handwritten digits data
===========================================================
In this example with compare the various initialization strategies for
K-means in terms of runtime and quality of the results.
As the ground truth is known here, we also apply different cluster
quality metrics to judge the goodness of fit of the cluster labels to the
ground truth.
Cluster quality metrics evaluated (see :ref:`clustering_evaluation` for
definitions and discussions of the metrics):
=========== ========================================================
Shorthand full name
=========== ========================================================
homo homogeneity score
compl completeness score
v-meas V measure
ARI adjusted Rand index
AMI adjusted mutual information
silhouette silhouette coefficient
=========== ========================================================
"""
print(__doc__)
from time import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.cluster import KMeans
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.preprocessing import scale
np.random.seed(42)
digits = load_digits()
data = scale(digits.data)
n_samples, n_features = data.shape
n_digits = len(np.unique(digits.target))
labels = digits.target
sample_size = 300
print("n_digits: %d, \t n_samples %d, \t n_features %d"
% (n_digits, n_samples, n_features))
print(79 * '_')
print('% 9s' % 'init'
' time inertia homo compl v-meas ARI AMI silhouette')
def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('% 9s %.2fs %i %.3f %.3f %.3f %.3f %.3f %.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estimator.labels_),
metrics.v_measure_score(labels, estimator.labels_),
metrics.adjusted_rand_score(labels, estimator.labels_),
metrics.adjusted_mutual_info_score(labels, estimator.labels_),
metrics.silhouette_score(data, estimator.labels_,
metric='euclidean',
sample_size=sample_size)))
bench_k_means(KMeans(init='k-means++', n_clusters=n_digits, n_init=10),
name="k-means++", data=data)
bench_k_means(KMeans(init='random', n_clusters=n_digits, n_init=10),
name="random", data=data)
# in this case the seeding of the centers is deterministic, hence we run the
# kmeans algorithm only once with n_init=1
pca = PCA(n_components=n_digits).fit(data)
bench_k_means(KMeans(init=pca.components_, n_clusters=n_digits, n_init=1),
name="PCA-based",
data=data)
print(79 * '_')
###############################################################################
# Visualize the results on PCA-reduced data
reduced_data = PCA(n_components=2).fit_transform(data)
kmeans = KMeans(init='k-means++', n_clusters=n_digits, n_init=10)
kmeans.fit(reduced_data)
# Step size of the mesh. Decrease to increase | the quality of the VQ.
h = .02 # point in the mesh [x_min, m_max]x[y_min, y_max].
# Plot the decision boundary. For that, we will assign a color to each
x_min, x_max = reduced_data[:, 0].min() + 1, reduced_data[:, 0].max() - 1
y_min, y_max = reduced_data[:, 1].min() + 1, reduced_data[:, 1].max() - 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
# | Obtain labels for each point in mesh. Use last trained model.
Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])
# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure(1)
plt.clf()
plt.imshow(Z, interpolation='nearest',
extent=(xx.min(), xx.max(), yy.min(), yy.max()),
cmap=plt.cm.Paired,
aspect='auto', origin='lower')
plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)
# Plot the centroids as a white X
centroids = kmeans.cluster_centers_
plt.scatter(centroids[:, 0], centroids[:, 1],
marker='x', s=169, linewidths=3,
color='w', zorder=10)
plt.title('K-means clustering on the digits dataset (PCA-reduced data)\n'
'Centroids are marked with white cross')
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xticks(())
plt.yticks(())
plt.show()
|
betrisey/home-assistant | homeassistant/components/sensor/scrape.py | Python | mit | 3,388 | 0 | """
Support for getting data from websites with scraping.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.scrape/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.components.sensor.rest import RestData
from homeassistant.const import (
CONF_NAME, CONF_RESOURCE, CONF_UNIT_OF_MEASUREMENT, STATE_UNKNOWN,
CONF_VALUE_TEMPLATE, CONF_VERIFY_SSL)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['beautifulsoup4==4.5.1']
_LOGGER = logging.getLogger(__name__)
CONF_SELECT = 'select'
DEFAULT_NAME = 'Web scrape'
DEFAULT_VERIFY_SSL = True
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_RESOURCE): cv.string,
vol.Required(CONF_SELECT): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean,
})
# pylint: disable=too-many-locals
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Web scrape sensor."""
name = config.get(CONF_NAME)
resource = config.get(CONF_RESOURCE)
method = 'GET'
payload = auth = headers = None
verify_ssl = config.get(CONF_VERIFY_SSL)
select = config.get(CONF_SELECT)
unit = config.get(CONF_UNIT_OF_MEASUREMENT)
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
rest = RestData(method, resource, auth, headers, payload, verify_ssl)
rest.update()
if rest.data is None:
_LOGGER.error("Unable to fetch data from %s", resource)
return False
add_devices([
ScrapeSensor(hass, rest, | name, select, value_template, unit)
])
# pylint: disable=to | o-many-instance-attributes
class ScrapeSensor(Entity):
"""Representation of a web scrape sensor."""
# pylint: disable=too-many-arguments
def __init__(self, hass, rest, name, select, value_template, unit):
"""Initialize a web scrape sensor."""
self.rest = rest
self._name = name
self._state = STATE_UNKNOWN
self._select = select
self._value_template = value_template
self._unit_of_measurement = unit
self.update()
@property
def name(self):
"""Return the name of the sensor."""
return self._name
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return self._unit_of_measurement
@property
def state(self):
"""Return the state of the device."""
return self._state
def update(self):
"""Get the latest data from the source and updates the state."""
self.rest.update()
from bs4 import BeautifulSoup
raw_data = BeautifulSoup(self.rest.data, 'html.parser')
_LOGGER.debug(raw_data)
value = raw_data.select(self._select)[0].text
_LOGGER.debug(value)
if self._value_template is not None:
self._state = self._value_template.render_with_possible_json_value(
value, STATE_UNKNOWN)
else:
self._state = value
|
pfalcon/ScratchABlock | script_func_returns.py | Python | gpl-3.0 | 346 | 0 | from xform import *
from dataflow import *
import xform_inter
import script_preserveds
cg = None
def init():
global cg
cg = xform_inter.build_c | allgraph()
def apply(cfg):
script_preserveds.apply(cfg)
collect_call_live_out(cfg)
xform_inter | .calc_callsites_live_out(cg, cfg.props["name"])
xform_inter.collect_returns()
|
yandex/yandex-tank | yandextank/stepper/__init__.py | Python | lgpl-2.1 | 129 | 0 | #
from .main imp | ort Stepper, StepperWrapper # noqa
from .info import StepperInfo # noqa
from .format import StpdReader # no | qa
|
kret0s/gnuhealth-live | tryton/server/trytond-3.8.3/trytond/ir/model.py | Python | gpl-3.0 | 39,540 | 0.002099 | # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import re
import heapq
from sql import Null
from sql.aggregate import Max
from sql.conditionals import Case
from collections import defaultdict
try:
import simplejson as json
except ImportError:
import json
from ..model import ModelView, ModelSQL, fields, Unique
from ..report import Report
from ..wizard import Wizard, StateView, StateAction, Button
from ..transaction import Transaction
from ..cache import Cache
from ..pool import Pool
from ..pyson import Bool, Eval
from ..rpc import RPC
from .. import backend
from ..protocols.jsonrpc import JSONDecoder, JSONEncoder
from ..tools import is_instance_method
try:
from ..tools.StringMatcher import StringMatcher
except ImportError:
from difflib import SequenceMatcher as StringMatcher
__all__ = [
'Model', 'ModelField', 'ModelAccess', 'ModelFieldAccess', 'ModelButton',
'ModelData', 'PrintModelGraphStart', 'PrintModelGraph', 'ModelGraph',
]
IDENTIFIER = re.compile(r'^[a-zA-z_][a-zA-Z0-9_]*$')
class Model(ModelSQL, ModelView):
"Model"
__name__ = 'ir.model'
_order_name = 'model'
name = fields.Char('Model Description', translate=True, loading='lazy',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
model = fields.Char('Model Name', required=True,
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
info = fields.Text('Information',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
module = fields.Char('Module',
help="Module in which this model is defined", readonly=True)
global_search_p = fields.Boolean('Global Search')
fields = fields.One2Many('ir.model.field', 'model', 'Fields',
required=True)
@classmethod
def __setup__(cls):
super(Model, cls).__setup__()
table = cls.__table__()
cls._sql_constraints += [
('model_uniq', Unique(table, table.model),
'The model must be unique!'),
]
cls._error_messages.update({
'invalid_module': ('Module name "%s" is not a valid python '
'identifier.'),
})
cls._order.insert(0, ('model', 'ASC'))
cls.__rpc__.update({
'list_models': RPC(),
'list_history': RPC(),
'global_search': RPC(),
})
@classmethod
def register(cls, model, module_name):
pool = Pool()
Property = pool.get('ir.property')
cursor = Transaction().cursor
ir_model = cls.__table__()
cursor.execute(*ir_model.select(ir_model.id,
where=ir_model.model == model.__name__))
model_id = None
if cursor.rowcount == -1 or cursor.rowcount is None:
data = cursor.fetchone()
if data:
model_id, = data
elif cursor.rowcount != 0:
model_id, = cursor.fetchone()
if not model_id:
cursor.execute(*ir_model.insert(
[ir_model.model, ir_model.name, ir_model.info,
ir_model.module],
[[model.__name__, model._get_name(), model.__doc__,
module_name]]))
Property._models_get_cache.clear()
cursor.execute(*ir_model.select(ir_model.id,
where=ir_model.model == model.__name__))
(model_id,) = cursor.fetchone()
elif model.__doc__:
cursor.execute(*ir_model.update(
[ir_model.name, ir_model.info],
[model._get_name(), model.__doc__],
where=ir_model.id == model_id))
return model_id
@classmethod
def validate(cls, models):
super(Model, cls).validate(models)
cls.check_module(models)
@classmethod
def check_module(cls, models):
'''
Check module
'''
for model in models:
if model.module and not IDENTIFIER.match(model.module):
cls.raise_user_error('invalid_module', (model.rec_name,))
@classmethod
def list_models(cls):
'Return a list of all models names'
models = cls.search([], order=[
('module', 'ASC'), # Optimization assumption
('model', 'ASC'),
('id', 'ASC'),
])
return [m.model for m in models]
@classmethod
def list_history(cls):
'Return a list of all models with history'
return [name for name, model in Pool().iterobject()
if getattr(model, '_history', False)]
@classmethod
def create(cls, vlis | t):
pool = Pool()
Property = pool.get('ir.property')
res = super(Model, cls).create(vlist)
# Restart the cache of models_get
Property._models_get_cache.clear()
return res
@classmethod
def write(cls, models, values, *args):
pool = Pool()
Property = pool.get('ir.property')
super(Model, cls).write(models, values, *args) |
# Restart the cache of models_get
Property._models_get_cache.clear()
@classmethod
def delete(cls, models):
pool = Pool()
Property = pool.get('ir.property')
super(Model, cls).delete(models)
# Restart the cache of models_get
Property._models_get_cache.clear()
@classmethod
def global_search(cls, text, limit, menu='ir.ui.menu'):
"""
Search on models for text including menu
Returns a list of tuple (ratio, model, model_name, id, name, icon)
The size of the list is limited to limit
"""
pool = Pool()
ModelAccess = pool.get('ir.model.access')
if not limit > 0:
raise ValueError('limit must be > 0: %r' % (limit,))
models = cls.search(['OR',
('global_search_p', '=', True),
('model', '=', menu),
])
access = ModelAccess.get_access([m.model for m in models])
s = StringMatcher()
if isinstance(text, str):
text = text.decode('utf-8')
s.set_seq2(text)
def generate():
for model in models:
if not access[model.model]['read']:
continue
Model = pool.get(model.model)
if not hasattr(Model, 'search_global'):
continue
for record, name, icon in Model.search_global(text):
if isinstance(name, str):
name = name.decode('utf-8')
s.set_seq1(name)
yield (s.ratio(), model.model, model.rec_name,
record.id, name, icon)
return heapq.nlargest(int(limit), generate())
class ModelField(ModelSQL, ModelView):
"Model field"
__name__ = 'ir.model.field'
name = fields.Char('Name', required=True,
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
relation = fields.Char('Model Relation',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
model = fields.Many2One('ir.model', 'Model', required=True,
select=True, ondelete='CASCADE',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
field_description = fields.Char('Field Description', translate=True,
loading='lazy',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
ttype = fields.Char('Field Type',
states={
'readonly': Bool(Eval('module')),
},
depends=['module'])
groups = fields.Many2Many('ir.model.field-res.group', 'field',
'group', 'Groups')
help = fields.Text('Help', translate=True, loading='lazy',
states={
'readonly': Bool(Eval(' |
alfredgamulo/cloud-custodian | tests/test_lookup.py | Python | apache-2.0 | 2,809 | 0 | # Copyright 2019 Microsoft Corp
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from .common import BaseTest
from c7n.lookup import Lookup
class LookupTest(BaseTest):
def test_lookup_type(self):
number_schema = {'type': 'number'}
lookup_default_number = Look | up.lookup_type(number_schema)
string_schema = {'type': 'string'}
lookup_default_string = Lookup.lookup_type(string_schema)
self.assertEqual(number_schema, lookup_default_number['oneOf'][1])
self.assertEqual(number_schema,
lookup_defa | ult_number['oneOf'][0]['oneOf'][0]
['properties']['default-value'])
self.assertEqual(string_schema, lookup_default_string['oneOf'][1])
self.assertEqual(string_schema,
lookup_default_string['oneOf'][0]['oneOf'][0]
['properties']['default-value'])
def test_extract_no_lookup(self):
source = 'mock_string_value'
value = Lookup.extract(source)
self.assertEqual(source, value)
def test_extract_lookup(self):
data = {
'field_level_1': {
'field_level_2': 'value_1'
}
}
source = {
'type': Lookup.RESOURCE_SOURCE,
'key': 'field_level_1.field_level_2',
'default-value': 'value_2'
}
value = Lookup.extract(source, data)
self.assertEqual(value, 'value_1')
def test_get_value_from_resource_value_exists(self):
resource = {
'field_level_1': {
'field_level_2': 'value_1'
}
}
source = {
'type': Lookup.RESOURCE_SOURCE,
'key': 'field_level_1.field_level_2',
'default-value': 'value_2'
}
value = Lookup.get_value_from_resource(source, resource)
self.assertEqual(value, 'value_1')
def test_get_value_from_resource_value_not_exists(self):
resource = {
'field_level_1': {
'field_level_2': None
}
}
source = {
'type': Lookup.RESOURCE_SOURCE,
'key': 'field_level_1.field_level_2',
'default-value': 'value_2'
}
value = Lookup.get_value_from_resource(source, resource)
self.assertEqual(value, 'value_2')
def test_get_value_from_resource_value_not_exists_exception(self):
resource = {
'field_level_1': {
'field_level_2': None
}
}
source = {
'type': Lookup.RESOURCE_SOURCE,
'key': 'field_level_1.field_level_2'
}
with self.assertRaises(Exception):
Lookup.get_value_from_resource(source, resource)
|
Architektor/PySnip | venv/lib/python2.7/site-packages/twisted/internet/test/test_posixbase.py | Python | gpl-3.0 | 9,553 | 0.003036 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.internet.posixbase} and supporting code.
"""
from __future__ import division, absolute_import
from twisted.trial.unittest import TestCase
from twisted.internet.defer import Deferred
from twisted.internet.posixbase import PosixReactorBase, _Waker
from twisted.internet.protocol import ServerFactory
skipSockets = None
try:
from twisted.internet import unix
from twisted.test.test_unix import ClientProto
except ImportError:
skipSockets = "Platform does not support AF_UNIX sockets"
from twisted.internet.tcp import Port
from twisted.internet import reactor
class TrivialReactor(PosixReactorBase):
def __init__(self):
self._readers = {}
self._writers = {}
PosixReactorBase.__init__(self)
def addReader(self, reader):
self._readers[reader] = True
def removeReader(self, reader):
del self._readers[reader]
def addWriter(self, writer):
self._writers[writer] = True
def removeWriter(self, writer):
del self._writers[writer]
class PosixReactorBaseTests(TestCase):
"""
Tests for L{PosixReactorBase}.
"""
def _checkWaker(self, reactor):
self.assertIsInstance(reactor.waker, _Waker)
self.assertIn(reactor.waker, reactor._internalReaders)
self.assertIn(reactor.waker, reactor._readers)
def test_wakerIsInternalReader(self):
"""
When L{PosixReactorBase} is instantiated, it creates a waker and adds
it to its internal readers set.
"""
reactor = TrivialReactor()
self._checkWaker(reactor)
def test_removeAllSkipsInternalReaders(self):
"""
Any L{IReadDescriptors} in L{PosixReactorBase._internalReaders} are
left alone by L{P | osixReactorBase._removeAll}.
"""
reactor = TrivialReactor()
extra = object()
reactor._inter | nalReaders.add(extra)
reactor.addReader(extra)
reactor._removeAll(reactor._readers, reactor._writers)
self._checkWaker(reactor)
self.assertIn(extra, reactor._internalReaders)
self.assertIn(extra, reactor._readers)
def test_removeAllReturnsRemovedDescriptors(self):
"""
L{PosixReactorBase._removeAll} returns a list of removed
L{IReadDescriptor} and L{IWriteDescriptor} objects.
"""
reactor = TrivialReactor()
reader = object()
writer = object()
reactor.addReader(reader)
reactor.addWriter(writer)
removed = reactor._removeAll(
reactor._readers, reactor._writers)
self.assertEqual(set(removed), set([reader, writer]))
self.assertNotIn(reader, reactor._readers)
self.assertNotIn(writer, reactor._writers)
class TCPPortTests(TestCase):
"""
Tests for L{twisted.internet.tcp.Port}.
"""
if not isinstance(reactor, PosixReactorBase):
skip = "Non-posixbase reactor"
def test_connectionLostFailed(self):
"""
L{Port.stopListening} returns a L{Deferred} which errbacks if
L{Port.connectionLost} raises an exception.
"""
port = Port(12345, ServerFactory())
port.connected = True
port.connectionLost = lambda reason: 1 // 0
return self.assertFailure(port.stopListening(), ZeroDivisionError)
class TimeoutReportReactor(PosixReactorBase):
"""
A reactor which is just barely runnable and which cannot monitor any
readers or writers, and which fires a L{Deferred} with the timeout
passed to its C{doIteration} method as soon as that method is invoked.
"""
def __init__(self):
PosixReactorBase.__init__(self)
self.iterationTimeout = Deferred()
self.now = 100
def addReader(self, reader):
"""
Ignore the reader. This is necessary because the waker will be
added. However, we won't actually monitor it for any events.
"""
def removeAll(self):
"""
There are no readers or writers, so there is nothing to remove.
This will be called when the reactor stops, though, so it must be
implemented.
"""
return []
def seconds(self):
"""
Override the real clock with a deterministic one that can be easily
controlled in a unit test.
"""
return self.now
def doIteration(self, timeout):
d = self.iterationTimeout
if d is not None:
self.iterationTimeout = None
d.callback(timeout)
class IterationTimeoutTests(TestCase):
"""
Tests for the timeout argument L{PosixReactorBase.run} calls
L{PosixReactorBase.doIteration} with in the presence of various delayed
calls.
"""
def _checkIterationTimeout(self, reactor):
timeout = []
reactor.iterationTimeout.addCallback(timeout.append)
reactor.iterationTimeout.addCallback(lambda ignored: reactor.stop())
reactor.run()
return timeout[0]
def test_noCalls(self):
"""
If there are no delayed calls, C{doIteration} is called with a
timeout of C{None}.
"""
reactor = TimeoutReportReactor()
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, None)
def test_delayedCall(self):
"""
If there is a delayed call, C{doIteration} is called with a timeout
which is the difference between the current time and the time at
which that call is to run.
"""
reactor = TimeoutReportReactor()
reactor.callLater(100, lambda: None)
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 100)
def test_timePasses(self):
"""
If a delayed call is scheduled and then some time passes, the
timeout passed to C{doIteration} is reduced by the amount of time
which passed.
"""
reactor = TimeoutReportReactor()
reactor.callLater(100, lambda: None)
reactor.now += 25
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 75)
def test_multipleDelayedCalls(self):
"""
If there are several delayed calls, C{doIteration} is called with a
timeout which is the difference between the current time and the
time at which the earlier of the two calls is to run.
"""
reactor = TimeoutReportReactor()
reactor.callLater(50, lambda: None)
reactor.callLater(10, lambda: None)
reactor.callLater(100, lambda: None)
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 10)
def test_resetDelayedCall(self):
"""
If a delayed call is reset, the timeout passed to C{doIteration} is
based on the interval between the time when reset is called and the
new delay of the call.
"""
reactor = TimeoutReportReactor()
call = reactor.callLater(50, lambda: None)
reactor.now += 25
call.reset(15)
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 15)
def test_delayDelayedCall(self):
"""
If a delayed call is re-delayed, the timeout passed to
C{doIteration} is based on the remaining time before the call would
have been made and the additional amount of time passed to the delay
method.
"""
reactor = TimeoutReportReactor()
call = reactor.callLater(50, lambda: None)
reactor.now += 10
call.delay(20)
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, 60)
def test_cancelDelayedCall(self):
"""
If the only delayed call is canceled, C{None} is the timeout passed
to C{doIteration}.
"""
reactor = TimeoutReportReactor()
call = reactor.callLater(50, lambda: None)
call.cancel()
timeout = self._checkIterationTimeout(reactor)
self.assertEqual(timeout, None)
class ConnectedDatagramPortTests(TestC |
PyCQA/pylint | tests/functional/c/consider/consider_using_dict_items.py | Python | gpl-2.0 | 3,585 | 0.003905 | """Emit a message for iteration through dict keys and subscripting dict with key."""
# pylint: disable=line-too-long,missing-docstring,unsubscriptable-object,too-few-public-methods,redefined-outer-name,use-dict-literal,modified-iterating-dict
def bad():
a_dict = {1: 1, 2: 2, 3: 3}
for k in a_dict: # [consider-using-dict-items]
print(a_dict[k])
another_dict = dict()
for k in another_dict: # [consider-using-dict-items]
print(another_dict[k])
def good():
a_dict = {1: 1, 2: 2, 3: 3}
for k in a_dict:
print(k)
out_of_scope_dict = dict()
def another_bad():
for k in out_of_scope_dict: # [consider-using-dict-items]
print(out_of_scope_dict[k])
def another_good():
for k in out_of_scope_dict:
k = 1
k = 2
k = 3
print(out_of_scope_dict[k])
|
b_dict = {}
for k2 in b_dict: # Should not emit warning, key access necessary
b_dict[k2] = 2
for k2 in b_dict: # Should not emit warning, key access necessary (AugAssign)
b_dict[k2] += 2
|
# Warning should be emitted in this case
for k6 in b_dict: # [consider-using-dict-items]
val = b_dict[k6]
b_dict[k6] = 2
for k3 in b_dict: # [consider-using-dict-items]
val = b_dict[k3]
for k4 in b_dict.keys(): # [consider-iterating-dictionary,consider-using-dict-items]
val = b_dict[k4]
class Foo:
c_dict = {}
# Should emit warning when iterating over a dict attribute of a class
for k5 in Foo.c_dict: # [consider-using-dict-items]
val = Foo.c_dict[k5]
c_dict = {}
# Should NOT emit warning whey key used to access a different dict
for k5 in Foo.c_dict: # This is fine
val = b_dict[k5]
for k5 in Foo.c_dict: # This is fine
val = c_dict[k5]
# Should emit warning within a list/dict comprehension
val = {k9: b_dict[k9] for k9 in b_dict} # [consider-using-dict-items]
val = [(k7, b_dict[k7]) for k7 in b_dict] # [consider-using-dict-items]
# Should emit warning even when using dict attribute of a class within comprehension
val = [(k7, Foo.c_dict[k7]) for k7 in Foo.c_dict] # [consider-using-dict-items]
val = any(True for k8 in Foo.c_dict if Foo.c_dict[k8]) # [consider-using-dict-items]
# Should emit warning when dict access done in ``if`` portion of comprehension
val = any(True for k8 in b_dict if b_dict[k8]) # [consider-using-dict-items]
# Should NOT emit warning whey key used to access a different dict
val = [(k7, b_dict[k7]) for k7 in Foo.c_dict]
val = any(True for k8 in Foo.c_dict if b_dict[k8])
# Should NOT emit warning, essentially same check as above
val = [(k7, c_dict[k7]) for k7 in Foo.c_dict]
val = any(True for k8 in Foo.c_dict if c_dict[k8])
# Should emit warning, using .keys() of Foo.c_dict
val = any(True for k8 in Foo.c_dict.keys() if Foo.c_dict[k8]) # [consider-iterating-dictionary,consider-using-dict-items]
# Test false positive described in #4630
# (https://github.com/PyCQA/pylint/issues/4630)
d = {'key': 'value'}
for k in d: # this is fine, with the reassignment of d[k], d[k] is necessary
d[k] += '123'
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1')
for k in d: # if this gets rewritten to d.items(), we are back to the above problem
d[k] = d[k] + 1
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1')
for k in d: # [consider-using-dict-items]
if '1' in d[k]: # index lookup necessary here, do not emit error
print('found 1')
|
kodki/cortext | cortext/text.py | Python | mit | 1,056 | 0.000947 | import nltk
class Text:
def __init__(self, raw_text):
self.raw_text = raw_text
def parse(self):
sentences = nltk.sent_tokenize(self.raw_text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
self.tagged_sentences = [self.tag(words) for words in tokens]
return self
def tag(self, sentence):
initial_tagged_words = nltk.pos_tag(sentence)
tagged_words = []
consecutive_names = []
last_tag = None
for tagged_word in initial_tagged_words:
if ta | gged_word[1].startsw | ith('NNP'):
consecutive_names.append(tagged_word[0])
last_tag = tagged_word[1]
else:
if consecutive_names:
tagged_words.append((' '.join(consecutive_names), last_tag))
consecutive_names = []
tagged_words.append(tagged_word)
if consecutive_names:
tagged_words.append((' '.join(consecutive_names), last_tag))
return tagged_words
|
m3wolf/scimap | tests/test_pawley_refinement.py | Python | gpl-3.0 | 6,933 | 0.002021 | # -*- coding: utf-8 -*-
#
# Copyright © 2018 Mark Wolf
#
# This file is part of scimap.
#
# Scimap 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.
#
# Scimap 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 Scimap. If not, see <http://www.gnu.org/licenses/>.
# flake8: noqa
import unittest
import os
import warnings
import sys
# sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
import matplotlib.pyplot as plt
import numpy as np
from numpy.polynomial.chebyshev import chebval
from scimap import XRDScan, standards
from scimap.utilities import q_to_twotheta, twotheta_to_q
from scimap.peakfitting import remove_peak_from_df
from scimap.pawley_refinement import PawleyRefinement, predict_diffractogram, gaussian, cauchy
TESTDIR = os.path.join(os.path.dirname(__file__), "test-data-xrd")
COR_BRML = os.path.join(TESTDIR, 'corundum.brml')
@unittest.skip
class PawleyRefinementTest(unittest.TestCase):
wavelengths = (
(1.5406, 1), # Kα1
(1.5444, 0.5), # Kα2
)
def test_refine(self):
# Prepare the test objects
scan = XRDScan(COR_BRML, phase=standards.Corundum())
two_theta = q_to_twotheta(scan.scattering_lengths, wavelength=scan.wavelength)
refinement = PawleyRefinement(wavelengths=self.wavelengths,
phases=[scan.phases[0]],
num_bg_coeffs=9)
# Set starting parameters a bit closer to keep from taking too long
scan.phases[0].unit_cell.a = 4.755
scan.phases[0].unit_cell.c = 12.990
for r in scan.phases[0].reflection_list:
r.intensity *= 200
# Do the refinement
refinement.refine(two_theta=two_theta, intensities=scan.intensities)
predicted = refinement.predict(two_theta=two_theta)
actual = scan.diffractogram.counts.values
refinement.plot(two_theta=two_theta, intensities=scan.intensities)
plt.show()
# Check scale factors
scale = refinement.scale_factor(two_theta=two_theta)
print(scale)
# Check phase fractions
fracs = refinement.phase_fractions(two_theta=two_theta)
np.testing.assert_almost_equal(fracs, (1, ))
# Check background fitting
bg = refinement.background(two_theta=two_theta)
self.assertEqual(bg.shape, actual.shape)
# Check refined unit-cell parameters
unit_cell = refinement.unit_cells()
self.assertAlmostEqual(
unit_cell[0],
4.758877,
places=3,
)
self.assertAlmostEqual(
unit_cell[2],
12.992877,
places=3
)
peak_widths = refinement.peak_breadths(two_theta, scan.intensities)
self.assertAlmostEqual(peak_widths[0], 0.046434, places=5)
# Check that the refinement is of sufficient quality
error = np.sqrt(np.sum((actual-predicted)**2))/len(actual)
self.assertLess(error, 1.5)
def test_reflection_list(self):
corundum = standards.Corundum()
# Determine the min and max values for 2θ range
two_theta_range = (10, 80)
d_min = 1.5406 / 2 / np.sin(np.radians(40))
d_max = 1.5444 / 2 / np.sin(np.radians(5))
# Calculate expected reflections
d_list = [corundum.unit_cell.d_spacing(r.hkl) for r in corundum.reflection_list]
d_list = np.array(d_list)
h_list = np.array([r.intensity for r in corundum.reflection_list])
size_list = np.array([corundum.crystallite_size for d in d_list])
strain_list = np.array([corundum.strain for d in d_list])
# Restrict values to only those valid for this two-theta range
valid_refs = np.logical_and(d_list >= d_min, d_list <= d_max)
d_list = d_list[valid_refs]
h_list = h_list[valid_refs]
size_list = size_list[valid_refs]
strain_list = strain_list[valid_refs]
# Calculate the actual list and compare
ref_list = tuple(zip(d_list, h_list, size_list, strain_list))
refinement = PawleyRefinement(phases=[corundum],
wavelengths=self.wavelengths)
output = refinement.reflection_list(two_theta=two_theta_range, clip=True)
np.testing.assert_equal(output, ref_list)
def test_predict_diffractogram(self):
two_theta = np.linspace(10, 80, num=40001)
wavelengths = self.wavelengths
bg_coeffs = np.ones(shape=(10,))
bg_x = np.linspace(10/90, 80/90, num=len(two_theta)) - 1
bg = chebval(bg_x, bg_coeffs)
# Check background
result = predict_diffractogram(
two_theta=two_theta,
wavelengths=wavelengths,
background_coeffs=bg_coeffs,
reflections=(),
)
np.testing.assert_almost_equal(result, bg)
# Check list of reflections
reflections = np.array((
(3.0, 79, 100, 0),
(3/1.41, 15, 100, 0),
(1.4, 41, 100, 0),
(0.5, 27, 100, 0),
))
wi | th warnings.catch_warn | ings(record=True) as w:
warnings.simplefilter('always')
result = predict_diffractogram(
two_theta=two_theta,
wavelengths=wavelengths,
background_coeffs=(0,),
u=0.01, v=0, w=0,
reflections=reflections,
lg_mix=0.5,
)
# Check that a warning is raised for the invalid
# reflection (0.5Å)
self.assertEqual(len(w), 2, "No warning raised")
# plt.plot(two_theta, result)
# plt.show()
self.assertAlmostEqual(np.max(result), 79, places=0)
def test_peak_shapes(self):
x = np.linspace(0, 10, num=501)
beta = 0.05
height = 20
gauss = gaussian(x, center=5, height=height, breadth=beta)
self.assertEqual(np.max(gauss), height)
area = np.trapz(gauss, x=x)
self.assertAlmostEqual(area/height, beta)
# Now check Cauchy function
cauch = cauchy(x, center=5, height=height, breadth=beta)
self.assertEqual(np.max(cauch), height)
# (Cauchy beta is less reliable because the tails have more weight)
area = np.trapz(cauch, x=x)
self.assertAlmostEqual(area/height, beta, places=2)
# plt.plot(x, gauss)
# plt.plot(x, cauch)
# plt.show()
|
dawehner/root | geom/gdml/writer.py | Python | lgpl-2.1 | 11,603 | 0.038955 | # @(#)root/gdml:$Id$
# Author: Witold Pokorski 05/06/2006
# This is the application-independent part of the GDML 'writer' implementation.
# It contains the 'writeFile' method (at the end of the file) which does the actual
# formating and writing out of the GDML file as well as the specialized 'add-element'
# methods for all the supported GDML elements. These methods are used to build
# the content of the GDML document, which is then generatd using the 'writeFile' method.
# The constructor of this class takes the output file (.gdml) as argument.
# An instance of this class should be passed to the constructor of application-specific
# 'writer binding' (in the present case ROOTwriter) as argument.
# For any question or remarks concerning this code, please send an email to
# Witold.Pokorski@cern.ch.
class writer(object):
def __init__(self, fname):
self.gdmlfile = fname
self.define = ['define',{},[]]
| self.materials = ['m | aterials',{},[]]
self.solids = ['solids',{},[]]
self.structure = ['structure',{},[]]
self.document = ['gdml',{'xmlns:gdml':"http://cern.ch/2001/Schemas/GDML",
'xmlns:xsi':"http://www.w3.org/2001/XMLSchema-instance",
'xsi:noNamespaceSchemaLocation':"gdml.xsd"},
[self.define, self.materials, self.solids, self.structure]]
def addPosition(self, name, x, y, z):
self.define[2].append(['position',{'name':name, 'x':x, 'y':y, 'z':z, 'unit':'cm'},[]])
def addRotation(self, name, x, y, z):
self.define[2].append(['rotation',{'name':name, 'x':x, 'y':y, 'z':z, 'unit':'deg'},[]])
def addMaterial(self, name, a, z, rho):
self.materials[2].append(['material', {'name':name, 'Z':z},
[['D',{'value':rho},[]], ['atom',{'value':a},[]]] ] )
def addMixture(self, name, rho, elems):
subel = [ ['D',{'value':rho},[]] ]
for el in elems.keys():
subel.append(['fraction',{'n':elems[el],'ref':el}, []])
self.materials[2].append(['material',{'name':name},
subel])
def addElement(self, symb, name, z, a):
self.materials[2].append(['element', {'name':name, 'formula':symb, 'Z':z},
[['atom', {'value':a},[]] ]])
def addReflSolid(self, name, solid, dx, dy, dz, sx, sy, sz, rx, ry, rz):
self.solids[2].append(['reflectedSolid',{'name':name, 'solid':solid, 'dx':dx, 'dy':dy, 'dz':dz, 'sx':sx, 'sy':sy, 'sz':sz, 'rx':rx, 'ry':ry, 'rz':rz},[]])
def addBox(self, name, dx, dy, dz):
self.solids[2].append(['box',{'name':name, 'x':dx, 'y':dy, 'z':dz, 'lunit':'cm'},[]])
def addParaboloid(self, name, rlo, rhi, dz):
self.solids[2].append(['paraboloid',{'name':name, 'rlo':rlo, 'rhi':rhi, 'dz':dz, 'lunit':'cm'},[]])
def addArb8(self, name, v1x, v1y, v2x, v2y, v3x, v3y, v4x, v4y, v5x, v5y, v6x, v6y, v7x, v7y, v8x, v8y, dz):
self.solids[2].append(['arb8',{'name':name, 'v1x':v1x, 'v1y':v1y, 'v2x':v2x, 'v2y':v2y, 'v3x':v3x, 'v3y':v3y, 'v4x':v4x, 'v4y':v4y, 'v5x':v5x, 'v5y':v5y, 'v6x':v6x, 'v6y':v6y, 'v7x':v7x, 'v7y':v7y, 'v8x':v8x, 'v8y':v8y, 'dz':dz, 'lunit':'cm'},[]])
def addSphere(self, name, rmin, rmax, startphi, deltaphi, starttheta, deltatheta):
self.solids[2].append(['sphere',{'name':name, 'rmin':rmin, 'rmax':rmax,
'startphi':startphi, 'deltaphi':deltaphi,
'starttheta':starttheta, 'deltatheta':deltatheta,
'aunit':'deg', 'lunit':'cm'},[]])
def addCone(self, name, z, rmin1, rmin2, rmax1, rmax2, sphi, dphi):
self.solids[2].append(['cone',{'name':name, 'z':z, 'rmin1':rmin1, 'rmin2':rmin2,
'rmax1':rmax1, 'rmax2':rmax2,
'startphi':sphi, 'deltaphi':dphi, 'lunit':'cm', 'aunit':'deg'}, []] )
def addPara(self, name, x, y, z, alpha, theta, phi):
self.solids[2].append(['para',{'name':name, 'x':x, 'y':y, 'z':z,
'alpha':alpha, 'theta':theta, 'phi':phi, 'lunit':'cm', 'aunit':'deg'}, []] )
def addTrap(self, name, z, theta, phi, y1, x1, x2, alpha1, y2, x3, x4, alpha2):
self.solids[2].append(['trap', {'name':name, 'z':z, 'theta':theta, 'phi':phi,
'x1':x1, 'x2':x2, 'x3':x3, 'x4':x4,
'y1':y1, 'y2':y2, 'alpha1':alpha1, 'alpha2':alpha2, 'lunit':'cm', 'aunit':'deg'}, []])
def addTwistedTrap(self, name, z, theta, phi, y1, x1, x2, alpha1, y2, x3, x4, alpha2, twist):
self.solids[2].append(['twistTrap', {'name':name, 'z':z, 'theta':theta, 'phi':phi,
'x1':x1, 'x2':x2, 'x3':x3, 'x4':x4,
'y1':y1, 'y2':y2, 'alpha1':alpha1, 'alpha2':alpha2, 'twist':twist, 'aunit':'deg', 'lunit':'cm'}, []])
def addTrd(self, name, x1, x2, y1, y2, z):
self.solids[2].append(['trd',{'name':name, 'x1':x1, 'x2':x2,
'y1':y1, 'y2':y2, 'z':z, 'lunit':'cm'}, []])
def addTube(self, name, rmin, rmax, z, startphi, deltaphi):
self.solids[2].append(['tube',{'name':name, 'rmin':rmin, 'rmax':rmax,
'z':z, 'startphi':startphi, 'deltaphi':deltaphi, 'lunit':'cm', 'aunit':'deg'},[]])
def addCutTube(self, name, rmin, rmax, z, startphi, deltaphi, lowX, lowY, lowZ, highX, highY, highZ):
self.solids[2].append(['cutTube',{'name':name, 'rmin':rmin, 'rmax':rmax,
'z':z, 'startphi':startphi, 'deltaphi':deltaphi,
'lowX':lowX, 'lowY':lowY, 'lowZ':lowZ, 'highX':highX, 'highY':highY, 'highZ':highZ, 'lunit':'cm', 'aunit':'deg'},[]])
def addPolycone(self, name, startphi, deltaphi, zplanes):
zpls = []
for zplane in zplanes:
zpls.append( ['zplane',{'z':zplane[0], 'rmin':zplane[1], 'rmax':zplane[2]},[]] )
self.solids[2].append(['polycone',{'name':name,
'startphi':startphi, 'deltaphi':deltaphi, 'lunit':'cm', 'aunit':'deg'}, zpls])
def addTorus(self, name, r, rmin, rmax, startphi, deltaphi):
self.solids[2].append( ['torus',{'name':name, 'rtor':r, 'rmin':rmin, 'rmax':rmax,
'startphi':startphi, 'deltaphi':deltaphi, 'lunit':'cm', 'aunit':'deg'},[]] )
def addPolyhedra(self, name, startphi, deltaphi, numsides, zplanes):
zpls = []
for zplane in zplanes:
zpls.append( ['zplane',{'z':zplane[0], 'rmin':zplane[1], 'rmax':zplane[2]},[]] )
self.solids[2].append(['polyhedra',{'name':name,
'startphi':startphi, 'deltaphi':deltaphi,
'numsides':numsides, 'lunit':'cm', 'aunit':'deg'}, zpls])
def addXtrusion(self, name, vertices, sections):
elems = []
for vertex in vertices:
elems.append( ['twoDimVertex',{'x':vertex[0], 'y':vertex[1]},[]] )
for section in sections:
elems.append( ['section',{'zOrder':section[0], 'zPosition':section[1], 'xOffset':section[2], 'yOffset':section[3], 'scalingFactor':section[4]},[]] )
self.solids[2].append(['xtru',{'name':name, 'lunit':'cm'}, elems])
def addEltube(self, name, x, y, z):
self.solids[2].append( ['eltube', {'name':name, 'dx':x, 'dy':y, 'dz':z, 'lunit':'cm'},[]] )
def addHype(self, name, rmin, rmax, inst, outst, z):
self.solids[2].append( ['hype', {'name':name, 'rmin':rmin, 'rmax':rmax,
'inst':inst, 'outst':outst, 'z':z, 'lunit':'cm', 'aunit':'deg'},[]] )
def addPos(self, subels, type, name, v):
if v[0]!=0.0 or v[1]!=0.0 or v[2]!=0.0:
subels.append( [type,{'name':name, 'x':v[0], 'y':v[1], 'z':v[2], 'unit':'cm'},[]] )
def addRot(self, subels, type, name, v):
if v[0]!=0.0 or v[1]!=0.0 or v[2]!= |
dimagi/commcare-hq | corehq/apps/sms/migrations/0004_add_sqlivrbackend_sqlkookoobackend.py | Python | bsd-3-clause | 624 | 0 | from django.db import migrations
class Migration(mi | grations.Migration):
dependencies = [
('sms', '0003_add_backend_models'),
]
operations = [
migrations.CreateModel(
name='SQLIVRBackend',
fields=[
],
options={
'proxy': True,
},
bases=('sms.sqlmobilebackend',),
),
migrations.CreateModel(
name='SQLKooKooBackend', |
fields=[
],
options={
'proxy': True,
},
bases=('sms.sqlivrbackend',),
),
]
|
SarahJaine/mo-cli | mo.py | Python | mit | 1,542 | 0.001297 | from cookiecutter.main import cookiecutter
import click
impo | rt requests
import sys
@click.group()
def cli():
'''Command-line utility to work with cookiecutter templates from GitHub repos.
Search https://github.com/istrategylabs 'mo' projects
to see available ISL cookiecutters.'''
pass
@cli.command()
@click.argument('framework', type=click.STRING)
@click.option('--user', '-u',
help='Specify git account to use for cookiecutters',
default='istrategylabs')
def init(framework, u | ser):
'''initialize a new cookiecutter template'''
# Check that cookiecutter template exists for requested framework
git_url = 'https://github.com/'
framework = framework.lower().replace(' ', '-')
mo_url = git_url+user+'/mo-'+framework
try:
response = requests.head(mo_url)
status = response.status_code
except requests.exceptions.ConnectionError as e:
sys.exit("Encountered an error with the connection.")
except Exception as e:
sys.exit(e)
if status != 200:
sys.exit("No '{0}' cookiecutter found at {1}."
.format(framework, git_url+user))
# Run cookiecutter template
if click.confirm('Ready to start cookiecutter {0}.git '
'in the current directory.\n'
'Do you want to continue?'.format(mo_url)):
try:
cookiecutter(mo_url+'.git')
except:
sys.exit("Problem encounted while cloning '{0}'.git"
.format(mo_url))
|
oscarbranson/tools | tools/chemistry.py | Python | gpl-3.0 | 3,869 | 0.005686 | """
The periodic table, and all it's info! And functions for doing chemical things.
"""
import os
import re
import pickle
import pandas as pd
def elements(all_isotopes=True):
"""
Loads a DataFrame of all elements and isotopes.
Scraped from https://www.webelements.com/
Returns
-------
pandas DataFrame with columns (element, atomic_number, isotope, atomic_weight, percent)
"""
el = pd.read_pickle(os.path.dirname(__file__) + '/periodic_table/elements.pkl')
if all_isotopes:
return el
else:
def wmean(g):
return (g.atomic_weight * g.percent).sum() / 100
iel = el.groupby('element').apply(wmean)
iel.name = 'atomic_weight'
return iel
def periodic_table():
"""
Loads dict containing all elements and associated metadata.
Scraped from https://www.webelements.com/
Returns
-------
dict
"""
with open(os.path.dirname(__file__) + '/periodic_table/periodic_table.pkl', 'rb') as f:
return pickle.load(f)
def decompose_molecule(molecule, n=1):
"""
Returns the chemical constituents of the molecule, and their number.
Parameters
----------
molecule : str
A molecule in standard chemical notation,
e.g. 'CO2', 'HCO3' or 'B(OH)4'.
Returns
-------
All elements in molecule with their associated counts : dict
"""
if isinstance(n, str):
n = int(n)
# define regexs
parens = re.compile('\(([A-z0-9()]+)\)([0-9]+)?')
stoich = re.compile('([A-Z][a-z]?)([0-9]+)?')
ps = parens.findall(molecule) # find subgroups in parentheses
rem = parens.sub('', molecule) # get remainder
if len(ps) > 0:
for s, ns in ps:
comp = decompose_molecule(s, ns)
for k, v in comp.items():
comp[k] = v * n
else:
comp = {}
for e, ns in stoich.findall(rem):
if e not in comp:
comp[e] = 0
if ns == '':
ns = 1 * n
else:
ns = int(ns) * n
comp[e] += ns
return comp
def calc_M(molecule):
"""
Returns molecular weight of molecule.
Parameters
----------
molecule : str
A molecule in standard chemical notation,
e.g. 'CO2', 'HCO3' or 'B(OH)4'.
Returns
-------
Molecular weight of molecule : dict
"""
# load periodic table
els = elements(all_isotopes=False)
comp = decompose_molecule(molecule)
m = 0
for k, v in comp.items():
m += els[k] * v
return m
def seawater(Sal=35., unit='mol/kg'):
"""
Standard mean composition of seawater.
From Dickson, Sabine and Christian (2007), Chapter 5, Table 3
@book{dickson2007guide,
title={Guide to best practices for ocean CO2 measurements.},
author={Dickson, Andrew Gilmore and Sabine, Christopher L and Christian, James Robert},
year={2007},
publisher={North Pacific Marine Science Organization},
howpublished="h | ttps://www.nodc.noaa.gov/ocads/oceans/Handbook_2007.html",
ISBN="1-897176-07-4"}
Parameters
----------
Sal : float
Salinity, default is 35
unit : str
| Either 'mol/kg' or 'g/kg'.
Returns
-------
Seawater composition in chosen units at specified salinity : dict
"""
sw = {"Cl": 0.54586,
"SO4": 0.02824,
"Br": 0.00084,
"F": 0.00007,
"Na": 0.46906,
"Mg": 0.05282,
"Ca": 0.01028,
"K": 0.01021,
"Sr": 0.00009,
"B": 0.00042}
for s in sw.keys():
sw[s] *= Sal / 35.
if unit == 'g/kg':
for k, v in sw.items():
sw[k] = calc_M(k) * v
return sw
if __name__ == '__main__':
print()
print(calc_M('B(OH)3)'))
|
gotostack/swift | test/unit/common/middleware/test_slo.py | Python | apache-2.0 | 65,372 | 0.000031 | # -*- coding: utf-8 -*-
# Copyright (c) 2013 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import unittest
from contextlib import nested
from mock import patch
from hashlib import md5
from swift.common import swob, utils
from swift.common.exceptions import ListingIterError, SegmentError
from swift.common.middleware import slo
from swift.common.swob import Request, Response, HTTPException
from swift.common.utils import json
from test.unit.common.middleware.helpers import FakeSwift
test_xml_data = '''<?xml version="1.0" encoding="UTF-8"?>
<static_large_object>
<object_segment>
<path>/cont/object</path>
<etag>etagoftheobjectsegment</etag>
<size_bytes>100</size_bytes>
</object_segment>
</static_large_object>
'''
test_json_data = json.dumps([{'path': '/cont/object',
'etag': 'etagoftheobjectsegment',
'size_bytes': 100}])
def fake_start_response(*args, **kwargs):
pass
class SloTestCase(unittest.TestCase):
def setUp(self):
self.app = FakeSwift()
self.slo = slo.filter_factory({})(self.app)
self.slo.min_segment_size = 1
def call_app(self, req, app=None, expect_exception=False):
if app is None:
app = self.app
req.headers.setdefault("User-Agent", "Mozzarella Foxfire")
status = [None]
headers = [None]
def start_response(s, h, ei=None):
status[0] = s
headers[0] = h
body_iter = app(req.environ, start_response)
body = ''
caught_exc = None
try:
for chunk in body_iter:
body += chunk
except Exception as exc:
if expect_exception:
caught_exc = exc
else:
raise
if expect_exception:
return status[0], headers[0], body, caught_exc
else:
return status[0], headers[0], body
def call_slo(self, req, **kwargs):
return self.call_app(req, app=self.slo, **kwargs)
class TestSloMiddleware(SloTestCase):
def setUp(self):
super(TestSloMiddleware, self).setUp()
self.app.register(
'GET', '/', swob.HTTPOk, {}, 'passed')
self.app.register(
'PUT', '/', swob.HTTPOk, {}, 'passed')
def test_handle_multipart_no_obj(self):
req = Request.blank('/')
resp_iter = self.slo(req.environ, fake_start_response)
self.assertEquals(self.app.calls, [('GET', '/')])
self.assertEquals(''.join(resp_iter), 'passed')
def test_slo_header_assigned(self):
req = Request.blank(
'/v1/a/c/o', headers={'x-static-large-object': "true"},
environ={'REQUEST_METHOD': 'PUT'})
resp = ''.join(self.slo(req.environ, fake_start_response))
self.assert_(
resp.startswith('X-Static-Large-Object is a reserved header'))
def test_parse_input(self):
self.assertRaises(HTTPException, slo.parse_input, 'some non json')
data = json.dumps(
[{'path': '/cont/object', 'etag': 'etagoftheobjecitsegment',
'size_bytes': 100}])
self.assertEquals('/cont/object',
slo.parse_input(data)[0]['path'])
class TestSloPutManifest(SloTestCase):
def setUp(self):
super(TestSloPutManifest, self).setUp()
self.app.register(
'GET', '/', swob.HTTPOk, {}, 'passed')
self.app.register(
'PUT', '/', swob.HTTPOk, {}, 'passed')
self.app.register(
'HEAD', '/v1/AUTH_test/cont/object',
swob.HTTPOk,
{'Content-Length': '100', 'Etag': 'etagoftheobjectsegment'},
None)
self.app.register(
'HEAD', '/v1/AUTH_test/cont/object\xe2\x99\xa1',
swob.HTTPOk,
{'Content-Length': '100', 'Etag': 'etagoftheobjectsegment'},
None)
self.app.register(
'HEAD', '/v1/AUTH_test/cont/small_object',
swob.HTTPOk,
{'Content-Length': '10', 'Etag': 'etagoftheobjectsegment'},
None)
self.app.register(
'PUT', '/v1/AUTH_test/c/man', swob.HTTPCreated, {}, None)
self.app.register(
'DELETE', '/v1/AUTH_test/c/man', swob.HTTPNoContent, {}, None)
self.app.register(
'HEAD', '/v1/AUTH_test/checktest/a_1',
swob.HTTPOk,
{'Content-Length': '1', 'Etag': 'a'},
None)
self.app.register(
'HEAD', '/v1/AUTH_test/checktest/badreq',
swob.HTTPBadRequest, {}, None)
self.app.register(
'HEAD', '/v1/AUTH_test/checktest/b_2',
swob.HTTPOk,
{'Content-Length': '2', 'Etag': 'b',
'Last-Modified': 'Fri, 01 Feb 2012 20:38:36 GMT'},
None)
self.app.register(
'GET', '/v1/AUTH_test/checktest/slob',
swob.HTTPOk,
{'X-Static-Large-Object': 'true', 'Etag': 'slob-etag'},
None)
self.app.register(
'PUT', '/v1/AUTH_test/checktest/man_3', swob.HTTPCreated, {}, None)
def test_put_manifest_too_quick_fail(self):
req = Request.blank('/v1/a/c/o')
req.content_length = self.slo.max_manifest_size + 1
try:
self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException as e:
pass
self.assertEquals(e.status_int, 413)
with patch.object(self.slo, 'max_manifest_segments', 0):
req = Request.blank('/v1/a/c/o', body=test_json_data)
e = None
try:
self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException as e:
pass
self.assertEquals(e.status_int, 413)
with patch.object(self.slo, 'min_segment_size', 1000):
req = Request.blank('/v1/a/c/o', body=test_json_data)
try:
self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException as e:
pass
self.assertEquals(e.status_int, 400)
req = Request.blank('/v1/a/c/o', headers={'X-Copy-From': 'lala'})
try:
self.slo.handle_multipart_put(req, fake_start_response)
except HTTPException as e:
pass
self.assertEquals(e.status_int, 405)
# ignores requests to /
req = Request.blank(
'/?multipart-manifest=put',
environ={'REQUEST_METHOD': 'PUT'}, body=test_json_data)
self.asser | tEquals(
self.slo.handle_multipart_put(req, fake_start_response),
['passed'])
def test_handle_multipart_put_success(self):
req = Request.blank(
'/v1/AUTH_test/c/man?multipart-manifest=put',
environ={'REQUEST_METHOD': 'PUT'}, headers={'Accept': 'test'},
body=test_json_data)
self.assertTrue('X-Static-Large-Object' not in req.headers)
def my_fake_start_response(*args, **kw | args):
gen_etag = '"' + md5('etagoftheobjectsegment').hexdigest() + '"'
self.assertTrue(('Etag', gen_etag) in args[1])
self.slo(req.environ, my_fake_start_response)
self.assertTrue('X-Static-Large-Object' in req.headers)
def test_handle_multipart_put_success_allow_small_last_segment(self):
with patch.object(self.slo, 'min_segment_size', 50):
test_json_data = json.dumps([{'path': '/cont/object',
'etag': 'etagoftheobjectsegment',
'size_bytes': 100},
|
fingeronthebutton/RIDE | src/robotide/lib/robot/libraries/BuiltIn.py | Python | apache-2.0 | 140,502 | 0.001224 | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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 re
import time
import token
from tokenize import generate_tokens, untokenize
from StringIO import StringIO
from robotide.lib.robot.api import logger
from robotide.lib.robot.errors import (ContinueForLoop, DataError, ExecutionFailed,
ExecutionFailures, ExecutionPassed, ExitForLoop,
PassExecution, ReturnFromKeyword)
from robotide.lib.robot.running import Keyword, RUN_KW_REGISTER
from robotide.lib.robot.running.context import EXECUTION_CONTEXTS
from robotide.lib.robot.running.usererrorhandler import UserErrorHandler
from robotide.lib.robot.utils import (asserts, DotDict, escape, format_assign_message,
get_error_message, get_time, is_falsy, is_integer,
is_string, is_truthy, is_unicode, JYTHON, Matcher,
normalize, NormalizedDict, parse_time, prepr,
RERAISED_EXCEPTIONS, plural_or_not as s,
secs_to_timestr, seq2str, split_from_equals,
timestr_to_secs, type_name, unic)
from robotide.lib.robot.variables import (is_list_var, is_var, DictVariableTableValue,
VariableTableValue, VariableSplitter,
variable_not_found)
from robotide.lib.robot.version import get_version
if JYTHON:
from java.lang import String, Number
# TODO: The name of this decorator should be changed. It is used for avoiding
# arguments to be resolved by many other keywords than run keyword variants.
# Should also consider:
# - Exposing this functionality to external libraries. Would require doc
# enhancements and clean way to expose variables to make resolving them
# based on needs easier.
# - Removing the functionality that run keyword variants can be overridded
# by custom keywords without a warning.
def run_keyword_variant(resolve):
def decorator(method):
RUN_KW_REGISTER.register_run_keyword('BuiltIn', method.__name__, resolve)
return method
return decorator
class _BuiltInBase(object):
@property
def _context(self):
if EXECUTION_CONTEXTS.current is None:
raise RobotNotRunningError('Cannot access execution context')
return EXECUTION_CONTEXTS.current
@property
def _namespace(self):
return self._context.namespace
def _get_namespace(self, top=False):
ctx = EXECUTION_CONTEXTS.top if top else EXECUTION_CONTEXTS.current
return ctx.namespace
@property
def _variables(self):
return self._namespace.variables
def _matches(self, string, pattern):
# Must use this instead of fnmatch when string may contain newlines.
matcher = Matcher(pattern, caseless=False, spaceless=False)
return matcher.match(string)
def _is_true(self, condition):
if is_string(condition):
condition = self.evaluate(condition, modules='os,sys')
return bool(condition)
def _log_types(self, *args):
msg = ["Argument types are:"] + [self._get_type(a) for a in args]
self.log('\n'.join(msg), 'DEBUG')
def _get_type(self, arg):
# In IronPython type(u'x') is str. We want to report unicode anyway.
if is_unicode(arg):
return "<type 'unicode'>"
return str(type(arg))
class _Converter(_BuiltInBase):
def convert_to_integer(self, item, base=None):
"""Converts the given item to an integer number.
If the given item is a string, it is by default expected to be an
integer in base 10. There are two ways to convert from other bases:
- Give base explicitly to the keyword as ``base`` argument.
- Prefix the given string with the base so that ``0b`` means binary
(base 2), ``0o`` means octal (base 8), and ``0x`` means hex (base 16).
The prefix is considered only when ``base`` argument is not given and
may itself be prefixed with a plus or minus sign.
The syntax is case-insensitive and possible spaces are ignored.
Examples:
| ${result} = | Convert To Integer | 100 | | # Result is 100 |
| ${result} = | Convert To Integer | FF AA | 16 | # Result is 65450 |
| ${result} = | Convert To Integer | 100 | 8 | # Result is 64 |
| ${result} = | Convert To Integer | -100 | 2 | # Result is -4 |
| ${result} = | Convert To Integer | 0b100 | | # Result is 4 |
| ${result} = | Convert To Integer | -0x100 | | # Result is -256 |
See also `Convert To Number`, `Convert To Binary`, `Convert To Octal`,
`Convert To Hex`, and `Convert To Bytes`.
"""
self._log_types(item)
return self._convert_to_integer(item, base)
def _convert_to_integer(self, orig, base=None):
try:
item = self._handle_java_numbers(orig)
item, base = self._get_base(item, base)
if base:
return int(item, self._convert_to_integer(base))
return int(item)
except:
raise RuntimeError("'%s' cannot be converted to an integer: %s"
% (orig, get_error_message()))
def _handle_java_numbers(self, item):
if not JYTHON:
return item
if isinstance(item, String):
return unic(item)
if isinstance(item, Number):
return item.doubleValue()
return item
def _get_base(self, item, base):
if not is_string(item):
return item, base
item = normalize(item)
if item.startswith(('-', '+')):
sign = item[0]
item = item[1:]
else:
sign = ''
bases = {'0b': 2, '0o': 8, '0x': 16}
if base or not item.startswith(tuple(bases)):
return sign+item, base
return sign+item[2:], bases[item[:2]]
def convert_to_binary(self, item, base=None, prefix=None, length=None):
"""Converts the given item to a binary string.
The ``item``, with an optional ``base``, is first converted to an
integer using `Convert To Integer` internally. After that it
is converted to a binary number (base 2) represented as a
string such as ``1011``.
The returned value can contain an optional ``prefix`` and can be
required to be of minimum ``length`` (excluding the prefix and a
possible minus sign). If the value is initially shorter than
the required lengt | h, it is padded with zeros.
Examples:
| ${result} = | Convert To Binary | 10 | | | # Result is 1010 |
| ${result} = | Convert To Binary | F | base=16 | prefix=0b | # Result is 0b1111 |
| ${result} = | Convert To Binary | -2 | prefix=B | length=4 | # Result is -B0010 |
| See also `Convert To Integer`, `Convert To Octal` and `Convert To Hex`.
"""
return self._convert_to_bin_oct_hex(bin, item, base, prefix, length)
def convert_to_octal(self, item, base=None, prefix=None, length=None):
"""Converts the given item to an octal string.
The ``item``, with an optional ``base``, is first converted to an
integer using `Convert To Integer` internally. After that it
is converted to an octal number (base 8) represented as a
string such as ``775``.
The returned value can contain an optional ``prefix`` and can be
required to be of minimum ``length`` (excluding the prefix and a
possible minus |
devsar/ae-people | apps/users/forms.py | Python | apache-2.0 | 6,966 | 0.014355 | import re
from django import forms
from django.core.urlresolvers import reverse
| from django.contrib.formtools.wizard import FormWizard
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.utils.translation import ugettext_lazy as _
from google.appengine.ext.db import djangoforms
from google.appengine.api.labs import taskqueue
from uni_form.helpers import FormHelper, Submit
from uni_form.help | ers import Layout, Fieldset, Row
from models import Developer
from users.utils import LocationField
from country.models import COUNTRIES
class DeveloperForm(djangoforms.ModelForm):
#geolocation = LocationField()
about_me = forms.CharField(widget=forms.Textarea,
help_text="accepts textile markup (<a target='_new' href='http://textile.thresholdstate.com/'>reference</a>)",
required=False)
location = LocationField()
country = forms.ChoiceField(choices=COUNTRIES)
tags = forms.CharField(help_text=_("space separated"))
class Meta:
model = Developer
#fields = ['alias', 'email_contact', 'first_name', 'last_name', 'location', 'photo']
exclude = ('_class', 'user', 'last_login', 'sign_up_date', 'location_geocells', 'photo')
def clean_tags(self):
tags = self.cleaned_data['tags']
if "," in tags:
tags = [tag.strip().replace(" ","-") for tag in tags.split(",")]
else:
tags = tags.split(" ")
return filter(len, map(lambda x: x.strip().lower(), tags))
def clean_alias(self):
alias = self.cleaned_data["alias"].strip()
if re.match("^([\w\d_]+)$", alias) is None:
raise forms.ValidationError(_("alias not valid, use only letters, numbers or underscores"))
if self.instance and self.instance.alias == alias:
return alias
if Developer.all(keys_only=True).filter("alias =", alias).get():
raise forms.ValidationError(_("alias not available"))
return alias
# Attach a formHelper to your forms class.
helper = FormHelper()
# create the layout object
layout = Layout(
# first fieldset shows the company
Fieldset('Basic', 'alias',
Row('first_name','last_name'),
'about_me',
'python_sdk',
'java_sdk',
'tags', css_class="developer_basic"),
# second fieldset shows the contact info
Fieldset('Contact details',
'public_contact_information',
'email_contact',
'phone',
'personal_blog',
'personal_page',
css_class="developer_contact_details"),
Fieldset('Location',
'country',
'location_description',
'location',
css_class="developer_contact_details")
)
helper.add_layout(layout)
submit = Submit('save',_('Save'))
helper.add_input(submit)
class SignUpStep1Form(forms.Form):
alias = forms.CharField()
first_name = forms.CharField()
last_name = forms.CharField()
def clean_alias(self):
alias = self.cleaned_data["alias"].strip()
if re.match("^([\w\d_]+)$", alias) is None:
raise forms.ValidationError(_("alias not valid, use only letters, numbers or underscores"))
if Developer.all(keys_only=True).filter("alias =", alias).get():
raise forms.ValidationError(_("alias not available"))
return alias
class SignUpStep2Form(forms.Form):
SDK_CHOICES = (
('python', 'python'),
('java', 'java')
)
email_contact = forms.CharField(help_text="protected with reCAPTCHA Mailhide", required=False)
phone = forms.CharField(required=False)
personal_blog = forms.URLField(required=False)
personal_page = forms.URLField(required=False)
about_me = forms.CharField(widget=forms.Textarea,
help_text="accepts textile markup (<a target='_new' href='http://textile.thresholdstate.com/'>reference</a>)",
required=False)
sdks = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=SDK_CHOICES,help_text="which SDKs you use?", required=False)
tags = forms.CharField(help_text=_("space separated"), required=False)
def clean_tags(self):
tags = self.cleaned_data['tags']
if "," in tags:
tags = [tag.strip().replace(" ","-") for tag in tags.split(",")]
else:
tags = tags.split(" ")
return filter(len, map(lambda x: x.strip().lower(), tags))
class SignUpStep3Form(forms.Form):
location = LocationField()
location_description = forms.CharField()
country = forms.ChoiceField(choices=COUNTRIES)
class SignUpWizard(FormWizard):
def get_template(self, step):
return 'users/sign_up_%s.html' % step
def done(self, request, form_list):
cleaned_data = {}
[cleaned_data.update(form.cleaned_data) for form in form_list]
import logging
logging.info(cleaned_data)
form = DeveloperForm(cleaned_data)
developer = Developer(
user = request.user,
alias = cleaned_data['alias'],
email_contact = cleaned_data['email_contact'] or None,
first_name = cleaned_data['first_name'],
last_name = cleaned_data['last_name'],
location = cleaned_data['location'] or None,
location_description = cleaned_data['location_description'] or None,
country = cleaned_data['country'],
phone = cleaned_data['phone'] or None,
personal_blog = cleaned_data['personal_blog'] or None,
personal_page = cleaned_data['personal_page'] or None,
public_contact_information = True,
about_me = cleaned_data['about_me'] or None,
python_sdk = "python" in cleaned_data['sdks'],
java_sdk = "java" in cleaned_data['sdks'],
tags = cleaned_data['tags'] or []
)
developer.put()
taskqueue.add(url=reverse("users_fusiontable_insert", args=[str(developer.key())]))
taskqueue.add(url=reverse("country_update_country", kwargs={'country_code': developer.country}))
request.flash['message'] = unicode(_("Welcome!"))
request.flash['severity'] = "success"
return HttpResponseRedirect(reverse('users_avatar_change'))
|
hbuschme/TextGridTools | tgt/tests/test_core.py | Python | gpl-3.0 | 33,889 | 0.00059 | # -*- coding: utf-8 -*-
# TextGridTools -- Read, write, and manipulate Praat TextGrid files
# Copyright (C) 2013-2014 Hendrik Buschmeier, Marcin Włodarczak
#
# 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 __future__ import division, print_function
import unittest
from ..core import *
class TestTime(unittest.TestCase):
def setUp(self):
self.t1 = Time(1.0)
self.t2 = Time(1.1)
self.t3 = Time(1.01)
self.t4 = Time(1.001)
self.t5 = Time(1.00001)
def test_equals(self):
self.assertTrue(self.t1 == self.t1)
self.assertFalse(self.t1 == self.t2)
self.assertFalse(self.t1 == self.t3)
self.assertFalse(self.t1 == self.t4)
self.assertTrue(self.t1 == self.t5)
def test_not_equals(self):
self.assertFalse(self.t1 != self.t1)
self.assertTrue(self.t1 != self.t2)
self.assertTrue(self.t1 != self.t3)
self.assertTrue(self.t1 != self.t4)
self.assertFalse(self.t1 != self.t5)
def test_less(self):
self.assertFalse(self.t1 < self.t1)
self.assertTrue(self.t1 < self.t2)
self.assertTrue(self.t1 < self.t3)
self.assertTrue(self.t1 < self.t4)
self.assertFalse(self.t1 < self.t5)
def test_greater(self):
self.assertFalse(self.t1 > self.t1)
self.assertFalse(self.t1 > self.t2)
self.assertFalse(self.t1 > self.t3)
self.assertFalse(self.t1 > self.t4)
self.assertFalse(self.t1 > self.t5)
self.assertTrue(self.t2 > self.t1)
def test_greater_equal(self):
self.assertTrue(self.t1 >= self.t1)
self.assertFalse(self.t1 >= self.t2)
self.assertFalse(self.t1 >= self.t3)
self.assertFalse(self.t1 >= self.t4)
self.assertTrue(self.t1 >= self.t5)
self.assertTrue(self.t2 >= self.t1)
def test_less_equal(self):
self.assertTrue(self.t1 <= self.t1)
self.assertTrue(self.t1 <= self.t2)
self.assertTrue(self.t1 <= self.t3)
self.assertTrue(self.t1 <= self.t4)
self.assertTrue(self.t1 <= self.t5)
self.assertFalse(self.t2 <= self.t1)
class TestTier(unittest.TestCase):
def test_adding(self):
t = Tier()
# Add to empty tier
ao1 = Annotation(0.0, 0.5, 'ao1')
t.add_annotation(ao1)
self.assertTrue(len(t) == 1)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.5)
# Append to tier leaving empty space
ao2 = Annotation(0.6, 0.75, 'ao2')
t.add_annotation(ao2)
self.assertTrue(len(t) == 2)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.75)
ao3 = Annotation(0.81, 0.9, 'ao3')
t.add_annotation(ao3)
self.assertTrue(len(t) == 3)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# Insert between existing annotations
# - leaving gaps on both sides
ao4 = Annotation(0.75, 0.77, 'ao4')
t.add_annotation(ao4)
self.assertTrue(len(t) == 4)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# - meeting preceeding annotation
ao5 = Annotation(0.77, 0.79, 'ao5')
t.add_annotation(ao5)
self.assertTrue(len(t) == 5)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# - meeting preceeding and succeeding annotation
ao6 = Annotation(0.8, 0.81, 'ao6')
t.add_annotation(ao6)
self.assertTrue(len(t) == 6)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
# Insert at a place that is already occupied
# - within ao3
with self.assertRaises(ValueError):
ao7 = Annotation(0.85, 0.87, 'ao7')
t.add_annotation(ao7)
# - same boundaries as ao3
with self.assertRaises(ValueError):
ao8 = Annotation(0.81, 0.9, 'ao8')
t.add_annotation(ao8)
# - start time earlier than start time of ao3
with self.assertRaises(ValueError):
ao9 = Annotation(0.8, 0.89, 'ao9')
t.add_annotation(ao9)
# - end time later than end time of ao3
with self.assertRaises(ValueError):
ao10 = Annotation(0.82, 0.91, 'ao10')
t.add_annotation(ao10)
# - start time earlier than start time of ao3 and
# end time later than end time of ao3
with self.assertRaises(ValueError):
ao11 = Annotation(0.8, 0.91, 'ao11')
t.add_annotation(ao11)
# - Check that no annotation was added
self.assertTrue(len(t) == 6)
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 0.9)
def test_start_end_times(self):
t = Tier(1, 2)
# Check whether specified start/end times are used
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 2)
# Check whether adding an annotation within specified
# start and end times leaves them unchanged
t.add_annotation(Annotation(1.1, 1.9, 'text'))
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 2)
# Expand end time by adding an annotation that ends later
t.add_annotation(Annotation(2, 3, 'text'))
self.assertTrue(t.start_time == 1)
self.assertTrue(t.end_time == 3)
# Expand start time by adding an annotation that starts ealier
t.add_annotation(Annotation(0, 1, 'text'))
self.assertTrue(t.start_time == 0)
self.assertTrue(t.end_time == 3)
def test_queries(self):
t = Tier()
ao1 = Annotation(0, 1, 'ao1')
ao2 = Annotation(1, 2, 'ao2')
ao3 = Annotation(5, 6, 'ao3')
t.add_annotations([ao1, ao2, ao3])
# Query with start time
# - query for existing objects
ao1_retr = t.get_annotation_by_start_time(ao1.start_time)
self.assertTrue(ao1_retr == ao1)
ao2_retr = t.get_annotation_by_start_time(ao2.start_time)
self.assertTrue(ao2_retr == ao2)
ao3_retr = t.get_annotation_by_start_time(ao3.start_time)
self.assertTrue(ao3_retr == ao3)
# - query for non-existing object
aox_retr = t.get_annotation_by_start_time(0.5)
self.assertTrue(aox_retr is None)
# Query with end time
# - query for existing objects
ao1_retr = t.get_annotation_by_end_time(ao1.end_time)
self.assertTrue(ao1_retr == ao1)
ao2_retr = t.get_annotation_by_end_time(ao2.end_time)
self.assertTrue(ao2_retr == ao2)
ao3_retr = t.get_annotation_by_end_time(ao3.end_time)
self.assertTrue(ao3_retr == ao3)
# - query for non-existing object
aox_retr = t.get_annotation_by_end_time(0.5)
self.assertTrue(aox_retr is None)
# Query with time
# - query for existing objects
# - time falls within object
ao1_retr = t.get_annotations_by_time(ao1.start_time + (ao1.end_time - ao1.start_time) * 0.5)
self.assertTrue(ao1_retr[0] == ao1)
# - time equals end time of object
ao2_retr = t.get_annotations_by_time(ao2.end_tim | e)
self.assertTrue(ao2_retr[0] == ao2)
# - time equals start time of object
ao3_retr = t.get_annotations_by_time(ao3.start_time)
self.assertTrue(ao3_retr[0] == ao3)
# - time equals start time of one object and end_ | time of another
ao12_retr = t.get_annotations_by_time(ao1.end_time)
|
hlzz/dotfiles | graphics/VTK-7.0.0/ThirdParty/Twisted/twisted/python/dist.py | Python | bsd-3-clause | 15,309 | 0.000914 | # -*- test-case-name: twisted.python.test.test_dist -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Distutils convenience functionality.
Don't use this outside of Twisted.
Maintainer: Christopher Armstrong
"""
from distutils.command import build_scripts, install_data, build_ext
from distutils.errors import CompileError
from distutils import core
from distutils.core import Extension
import fnmatch
import os
import platform
import sys
from twisted import copyright
from twisted.python.compat import execfile
STATIC_PACKAGE_METADATA = dict(
name="Twisted",
version=copyright.version,
description="An asynchronous networking framework written in Python",
author="Twisted Matrix Laboratories",
author_email="twisted-python@twistedmatrix.com",
mai | ntainer="Glyph Lefkowitz",
maintainer_email="glyph@twistedmatrix.com",
url="http://twistedmatrix.com/",
license="MIT",
long_description="""\
An extensible framework for Python programming, with special f | ocus
on event-based network programming and multiprotocol integration.
""",
classifiers=[
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
],
)
twisted_subprojects = ["conch", "lore", "mail", "names",
"news", "pair", "runner", "web",
"words"]
class ConditionalExtension(Extension):
"""
An extension module that will only be compiled if certain conditions are
met.
@param condition: A callable of one argument which returns True or False to
indicate whether the extension should be built. The argument is an
instance of L{build_ext_twisted}, which has useful methods for checking
things about the platform.
"""
def __init__(self, *args, **kwargs):
self.condition = kwargs.pop("condition", lambda builder: True)
Extension.__init__(self, *args, **kwargs)
def setup(**kw):
"""
An alternative to distutils' setup() which is specially designed
for Twisted subprojects.
Pass twisted_subproject=projname if you want package and data
files to automatically be found for you.
@param conditionalExtensions: Extensions to optionally build.
@type conditionalExtensions: C{list} of L{ConditionalExtension}
"""
return core.setup(**get_setup_args(**kw))
def get_setup_args(**kw):
if 'twisted_subproject' in kw:
if 'twisted' not in os.listdir('.'):
raise RuntimeError("Sorry, you need to run setup.py from the "
"toplevel source directory.")
projname = kw['twisted_subproject']
projdir = os.path.join('twisted', projname)
kw['packages'] = getPackages(projdir, parent='twisted')
kw['version'] = getVersion(projname)
plugin = "twisted/plugins/twisted_" + projname + ".py"
if os.path.exists(plugin):
kw.setdefault('py_modules', []).append(
plugin.replace("/", ".")[:-3])
kw['data_files'] = getDataFiles(projdir, parent='twisted')
del kw['twisted_subproject']
else:
if 'plugins' in kw:
py_modules = []
for plg in kw['plugins']:
py_modules.append("twisted.plugins." + plg)
kw.setdefault('py_modules', []).extend(py_modules)
del kw['plugins']
if 'cmdclass' not in kw:
kw['cmdclass'] = {
'install_data': install_data_twisted,
'build_scripts': build_scripts_twisted}
if "conditionalExtensions" in kw:
extensions = kw["conditionalExtensions"]
del kw["conditionalExtensions"]
if 'ext_modules' not in kw:
# This is a workaround for distutils behavior; ext_modules isn't
# actually used by our custom builder. distutils deep-down checks
# to see if there are any ext_modules defined before invoking
# the build_ext command. We need to trigger build_ext regardless
# because it is the thing that does the conditional checks to see
# if it should build any extensions. The reason we have to delay
# the conditional checks until then is that the compiler objects
# are not yet set up when this code is executed.
kw["ext_modules"] = extensions
class my_build_ext(build_ext_twisted):
conditionalExtensions = extensions
kw.setdefault('cmdclass', {})['build_ext'] = my_build_ext
return kw
def getVersion(proj, base="twisted"):
"""
Extract the version number for a given project.
@param proj: the name of the project. Examples are "core",
"conch", "words", "mail".
@rtype: str
@returns: The version number of the project, as a string like
"2.0.0".
"""
if proj == 'core':
vfile = os.path.join(base, '_version.py')
else:
vfile = os.path.join(base, proj, '_version.py')
ns = {'__name__': 'Nothing to see here'}
execfile(vfile, ns)
return ns['version'].base()
# Names that are exluded from globbing results:
EXCLUDE_NAMES = ["{arch}", "CVS", ".cvsignore", "_darcs",
"RCS", "SCCS", ".svn"]
EXCLUDE_PATTERNS = ["*.py[cdo]", "*.s[ol]", ".#*", "*~", "*.py"]
def _filterNames(names):
"""
Given a list of file names, return those names that should be copied.
"""
names = [n for n in names
if n not in EXCLUDE_NAMES]
# This is needed when building a distro from a working
# copy (likely a checkout) rather than a pristine export:
for pattern in EXCLUDE_PATTERNS:
names = [n for n in names
if (not fnmatch.fnmatch(n, pattern))
and (not n.endswith('.py'))]
return names
def relativeTo(base, relativee):
"""
Gets 'relativee' relative to 'basepath'.
i.e.,
>>> relativeTo('/home/', '/home/radix/')
'radix'
>>> relativeTo('.', '/home/radix/Projects/Twisted') # curdir is /home/radix
'Projects/Twisted'
The 'relativee' must be a child of 'basepath'.
"""
basepath = os.path.abspath(base)
relativee = os.path.abspath(relativee)
if relativee.startswith(basepath):
relative = relativee[len(basepath):]
if relative.startswith(os.sep):
relative = relative[1:]
return os.path.join(base, relative)
raise ValueError("%s is not a subpath of %s" % (relativee, basepath))
def getDataFiles(dname, ignore=None, parent=None):
"""
Get all the data files that should be included in this distutils Project.
'dname' should be the path to the package that you're distributing.
'ignore' is a list of sub-packages to ignore. This facilitates
disparate package hierarchies. That's a fancy way of saying that
the 'twisted' package doesn't want to include the 'twisted.conch'
package, so it will pass ['conch'] as the value.
'parent' is necessary if you're distributing a subpackage like
twisted.conch. 'dname' should point to 'twisted/conch' and 'parent'
should point to 'twisted'. This ensures that your data_files are
generated correctly, only using relative paths for the first element
of the tuple ('twisted/conch/*').
The default 'parent' is the current working directory.
"""
parent = parent or "."
ignore = ignore or []
result = []
for directory, subdirectories, filenames in os.walk(dname):
resultfiles = []
for exname in EXCLUDE_NAMES:
if exname in subdirectories:
subdirectories.remove(exname)
for ig in ignore:
if ig in subdirectories:
subdirectories.remove(ig)
for filename in _filterNames(filenames):
resultfiles.append(filename)
if resultfiles:
result.app |
arosswilson/rossreckons | rossreckons/wsgi.py | Python | mit | 400 | 0 | """
WSGI config for rossreckons project.
It exposes the WSGI callable as a module-level variable | named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rossreckons.settings")
| application = get_wsgi_application()
|
GiulioRossetti/ndlib | ndlib/models/epidemics/UTLDRModel.py | Python | bsd-2-clause | 28,297 | 0.003216 | from ..DiffusionModel import DiffusionModel
import numpy as np
import future
__author__ = ["Giulio Rossetti"]
__license__ = "BSD-2-Clause"
class UTLDRModel(DiffusionModel):
def __init__(self, graph, seed=None):
super(self.__class__, self).__init__(graph, seed)
self.params['nodes']['vaccinated'] = {n: False for n in self.graph.nodes}
self.params['nodes']['tested'] = {n: False for n in self.graph.nodes}
self.params['nodes']['ICU'] = {n: False for n in self.graph.nodes}
self.params['nodes']['filtered'] = {n: [] for n in self.graph.nodes}
self.icu_b = self.graph.number_of_nodes()
self.lockdown = False
self.name = "UTLDR"
self.available_statuses = {
"Susceptible": 0,
"Exposed": 2,
"Infected": 1,
"Recovered": 3,
"Identified_Exposed": 4,
"Hospitalized_mild": 5,
"Hospitalized_severe_ICU": 6,
"Hospitalized_severe": 7,
"Lockdown_Susceptible": 8,
"Lockdown_Exposed": 9,
"Lockdown_Infected": 10,
"Dead": 11,
"Vaccinated": 12,
}
self.parameters = {
"model": {
"sigma": {
"descr": "Incubation rate (1/expected iterations)",
"range": [0, 1],
"optional": False
},
"beta": {
"descr": "Infection rate (1/expected iterations)",
"range": [0, 1],
"optional": False
},
"gamma": {
"descr": "Recovery rate - Mild, Asymptomatic, Paucisymptomatic (1/expected iterations)",
"range": [0, 1],
"optional": False
},
"gamma_t": {
"descr": "Recovery rate - Severe in ICU (1/expected iterations)",
"range": [0, 1],
"optional": True,
"default": 0.6
},
"gamma_f": {
"descr": "Recovery rate - Severe not in ICU (1/expected iterations)",
"range": [0, 1],
"optional": True,
"default": 0.95
},
"omega": {
"descr": "Death probability - Mild, Asymptomatic, Paucisymptomatic",
"range": [0, 1],
"optional": True,
"default": 0
},
"omega_t": {
"descr": "Death probability - Severe in ICU",
"range": [0, 1],
"optional": True,
"default": 0
},
"omega_f | ": {
"descr": "Death probability - Severe not in ICU",
"range": [0, 1],
"optional": True,
"default": 0
},
"phi_e": {
"descr": "Testing probability if Exposed",
"range": [0 | , 1],
"optional": True,
"default": 0
},
"phi_i": {
"descr": "Testing probability if Infected",
"range": [0, 1],
"optional": True,
"default": 0
},
"kappa_e": {
"descr": "Test False Negative probability if Exposed",
"range": [0, 1],
"optional": True,
"default": 0.7
},
"kappa_i": {
"descr": "Test False Negative probability if Infected",
"range": [0, 1],
"optional": True,
"default": 0.9
},
"epsilon_e": {
"descr": "Social restriction due to quarantine (percentage of pruned edges)",
"range": [0, 1],
"optional": True,
"default": 1
},
"epsilon_l": {
"descr": "Social restriction due to lockdown (maximum household size)",
"range": [0, 1],
"optional": True,
"default": 1
},
"lambda": {
"descr": "Lockdown effectiveness (percentage of compliant individuals)",
"range": [0, 1],
"optional": True,
"default": 1
},
"mu": {
"descr": "Lockdown duration (1/expected iterations)",
"range": [0, 1],
"optional": True,
"default": 1
},
"p": {
"descr": "Probability of long-range interactions",
"range": [0, 1],
"optional": True,
"default": 0
},
"p_l": {
"descr": "Probability of long-range interactions if in Lockdown",
"range": [0, 1],
"optional": True,
"default": 0
},
"lsize": {
"descr": "Percentage of long-range interactions w.r.t short-range ones",
"range": [0, 1],
"optional": True,
"default": 0.25
},
"icu_b": {
"descr": "Beds availability in ICU (absolute value)",
"range": [0, np.infty],
"optional": True,
"default": self.graph.number_of_nodes()
},
"iota": {
"descr": "Severe case probability (needing ICU treatments)",
"range": [0, 1],
"optional": True,
"default": 1
},
"z": {
"descr": "Probability of infection from corpses",
"range": [0, 1],
"optional": True,
"default": 0
},
"s": {
"descr": "Probability of absent immunization",
"range": [0, 1],
"optional": True,
"default": 0
},
"v": {
"descr": "Probability of vaccination (single chance per agent)",
"range": [0, 1],
"optional": True,
"default": 0
},
"f": {
"descr": "Probability of Vaccination nullification (inverse of temporal coverage)",
"range": [0, 1],
"optional": True,
"default": 0
},
},
"nodes": {
"activity": {
"descr": "Node interactions per iteration (sample size of existing social relationships, "
"with replacement)",
"range": [0, 1],
"optional": True,
"default": 1
},
"segment": {
"descr": "Node class (e.g., age, gender)",
"range": str,
"optional": True,
"default": None
},
},
"edges": {},
}
def iteration(self, node_status=True):
"""
:param node_status:
:return:
"""
self.clean_initial_status(self.available_statuses.values())
actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)}
if self.actual_iteration == 0:
self.icu_b = self.params['model']['icu_b']
self.actual_iteration += 1
delta, node_count, status_delta = self.status_delta(actual_status)
if node_st |
fiete201/qutebrowser | qutebrowser/utils/__init__.py | Python | gpl-3.0 | 830 | 0 | # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser 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.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied w | arranty of
# MERCHANTABILITY or FITNESS F | OR 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 qutebrowser. If not, see <https://www.gnu.org/licenses/>.
"""Misc utility functions."""
|
MountainMan22/Boto-Automation | tests/test_vi_virtual_machine.py | Python | gpl-2.0 | 11,730 | 0.005627 | import os
import random
import time
import ConfigParser
from unittest import TestCase
from pysphere import VIServer, VMPowerState, ToolsStatus
class VIVirtualMachineTest(TestCase):
@classmethod
def setUpClass(cls):
config_path = os.path.join(os.path.dirname(__file__), "config.ini")
cls.config = ConfigParser.ConfigParser()
cls.config.read(config_path)
host = cls.config.get("READ_ONLY_ENV", "host")
user = cls.config.get("READ_ONLY_ENV", "user")
pswd = cls.config.get("READ_ONLY_ENV", "password")
host2 = cls.config.get("SANDBOX_ENV", "host")
user2 = cls.config.get("SANDBOX_ENV", "user")
pswd2 = cls.config.get("SANDBOX_ENV", "password")
cls.server = VIServer()
cls.server.connect(host, user, pswd)
cls.server2 = VIServer()
cls.server2.connect(host2, user2, pswd2)
cls.vm_tools_path = cls.config.get("SANDBOX_ENV", "windows_vm_with_tools")
cls.vm_tools_snap = cls.config.get("SANDBOX_ENV", "windwos_vm_snapshot")
cls.vm_tools_user = cls.config.get("SANDBOX_ENV", "windows_vm_username")
cls.vm_tools_pass = cls.config.get("SANDBOX_ENV", "windows_vm_password")
cls.vm_tools = cls.server2.get_vm_by_path(cls.vm_tools_path)
cls.vm_toy_path = cls.config.get("SANDBOX_ENV", "writable_vm")
cls.vm_toy = cls.server2.get_vm_by_path(cls.vm_toy_path)
@classmethod
def tearDownClass(cls):
cls.server.disconnect | ()
if cls.vm_tools.get_status(basic_status=True) != VMPowerState.POWERED_OFF:
cls.vm_tools.power_off()
if cls.vm_toy.get_status(basic_status=True) != VMPowerState.POWERED_OFF:
cls.vm_toy.power_off()
| cls.server2.disconnect()
def test_get_resource_pool_name(self):
for mor in self.server.get_resource_pools().iterkeys():
vms = self.server.get_registered_vms(resource_pool=mor)
if not vms:
continue
path = random.choice(vms)
print "picked:", path
vm = self.server.get_vm_by_path(path)
assert vm.get_resource_pool_name()
def test_vm_status(self):
vm = self.get_random_vm()
expected = {
VMPowerState.BLOCKED_ON_MSG: ["is_blocked_on_msg", False],
VMPowerState.POWERED_OFF: ["is_powered_off", False],
VMPowerState.POWERED_ON: ["is_powered_on", False],
VMPowerState.POWERING_OFF: ["is_powering_off", False],
VMPowerState.POWERING_ON: ["is_powering_on", False],
VMPowerState.RESETTING: ["is_resetting", False],
VMPowerState.REVERTING_TO_SNAPSHOT: ["is_reverting", False],
VMPowerState.SUSPENDED: ["is_suspended", False],
VMPowerState.SUSPENDING: ["is_suspending", False],
}
sta = vm.get_status()
assert sta in expected
expected[sta][1] = True
for method, result in expected.itervalues():
assert getattr(vm, method)() is result
def test_power_ops(self):
vm = self.vm_toy
if not vm.is_powered_off():
vm.power_off()
assert vm.is_powered_off()
vm.power_on()
assert vm.is_powered_on()
assert not vm.is_powered_off()
vm.suspend()
assert vm.is_suspended()
assert not vm.is_powered_on()
vm.power_on()
assert vm.is_powered_on()
vm.reset()
assert vm.is_powered_on()
vm.power_off()
assert vm.is_powered_off()
assert not(vm.is_powered_on() or vm.is_suspended())
def test_extra_config(self):
#just check no exception are raised
vm = self.vm_toy
vm.set_extra_config({'isolation.tools.diskWiper.disable':'TRUE',
'isolation.tools.diskShrink.disable':'TRUE'})
def test_guest_power_ops(self):
vm = self.start_vm_with_tools()
time.sleep(20)
assert self.retry_guest_operation(vm.reboot_guest, 240)
time.sleep(20)
assert self.wait_for_status(vm, [VMPowerState.POWERED_ON], 60)
vm = self.start_vm_with_tools()
time.sleep(20)
assert self.retry_guest_operation(vm.standby_guest, 240)
assert self.wait_for_status(vm, [VMPowerState.SUSPENDED], 60)
vm = self.start_vm_with_tools()
time.sleep(20)
assert self.retry_guest_operation(vm.shutdown_guest, 240)
assert self.wait_for_status(vm, [VMPowerState.POWERED_OFF], 60)
def test_get_properties(self):
vm = self.get_random_vm()
props = vm.get_properties(from_cache=False)
for p in ["name", "guest_id", "guest_full_name", "path", "memory_mb",
"num_cpu", "devices", "hostname", "ip_address", "net",
"files", "disks"]:
if p in props:
assert vm.get_property(p) == props[p]
props2 = vm.get_properties(from_cache=True)
assert props == props2
def test_tools_status(self):
vm = self.get_random_vm()
assert vm.get_tools_status() in [ToolsStatus.NOT_INSTALLED,
ToolsStatus.NOT_RUNNING,
ToolsStatus.RUNNING,
ToolsStatus.RUNNING_OLD,
ToolsStatus.UNKNOWN]
def test_vm_property(self):
vm = self.get_random_vm()
assert (vm.properties.name
and vm.properties.name == vm.get_property("name"))
def test_guest_file_ops(self):
vm = self.start_vm_with_tools()
vm.login_in_guest(self.vm_tools_user, self.vm_tools_pass)
short_dir_name = str(random.randint(10000, 99999))
short_dir_name2 = str(random.randint(10000, 99999))
random_dir_name = "C:\\" + short_dir_name
random_dir_name2 = "C:\\" + short_dir_name2
random_file_name = str(random.randint(10000, 99999))
random_file_name2 = str(random.randint(10000, 99999))
random_content = str(random.randint(10000, 99999))
local_path = os.path.join(os.path.dirname(__file__), "test_file.txt")
fd = open(local_path, "w")
fd.write(random_content)
fd.close()
local_path2 = os.path.join(os.path.dirname(__file__), "downloaded.txt")
remote_path = random_dir_name2 + "\\" + random_file_name
remote_path2 = random_dir_name2 + "\\" + random_file_name2
vm.make_directory(random_dir_name)
vm.move_directory(random_dir_name, random_dir_name2)
vm.send_file(local_path, remote_path)
vm.move_file(remote_path, remote_path2)
vm.get_file(remote_path2, local_path2, overwrite=True)
fd = open(local_path2, "r")
downloaded_content = fd.read()
fd.close()
#this assert tests: make_directory, move_directory,
# send_file, move_file, get_file
assert random_content == downloaded_content
#check list files without regex
files = vm.list_files(random_dir_name2)
assert len(files) == 3 # '.', '..', and our file
assert {'path': '.', 'type': 'directory', 'size': 0} in files
assert {'path': '..', 'type': 'directory', 'size': 0} in files
assert {'path': random_file_name2, 'type': 'file', 'size': 5} in files
#check list files with regex
files = vm.list_files(random_dir_name2, match_pattern=random_file_name2)
assert len(files) == 1 # just our file
assert {'path': random_file_name2, 'type': 'file', 'size': 5} in files
#check delete file
vm.delete_file(remote_path2)
files = vm.list_files(random_dir_name2)
assert len(files) == 2 # '.', '..'
assert {'path': '.', 'type': 'directory', 'size': 0} in files
assert {'path': '..', 'type': 'directory', 'size': 0} in files
#check d |
mar10/wsgidav | wsgidav/samples/hg_dav_provider.py | Python | mit | 22,535 | 0.00071 | # -*- coding: utf-8 -*-
# (c) 2009-2022 Martin Wendt and contributors; see WsgiDAV https://github.com/mar10/wsgidav
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
"""
DAV provider that publishes a Mercurial repository.
Note: This is **not** production code!
The repository is rendered as three top level collections.
edit:
Contains the working directory, i.e. all files. This includes uncommitted
changes and untracked new files.
This folder is writable.
released:
Contains the latest committed files, also known as 'tip'.
This folder is read-only.
archive:
Contains the last 10 revisions as sub-folders.
This folder is read-only.
Sample layout::
/<share>/
edit/
server/
ext_server.py
README.txt
released/
archive/
19/
18/
...
Supported features:
#. Copying or moving files from ``/edit/..`` to the ``/edit/..`` folder will
result in a ``hg copy`` or ``hg rename``.
#. Deleting resources from ``/edit/..`` will result in a ``hg remove``.
#. Copying or moving files from ``/edit/..`` to the ``/released`` folder will
result in a ``hg commit``.
Note that the destination path is ignored, instead the source path is used.
So a user can drag a file or folder from somewhere under the ``edit/..``
directory and drop it directly on the ``released`` directory to commit
changes.
#. To commit all changes, simply drag'n'drop the ``/edit`` folder on the
``/released`` folder.
#. Creating new collections results in creation of a file called ``.directory``,
which is then ``hg add`` ed since Mercurial doesn't track directories.
#. Some attributes are published as live properties, such as ``{hg:}date``.
Known limitations:
#. This 'commit by drag-and-drop' only works, if the WebDAV clients produces
MOVE or COPY requests. Alas, some clients will send PUT, MKCOL, ... sequences
instead.
#. Adding and then removing a file without committing after the 'add' will
leave this file on disk (untracked)
This happens for example whit lock files that Open Office Write and other
applications will create.
#. Dragging the 'edit' folder onto 'released' with Windows File Explorer will
remove the folder in the explorer view, although WsgiDAV did not delete it.
This seems to be done by the client.
See:
http://mercurial.selenic.com/wiki/MercurialApi
Requirements:
``easy_install mercurial`` or install the API as non-standalone version
from here: http://mercurial.berkwood.com/
ht | tp://mercurial.berkwood.com/binaries/mercurial-1.4.win32-py2.6.exe
"""
import os
import sys
import time
from hashlib import md5
from pprint import pprint
from wsgidav import util
from wsgidav.dav_error import HTTP_FORBIDDEN, DAVError
from wsgidav.dav_provider import DAVProvider, _DAVResource
from wsgidav.samples.dav_provider_tools import VirtualCollection
try:
import mercurial.ui
from mercurial import commands, hg
from mercurial.__version__ import version as hgversion
# | from mercurial import util as hgutil
except ImportError:
print(
"Could not import Mercurial API. Try 'easy_install -U mercurial'.",
file=sys.stderr,
)
raise
__docformat__ = "reStructuredText en"
_logger = util.get_module_logger(__name__)
BUFFER_SIZE = 8192
# ============================================================================
# HgResource
# ============================================================================
class HgResource(_DAVResource):
"""Abstract base class for all resources."""
def __init__(self, path, is_collection, environ, rev, localHgPath):
super().__init__(path, is_collection, environ)
self.rev = rev
self.localHgPath = localHgPath
self.absFilePath = self._getFilePath()
assert "\\" not in self.localHgPath
assert "/" not in self.absFilePath
if is_collection:
self.fctx = None
else:
# Change Context for the requested revision:
# rev=None: current working dir
# rev="tip": TIP
# rev=<int>: Revision ID
wdctx = self.provider.repo[self.rev]
self.fctx = wdctx[self.localHgPath]
# util.status("HgResource: path=%s, rev=%s, localHgPath=%s, fctx=%s" % (
# self.path, self.rev, self.localHgPath, self.fctx))
# util.status("HgResource: name=%s, dn=%s, abspath=%s" % (
# self.name, self.get_display_name(), self.absFilePath))
def _getFilePath(self, *addParts):
parts = self.localHgPath.split("/")
if addParts:
parts.extend(addParts)
return os.path.join(self.provider.repo.root, *parts)
def _commit(self, message):
user = self.environ.get("wsgidav.auth.user_name") or "Anonymous"
commands.commit(
self.provider.ui,
self.provider.repo,
self.localHgPath,
addremove=True,
user=user,
message=message,
)
def _check_write_access(self):
"""Raise HTTP_FORBIDDEN, if resource is unwritable."""
if self.rev is not None:
# Only working directory may be edited
raise DAVError(HTTP_FORBIDDEN)
def get_content_length(self):
if self.is_collection:
return None
return self.fctx.size()
def get_content_type(self):
if self.is_collection:
return None
# (mimetype, _mimeencoding) = mimetypes.guess_type(self.path)
# if not mimetype:
# return "application/octet-stream"
# return mimetype
return util.guess_mime_type(self.path)
def get_creation_date(self):
# statresults = os.stat(self._file_path)
# return statresults[stat.ST_CTIME]
return None # TODO
def get_display_name(self):
if self.is_collection or self.fctx.filerev() is None:
return self.name
return "%s@%s" % (self.name, self.fctx.filerev())
def get_etag(self):
return (
md5(self.path).hexdigest()
+ "-"
+ util.to_str(self.get_last_modified())
+ "-"
+ str(self.get_content_length())
)
def get_last_modified(self):
if self.is_collection:
return None
# (secs, tz-ofs)
return self.fctx.date()[0]
def support_ranges(self):
return False
def get_member_names(self):
assert self.is_collection
cache = self.environ["wsgidav.hg.cache"][util.to_str(self.rev)]
dirinfos = cache["dirinfos"]
if self.localHgPath not in dirinfos:
return []
return dirinfos[self.localHgPath][0] + dirinfos[self.localHgPath][1]
# return self.provider._listMembers(self.path)
def get_member(self, name):
# Rely on provider to get member oinstances
assert self.is_collection
return self.provider.get_resource_inst(
util.join_uri(self.path, name), self.environ
)
def get_display_info(self):
if self.is_collection:
return {"type": "Directory"}
return {"type": "File"}
def get_property_names(self, *, is_allprop):
"""Return list of supported property names in Clark Notation.
See DAVResource.get_property_names()
"""
# Let base class implementation add supported live and dead properties
propNameList = super().get_property_names(is_allprop=is_allprop)
# Add custom live properties (report on 'allprop' and 'propnames')
if self.fctx:
propNameList.extend(
[
"{hg:}branch",
"{hg:}date",
"{hg:}description",
"{hg:}filerev",
"{hg:}rev",
"{hg:}user",
]
)
return propNameList
def get_property_value(self, name):
"""Return the value of a property.
See get_property_value()
"""
|
JulyKikuAkita/PythonPrac | cs15211/IsSubsequence.py | Python | apache-2.0 | 5,737 | 0.002789 | __source__ = 'https://leetcode.com/problems/is-subsequence/description/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/is-subsequence.py
# Time: O(n)
# Space: O(1)
#
# Description: Leetcode # 392. Is Subsequence
#
# Given a string s and a string t, check if s is subsequence of t.
#
# You may assume that there is only lower case English letters in both s and t.
# t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
#
# A subsequence of a string is a new string which is formed from
# the original string by deleting some (can be none) of the characters
# without disturbing the relative positions of the remaining characters.
# (ie, "ace" is a subsequence of "abcde" while "aec" is not).
#
# Example 1:
# s = "abc", t = "ahbgdc"
#
# Return true.
#
# Example 2:
# s = "axc", t = "ahbgdc"
#
# Return false.
#
# Follow up:
# If there are lots of incoming S, say S1, S2, ... , Sk where k >= 1B,
# and you want to check one by one to see if T has its subsequence.
# In this scenario, how would you change your code?
#
# Companies
# Pinterest
# Related Topics
# Binary Search Dynamic Programming Greedy
#
import unittest
# Greedy solution.
# 128ms 75.77%
class Solution(object):
def isSubsequence(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if not s:
return True
i = 0
for c in t:
if c == s[i]:
i += 1
if i == len(s):
break
return i == len(s)
def isSubsequence2(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
t = iter(t)
return all(c in t for c in s)
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
# two pointers:
# 17ms 77.84%
class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int indexS = 0, indexT = 0;
while (indexT < t.length()) {
if (t.charAt(indexT) == s.charAt(indexS)) {
indexS++;
if (indexS == s.length()) return true;
}
indexT++;
}
return false;
}
}
# 1ms 100%
class Solution {
public boolean isSubsequence(String s, String t) {
if (s.length() == 0) return true;
int prev = t.indexOf(s.charAt(0));
if (prev == -1) return false;
for (int i = 1; i < s.length(); i++) {
prev = t.indexOf(s.charAt(i), prev + 1);
if (prev == -1) return false;
}
return true;
}
}
# 1ms 100%
class Solution {
public boolean isSubsequence(String s, String t) {
int[] a = new int[s.length() + 1];
a[0] = -1;
for (int i = 0; i < s.length(); i++) {
int index = t.indexOf(s.charAt(i), a[i] + 1);
if (index == -1) {
return false;
}
a[i + 1] = index;
}
return true;
}
}
# quick examples fro java Collections.binarySearch(list, key)
# http://www.geeksforgeeks.org/collections-binarysearch-java-examples/
// Returns index of key in sorted list sorted in
// ascending order
public static int binarySearch(List s | list, T key)
// Returns index of key in sorted list sorted in
// order defined by Comparator c.
public static int binarySearch(List slist, T key, Comparator c) |
If key is not present, the it returns "(-(insertion point) - 1)".
The insertion point is defined as the point at which the key
would be inserted into the list.
public static void main(String[] args)
{
List al = new ArrayList();
al.add(1);
al.add(2);
al.add(3);
al.add(10);
al.add(20);
// 10 is present at index 3.
int index = Collections.binarySearch(al, 10);
System.out.println(index);
// 13 is not present. 13 would have been inserted
// at position 4. So the function returns (-4-1)
// which is -5.
index = Collections.binarySearch(al, 15);
System.out.println(index);
}
Binary search solution for follow-up with detailed comments
Re: Java binary search using TreeSet got TLE
I think the Map and TreeSet could be simplified by Array and binarySearch.
Since we scan T from beginning to the end (index itself is in increasing order),
List will be sufficient. Then we can use binarySearch to replace with TreeSet
ability which is a little overkill for this problem. Here is my solution.
// Follow-up: O(N) time for pre-processing, O(Mlog?) for each S.
// Eg-1. s="abc", t="bahbgdca"
// idx=[a={1,7}, b={0,3}, c={6}]
// i=0 ('a'): prev=1
// i=1 ('b'): prev=3
// i=2 ('c'): prev=6 (return true)
// Eg-2. s="abc", t="bahgdcb"
// idx=[a={1}, b={0,6}, c={5}]
// i=0 ('a'): prev=1
// i=1 ('b'): prev=6
// i=2 ('c'): prev=? (return false)
# 49ms 18.85%
class Solution {
public boolean isSubsequence(String s, String t) {
List<Integer>[] idx = new List[256]; // Just for clarity
for (int i = 0; i < t.length(); i++) {
if (idx[t.charAt(i)] == null)
idx[t.charAt(i)] = new ArrayList<>();
idx[t.charAt(i)].add(i);
}
int prev = 0;
for (int i = 0; i < s.length(); i++) {
if (idx[s.charAt(i)] == null) return false; // Note: char of S does NOT exist in T causing NPE
int j = Collections.binarySearch(idx[s.charAt(i)], prev);
if (j < 0) j = -j - 1;
if (j == idx[s.charAt(i)].size()) return false;
prev = idx[s.charAt(i)].get(j) + 1;
}
return true;
}
}
''' |
microelly2/freecad-objecttree | objecttree.py | Python | lgpl-3.0 | 28,721 | 0.057066 | # -*- coding: utf-8 -*-
#-------------------------------------------------
#-- object tree
#--
#-- microelly 2015
#--
#-- GNU Lesser General Public License (LGPL)
#-------------------------------------------------
import FreeCAD
import PySide
from PySide import QtCore, QtGui, QtSvg
global QtGui,QtCore
global fullRefresh, parentsView, childrensView, familyView, renderWidget
global doSomething,search, createTree, sayWidgetTree,cm,vlines,TypeIcon
global w, refresh
import os
global __version__
__version__ = "(version 0.10 2015-06-18)"
from configmanager import ConfigManager
global AppHomePath
AppHomePath=FreeCAD.ConfigGet('AppHomePath')
cm=ConfigManager("ObjectTree")
def TypeIcon(typeId='Part::Cut'):
typeIcons={
'Part::MultiFuse' : "icons:Part_Fuse.svg",
'Part::MultiCommon' : "icons:Part_Common.svg",
'Sketcher::SketchObject' : "icons:Sketcher_Sketch.svg",
#'Draft::Clone' : "Draft_Clone.svg",
# 'App::DocumentObjectGroup' : icons:
'Drawing::FeaturePage' : 'icons:Page.svg',
'Drawing::FeatureViewPart' : 'icons:Draft_Drawing.svg'
#'Drawing::FeatureViewPart' : 'icons:Drawing-orthoviews.svg',
}
tk=typeId.replace("::", "_");
f2=QtCore.QFileInfo("icons:"+ tk + ".svg")
if f2.exists():
return QtGui.QIcon("icons:"+ tk + ".svg")
if typeIcons.has_key(typeId):
f2=QtCore.QFileInfo(typeIcons[typeId])
if f2.exists():
return QtGui.QIcon(typeIcons[typeId])
FreeCAD.Console.PrintError("TypeIcon: " + typeId + " - no Icon found \n")
return QtGui.QIcon('icons:freecad.svg')
def createTree(obj,n,mode):
if n<2:
tree={'obj':obj,'subs':[],'subtyp':n,'status':'normal','a_label':obj.Label,'a_typeId':obj.TypeId}
else:
tree={'obj':obj,'subs':[],'subtyp':n,'status':'hide','a_label':obj.Label,'a_typeId':obj.TypeId}
print "--------------------"
print obj.Label
k=obj.OutList
print "--------------------"
for it in k:
print it.Label, " => ",it.TypeId
print "--------------------"
if mode == 'parents':
if obj.TypeId=='PartDesign::Mirrored' or obj.TypeId=='PartDesign::LinearPattern':
k=obj.OutList
for el in k:
FreeCAD.Console.PrintMessage("\n: "+el.Label + "--"+el.TypeId + "\n")
FreeCAD.Console.PrintMessage("\n size:" + str(len(k)) + "\n")
#if len(k)>1:
ske=k[-1]
FreeCAD.Console.PrintMessage("Sonder: "+ske.Label)
#else:
# stske=[]
pad=k[0]
stske=createTree(pad,n+2,mode)
FreeCAD.Console.PrintMessage(" pad "+ pad.Label)
tree1={'obj':ske,'subs':[stske],'subtyp':n+1,'status':'normal'}
tree['subs']=[tree1]
elif obj.TypeId=='PartDesign::MultiTransform':
k=obj.OutList
for el in k:
FreeCAD.Console.PrintMessage("\n: "+el.Label + "--"+el.TypeId + "\n")
FreeCAD.Console.PrintMessage("\n size:" + str(len(k)) + "\n")
#if len(k)>1:
ske=k[0]
FreeCAD.Console.PrintMessage("Sonder: "+ske.Label)
# hier fehlt die hierarchie ...
#else:
# stske=[]
pad=k[-1]
stske=createTree(pad,n+len(k)+0,mode)
FreeCAD.Console.PrintMessage(" pad "+ pad.Label)
treealt={'obj':ske,'subs':[stske],'subtyp':n+len(k)-1,'status':'normal'}
# tree['subs']=[treealt]
k.pop()
# k.reverse()
# treealt=["intitree-----------------------------------"]
print "#######"
m=n+len(k)
for it in k:
print "++++++++++++++++"
print it.Label," " ,it.TypeId," m",m
treeneu={'obj':it,'subs':[treealt],'subtyp':m,'status':'normal','a_label':it.Label}
m -= 1
treealt=treeneu
import pprint
pprint.pprint(treealt)
print "########"
tree['subs']=[treealt]
tree['subtyp']=n
else:
for s in obj.OutList:
st=createTree(s,n+1,mode)
#st[s]['subtyp']=n
tree['subs'].append(st)
elif mode == 'children':
for s in obj.InList:
st=createTree(s,n+1,mode)
#st[s]['subtyp']=n
tree['subs'].append(st)
else:
FreeCAD.Console.PrintError("unknown mode:" + mode + "\n")
raise Exception
#FreeCAD.Console.PrintMessage(str(n) + " " + obj.Label +" typeId=")
#FreeCAD.Console.PrintMessage(obj.TypeId +"\n")
return tree
def sayTree(ot):
''' print output of the tree structure for testing'''
ss="#"
for k in ot.keys():
if k=='subtyp':
ss= "* " * ot[k]
if k == 'obj':
name = ot[k].Label
# print ss + name
for s in ot['subs']:
sayTree(s)
#------------------------------------------
import sys
from PySide import QtCore, QtGui
if False:
try:
import FreeCAD
FreeCAD.open(u"/home/thomas/freecad_buch/b142_otreee/m02_mouse_events_testcase.fcstd")
#FreeCAD.open(u"E:/freecadbuch_2/b142_otreee/m02_mouse_events_testcase.fcstd")
App.setActiveDocument("m02_mouse_events_testcase")
App.ActiveDocument=App.getDocument("m02_mouse_events_testcase")
Gui.ActiveDocument=Gui.getDocument("m02_mouse_events_testcase")
App.ActiveDocument.Torus.ViewObject.Visibility=True
App.ActiveDocument.Sphere.ViewObject.Visibility=True
App.ActiveDocument.Cylinder.ViewObject.Visibility=True
FreeCADGui.Selection.clearSelection()
for s in [App.ActiveDocument.Box001, App.ActiveDocument.Sphere001,App.ActiveDocument.Cone001]:
FreeCADGui.Selection.addSelection(s)
except:
pass
if False:
os=FreeCAD.ActiveDocument.Objects
for obj in os:
obj.ViewObject.Visibility=False
App.ActiveDocument.Torus.ViewObject.Visibility=True
App.ActiveDocument.Sphere.ViewObject.Visibility=True
App.ActiveDocument.Cylinder.ViewObject.Visibility=True
FreeCADGui.Selection.clearSelection()
for s in [App.ActiveDocument.Box001, App.ActiveDocument.Sphere001,App.ActiveDocument.Cone001]:
FreeCADGui.Selection.addSelection(s)
global buff
buff={}
def initBuff():
os=FreeCAD.ActiveDocument.Objects
for obj in os:
try:
v=obj.ViewObject.Visibility
t=obj.ViewObject.Transparency
buff[obj]=[v,t]
say("!" +obj.Label + ":"+str(obj.ViewObject.Transparency) + "-- "+ str(obj.ViewObject.Visibility))
v=obj.ViewObject.Visibility=False
except:
say (obj.Label + "not init buff")
initBuff()
global context
context={}
os=FreeCADGui.Selection.getSelection()
for obj in os:
context[obj]=True
global lastObj
lastObj=False
try:
lastObj =[FreeCAD.ActiveDocument.ActiveObject,FreeCAD.ActiveDocument.ActiveObject.ViewObject.ShapeColor]
except:
pass
class MyBut(QtGui.QPushButton):
def __init__(self,icon,name):
QtGui.QPushButton.__init__(self,icon,name)
#QtGui.QPushButton.__init__(self,name)
# self.obj=FreeCAD.ActiveDocument.Box
def enterEvent(self,ev):
global lastObj
import random
self.obvisi=self.obj.ViewObject.Visibility
self.color=self.obj.ViewObject.ShapeColor
self.obj.ViewObject.ShapeColor=(1.0,0.5,1.0)
self.obj.ViewObject.Transparency=0
self.obj.ViewObject.DisplayMode = "Flat Lines"
self.obj.ViewObject.Visibility=True
say("mouse enter A " + self.obj.Label)
try:
if lastObj:
lo=lastObj[0]
loc=lastObj[1]
lo.ViewObject.ShapeColor=(random.random(),random.random(),random.random())
lastObj=[self.obj,self.color]
#FreeCADGui.SendMsgToActiveView("ViewFit")
FreeCAD.ActiveDocument.recompute()
say(lo.ViewObject.ShapeColor)
except:
sayexc("hk2")
def leaveEvent(self,ev):
say("mouse Leave A " + self.obj.Label)
try:
self.obj.ViewObject.Visibility=False
self.obj.ViewObject.ShapeColor=self.color
self.obj.ViewObject.Transparency=90
self.obj.View | Object.DisplayMode = "Shaded"
if context.has_key(self.obj) and context[self.obj]:
pass
self.obj.ViewObject.Visibility=True
except:
sayexc("hu44")
FreeCAD.ActiveDocument.recompute()
| def mousePressEvent(self, ev):
#FreeCAD.Console.PrintMessage("k mouse press")
say("mouse Press A " + self.obj.Label)
#FreeCAD.Console.PrintMessage("Label clicked " + ot['obj'].Label + "\n")
FreeCADGui.Selection.clearSelection()
## FreeCADGui.Selection.addSelection(self.ot['obj'])
FreeCADGui.Selection.addSelection(self.obj)
fullRefresh('family')
def eventFilter1(self,ev):
FreeCAD.Console.PrintMessage("kgdfgfdk")
say(" c gfgdfgfd nter event")
say(ev)
global hideall
def hideall():
os=FreeCAD.ActiveDocument.Objects
for obj in os:
FreeCAD.Console.PrintMessage("!# ")
obj.ViewObject.Transparency=90
self.obj.ViewObject.DisplayMode = "Shaded"
obj.ViewObject.Visibility=False
global showall2
def showall2():
os=F |
eriktaubeneck/ordbok | ordbok/exceptions.py | Python | mit | 3,492 | 0 | class OrdbokException(Exception):
pass
class OrdbokKeyException(OrdbokException):
def __init__(self, key, config_file):
self.key = key
self.config_file_path = config_file.config_file_path
class OrdbokMissingConfigFileException(OrdbokKeyException):
def __repr__(self):
return ('{0} is required to be specified in {1} '
'but {1} was not registered with Ordbok'.format(
self.key, self.config_file_path))
class OrdbokLowercaseKeyException(OrdbokKeyException):
def __repr__(self):
return '{} config key in {} must be uppercase.'.format(
self.key, self.config_filename)
class OrdbokMissingKeyException(OrdbokKeyException):
def __repr__ | (self):
return (' | {} config key should be specified in {} but was not found.'
''.format(self.key, self.config_filename))
class OrdbokSelfReferenceException(OrdbokKeyException):
def __repr__(self):
return ('Cannot require {} to be required in its own file ({}).'
''.format(self.key, self.config_filename))
class OrdbokAmbiguousConfigFileException(OrdbokException):
def __init__(self, referenced_config_files):
self.referenced_config_files = referenced_config_files
def __repr__(self):
return ('Config file names are ambiguous. Please make them '
'distinct: {}'.format(self.referenced_config_files))
class OrdbokPreviouslyLoadedException(OrdbokException):
def __init__(self, config_files_lookup,
referenced_config_file, config_file):
self.previously_loaded_filename = (
config_files_lookup[referenced_config_file].filename)
self.current_filename = config_file.filename
def __repr__(self):
return ('Cannot specify {0} required Ordbok config variables in '
'{1}, {0} is loaded before {1}.'.format(
self.previously_loaded_filename, self.current_filename))
class OrdbokNestedRequiredKeyException(OrdbokException):
def __init__(self, value):
self.value = value
def __repr__(self):
return ('Cannot specifiy {} required Ordbok config variable '
'in a nested config dictionary'.format(self.value))
class OrdbokMissingPrivateKeyException(OrdbokException):
def __repr__(self):
return ('PRIVATE_KEY_ORDBOK config variable not found. '
'Please set in configuration loaded before PrivateConfigFile '
'or in the OS environment as PRIVATE_KEY_ORDBOK.')
class OrdbokTargetedEnvKeyException(OrdbokException):
def __init__(self, key, env_key):
self.key = key
self.env_key = env_key
def __repr__(self):
return ('{} config key should be specified in the environment as '
'{} but was not found.'.format(self.key, self.env_key))
class OrdbokMissingPrivateConfigFile(OrdbokException):
def __init__(self, config_file):
self.config_file_path = config_file.config_file_path
def __repr__(self):
return ("Private config file '{0}' not found. Please create and run "
"`ordbok encrypt {0}`.".format(self.config_file_path))
class OrdbokMissingEncryptedPrivateConfigFile(OrdbokMissingPrivateConfigFile):
def __repr__(self):
return ("Encrypted version of private config file '{0}' not found. "
"Please run `ordbok encrypt {0}`.".format(
self.config_file_path))
|
tuxar-uk/Merlyn | x/slave.py | Python | mit | 3,181 | 0.038981 | #!/usr/bin/env python3
# Requires PyAudio and PySpeech.
import speech_recognition as sr
from fuzzywuzzy import fuzz
from time import ctime
import time
import os
from subprocess import Popen
from gtts import gTTS
import sys
import pyjokes
import SR
import sys
#stderr = open('slave.log', 'w')
#sys.stderr = stderr
devnull = open(os.devnull, 'w')
browser = "google-chrome"
web = 0
say = 1
run = 2
exe = 3
fun = 4
cti = ctime()
#joke = pyjokes.get_joke()
cmds = {
"amazon" : (web, "http://amazon.co.uk/"),
"calculator": (run, "galculator"),
"chess" : (run, "xboard"),
"commands" : (exe, "xxx"),
"dictation" : (web, "https://dictation.io/"),
"files" : (run, "pcmanfm"),
"google" : (web, "https://www.google.co.uk/#q="),
"joke" : (exe, pyjokes.get_joke),
"map" : (web, "https://google.co.uk/maps/place/"),
"meaning" : (say, "42"),
"music" : (web, "https://www.youtube.com/watch?v=ViIx5uagasY&list=PL-MQ2wS-IPhApRRjqilUit2xBXfH0Li8y"),
"name" : (say, "My name is Juniper Kate."),
"news" : (web, "https://news.google.co.uk/"),
"pinball" : (run, "pinball"),
"reddit" : (web, "https://www.reddit.com/"),
"rhythmbox" : (run, "rhythmbox"),
"stop" : (exe, sys.exit),
"time" : (exe, ctime),
"wikipedia" : (web, "https://www.wikiwand.com/en/"),
"youtube" : (web, "https://www.youtube.com/")
}
cmdstr = ''
for key in sorted(cmds.keys()):
cmdstr += key + ", "
cmds["commands"] = cmdstr
print("Welcome to My Master's Voice! Please speak one of the following commands:", cmdstr)
keygen = [(key,0.1) for key in cmds.keys()]
print (keygen)
def speak(text):
print(">", text)
# tts = gTTS(text=text, lang='en')
# tts.save("audio.mp3")
# Popen(["mpg321", "audio.mp3"], stdout=devnull, stderr=devnull)
def nearest_word(word, words):
max = 0
for w in words:
d = fuzz.ratio(w, word)
if d > max:
new = w
max = d
return (new, max)
r = sr.Recognizer()
#r.energy_threshold = 2
while True:
speak("Alan, what do you want me to do?")
# Record Audio
with sr.Microphone() as source:
print("Say something!")
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
# text = SR.getSpeechText(r, sr, audio)
text = (r.recognize_sphinx(audio, keyword_entries = keygen))
# text = r.recognize_sphinx(audio)
if text is None or len(text) < 3:
speak("Sorry, I didn't understand!")
continue
print("<", text)
text = text.lower()
words = text.spl | it()
w = words[0]
if w not in cmds:
(new, d) = nearest_word(w, cmds.keys())
if d > 66:
w = new
speak("Correcting to " + w)
if w not in cmds:
max = 0
for word in words:
(alt, d) = nearest_word(word, cmds.keys())
if d > max:
| new = alt
max = d
if max > 66:
w = new
speak(w)
if w in cmds:
t = cmds[w][0]
p = cmds[w][1]
if t == web:
for i in range(1,len(words)):
p += words[i]+' '
Popen([browser, p])
elif t == say:
speak(p)
elif t == exe:
speak(p())
elif t == fun:
p()
elif t == run:
Popen(p)
else:
try:
Popen(text)
except FileNotFoundError:
speak("I don't know, really I don't. Sorry")
|
flass/agrogenom | pipeline/scripts_agrogenom/3_Ananalysis_of_genome_histories/phyloprofile_to_db.py | Python | gpl-3.0 | 757 | 0.025099 | #!/usr/bin/python
"""to build genome.phylogenetic_profile table in agrogenomdb"""
import sys, os, tree2
nfphyloprofile = sys.argv[1]
nfout = sys.argv[2]
fphyloprofile = open(nfphyloprofile, 'r')
fout = open(nfout, 'w')
dboolstr = {True:'T', False:'F', '1':'T', '0':'F'}
header = fphylopro | file.readline().rstrip('\n').split('\t')[1:]
for line in fphyloprofile:
lsp = line.rstrip('\n').split('\t')
subfam = lsp[0]
profile = lsp[1:]
for i in range(len(profile)):
try:
fout.write('\t'.join([subfam, header[i], dboolstr[bool(int(profile[i]))], profile[i]])+'\n')
#~ fout.wr | ite('\t'.join([subfam, header[i], profile[i]])+'\n')
except KeyError, e:
print [subfam, header[i], profile[i]]
raise KeyError, e
fphyloprofile.close()
fout.close()
|
WALR/taiga-back | taiga/base/api/request.py | Python | agpl-3.0 | 14,953 | 0.000669 | # Copyright (C) 2015 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2015 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# This code is partially taken from django-rest-framework:
# Copyright (c) 2011-2014, Tom Christie
"""
The Request class is used as a wrapper around the standard request object.
The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header,
and available as `request.DATA`
- full support of PUT method, including support for file uploads
- form overloading of HTTP me | thod, content type and content
"""
from django.conf import settings
from django.http import QueryDict
| from django.http.multipartparser import parse_header
from django.utils.datastructures import MultiValueDict
from django.utils.six import BytesIO
from taiga.base import exceptions
from . import HTTP_HEADER_ENCODING
from .settings import api_settings
def is_form_media_type(media_type):
"""
Return True if the media type is a valid form media type.
"""
base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))
return (base_media_type == "application/x-www-form-urlencoded" or
base_media_type == "multipart/form-data")
class override_method(object):
"""
A context manager that temporarily overrides the method on a request,
additionally setting the `view.request` attribute.
Usage:
with override_method(view, request, "POST") as request:
... # Do stuff with `view` and `request`
"""
def __init__(self, view, request, method):
self.view = view
self.request = request
self.method = method
def __enter__(self):
self.view.request = clone_request(self.request, self.method)
return self.view.request
def __exit__(self, *args, **kwarg):
self.view.request = self.request
class Empty(object):
"""
Placeholder for unset attributes.
Cannot use `None`, as that may be a valid value.
"""
pass
def _hasattr(obj, name):
return not getattr(obj, name) is Empty
def clone_request(request, method):
"""
Internal helper method to clone a request, replacing with a different
HTTP method. Used for checking permissions against other methods.
"""
ret = Request(request=request._request,
parsers=request.parsers,
authenticators=request.authenticators,
negotiator=request.negotiator,
parser_context=request.parser_context)
ret._data = request._data
ret._files = request._files
ret._content_type = request._content_type
ret._stream = request._stream
ret._method = method
if hasattr(request, "_user"):
ret._user = request._user
if hasattr(request, "_auth"):
ret._auth = request._auth
if hasattr(request, "_authenticator"):
ret._authenticator = request._authenticator
return ret
class ForcedAuthentication(object):
"""
This authentication class is used if the test client or request factory
forcibly authenticated the request.
"""
def __init__(self, force_user, force_token):
self.force_user = force_user
self.force_token = force_token
def authenticate(self, request):
return (self.force_user, self.force_token)
class Request(object):
"""
Wrapper allowing to enhance a standard `HttpRequest` instance.
Kwargs:
- request(HttpRequest). The original request instance.
- parsers_classes(list/tuple). The parsers to use for parsing the
request content.
- authentication_classes(list/tuple). The authentications used to try
authenticating the request's user.
"""
_METHOD_PARAM = api_settings.FORM_METHOD_OVERRIDE
_CONTENT_PARAM = api_settings.FORM_CONTENT_OVERRIDE
_CONTENTTYPE_PARAM = api_settings.FORM_CONTENTTYPE_OVERRIDE
def __init__(self, request, parsers=None, authenticators=None,
negotiator=None, parser_context=None):
self._request = request
self.parsers = parsers or ()
self.authenticators = authenticators or ()
self.negotiator = negotiator or self._default_negotiator()
self.parser_context = parser_context
self._data = Empty
self._files = Empty
self._method = Empty
self._content_type = Empty
self._stream = Empty
if self.parser_context is None:
self.parser_context = {}
self.parser_context["request"] = self
self.parser_context["encoding"] = request.encoding or settings.DEFAULT_CHARSET
force_user = getattr(request, "_force_auth_user", None)
force_token = getattr(request, "_force_auth_token", None)
if (force_user is not None or force_token is not None):
forced_auth = ForcedAuthentication(force_user, force_token)
self.authenticators = (forced_auth,)
def _default_negotiator(self):
return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS()
@property
def method(self):
"""
Returns the HTTP method.
This allows the `method` to be overridden by using a hidden `form`
field on a form POST request.
"""
if not _hasattr(self, "_method"):
self._load_method_and_content_type()
return self._method
@property
def content_type(self):
"""
Returns the content type header.
This should be used instead of `request.META.get("HTTP_CONTENT_TYPE")`,
as it allows the content type to be overridden by using a hidden form
field on a form POST request.
"""
if not _hasattr(self, "_content_type"):
self._load_method_and_content_type()
return self._content_type
@property
def stream(self):
"""
Returns an object that may be used to stream the request content.
"""
if not _hasattr(self, "_stream"):
self._load_stream()
return self._stream
@property
def QUERY_PARAMS(self):
"""
More semantically correct name for request.GET.
"""
return self._request.GET
@property
def DATA(self):
"""
Parses the request body and returns the data.
Similar to usual behaviour of `request.POST`, except that it handles
arbitrary parsers, and also works on methods other than POST (eg PUT).
"""
if not _hasattr(self, "_data"):
self._load_data_and_files()
return self._data
@property
def FILES(self):
"""
Parses the request body and returns any files uploaded in the request.
Similar to usual behaviour of `request.FILES`, except that it handles
arbitrary parsers, and also works on methods other than POST (eg PUT).
"""
if not _hasattr(self, "_files"):
self._load_data_and_files()
return self._files
@property
def user(self):
"""
Returns the user associated with the current request, as authenticated
by the authentication classes provided to the request.
"""
if not hasattr(self, "_user"):
self._authenticate()
return self._user
@user.setter
def user(self, value):
"""
Sets the user on the current request. This is necessary to maintain
compatibility with django.contri |
Lazar-T/blic_news | storiesText.py | Python | mit | 2,806 | 0 | import urllib
from bs4 import BeautifulSoup
page_url = 'http://www.blic.rs/'
page = urllib.urlopen(page_url)
soup = BeautifulSoup(page)
a = soup.find(id="cat_boxes")
b = a.find_all('a')
def firstHeadline():
text1 = soup.select("#home_main_article_text")[0].h1.text
href1 = soup.select("#home_main_article_text | ")[0].a.get('href')
return text1, href1
def secondHeadline():
text2 = soup.select("#home_main_article_text")[1].h1.text
href2 = soup.select("#home_main_article_text")[1].a.get('href')
return text2, href2
def thirdHeadline():
| text3 = soup.select("#home_main_article_text")[2].h1.text
href3 = soup.select("#home_main_article_text")[2].a.get('href')
return text3, href3
def fourthHeadline():
text4 = soup.select("#home_main_article_text")[3].h1.text
href4 = soup.select("#home_main_article_text")[3].a.get('href')
return text4, href4
def fifthHeadline():
text5 = soup.select("#home_main_article_text")[4].h1.text
href5 = soup.select("#home_main_article_text")[4].a.get('href')
return text5, href5
def world_story_one():
text10 = b[9].text
href10 = b[8].get('href')
return text10, href10
def world_story_two():
text11 = b[11].text
href11 = b[11].get('href')
return text11, href11
def world_story_three():
text12 = b[12].text
href12 = b[12].get('href')
return text12, href12
def world_story_four():
text13 = b[13].text
href13 = b[13].get('href')
return text13, href13
def chronic_story_one():
text14 = b[16].text
href14 = b[15].get('href')
return text14, href14
def chronic_story_two():
text15 = b[18].text
href15 = b[18].get('href')
return text15, href15
def chronic_story_three():
text16 = b[19].text
href16 = b[19].get('href')
return text16, href16
def chronic_story_four():
text17 = b[20].text
href17 = b[20].get('href')
return text17, href17
def society_story_one():
text18 = b[23].text
href18 = b[22].get('href')
return text18, href18
def society_story_two():
text19 = b[25].text
href19 = b[25].get('href')
return text19, href19
def society_story_three():
text20 = b[26].text
href20 = b[26].get('href')
return text20, href20
def society_story_four():
text21 = b[27].text
href21 = b[27].get('href')
return text21, href21
def economy_story_one():
text22 = b[30].text
href22 = b[29].get('href')
return text22, href22
def economy_story_two():
text23 = b[32].text
href23 = b[32].get('href')
return text23, href23
def economy_story_three():
text24 = b[33].text
href24 = b[33].get('href')
return text24, href24
def economy_story_four():
text25 = b[34].text
href25 = b[34].get('href')
return text25, href25
|
aptivate/ckanext-mapactiontheme | ckanext/mapactiontheme/controllers/package.py | Python | agpl-3.0 | 1,023 | 0.001955 | import ckan.controllers.package as package
import ckan.lib.dictization.model_dictize as model_dictize
import ckan.model as model
from ckan.common import c
class MapactionPackageController(package.PackageController):
def groups(self, id):
q = model.Session.query(model.Group) \
.filter(model.Group.is_organization == False) \
.filter(model.Group.state == 'active')
groups = q.all()
'''
package = c.get('package')
if package:
groups = set(groups) - set(package.get_groups())
'''
context = {'model': model, 'session': model.Session,
'user': c.user or c.author, 'for_view': True, |
'auth_user_obj': c.userobj, 'use_cache': False}
group_list = model_dictize.group_list_dictize(groups, context)
c.event_dropdown = [[group['id'], group['display_name']]
fo | r group in group_list]
return super(MapactionPackageController, self).groups(id) |
conorsch/securedrop | molecule/testinfra/mon/test_mon_network.py | Python | agpl-3.0 | 3,154 | 0.000317 | import io
import os
import difflib
import pytest
from jinja2 import Template
import testutils
securedrop_test_vars = testutils.securedrop_test_vars
testinfra_hosts = [securedrop_test_vars.monitor_hostname]
@pytest.mark.skip_in_prod
def test_mon_iptables_rules(host):
local = host.get_host("local://")
time_service_user = (
host.check_output("id -u systemd-timesync")
if securedrop_test_vars.securedrop_target_distribution == "focal"
else 0
)
# Build a dict of variables to pass to jinja for iptables comparison
kwargs = dict(
app_ip=os.environ.get('APP_IP', securedrop_test_vars.app_ip),
default_interface=host.check_output(
"ip r | head -n 1 | awk '{ print $5 }'"),
tor_user_id=host.check_output("id -u debian-tor"),
time_service_user=time_service_user,
ssh_group_gid=host.check_output("getent group ssh | cut -d: -f3"),
postfix_user_id=host.check_output("id -u postfix"),
dns_server=securedro | p_test_vars.dns_server)
# Required for testing under Qubes.
if local.interface("eth0").exis | ts:
kwargs["ssh_ip"] = local.interface("eth0").addresses[0]
# Build iptables scrape cmd, purge comments + counters
iptables = r"iptables-save | sed 's/ \[[0-9]*\:[0-9]*\]//g' | egrep -v '^#'"
environment = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging")
iptables_file = "{}/iptables-mon-{}.j2".format(
os.path.dirname(os.path.abspath(__file__)),
environment)
# template out a local iptables jinja file
jinja_iptables = Template(io.open(iptables_file, 'r').read())
iptables_expected = jinja_iptables.render(**kwargs)
with host.sudo():
# Actually run the iptables scrape command
iptables = host.check_output(iptables)
# print diff comparison (only shows up in pytests if test fails or
# verbosity turned way up)
for iptablesdiff in difflib.context_diff(iptables_expected.split('\n'),
iptables.split('\n')):
print(iptablesdiff)
# Conduct the string comparison of the expected and actual iptables
# ruleset
assert iptables_expected == iptables
@pytest.mark.skip_in_prod
@pytest.mark.parametrize('ossec_service', [
dict(host="0.0.0.0", proto="tcp", port=22, listening=True),
dict(host="0.0.0.0", proto="udp", port=1514, listening=True),
dict(host="0.0.0.0", proto="tcp", port=1515, listening=False),
])
def test_listening_ports(host, ossec_service):
"""
Ensure the OSSEC-related services are listening on the
expected sockets. Services to check include ossec-remoted
and ossec-authd. Helper services such as postfix are checked
separately.
Note that the SSH check will fail if run against a prod host, due
to the SSH-over-Tor strategy. We can port the parametrized values
to config test YAML vars at that point.
"""
socket = "{proto}://{host}:{port}".format(**ossec_service)
with host.sudo():
assert (host.socket(socket).is_listening ==
ossec_service['listening'])
|
srinathv/bokeh | bokeh/tests/test_resources.py | Python | bsd-3-clause | 6,016 | 0.001828 | from __future__ import absolute_import
import unittest
import bokeh.resources as resources
from bokeh.resources import _get_cdn_urls
WRAPPER = """Bokeh.$(function() {
foo
});"""
WRAPPER_DEV = '''require(["jquery", "main"], function($, Bokeh) {
Bokeh.set_log_level("info");
Bokeh.$(function() {
foo
});
});'''
LOG_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal']
DEFAULT_LOG_JS_RAW = 'Bokeh.set_log_level("info");'
## Test JSResources
def test_js_resources_default_mode_is_inline():
r = resources.JSResources()
assert r.mode == "inline"
def test_js_resources_inline_has_no_css_resources():
r = resources.JSResources(mode="inline")
assert r.mode == "inline"
assert r.dev is False
assert len(r.js_raw) == 3
assert r.js_raw[-1] == DEFAULT_LOG_JS_RAW
assert hasattr(r, 'css_raw') is False
assert r.messages == []
## Test CSSResources
def test_css_resources_default_mode_is_inline():
r = resources.CSSResources()
assert r.mode == "inline"
def test_inline_css_resources():
r = resources.CSSResources(mode="inline")
assert r.mode == "inline"
assert r.dev is False
assert len(r.css_raw) == 2
assert hasattr(r, 'js_raw') is False
assert r.messages == []
class TestResources(unittest.TestCase):
def test_basic(self):
r = resources.Resources()
self.assertEqual(r.mode, "inline")
def test_log_level(self):
r = resources.Resources()
for level in LOG_LEVELS:
r.log_level = level
self.assertEqual(r.log_level, level)
if not r.dev:
self.assertEqual(r.js_raw[-1], 'Bokeh.set_log_level("%s");' % level)
self.assertRaises(Valu | eError, setattr, r, "log_level", "foo")
def test_module_attrs(self):
| self.assertEqual(resources.CDN.mode, "cdn")
self.assertEqual(resources.INLINE.mode, "inline")
def test_inline(self):
r = resources.Resources(mode="inline")
self.assertEqual(r.mode, "inline")
self.assertEqual(r.dev, False)
self.assertEqual(len(r.js_raw), 3)
self.assertEqual(r.js_raw[-1], DEFAULT_LOG_JS_RAW)
self.assertEqual(len(r.css_raw), 2)
self.assertEqual(r.messages, [])
def test_get_cdn_urls(self):
dev_version = "0.0.1dev"
result = _get_cdn_urls(dev_version)
url = result['js_files'][0]
self.assertIn('bokeh/dev', url)
def test_cdn(self):
resources.__version__ = "1.0"
r = resources.Resources(mode="cdn", version="1.0")
self.assertEqual(r.mode, "cdn")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
resources.__version__ = "1.0-1-abc"
r = resources.Resources(mode="cdn", version="1.0")
self.assertEqual(r.messages, [
{'text': "Requesting CDN BokehJS version '1.0' from Bokeh development version '1.0-1-abc'. This configuration is unsupported and may not work!",
'type': 'warn'}
])
def test_server(self):
r = resources.Resources(mode="server")
self.assertEqual(r.mode, "server")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
r = resources.Resources(mode="server", root_url="http://foo/")
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_server_dev(self):
r = resources.Resources(mode="server-dev")
self.assertEqual(r.mode, "server")
self.assertEqual(r.dev, True)
self.assertEqual(len(r.js_raw), 1)
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
r = resources.Resources(mode="server-dev", root_url="http://foo/")
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_relative(self):
r = resources.Resources(mode="relative")
self.assertEqual(r.mode, "relative")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_relative_dev(self):
r = resources.Resources(mode="relative-dev")
self.assertEqual(r.mode, "relative")
self.assertEqual(r.dev, True)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_absolute(self):
r = resources.Resources(mode="absolute")
self.assertEqual(r.mode, "absolute")
self.assertEqual(r.dev, False)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_absolute_dev(self):
r = resources.Resources(mode="absolute-dev")
self.assertEqual(r.mode, "absolute")
self.assertEqual(r.dev, True)
self.assertEqual(r.js_raw, [DEFAULT_LOG_JS_RAW])
self.assertEqual(r.css_raw, [])
self.assertEqual(r.messages, [])
def test_argument_checks(self):
self.assertRaises(ValueError, resources.Resources, "foo")
for mode in ("inline", "cdn", "server", "server-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, root_dir="foo")
for mode in ("inline", "server", "server-dev", "relative", "relative-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, version="foo")
for mode in ("inline", "cdn", "relative", "relative-dev", "absolute", "absolute-dev"):
self.assertRaises(ValueError, resources.Resources, mode, root_url="foo")
|
GNOME-MouseTrap/mousetrap | src/mousetrap/vision.py | Python | gpl-2.0 | 6,987 | 0.001288 | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
'''
All things computer vision.
'''
import cv2
from mousetrap.i18n import _
from mousetrap.image import Image
import mousetrap.plugins.interface as interface
import logging
LOGGER = logging.getLogger(__name__)
FRAME_WIDTH = 3
FRAME_HEIGHT = 4
class Camera(object):
S_CAPTURE_OPEN_ERROR = _(
'Device #%d does not support video capture interface')
S_CAPTURE_READ_ERROR = _('Error while capturing. Camera disconnected?')
def __init__(self, config):
self._config = config
self._device = \
self._new_capture_device(config['camera']['device_index'])
self.set_dimensions(
config['camera']['width'],
config['camera']['height'],
)
@classmethod
def _new_capture_device(cls, device_index):
capture = cv2.VideoCapture(device_index)
if not capture.isOpened():
capture.release()
raise IOError(cls.S_CAPTURE_OPEN_ERROR % device_index)
return capture
def set_dimensions(self, width, height):
self._device.set(FRAME_WIDTH, width)
self._device.set(FRAME_HEIGHT, height)
def read_image(self):
ret, image = self._device.read()
if not ret:
raise IOError(self.S_CAPTURE_READ_ERROR)
return Image(self._config, image)
class HaarLoader(object):
def __init__(self, config):
se | lf._config = config
self._haar_files = config['haar_files']
self._haar_cache = {}
| def from_name(self, name):
if not name in self._haar_files:
raise HaarNameError(name)
haar_file = self._haar_files[name]
haar = self.from_file(haar_file, name)
return haar
def from_file(self, file_, cache_name=None):
import os
if cache_name in self._haar_cache:
return self._haar_cache[cache_name]
current_dir = os.path.dirname(os.path.realpath(__file__))
haar_file = os.path.join(current_dir, file_)
haar = cv2.CascadeClassifier(haar_file)
if not cache_name is None:
if not cache_name in self._haar_cache:
self._haar_cache[cache_name] = haar
return haar
class HaarNameError(Exception):
pass
class FeatureDetector(object):
_INSTANCES = {}
@classmethod
def get_detector(cls, config, name, scale_factor=1.1, min_neighbors=3):
key = (name, scale_factor, min_neighbors)
if key in cls._INSTANCES:
LOGGER.info("Reusing %s detector.", key)
return cls._INSTANCES[key]
cls._INSTANCES[key] = FeatureDetector(
config, name, scale_factor, min_neighbors)
return cls._INSTANCES[key]
@classmethod
def clear_all_detection_caches(cls):
for instance in cls._INSTANCES.values():
instance.clear_cache()
def __init__(self, config, name, scale_factor=1.1, min_neighbors=3):
'''
name - name of feature to detect
scale_factor - how much the image size is reduced at each image scale
while searching. Default 1.1.
min_neighbors - how many neighbors each candidate rectangle should have
to retain it. Default 3.
'''
LOGGER.info("Building detector: %s",
(name, scale_factor, min_neighbors))
self._config = config
self._name = name
self._single = None
self._plural = None
self._image = None
self._cascade = HaarLoader(config).from_name(name)
self._scale_factor = scale_factor
self._min_neighbors = min_neighbors
self._last_attempt_successful = False
self._detect_cache = {}
def detect(self, image):
if image in self._detect_cache:
message = "Detection cache hit: %(image)d -> %(result)s" % \
{'image':id(image), 'result':self._detect_cache[image]}
LOGGER.debug(message)
if isinstance(self._detect_cache[image], FeatureNotFoundException):
message = str(self._detect_cache[image])
raise FeatureNotFoundException(message,
cause=self._detect_cache[image])
return self._detect_cache[image]
try:
self._image = image
self._detect_plural()
self._exit_if_none_detected()
self._unpack_first()
self._extract_image()
self._calculate_center()
self._detect_cache[image] = self._single
return self._detect_cache[image]
except FeatureNotFoundException as exception:
self._detect_cache[image] = exception
raise
def _detect_plural(self):
self._plural = self._cascade.detectMultiScale(
self._image.to_cv_grayscale(),
self._scale_factor,
self._min_neighbors,
)
def _exit_if_none_detected(self):
if len(self._plural) == 0:
message = _('Feature not detected: %s') % (self._name)
if self._last_attempt_successful:
self._last_attempt_successful = False
LOGGER.info(message)
raise FeatureNotFoundException(message)
else:
if not self._last_attempt_successful:
self._last_attempt_successful = True
message = _('Feature detected: %s') % (self._name)
LOGGER.info(message)
def _unpack_first(self):
self._single = dict(
zip(['x', 'y', 'width', 'height'],
self._plural[0]))
def _calculate_center(self):
self._single["center"] = {
"x": (self._single["x"] + self._single["width"]) // 2,
"y": (self._single["y"] + self._single["height"]) // 2,
}
def _extract_image(self):
single = self._single
from_y = single['y']
to_y = single['y'] + single['height']
from_x = single['x']
to_x = single['x'] + single['width']
image_cv_grayscale = self._image.to_cv_grayscale()
single["image"] = Image(
self._config,
image_cv_grayscale[from_y:to_y, from_x:to_x],
is_grayscale=True,
)
def clear_cache(self):
self._detect_cache.clear()
class FeatureDetectorClearCachePlugin(interface.Plugin):
def __init__(self, config):
super(FeatureDetectorClearCachePlugin, self).__init__(config)
self._config = config
def run(self, app):
FeatureDetector.clear_all_detection_caches()
class FeatureNotFoundException(Exception):
def __init__(self, message, cause=None):
if cause is not None:
message = message + ', caused by ' + repr(cause)
self.cause = cause
super(FeatureNotFoundException, self).__init__(message)
|
flgiordano/netcash | +/google-cloud-sdk/lib/surface/auth/application_default/revoke.py | Python | bsd-3-clause | 1,851 | 0.003241 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Revoke credentials being used by Application Default Credentials."""
from googlecloudsdk.api_lib.auth import util as auth_util
from googlecloudsdk.calliope import base
from g | ooglecloudsdk.calliope import exceptions as c_exc
from googlecloudsdk.core.credentials import store as c_store
class Revoke(base.Command):
"""Revoke Application Default Credentials.
Revokes Application Defau | lt Credentials that have been set up by commands
in the Google Cloud SDK. The credentials are revoked remotely only if
they are user credentials. In all cases, the file storing the credentials is
removed.
This does not effect any credentials set up through other means,
for example credentials referenced by the Application Default Credentials
environment variable or service account credentials that are active on
a Google Compute Engine virtual machine.
"""
@staticmethod
def Args(parser):
parser.add_argument(
'--brief', action='store_true',
help='Minimal user output.')
@c_exc.RaiseToolExceptionInsteadOf(c_store.Error)
def Run(self, args):
"""Revoke Application Default Credentials."""
auth_util.RevokeCredsInWellKnownFile(args.brief)
return ''
def Display(self, unused_args, result):
pass
|
ifduyue/sentry | src/sentry/api/endpoints/organization_integration_repos.py | Python | bsd-3-clause | 1,418 | 0.002821 | from __future__ import absolute_import
from django.http import Http404
from sentry.constants import ObjectStatus
from sentry.api.bases.organization import (
OrganizationEndpoint, OrganizationIntegrationsPermission
)
from sentry.integrations.exceptions import IntegrationError
from sentry.integrations.repositories import RepositoryMixin
from sentry.models import Integration
class OrganizationIntegrationReposEndpoint(OrganizationEndpoint):
permission_classes = (OrganizationIntegrationsPermission, )
def get(self, request, organization, integration_id | ):
try:
integration = Integration.objects.get(id=integration_id, organizations=organization)
except Integration.DoesNotExist:
raise Http404
if integration.status == ObjectStatus.DISABLED:
c | ontext = {'repos': []}
return self.respond(context)
install = integration.get_installation(organization.id)
if isinstance(install, RepositoryMixin):
try:
repositories = install.get_repositories(request.GET.get('search'))
except IntegrationError as e:
return self.respond({'detail': e.message}, status=400)
context = {'repos': repositories, 'searchable': install.repo_search}
return self.respond(context)
return self.respond({'detail': 'Repositories not supported'}, status=400)
|
googleapis/python-compute | samples/ingredients/instances/custom_hostname/get.py | Python | apache-2.0 | 1,531 | 0.002613 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHO | UT WARRANTIES OR CONDITIONS OF ANY KIND, either | express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This is an ingredient file. It is not meant to be run directly. Check the samples/snippets
# folder for complete code samples that are ready to be used.
# Disabling flake8 for the ingredients file, as it would fail F821 - undefined name check.
# flake8: noqa
from google.cloud import compute_v1
# <INGREDIENT get_hostname>
def get_hostname(project_id: str, zone: str, instance_name: str) -> str:
"""
Retrieve the hostname of given instance.
Args:
project_id: project ID or project number of the Cloud project you want to use.
zone: name of the zone you want to use. For example: "us-west3-b"
instance_name: name of the virtual machine to check.
Returns:
The hostname of an instance.
"""
instance_client = compute_v1.InstancesClient()
instance = instance_client.get(
project=project_id, zone=zone, instance=instance_name
)
return instance.hostname
# </INGREDIENT>
|
catalyst/patch-friend | patch/manage.py | Python | gpl-3.0 | 918 | 0 | #!/usr/bin/env pytho | n
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "patch.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that D | jango is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
# from django.core.management import execute_from_command_line
#
# execute_from_command_line(sys.argv)
|
WilliamMayor/scytale.xyz | scripts/encrypt/caesar.py | Python | mit | 222 | 0 | from scytale.ciphers import Caesar
i | f __name__ == '__main__':
plaintext = input('Plaintext: ')
key = int(input('Key: '))
ciphertext = Caesar(key=key).encrypt(plaintext)
print(f'Ciphertext: { | ciphertext}')
|
lmann4/cis526-final-project | resource_management/apps/employees/urls.py | Python | mit | 807 | 0.007435 | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from apps.employees import ajax
from . import vie | ws
urlpatterns = (
url(r'^home/$', login_required(views.home), name="employee_home_redirect"),
url(r'^(?P<pk>[\d]+)/$', login_required(views.EmployeeDetail.as_view()), name="employee_detail"),
url(r'^schedule/add$', login_required(views.ScheduleAdd.as_view()), name="employee_schedule_add"),
url(r'^schedule/$', login_required(views.schedule), name="employee_schedule"),
url(r'^admin/$', login_required(views.EmployeeAdminPanel.as_view()), name="employee_admin"),
url(r'^sub | -board/$', login_required(views.SubBoard.as_view()), name="sub_board"),
url(r'^ajax/take_slip/$', login_required(ajax.SubSlipAjax.as_view()), name="take_slip"),
)
|
hnakamur/saklient.python | saklient/cloud/errors/mustbeofsamezoneexception.py | Python | mit | 731 | 0.010292 | # -*- coding:utf-8 -*-
from ...errors.httpbadrequestexception import Ht | tpBadRequestException
import saklient
# module saklient.cloud.errors.mustbeofsamezoneexception
class MustBeOfSameZoneEx | ception(HttpBadRequestException):
## 不適切な要求です。参照するリソースは同一ゾーンに存在しなければなりません。
## @param {int} status
# @param {str} code=None
# @param {str} message=""
def __init__(self, status, code=None, message=""):
super(MustBeOfSameZoneException, self).__init__(status, code, "不適切な要求です。参照するリソースは同一ゾーンに存在しなければなりません。" if message is None or message == "" else message)
|
adsabs/adsabs-pyingest | examples/ex_atel.py | Python | mit | 401 | 0 | #!/usr/bin/env python
import os
impor | t sys
from pyingest.parsers.atel import ATelParser
from pyingest.serializers.classic import Tagged
rss_url = 'http://www.astronomerstelegram.org/?adsbiblio'
parser = ATelParser()
documents = parser.parse(rss_url, data_tag='item')
outputfp = open('atel.tag', 'a')
for d in documents:
serializer = Tagged()
| serializer.write(d, outputfp)
outputfp.close()
|
kuz/BrainActivity3D | lib/__init__.py | Python | gpl-3.0 | 39 | 0.025641 | """
Pull | third-party libraries here |
""" |
JaapJoris/bps | bps/utils.py | Python | agpl-3.0 | 267 | 0.011236 | import random
def read(file):
with op | en(file) as f:
return f.read()
HUMAN_FRIENDLY_CHARS = '234679ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
def random_string(length):
return ''.join(random.choice(HUMAN_FRIENDLY_CHARS) f | or x in range(length))
|
linuxlewis/channels | channels/binding/websockets.py | Python | bsd-3-clause | 5,020 | 0.000398 | import json
from django.core import serializers
from django.core.serializers.json import DjangoJSONEncoder
from .base import Binding
from ..generic.websockets import WebsocketDemultiplexer
from ..sessions import enforce_ordering
class WebsocketBinding(Binding):
"""
Websocket-specific outgoing binding subclass that uses JSON encoding
and the built-in JSON/WebSocket multiplexer.
To implement outbound, implement:
- group_names, which returns a list of group names to send to
To implement inbound, implement:
- has_permission, which says if the user can do the action on an instance
Optionally also implement:
- serialize_data, which returns JSON-safe data from a model instance
- create, which takes incoming data and makes a model instance
- update, which takes incoming data and a model instance and applies one to the other
"""
# Mark as abstract
model = None
# Stream multiplexing name
stream = None
# Decorators
strict_ordering = False
slight_ordering = False
# Outbound
@classmethod
def encode(cls, stream, payload):
return WebsocketDemultiplexer.encode(stream, payload)
def serialize(self, instance, action):
payload = {
"action": action,
"pk": instance.pk,
"data": self.serialize_data(instance),
"model": self.model_label,
}
return payload
def serialize_data(self, instance):
"""
Serializes model data into JSON-compatible types.
"""
if self.fields == ['__all__']:
fields = None
else:
fields = self.fields
data = serializers.serialize('json', [instance], fields=fields)
return json.loads(data)[0]['fields']
# Inbound
@classmethod
def get_handler(cls):
"""
Adds decorators to trigger_inbound.
"""
# Get super-handler
handler = super(WebsocketBinding, cls).get_handler()
# Ordering decorators
if cls.strict_ordering:
return enforce_ordering(handler, | slight=False)
elif cls.slight_ordering:
return enforce_ordering(handler, slight=True)
else:
return handler
def deserialize(self, message):
"""
You must hook this up behind a Deserializer, so we expect the JSON
already dealt with.
"""
action = message['action']
pk = message.get('pk', None)
data = mes | sage.get('data', None)
return action, pk, data
def _hydrate(self, pk, data):
"""
Given a raw "data" section of an incoming message, returns a
DeserializedObject.
"""
s_data = [
{
"pk": pk,
"model": self.model_label,
"fields": data,
}
]
# TODO: Avoid the JSON roundtrip by using encoder directly?
return list(serializers.deserialize("json", json.dumps(s_data)))[0]
def create(self, data):
self._hydrate(None, data).save()
def update(self, pk, data):
instance = self.model.objects.get(pk=pk)
hydrated = self._hydrate(pk, data)
for name in data.keys():
if name in self.fields or self.fields == ['__all__']:
setattr(instance, name, getattr(hydrated.object, name))
instance.save()
class WebsocketBindingWithMembers(WebsocketBinding):
"""
Outgoing binding binding subclass based on WebsocketBinding.
Additionally enables sending of member variables, properties and methods.
Member methods can only have self as a required argument.
Just add the name of the member to the send_members-list.
Example:
class MyModel(models.Model):
my_field = models.IntegerField(default=0)
my_var = 3
@property
def my_property(self):
return self.my_var + self.my_field
def my_function(self):
return self.my_var - self.my_vield
class MyBinding(BindingWithMembersMixin, WebsocketBinding):
model = MyModel
stream = 'mystream'
send_members = ['my_var', 'my_property', 'my_function']
"""
model = None
send_members = []
encoder = DjangoJSONEncoder()
def serialize_data(self, instance):
data = super(WebsocketBindingWithMembers, self).serialize_data(instance)
member_data = {}
for m in self.send_members:
member = instance
for s in m.split('.'):
member = getattr(member, s)
if callable(member):
member_data[m.replace('.', '__')] = member()
else:
member_data[m.replace('.', '__')] = member
member_data = json.loads(self.encoder.encode(member_data))
# the update never overwrites any value from data,
# because an object can't have two attributes with the same name
data.update(member_data)
return data
|
afrolov1/nova | nova/openstack/common/network_utils.py | Python | apache-2.0 | 5,553 | 0 | # Copyright 2012 OpenStack Foundation.
# 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.
"""
Network-related utilities and helper functions.
"""
import socket
from six.moves.urllib import parse
from nova.openstack.common.gettextutils import _LW
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def parse_host_port(address, default_port=None):
"""Interpret a string as a host:port pair.
An IPv6 address MUST be escaped if accompanied by a port,
because otherwise ambiguity ensues: 2001:db8:85a3::8a2e:370:7334
means both [2001:db8:85a3::8a2e:370:7334] and
[2001:db8:85a3::8a2e:370]:7334.
>>> parse_host_port('server01:80')
('server01', 80)
>>> parse_host_port('server01')
('server01', None)
>>> parse_host_port('server01', default_port=1234)
('server01', 1234)
>>> parse_host_port('[::1]:80')
('::1', 80)
>>> parse_host_port('[::1]')
('::1', None)
>>> parse_host_port('[::1]', default_port=1234)
('::1', 1234)
>>> parse_host_port('2001:db8:85a3::8a2e:370:7334', default_port=1234)
('2001:db8:85a3::8a2e:370:7334', 1234)
"""
if address[0] == '[':
# Escaped ipv6
_host, _port = address[1:].split(']')
| host = _host
if ':' in _port:
port = _port.split(':')[1]
else:
port = default_port
else:
if address.count(':') == 1:
host, port = address.split(':')
e | lse:
# 0 means ipv4, >1 means ipv6.
# We prohibit unescaped ipv6 addresses with port.
host = address
port = default_port
return (host, None if port is None else int(port))
class ModifiedSplitResult(parse.SplitResult):
"""Split results class for urlsplit."""
# NOTE(dims): The functions below are needed for Python 2.6.x.
# We can remove these when we drop support for 2.6.x.
@property
def hostname(self):
netloc = self.netloc.split('@', 1)[-1]
host, port = parse_host_port(netloc)
return host
@property
def port(self):
netloc = self.netloc.split('@', 1)[-1]
host, port = parse_host_port(netloc)
return port
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL using urlparse.urlsplit(), splitting query and fragments.
This function papers over Python issue9374 when needed.
The parameters are the same as urlparse.urlsplit.
"""
scheme, netloc, path, query, fragment = parse.urlsplit(
url, scheme, allow_fragments)
if allow_fragments and '#' in path:
path, fragment = path.split('#', 1)
if '?' in path:
path, query = path.split('?', 1)
return ModifiedSplitResult(scheme, netloc,
path, query, fragment)
def set_tcp_keepalive(sock, tcp_keepalive=True,
tcp_keepidle=None,
tcp_keepalive_interval=None,
tcp_keepalive_count=None):
"""Set values for tcp keepalive parameters
This function configures tcp keepalive parameters if users wish to do
so.
:param tcp_keepalive: Boolean, turn on or off tcp_keepalive. If users are
not sure, this should be True, and default values will be used.
:param tcp_keepidle: time to wait before starting to send keepalive probes
:param tcp_keepalive_interval: time between successive probes, once the
initial wait time is over
:param tcp_keepalive_count: number of probes to send before the connection
is killed
"""
# NOTE(praneshp): Despite keepalive being a tcp concept, the level is
# still SOL_SOCKET. This is a quirk.
if isinstance(tcp_keepalive, bool):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, tcp_keepalive)
else:
raise TypeError("tcp_keepalive must be a boolean")
if not tcp_keepalive:
return
# These options aren't available in the OS X version of eventlet,
# Idle + Count * Interval effectively gives you the total timeout.
if tcp_keepidle is not None:
if hasattr(socket, 'TCP_KEEPIDLE'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPIDLE,
tcp_keepidle)
else:
LOG.warning(_LW('tcp_keepidle not available on your system'))
if tcp_keepalive_interval is not None:
if hasattr(socket, 'TCP_KEEPINTVL'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPINTVL,
tcp_keepalive_interval)
else:
LOG.warning(_LW('tcp_keepintvl not available on your system'))
if tcp_keepalive_count is not None:
if hasattr(socket, 'TCP_KEEPCNT'):
sock.setsockopt(socket.IPPROTO_TCP,
socket.TCP_KEEPCNT,
tcp_keepalive_count)
else:
LOG.warning(_LW('tcp_keepknt not available on your system'))
|
cipriantarta/python-capture | capture.py | Python | bsd-3-clause | 2,890 | 0.001038 | import os
import socket
import subprocess
import time
import sys
class Streamer:
command = 'ffmpeg ' \
'-y ' \
'-f avfoundation ' \
'-r 30 ' \
'-pixel_format bgr0 ' \
' | -s 640x480 ' \
'-video_device_index 0 ' \
'-i ":0" ' \
'-c:v libvpx ' \
'-b:v 1M ' \
| '-c:a libvorbis ' \
'-b:a 96k ' \
'-deadline realtime ' \
'-flags +global_header ' \
'-cpu-used 1 ' \
'-threads 8 ' \
'-f segment ' \
'-f webm ' \
'-'
__connected = False
def __init__(self, host, port):
self.server = None
self.host = host
self.port = port
def connect(self):
while True:
try:
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Connecting to {}:{}...'.format(self.host, self.port))
self.server.connect((self.host, self.port))
self.__connected = True
print('Connected.\n')
break
except ConnectionRefusedError:
print('Connection refused. Retrying in 3 seconds.\n')
time.sleep(3)
def stream(self):
p = subprocess.Popen(self.command.split(), stdin=open(os.devnull), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print('Streaming...\n')
while True:
data = p.stdout.read(1024)
if len(data) == 0:
err = p.stderr.readlines()
if len(err) > 0:
print('Error')
print(''.join([l.decode() for l in err]))
break
try:
self.server.send(data)
except BrokenPipeError:
print('Disconnected from server. Reconnecting in 3 seconds\n')
time.sleep(3)
self.connect()
print('Streaming...\n')
def close(self):
if not self.connected:
return
print('Disconnected.')
self.server.close()
@property
def connected(self):
return self.__connected
if __name__ == '__main__':
try:
host = sys.argv[1]
except IndexError:
host = 'localhost'
try:
port = int(sys.argv[2])
except IndexError:
port = 8889
except ValueError:
print('Invalid port.')
exit(1)
streamer = Streamer(host, port)
try:
streamer.connect()
streamer.stream()
except KeyboardInterrupt:
print('Exiting...')
except OSError as e:
print(e)
exit(1)
finally:
streamer.close()
|
synctree/synctree-awsebcli | ebcli/objects/environment.py | Python | apache-2.0 | 1,422 | 0.000703 | # Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with t | he License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHO | UT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
class Environment(object):
def __init__(self, version_label=None, status=None, app_name=None,
health=None, id=None, date_updated=None,
platform=None, description=None,
name=None, date_created=None, tier=None,
cname=None, option_settings=None, is_abortable=False):
self.version_label = version_label
self.status = status
self.app_name = app_name
self.health = health
self.id = id
self.date_updated = date_updated
self.platform = platform
self.description = description
self.name = name
self.date_created = date_created
self.tier = tier
self.cname = cname
self.option_settings = option_settings
self.is_abortable = is_abortable
def __str__(self):
return self.name |
alaudo/coderdojo-python | code/11 - empty.py | Python | cc0-1.0 | 126 | 0 | text = input("Enter something ") |
if (text.strip()):
print("This text is not empty")
| else:
print("This text is EMPTY")
|
gnmiller/craig-bot | craig-bot/lib/python3.6/site-packages/discord/colour.py | Python | mit | 7,005 | 0.003712 | # -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2019 Rapptz
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 colorsys
class Colour:
"""Represents a Discord role colour. This class is similar
to an (red, green, blue) :class:`tuple`.
There is an alias for this called Color.
.. container:: operations
.. describe:: x == y
Checks if two colours are equal.
.. describe:: x != y
Checks if two colours are not equal.
.. describe:: hash(x)
Return the colour's hash.
.. describe:: str(x)
Returns the hex format for the colour.
Attributes
------------
value: :class:`int`
The raw integer colour value.
"""
__slots__ = ('value',)
def __init__(self, value):
if not isinstance(value, int):
raise TypeError('Expected int parameter, received %s instead.' % value.__class__.__name__)
self.value = value
def _get_byte(self, byte):
return (self.value >> (8 * byte)) & 0xff
def __eq__(self, other):
return isinstance(other, Colour) and self.value == other.value
def __ne__(self, other):
return not self.__eq__(other)
def __str__(self):
return '#{:0>6x}'.format(self.value)
def __repr__(self):
return '<Colour value=%s>' % self.value
def __hash__(self):
return hash(self.value)
@property
def | r(self):
"""Returns the r | ed component of the colour."""
return self._get_byte(2)
@property
def g(self):
"""Returns the green component of the colour."""
return self._get_byte(1)
@property
def b(self):
"""Returns the blue component of the colour."""
return self._get_byte(0)
def to_rgb(self):
"""Returns an (r, g, b) tuple representing the colour."""
return (self.r, self.g, self.b)
@classmethod
def from_rgb(cls, r, g, b):
"""Constructs a :class:`Colour` from an RGB tuple."""
return cls((r << 16) + (g << 8) + b)
@classmethod
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb))
@classmethod
def default(cls):
"""A factory method that returns a :class:`Colour` with a value of 0."""
return cls(0)
@classmethod
def teal(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x1abc9c``."""
return cls(0x1abc9c)
@classmethod
def dark_teal(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x11806a``."""
return cls(0x11806a)
@classmethod
def green(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``."""
return cls(0x2ecc71)
@classmethod
def dark_green(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x1f8b4c``."""
return cls(0x1f8b4c)
@classmethod
def blue(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x3498db``."""
return cls(0x3498db)
@classmethod
def dark_blue(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x206694``."""
return cls(0x206694)
@classmethod
def purple(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x9b59b6``."""
return cls(0x9b59b6)
@classmethod
def dark_purple(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x71368a``."""
return cls(0x71368a)
@classmethod
def magenta(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xe91e63``."""
return cls(0xe91e63)
@classmethod
def dark_magenta(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xad1457``."""
return cls(0xad1457)
@classmethod
def gold(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xf1c40f``."""
return cls(0xf1c40f)
@classmethod
def dark_gold(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xc27c0e``."""
return cls(0xc27c0e)
@classmethod
def orange(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xe67e22``."""
return cls(0xe67e22)
@classmethod
def dark_orange(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xa84300``."""
return cls(0xa84300)
@classmethod
def red(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0xe74c3c``."""
return cls(0xe74c3c)
@classmethod
def dark_red(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x992d22``."""
return cls(0x992d22)
@classmethod
def lighter_grey(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x95a5a6``."""
return cls(0x95a5a6)
@classmethod
def dark_grey(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x607d8b``."""
return cls(0x607d8b)
@classmethod
def light_grey(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x979c9f``."""
return cls(0x979c9f)
@classmethod
def darker_grey(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x546e7a``."""
return cls(0x546e7a)
@classmethod
def blurple(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x7289da``."""
return cls(0x7289da)
@classmethod
def greyple(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x99aab5``."""
return cls(0x99aab5)
Color = Colour
|
2achary/sequencehelpers | setup.py | Python | mit | 467 | 0.002141 | from distutils.core im | port setup
setup(
name='sequencehelpers',
py_modules=['sequencehelpers'],
version='0.2.1',
description="A library consisting of functions for interacting with sequences and iterables.",
author='Zach Swift',
author_email='cras.zswift@gmail.com',
url='https://github.com/2achary/sequencehelpers',
download_url='https://github.com/2achary/sequence/tarball/0.2.1',
keywords=['sequence', 'single', 'distinct'], |
classifiers=[],
)
|
seecr/meresco-solr | meresco/solr/__init__.py | Python | gpl-2.0 | 1,228 | 0.001629 | ## begin license ##
#
# "Meresco Solr" is a set of components and tools
# to integrate Solr into "Meresco."
#
# Copyright (C) 2011-2013 Seecr (Seek You Too B.V.) http://seecr.nl
# Copyright (C) 2012 SURF http://www.surf.nl
# Copyright (C) 2013 Stichting Kennisnet http://www.kennisnet.nl
#
# This file is part of "Meresco Solr"
#
# "Meresco Solr" 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; e | ither version 2 of the License, or
# (at your option) any later version.
#
# "Meresco S | olr" 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 "Meresco Solr"; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
## end license ##
from solrinterface import SolrInterface, UNTOKENIZED_PREFIX, SORTED_PREFIX
from fields2solrdoc import Fields2SolrDoc
from cql2solrlucenequery import Cql2SolrLuceneQuery
|
avedaee/DIRAC | TransformationSystem/Client/TransformationClient.py | Python | gpl-3.0 | 22,189 | 0.040786 | """ Class that contains client access to the transformation DB handler. """
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
rpc = None
url = None
class TransformationClient( Client, FileCatalogueBase ):
""" Exposes the functionality available in the DIRAC/TransformationHandler
This inherits the DIRAC base Client for direct execution of server functionality.
The following methods are available (although not visible here).
Transformation (table) manipulation
deleteTransformation(transName)
getTransformationParameters(transName,paramNames)
getTransformationWithStatus(status)
setTransformationParameter(transName,paramName,paramValue)
deleteTransformationParameter(transName,paramName)
TransformationFiles table manipulation
addFilesToTransformation(transName,lfns)
addTaskForTransformation(transName,lfns=[],se='Unknown')
getTransformationStats(transName)
TransformationTasks table manipulation
setTaskStatus(transName, taskID, status)
setTaskStatusAndWmsID(transName, taskID, status, taskWmsID)
getTransformationTaskStats(transName)
deleteTasks(transName, taskMin, taskMax)
extendTransformation( transName, nTasks)
getTasksToSubmit(transName,numTasks,site='')
TransformationLogging table manipulation
getTransformationLogging(transName)
File/directory manipulation methods (the remainder of the interface can be found below)
getFileSummary(lfns)
exists(lfns)
Web monitoring tools
getDistinctAttributeValues(attribute, selectDict)
getTransformationStatusCounters()
getTransformationSummary()
getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems)
"""
def __init__( self, **kwargs ):
Client.__init__( self, **kwargs )
opsH = Operations()
self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 )
self.setServer( 'Transformation/TransformationManager' )
def setServer( self, url ):
self.serverURL = url
def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None,
rpc = '', url = '' ):
rpcClient = self._getRPC( rpc = rpc, url = url )
return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp )
def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask,
transformationGroup = 'General',
groupSize = 1,
inheritedFrom = 0,
body = '',
maxTasks = 0,
eventsPerTask = 0,
addFiles = True,
rpc = '', url = '', timeout = 1800 ):
""" add a new transformation
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addTransformation( transName, description, longDescription, transType, plugin,
agentType, fileMask, transformationGroup, groupSize, inheritedFrom,
body, maxTasks, eventsPerTask, addFiles )
def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate',
orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ):
""" gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformations = []
# getting transformations - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit,
extraParams, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
tran | sformations = transformations + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformations )
def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getTransformation( transName, extraParams )
def getTransformationFiles( self, condDict = {}, older = None, newer = None, timeStamp = 'LastU | pdate',
orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ):
""" gets all the transformation files for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationFiles = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationFiles = transformationFiles + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationFiles )
def getTransformationTasks( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime',
orderAttribute = None, limit = 10000, inputVector = False, rpc = '',
url = '', timeout = None ):
""" gets all the transformation tasks for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationTasks = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit,
inputVector, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationTasks = transformationTasks + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationTasks )
def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ):
""" Clean the transformation, and set the status parameter (doing it here, for easier extensibility)
"""
# Cleaning
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
res = rpcClient.cleanTransformation( transID )
if not res['OK']:
return res
# Setting the status
return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' )
def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ):
""" move files input to a transformation, to the derived one
"""
prod = transDict['TransformationID']
parentProd = int( transDict.get( 'InheritedFrom', 0 ) )
movedFiles = {}
if not parentProd:
gLogger.warn( "[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..." % prod )
return S_OK( ( pare |
artreven/pp_api | pp_api/gs_calls.py | Python | mit | 11,664 | 0.000343 | import logging
from requests.exceptions import HTTPError
from pp_api import utils as u
from pp_api import pp_calls
module_logger = logging.getLogger(__name__)
class GraphSearch:
timeout = None
def __init__(self, server, auth_data=None, session=None, timeout=None):
self.server = server
session = u.get_session(session, auth_data)
self.auth_data = auth_data
self.session = session
self.timeout = timeout
def delete(self, search_space_id, id_=None, source=None):
if id_ is not None:
suffix = '/GraphSearch/api/content/delete/id'
data = {
'identifier': id_,
'searchSpaceId': search_space_id
}
elif source is not None:
suffix = '/GraphSearch/api/content/delete/source'
data = {
'identifier': source,
}
else:
assert 0
| dest_url = self.server + suffix
r = self.session.post(
dest_url,
json=data,
timeout=self.timeout
)
try:
r.raise_for_status()
except Exception as e:
msg = 'JSON data of the failed POST request: {}\n'.format(data)
msg += 'URL of the failed POST request: {}\n'.format(dest_url)
msg += 'Response text: {}'.form | at(r.text)
module_logger.error(msg)
raise e
return r
def clean(self, search_space_id):
"""
Remove first 100000 document from GraphSearch.
"""
r = self.search(
count=100000,
search_space_id=search_space_id
)
for result in r.json()['results']:
id_ = result['id']
r = self.delete(
id_=id_,
search_space_id=search_space_id
)
def in_gs(self, uri, search_space_id):
"""
Check if document with specified uri is contained in GS
:param uri: document uri
:return: Boolean
"""
id_filter = self.filter_id(id_=uri)
r = self.search(search_space_id=search_space_id,
search_filters=id_filter)
return r.json()['total'] > 0
def _create(self, id_, title, author, date, search_space_id,
text=None, update=False,
text_limit=True, **kwargs):
"""
:param id_: should be a URL starting from protocol (e.g. http://)
:param title:
:param author:
:param date: datetime object
:param kwargs: any additional fields in key=value format. Fields should exist in GS.
:return:
"""
if text_limit and len(text) > 12048:
text = text[:12000]
module_logger.warning('Text was too long ({} chars), has been '
'shortened tp 12000 chars'.format(len(text)))
if not update:
suffix = '/GraphSearch/api/content/create'
else:
suffix = '/GraphSearch/api/content/update'
data = {
'identifier': id_,
'title': title,
'author': author,
'date': date.strftime('%Y-%m-%dT%H:%M:%SZ'),
'text': text,
'useExtraction': False,
'searchSpaceId': search_space_id
}
for k, v in kwargs.items():
if k is not None and v is not None and v != [None]:
data[k] = v
dest_url = self.server + suffix
r = self.session.post(
dest_url,
json=data,
timeout=self.timeout
)
try:
r.raise_for_status()
except Exception as e:
msg = 'JSON data of the failed POST request: {}\n'.format(data)
msg += 'URL of the failed POST request: {}\n'.format(dest_url)
msg += 'Response text: {}'.format(r.text)
module_logger.error(msg)
raise e
return r
def create_with_freqs(self, id_, title, author, date, cpts, search_space_id,
image_url=None,
text=None, update=False,
**kwargs):
cpt_uris = [x['uri'] for x in cpts]
cpt_freqs = {
x['uri'].split("/")[-1]: x['frequencyInDocument'] for x in cpts
}
cpt_facets = {
('dyn_flt_' + suffix): [freq] for suffix, freq in cpt_freqs.items()
}
cpt_facets.update({
'dyn_uri_all_concepts': cpt_uris
})
return self._create(
id_=id_, title=title, author=author, date=date,
text=text, facets=cpt_facets,
update=update, search_space_id=search_space_id,
dyn_txt_imageUrl=[image_url],
**kwargs
)
def extract_and_create(self, pid, id_, title, author, date, text,
search_space_id,
image_url=None,
text_to_extract=None,
update=False,
lang='en', **kwargs):
"""
Extract concepts from the text and create corresponding document with
concept frequencies.
:param pid: project id of the thesaurus in PoolParty
:param id_:
:param title:
:param author:
:param date:
:param text:
:return:
"""
pp = pp_calls.PoolParty(server=self.server, auth_data=self.auth_data)
if text_to_extract is None:
text_to_extract = text
r = pp.extract(
pid=pid, text=text_to_extract, lang=lang, **kwargs
)
cpts = pp.get_cpts_from_response(r)
self.create_with_freqs(
id_=id_, title=title, author=author,
date=date, text=text, cpts=cpts, update=update,
search_space_id=search_space_id, image_url=image_url,
language=lang,
**kwargs
)
return cpts
def extract_and_update(self, *args, **kwargs):
return self.extract_and_create(*args, update=True, **kwargs)
def search(self, search_space_id,
search_filters=None, locale='en', count=10000,
**kwargs):
"""
:param search_space_id: ID of search space from GS admin->configuration
:param search_filters: the filters (usually prepared by other methods of GS
:param locale: language (default: 'en')
:param kwargs: other kwargs, for example,
count - total number of results,
start - start index
:return: results as returned by GS API call
"""
suffix = '/GraphSearch/api/search'
data = {
'searchSpaceId': search_space_id,
'locale': locale,
'documentFacets': ['all'],
'count': count,
"searchFacets": [{"field": "dyn_uri_all_concepts"}]
}
if search_filters is not None:
data.update({'searchFilters': search_filters})
if kwargs:
data.update(**kwargs)
dest_url = self.server + suffix
r = self.session.post(
dest_url,
json=data,
timeout=self.timeout
)
try:
r.raise_for_status()
except Exception as e:
msg = 'JSON data of the failed POST request: {}\n'.format(data)
msg += 'URL of the failed POST request: {}\n'.format(dest_url)
msg += 'Response text: {}'.format(r.text)
module_logger.error(msg)
raise e
return r
@staticmethod
def filter_full_text(query_str):
search_filters = [
{'field': 'full_text_search',
'value': query_str,
'optional': False}
]
return search_filters
@staticmethod
def filter_cpt(cpt_uri):
search_filters = [
{'field': 'dyn_uri_all_concepts',
'value': cpt_uri}
]
return search_filters
@staticmethod
def filter_author(author):
search_filters = [
{'field': 'dyn_lit_author',
'value': author}
] |
sharad/calibre | src/calibre/ebooks/html/to_zip.py | Python | gpl-3.0 | 4,758 | 0.003993 | #!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import textwrap, os, glob
from calibre.customize import FileTypePlugin
from calibre.constants import numeric_version
class HTML2ZIP(FileTypePlugin):
name = 'HTML to ZIP'
author = 'Kovid Goyal'
description = textwrap.dedent(_('''\
Follow all local links in an HTML file and create a ZIP \
file containing all linked files. This plugin is run \
every time you add an HTML file to the library.\
'''))
version = numeric_version
file_types = set(['html', 'htm', 'xhtml', 'xhtm', 'shtm', 'shtml'])
supported_platforms = ['windows', 'osx', 'linux']
on_import = True
def run(self, htmlfile):
from calibre.ptempfile import TemporaryDirectory
from calibre.gui2.convert.gui_conversion import gui_convert
from calibre.customize.conversion import OptionRecommendation
from calibre.ebooks.epub import initialize_container
with TemporaryDirectory('_plugin_html2zip') as tdir:
recs =[('debug_pipeline', tdir, OptionRecommendation.HIGH)]
recs.append(['keep_ligatures', True, OptionRecommendation.HIGH])
if self.site_customization and self.site_customization.strip():
sc = self.site_customization.strip()
enc, _, bf = sc.partition('|')
if enc:
recs.append(['input_encoding', enc,
OptionRecommendation.HIGH])
if bf == 'bf':
recs.append(['breadth_first', True,
OptionRecommendation.HIGH])
gui_convert(htmlfile, tdir, recs, abort_after_input_dump=True)
of = self.temporary_file('_plugin_html2zip.zip')
tdir = os.path.join(tdir, 'input')
opf = glob.glob(os.path.join(tdir, '*.opf'))[0]
ncx = glob.glob(os.path.join(tdir, '*.ncx'))
if ncx:
os.remove(ncx[0])
epub = initialize_container(of.name, os.path.basename(opf))
epub.add_dir(tdir)
epub.close()
return of.name
def customization_help(self, gui=False):
return _('Character encoding for the input HTML files. Common choices '
| 'include: cp1252, cp1251, latin1 and utf-8.')
def do_user_config(self, parent=None):
'''
This method shows a configuration dialog for this plugin. It returns
True if the user clicks OK, False otherwise. The changes are
automatically applied.
'''
from PyQt5.Qt import (QDialog, QDialogButtonBox, QVBoxLayout,
QLabel, Qt, QLineEdit, QCheckBox)
config_dialog = QDialog(parent) |
button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
v = QVBoxLayout(config_dialog)
def size_dialog():
config_dialog.resize(config_dialog.sizeHint())
button_box.accepted.connect(config_dialog.accept)
button_box.rejected.connect(config_dialog.reject)
config_dialog.setWindowTitle(_('Customize') + ' ' + self.name)
from calibre.customize.ui import (plugin_customization,
customize_plugin)
help_text = self.customization_help(gui=True)
help_text = QLabel(help_text, config_dialog)
help_text.setWordWrap(True)
help_text.setTextInteractionFlags(Qt.LinksAccessibleByMouse
| Qt.LinksAccessibleByKeyboard)
help_text.setOpenExternalLinks(True)
v.addWidget(help_text)
bf = QCheckBox(_('Add linked files in breadth first order'))
bf.setToolTip(_('Normally, when following links in HTML files'
' calibre does it depth first, i.e. if file A links to B and '
' C, but B links to D, the files are added in the order A, B, D, C. '
' With this option, they will instead be added as A, B, C, D'))
sc = plugin_customization(self)
if not sc:
sc = ''
sc = sc.strip()
enc = sc.partition('|')[0]
bfs = sc.partition('|')[-1]
bf.setChecked(bfs == 'bf')
sc = QLineEdit(enc, config_dialog)
v.addWidget(sc)
v.addWidget(bf)
v.addWidget(button_box)
size_dialog()
config_dialog.exec_()
if config_dialog.result() == QDialog.Accepted:
sc = unicode(sc.text()).strip()
if bf.isChecked():
sc += '|bf'
customize_plugin(self, sc)
return config_dialog.result()
|
jmargeta/scikit-learn | sklearn/linear_model/bayes.py | Python | bsd-3-clause | 15,486 | 0.000904 | """
Various bayesian regression
"""
from __future__ import print_function
# Authors: V. Michel, F. Pedregosa, A. Gramfort
# License: BSD 3 clause
from math import log
import numpy as np
from scipy import linalg
from .base import LinearModel
from ..base import RegressorMixin
from ..utils.extmath import fast_logdet, pinvh
from ..utils import check_arrays
###############################################################################
# BayesianRidge regression
class BayesianRidge(LinearModel, RegressorMixin):
"""Bayesian ridge regression
Fit a Bayesian ridge model and optimize the regularization parameters
lambda (precision of the weights) and alpha (precision of the noise).
Parameters
----------
X : array, shape = (n_samples, n_features)
Training vectors.
y : array, shape = (length)
Target values for training vectors
n_iter : int, optional
Maximum number of iterations. Default is 300.
tol : float, optional
Stop the algorithm if w has converged. Default is 1.e-3.
alpha_1 : float, optional
Hyper-parameter : shape parameter for the Gamma distribution prior
over the alpha parameter. Default is 1.e-6
alpha_2 : float, optional
Hyper-parameter : inverse scale parameter (rate parameter) for the
Gamma distribution prior over the alpha parameter.
Default is 1.e-6.
lambda_1 : float, optional
Hyper-parameter : shape parameter for the Gamma distribution prior
over the lambda parameter. Default is 1.e-6.
lambda_2 : float, optional
Hyper-parameter : inverse scale parameter (rate parameter) for the
Gamma distribution prior over the lambda parameter.
Default is 1.e-6
compute_score : boolean, optional
If True, compute the objective function at each step of the model.
Default is False
fit_intercept : boolean, optional
wether to calculate the intercept for this model. If set
to false, no intercept will be used in calculations
(e.g. data is expected to be already centered).
Default is True.
normalize : boolean, optional, default False
If True, the regressors X will be normalized before regression.
copy_X : boolean, optional, default True
If True, X will be copied; else, it may be overwritten.
verbose : boolean, optional, default False
Verbose mode when fitting the model.
Attributes
----------
`coef_` : array, shape = (n_features)
Coefficients of the regression model (mean of distribution)
`alpha_` : float
estimated precision of the noise.
`lambda_` : array, shape = (n_features)
estimated precisions of the weights.
`scores_` : float
if computed, value of the objective function (to be maximized)
Examples
--------
>>> from sklearn import linear_model
>>> clf = linear_model.BayesianRidge()
>>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2])
... # doctest: +NORMALIZE_WHITESPACE
BayesianRidge(alpha_1=1e-06, alpha_2=1e-06, compute_score=False,
copy_X=True, fit_intercept=True, lambda_1=1e-06, lambda_2=1e-06,
n_iter=300, normalize=False, tol=0.001, verbose=False)
>>> clf.predict([[1, 1]])
array([ 1.])
Notes
-----
See examples/linear_model/plot_bayesian_ridge.py for an example.
"""
def __init__(self, n_iter=300, tol=1.e-3, alpha_1=1.e-6, alpha_2=1.e-6,
lambda_1=1.e-6, lambda_2=1.e-6, compute_score=False,
fit_intercept=True, normalize=False, copy_X=True,
verbose=False):
self.n_iter = n_iter
self.tol = tol
self.alpha_1 = alpha_1
self.alpha_2 = alpha_2
self.lambda_1 = lambda_1
self.lambda_2 = lambda_2
self.compute_score = compute_score
self.fit_intercept = fit_intercept
self.normalize = normalize
self.copy_X = copy_X
self.verbose = verbose
def fit(self, X, y):
"""Fit the model
Parameters
----------
X : numpy array of shape [n_samples,n_features]
Training data
y : numpy array of shape [n_samples]
Target values
Returns
-------
self : returns an instance of self.
"""
X, y = check_arrays(X, y, sparse_format='dense',
dtype=np.float)
X, y, X_mean, y_mean, X_std = self._center_data(
X, y, self.fit_intercept, self.normalize, self.copy_X)
n_samples, n_features = X.shape
### Initialization of the values of the parameters
alpha_ = 1. / np.var(y)
lambda_ = 1.
verbose = self.verbose
lambda_1 = self.lambda_1
lambda_2 = self.lambda_2
alpha_1 = self.alpha_1
alpha_2 = self.alpha_2
self.scores_ = list()
coef_old_ = None
XT_y = np.dot(X.T, y)
U, S, Vh = linalg.svd(X, full_matrices=False)
eigen_vals_ = S ** 2
### Convergence loop of the bayesian ridge regression
for iter_ in range(self.n_iter):
### Compute mu and sigma
# sigma_ = lambda_ / alpha_ * np.eye(n_features) + np.dot(X.T, X)
# coef_ = sigma_^-1 * XT * y
if n_samples > n_features:
coef_ = np.dot(Vh.T,
Vh / (eigen_vals_ + lambda_ / alpha_)[:, None])
coef_ = np.dot(coef_, XT_y)
if self.compute_score:
logdet_sigma_ = - np.sum(
np.log(lambda_ + alpha_ * eigen_vals_))
else:
coef_ = np.dot(X.T, np.dot(
U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T))
coef_ = np.dot(coef_, y)
if self.compute_score:
logdet_sigma_ = lambda_ * np.ones(n_features)
logdet_sigma_[:n_samples] += alpha_ * eigen_vals_
logdet_sigma_ = - np.sum(np.log(logdet_sigma_))
### Update alpha and lambda
rmse_ = np.sum((y - np.dot(X, coef_)) ** 2)
gamma_ = (np.sum((alpha_ * eigen_vals_)
/ (lambda_ + alpha_ * eigen_vals_)))
lambda_ = ((gamma_ + 2 * lambda_1)
/ (np.sum(coef_ ** 2) + 2 * lambda_2))
alpha_ = ((n_samples - gamma_ + 2 * alpha_1)
/ (rmse_ + 2 * alpha_2))
### Compute the objective function
if self.compu | te_score:
s = lambda_1 * log(lambda_) - lambda_2 * lambda_
s += alpha_1 * log(alpha_) - alpha_2 * alpha_
s += 0.5 * (n_fea | tures * log(lambda_)
+ n_samples * log(alpha_)
- alpha_ * rmse_
- (lambda_ * np.sum(coef_ ** 2))
- logdet_sigma_
- n_samples * log(2 * np.pi))
self.scores_.append(s)
### Check for convergence
if iter_ != 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol:
if verbose:
print("Convergence after ", str(iter_), " iterations")
break
coef_old_ = np.copy(coef_)
self.alpha_ = alpha_
self.lambda_ = lambda_
self.coef_ = coef_
self._set_intercept(X_mean, y_mean, X_std)
return self
###############################################################################
# ARD (Automatic Relevance Determination) regression
class ARDRegression(LinearModel, RegressorMixin):
"""Bayesian ARD regression.
Fit the weights of a regression model, using an ARD prior. The weights of
the regression model are assumed to be in Gaussian distributions.
Also estimate the parameters lambda (precisions of the distributions of the
weights) and alpha (precision of the distribution of the noise).
The estimation is done by an iterative procedures (Evidence Maximization)
Parameters
----------
X : array, shape = (n_samples, n_fe |
levilucio/SyVOLT | GM2AUTOSAR_MM/backward_matchers/models/ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable_MDL.py | Python | mit | 19,240 | 0.010083 | """
__ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable_MDL.py_____________________________________________________
Automatically generated AToM3 Model File (Do not modify directly)
Author: levi
Modified: Mon Aug 26 09:54:59 2013
_______________________________________________________________________________________________________________________
"""
from stickylink import *
from widthXfillXdecoration import *
from MT_pre__MatchModel import *
from MT_pre__ApplyModel import *
from MT_pre__Distributable import *
from MT_pre__SwCompToEcuMapping_component import *
from MT_pre__paired_with import *
from MT_pre__match_contains import *
from MT_pre__apply_contains import *
from MT_pre__trace_link import *
from LHS import *
from graph_MT_pre__paired_with import *
from graph_MT_pre__apply_contains import *
from graph_LHS import *
from graph_MT_pre__trace_link import *
from graph_MT_pre__match_contains import *
from graph_MT_pre__MatchModel import *
from graph_MT_pre__ApplyModel import *
from graph_MT_pre__Distributable import *
from graph_MT_pre__SwCompToEcuMapping_component import *
from ATOM3Enum import *
from ATOM3String import *
from ATOM3BottomType import *
from ATOM3Constraint import *
from ATOM3Attribute import *
from ATOM3Float import *
from ATOM3List import *
from ATOM3Link import *
from ATOM3Connection import *
from ATOM3Boolean import *
from ATOM3Appearance import *
from ATOM3Text import *
from ATOM3Action import *
from ATOM3Integer import *
from ATOM3Port import *
from ATOM3MSEnum import *
def ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable_MDL(self, rootNode, MT_pre__GM2AUTOSAR_MMRootNode=None, MoTifRuleRootNode=None):
# --- Generating attributes code for ASG MT_pre__GM2AUTOSAR_MM ---
if( MT_pre__GM2AUTOSAR_MMRootNode ):
# author
MT_pre__GM2AUTOSAR_MMRootNode.author.setValue('Annonymous')
# description
MT_pre__GM2AUTOSAR_MMRootNode.description.setValue('\n')
MT_pre__GM2AUTOSAR_MMRootNode.description.setHeight(15)
# name
MT_pre__GM2AUTOSAR_MMRootNode.name.setValue('')
MT_pre__GM2AUTOSAR_MMRootNode.name.setNone()
# --- ASG attributes over ---
# --- Generating attributes code for ASG MoTifRule ---
if( MoTifRuleRootNode ):
# author
MoTifRuleRootNode.author.setValue('Annonymous')
# description
MoTifRuleRootNode.description.setValue('\n')
MoTifRuleRootNode.description.setHeight(15)
# name
MoTifRuleRootNode.name.setValue('ConnVirtualDevice2Distributable_Back_SCTEMc2Distributable')
# --- ASG attributes over ---
self.obj47=MT_pre__MatchModel(self)
self.obj47.isGraphObjectVisual = True
if(hasattr(self.obj47, '_setHierarchicalLink')):
self.obj47._setHierarchicalLink(False)
# MT_label__
self.obj47.MT_label__.setValue('1')
# MT_pivotOut__
self.obj47.MT_pivotOut__.setValue('')
self.obj47.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj47.MT_subtypeMatching__.setValue(('True', 0))
self.obj47.MT_subtypeMatching__.config = 0
# MT_pivotIn__
self.obj47.MT_pivotIn__.setValue('')
self.obj47.MT_pivotIn__.setNone()
self.obj47.graphClass_= graph_MT_pre__MatchModel
if self.genGraphics:
new_obj = graph_MT_pre__MatchModel(73.0,80.0,self.obj47)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__MatchModel", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
self.obj47.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj47)
self.globalAndLocalPostcondition(self.obj47, rootNode)
self.obj47.postAction( rootNode.CREATE )
self.obj48=MT_pre__ApplyModel(self)
self.obj48.isGraphObjectVisual = True
if(hasattr(self.obj48, '_setHierarchicalLink')):
self.obj48._setHierarchicalLink(False)
# MT_label__
self.obj48.MT_label__.setValue('2')
# MT_pivotOut__
self.obj48.MT_pivotOut__.setValue('')
self.obj48.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj48.MT_subtypeMatching__.setValue(('True', 0))
self.obj48.MT_subtypeMatching__.config = 0
|
# MT_pivotIn__
self.obj48.MT_pivotIn__.setValue('')
self.obj48.MT_pivotIn__.setNone()
self.obj48.graphClass_= graph_MT_pre__ApplyModel
if self.genGraphics:
new_obj = graph_MT_pre__ApplyModel(72.0,240.0,self.obj48)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__ApplyModel", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
se | lf.obj48.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.obj48)
self.globalAndLocalPostcondition(self.obj48, rootNode)
self.obj48.postAction( rootNode.CREATE )
self.obj49=MT_pre__Distributable(self)
self.obj49.isGraphObjectVisual = True
if(hasattr(self.obj49, '_setHierarchicalLink')):
self.obj49._setHierarchicalLink(False)
# MT_pivotOut__
self.obj49.MT_pivotOut__.setValue('')
self.obj49.MT_pivotOut__.setNone()
# MT_subtypeMatching__
self.obj49.MT_subtypeMatching__.setValue(('True', 0))
self.obj49.MT_subtypeMatching__.config = 0
# MT_pre__classtype
self.obj49.MT_pre__classtype.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj49.MT_pre__classtype.setHeight(15)
# MT_pivotIn__
self.obj49.MT_pivotIn__.setValue('')
self.obj49.MT_pivotIn__.setNone()
# MT_label__
self.obj49.MT_label__.setValue('5')
# MT_pre__cardinality
self.obj49.MT_pre__cardinality.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj49.MT_pre__cardinality.setHeight(15)
# MT_pre__name
self.obj49.MT_pre__name.setValue('\n#===============================================================================\n# This code is executed when evaluating if a node shall be matched by this rule.\n# You can access the value of the current node\'s attribute value by: attr_value.\n# You can access any attribute x of this node by: this[\'x\'].\n# If the constraint relies on attribute values from other nodes,\n# use the LHS/NAC constraint instead.\n# The given constraint must evaluate to a boolean expression.\n#===============================================================================\n\nreturn True\n')
self.obj49.MT_pre__name.setHeight(15)
self.obj49.graphClass_= graph_MT_pre__Distributable
if self.genGraphics:
new_obj = graph_MT_pre__Distributable(280.0,120.0,self.obj49)
new_obj.DrawObject(self.UMLmodel)
self.UMLmodel.addtag_withtag("MT_pre__Distributable", new_obj.tag)
new_obj.layConstraints = dict() # Graphical Layout Constraints
new_obj.layConstraints['scale'] = [1.0, 1.0]
else: new_obj = None
self.obj49.graphObject_ = new_obj
# Add node to the root: rootNode
rootNode.addNode(self.o |
martinstastny/django-simplestore | simplestore/checkout/migrations/0011_auto_20170831_1618.py | Python | mit | 654 | 0.001529 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-08-31 14:18
from __future__ import unicode_literals
fro | m django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('check | out', '0010_auto_20170614_1434'),
]
operations = [
migrations.DeleteModel(
name='Payment',
),
migrations.AlterField(
model_name='orderitem',
name='product',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='order_items', to='products.Product'),
),
]
|
lbybee/okc_project | okc_scraper_no_q.py | Python | gpl-2.0 | 8,941 | 0.000783 | """okc_scraper includes all the functions needed to scrape profiles from
OKCupid"""
import requests
import cPickle as pickle
import time
from BeautifulSoup import BeautifulSoup
def authorize(username, password):
"""Log into OKCupid to scrape profiles"""
user_info = {"username": username, "password": password}
okc = requests.session()
okc.post("https://www.okcupid.com/login", data=user_info)
return okc
def getProfiles(okc):
"""Searches for profiles and returns a list of profiles (10)"""
# match_info = {"filter1": "0,63", "filter2": "2,100,18",
# "filter3": "5,2678400", "filter4": "1,1",
# "locid": "1", "custom_search": "0",
# "matchOrderBy": "SPECIAL_BLEND",
# "sa": "1", "sort_type": "0", "update_prefs": "1"}
soup = BeautifulSoup(okc.post("https://www.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=mwww.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=m").text)
users = soup.findAll("div", {"class": "user_info"})
return (["https://www.okcupid.com" +
user.find("a")["href"].replace("?cf=regular", "")
for user in users], soup)
def getProfile(okc, profile_link):
"""Takes a link to a profile and returns a BeautifulSoup object"""
page = BeautifulSoup(okc.get(profile_link).text)
return (page, page.find("form", {"id": "flag_form"})
.findAll("input")[0]["value"])
def getInfo(profile, profile_id):
"""Take a BeautifulSoup object corresponding to a profile's home page
and the profile's id and return a list of the profile's user info
(username, age, gender...)"""
try:
main = profile.find("div", {"id": "basic_info"}).findAll("span")
return {"id_table": {"user_id": profile_id,
"user_name": main[0].text,
"user_age": main[1].text,
"user_gender": main[2].text,
"user_orient": main[3].text,
"user_status": main[4].text,
"user_location": main[5].text}, }
except:
print profile
return {"id_table": {"user_id": profile_id,
"data": "NA"}}
def getEssays(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to a profiles home
page and returns a list of the profile's essays"""
etd = {"user_id": profile_id, }
essay_index = ["self_summary", "my_life", "good_at", "first_thing",
"favorite", "six_things", "lot_time", "typical_Friday",
"most_private"]
main = profile.find("div", {"id": "main_column"})
for i in range(0, 9):
try:
etd[essay_index[i]] = (main.find("div", {"id": "essay_text_"
+ str(i)})
.getText(' '))
except:
etd[essay_index[i]] = ""
return {"essay_table": etd, }
def getLookingFor(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to a profiles home
page and returns a list of the profile's looking for items"""
try:
main = (profile.find("div", {"id": "main_column"})
.find("div", {"id": "what_i_want"}).findAll("li"))
if len(main) == 4:
return {"looking_for_table": {"user_id": profile_id,
"other_user": main[0].text,
"other_age": main[1].text,
"other_location": main[2].text,
"other_type": main[3].text}, }
if len(main) == 5:
return {"looking_for_table": {"user_id": profile_id,
"other_user": main[0].text,
"other_age": main[1].text,
"other_location": main[2].text,
"other_status": main[3].text,
"other_type": main[4].text}, }
except:
print profile
return {"looking_for_table": {"user_id": profile_id,
"data": "NA"}}
def getDetails(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to profiles home
page and returns a list of profile's details"""
try:
main = profile.find("div", {"id": "profile_details"}).findAll("dd")
return {"details_table": {"user_id": profile_id,
"last_online": main[0].text,
"ethnicity": main[1].text,
"height": main[2].text,
"body_type": main[3].text,
"diet": main[4].text,
"smokes": main[5].text,
"drinks": main[6].text,
"religion": main[7].text,
"sign": main[8].text,
"education": main[9].text,
"job": main[10].text,
"income": main[11].text,
"offspring": main[12].text,
"pets": main[13].text,
"speaks": main[14].text}, }
except:
print profile
return {"details_table": {"user_id": profile_id,
"data": "NA"}}
def getQuestions(okc, profile_link, profile_id):
"""Take a link to a profile and return a list the questions a user
has answered"""
# Currently this doesn't return anything. All functions need to be
# changed up to work with mysql 07/19/2013 22:50
question_list = []
question_categories = ["Ethics", "Sex", "Religion", "Lifestyle",
"Dating", "Other"]
for category in question_categories:
q = BeautifulSoup(okc.get(profile_link + "/questions?"
+ category).text)
try:
max_page = int(q.find("div", {"class": "pages clearfix"})
.findAll("li")[1].find("a").text)
except IndexError:
max_page = 1
except AttributeError:
return []
for page in range(1, max_page + 1):
q_page = BeautifulSoup(okc.get(profile_link + "/questions?"
+ category + "="
+ str(page)).text)
questions = [q for q in q_page.find("div", {"id": "questions"})
.findAll("div",
{"class":
"question public talk clearfix"})]
for question in questions:
question_id = question["id"]
qtext = question.find("p", {"class": "qtext"}).text
atext = question | .find("p",
{"class":
"answer target clearfix | "}).text
question_list.append({"question_table":
{"user_id": profile_id,
"question_id": question_id,
"question_text": qtext,
"user_answer": atext,
"question_category": category},
})
return question_list
def pickleDict(dict_, dir):
"""Takes in a directory and a dictionary to be pickled and pickles
the dict in the directory"""
dict_id = dict_.keys()[0]
tab_i = pickle.load(open(dir + dict_id + ".p", "rb"))
tab_i.append(dict_)
pickle.dump(tab_i, |
louyihua/edx-platform | lms/djangoapps/badges/api/tests.py | Python | agpl-3.0 | 9,405 | 0.002446 | """
Tests for the badges API views.
"""
from ddt import ddt, data, unpack
from django.conf import settings
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from badges.tests.factories import BadgeAssertionFactory, BadgeClassFactory, RandomBadgeClassFactory
from openedx.core.lib.api.test_utils import ApiTestCase
from student.tests.factories import UserFactory
from util.testing import UrlResetMixin
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
FEATURES_WITH_BADGES_ENABLED = settings.FEATURES.copy()
FEATURES_WITH_BADGES_ENABLED['ENABLE_OPENBADGES'] = True
@override_settings(FEATURES=FEATURES_WITH_BADGES_ENABLED)
class UserAssertionTestCase(UrlResetMixin, ModuleStoreTestCase, ApiTestCase):
"""
Mixin for badge API tests.
"""
def setUp(self, *args, **kwargs):
super(UserAssertionTestCase, self).setUp(*args, **kwargs)
self.course = CourseFactory.create()
self.user = UserFactory.create()
# Password defined by factory.
self.client.login(username=self.user.username, password='test')
def url(self):
"""
Return the URL to look up the current user's assertions.
"""
return '/api/badges/v1/assertions/user/{}/'.format(self.user.username)
def check_class_structure(self, badge_class, json_class):
"""
Check a JSON response against a known badge class.
"""
self.assertEqual(badge_class.issuing_component, json_class['issuing_component'])
self.assertEqual(badge_class.slug, json_class['slug'])
self.assertIn(badge_class.image.url, json_class['image_url'])
self.assertEqual(badge_class.description, json_class['description'])
self.assertEqual(badge_class.criteria, json_class['criteria'])
self.assertEqual(badge_class.course_id and unicode(badge_class.course_id), json_class['course_id'])
def check_assertion_structure(self, assertion, json_assertion):
"""
Check a JSON response against a known assertion object.
"""
self.assertEqual(assertion.image_url, json_assertion['image_url'])
self.assertEqual(assertion.assertion_url, json_assertion['assertion_url'])
self.check_class_structure(assertion.badge_class, json_assertion['badge_class'])
def get_course_id(self, wildcard, badge_class):
"""
Used for tests which may need to test for a course_id or a wildcard.
"""
if wildcard:
return '*'
else:
return unicode(badge_class.course_id)
def create_badge_class(self, check_course, **kwargs):
"""
Create a badge class, using a course id if it's relevant to the URL pattern.
"""
if check_course:
return RandomBadgeClassFactory.create(course_id=self.course.location.course_key, **kwargs)
return RandomBadgeClassFactory.create(**kwargs)
def get_qs_args(self, check_course, wildcard, badge_class):
"""
Get a dictionary to be serialized into querystring params based on class settings.
"""
qs_args = {
'issuing_component': badge_class.issuing_component,
'slug': badge_class.slug,
}
if check_course:
qs_args['course_id'] = self.get_course_id(wildcard, badge_class)
return qs_args
class TestUserBadgeAssertions(UserAssertionTestCase):
"""
Test the general badge assertions retrieval view.
"""
def test_get_assertions(self):
"""
Verify we can get all of a user's badge assertions.
"""
for dummy in range(3):
BadgeAssertionFactory(user=self.user)
# Add in a course scoped badge-- these should not be excluded from the full listing.
BadgeAssertionFactory(use | r=self.user, bad | ge_class=BadgeClassFactory(course_id=self.course.location.course_key))
# Should not be included.
for dummy in range(3):
self.create_badge_class(False)
response = self.get_json(self.url())
# pylint: disable=no-member
self.assertEqual(len(response['results']), 4)
def test_assertion_structure(self):
badge_class = self.create_badge_class(False)
assertion = BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)
response = self.get_json(self.url())
# pylint: disable=no-member
self.check_assertion_structure(assertion, response['results'][0])
class TestUserCourseBadgeAssertions(UserAssertionTestCase):
"""
Test the Badge Assertions view with the course_id filter.
"""
def test_get_assertions(self):
"""
Verify we can get assertions via the course_id and username.
"""
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(course_id=course_key)
for dummy in range(3):
BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)
# Should not be included, as they don't share the target badge class.
for dummy in range(3):
BadgeAssertionFactory.create(user=self.user)
# Also should not be included, as they don't share the same user.
for dummy in range(6):
BadgeAssertionFactory.create(badge_class=badge_class)
response = self.get_json(self.url(), data={'course_id': course_key})
# pylint: disable=no-member
self.assertEqual(len(response['results']), 3)
unused_course = CourseFactory.create()
response = self.get_json(self.url(), data={'course_id': unused_course.location.course_key})
# pylint: disable=no-member
self.assertEqual(len(response['results']), 0)
def test_assertion_structure(self):
"""
Verify the badge assertion structure is as expected when a course is involved.
"""
course_key = self.course.location.course_key
badge_class = BadgeClassFactory.create(course_id=course_key)
assertion = BadgeAssertionFactory.create(badge_class=badge_class, user=self.user)
response = self.get_json(self.url())
# pylint: disable=no-member
self.check_assertion_structure(assertion, response['results'][0])
@attr(shard=3)
@ddt
class TestUserBadgeAssertionsByClass(UserAssertionTestCase):
"""
Test the Badge Assertions view with the badge class filter.
"""
@unpack
@data((False, False), (True, False), (True, True))
def test_get_assertions(self, check_course, wildcard):
"""
Verify we can get assertions via the badge class and username.
"""
badge_class = self.create_badge_class(check_course)
for dummy in range(3):
BadgeAssertionFactory.create(user=self.user, badge_class=badge_class)
if badge_class.course_id:
# Also create a version of this badge under a different course.
alt_class = BadgeClassFactory.create(
slug=badge_class.slug, issuing_component=badge_class.issuing_component,
course_id=CourseFactory.create().location.course_key
)
BadgeAssertionFactory.create(user=self.user, badge_class=alt_class)
# Same badge class, but different user. Should not show up in the list.
for dummy in range(5):
BadgeAssertionFactory.create(badge_class=badge_class)
# Different badge class AND different user. Certainly shouldn't show up in the list!
for dummy in range(6):
BadgeAssertionFactory.create()
response = self.get_json(
self.url(),
data=self.get_qs_args(check_course, wildcard, badge_class),
)
if wildcard:
expected_length = 4
else:
expected_length = 3
# pylint: disable=no-member
self.assertEqual(len(response['results']), expected_length)
unused_class = self.create_badge_class(check_course, slug='unused_slug', issuing_component='unused_component')
response = self.get_json(
self.url(),
data=self |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.