code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import torch
import tqdm
import numpy as np
from models import build_model_and_tokenizer
from dataset.tianchi_2020_dataset import get_test_dataloader
def _batch_trans(batch, device):
batch = tuple(t.to(device) for t in batch)
batch_data ={
'input_ids': batch[0],
'attention_mask': batch[1],
'token_type_ids': batch[2],
'labels': batch[3]
}
return batch_data
def infer_dataloader(models_list, dloader, device, return_loggits = False):
for m in models_list:
m.eval()
m.to(device)
all_preds_loggits = None
all_labels = None
for batch in tqdm.tqdm(dloader):
with torch.no_grad():
batch_data = _batch_trans(batch,device)
outputs = models_list[0](
input_ids=batch_data['input_ids'],
attention_mask=batch_data['attention_mask'],
token_type_ids=batch_data['token_type_ids'],
)
pred_loggits = outputs[0]
for i in range(1, len(models_list)):
pred_loggits += models_list[i](
input_ids=batch_data['input_ids'],
attention_mask=batch_data['attention_mask'],
token_type_ids=batch_data['token_type_ids'],
)[0]
pred_loggits = pred_loggits.softmax(dim=-1)
if all_preds_loggits is None:
all_preds_loggits = pred_loggits.detach().cpu().numpy()
all_labels = batch_data['labels'].detach().cpu().numpy()
else:
all_preds_loggits = np.append(all_preds_loggits, pred_loggits.detach().cpu().numpy(), axis=0)
all_labels = np.append(all_labels, batch_data['labels'].detach().cpu().numpy(), axis=0)
all_preds = np.argmax(all_preds_loggits, axis=1)
if return_loggits:
return all_preds, all_labels,all_preds_loggits
return all_preds,all_labels
def infer_with_model_data_build(cfg, model_path, test_data_path):
model_type = cfg.MODEL.model_type
model, tokenizer = build_model_and_tokenizer(model_type)
dataloader = get_test_dataloader(cfg, tokenizer, test_data_path)
print('samples: ', len(dataloader.dataset))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
models = []
if torch.cuda.is_available():
model.load_state_dict(torch.load(model_path), strict=True)
else:
map_location = torch.device('cpu')
model.load_state_dict(torch.load(model_path, map_location=map_location),
strict=True)
models.append(model)
preds, labels,pred_loggits = infer_dataloader(models, dataloader, device,return_loggits=True)
return preds, labels,pred_loggits | tools/infer.py | import torch
import tqdm
import numpy as np
from models import build_model_and_tokenizer
from dataset.tianchi_2020_dataset import get_test_dataloader
def _batch_trans(batch, device):
batch = tuple(t.to(device) for t in batch)
batch_data ={
'input_ids': batch[0],
'attention_mask': batch[1],
'token_type_ids': batch[2],
'labels': batch[3]
}
return batch_data
def infer_dataloader(models_list, dloader, device, return_loggits = False):
for m in models_list:
m.eval()
m.to(device)
all_preds_loggits = None
all_labels = None
for batch in tqdm.tqdm(dloader):
with torch.no_grad():
batch_data = _batch_trans(batch,device)
outputs = models_list[0](
input_ids=batch_data['input_ids'],
attention_mask=batch_data['attention_mask'],
token_type_ids=batch_data['token_type_ids'],
)
pred_loggits = outputs[0]
for i in range(1, len(models_list)):
pred_loggits += models_list[i](
input_ids=batch_data['input_ids'],
attention_mask=batch_data['attention_mask'],
token_type_ids=batch_data['token_type_ids'],
)[0]
pred_loggits = pred_loggits.softmax(dim=-1)
if all_preds_loggits is None:
all_preds_loggits = pred_loggits.detach().cpu().numpy()
all_labels = batch_data['labels'].detach().cpu().numpy()
else:
all_preds_loggits = np.append(all_preds_loggits, pred_loggits.detach().cpu().numpy(), axis=0)
all_labels = np.append(all_labels, batch_data['labels'].detach().cpu().numpy(), axis=0)
all_preds = np.argmax(all_preds_loggits, axis=1)
if return_loggits:
return all_preds, all_labels,all_preds_loggits
return all_preds,all_labels
def infer_with_model_data_build(cfg, model_path, test_data_path):
model_type = cfg.MODEL.model_type
model, tokenizer = build_model_and_tokenizer(model_type)
dataloader = get_test_dataloader(cfg, tokenizer, test_data_path)
print('samples: ', len(dataloader.dataset))
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
models = []
if torch.cuda.is_available():
model.load_state_dict(torch.load(model_path), strict=True)
else:
map_location = torch.device('cpu')
model.load_state_dict(torch.load(model_path, map_location=map_location),
strict=True)
models.append(model)
preds, labels,pred_loggits = infer_dataloader(models, dataloader, device,return_loggits=True)
return preds, labels,pred_loggits | 0.498047 | 0.248762 |
import logging
from typing import Any, List, Optional, Union
from eth_typing import URI
from web3 import HTTPProvider
from web3._utils.rpc_abi import RPC
from web3.middleware.geth_poa import geth_poa_cleanup
from web3.types import RPCEndpoint, RPCResponse
logger = logging.getLogger(__name__)
class NoActiveProviderError(Exception):
"""Base exception if all providers are offline"""
class MultiHTTPProvider(HTTPProvider):
"""
Provider that switches rpc endpoint if default one is broken.
Does not support subscriptions for now.
"""
_http_providers: List[HTTPProvider] = []
_current_provider_index: int = 0
_last_working_provider_index: int = 0
def __init__(
self,
endpoint_urls: List[Union[URI, str]],
request_kwargs: Optional[Any] = None,
session: Optional[Any] = None,
):
logger.info({"msg": "Initialize MultiHTTPProvider"})
self._hosts_uri = endpoint_urls
self._http_providers = [
HTTPProvider(host_uri, request_kwargs, session)
for host_uri in endpoint_urls
]
super().__init__(endpoint_urls[0], request_kwargs, session)
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
try:
response = self._http_providers[self._current_provider_index].make_request(
method, params
)
if method in (RPC.eth_getBlockByHash, RPC.eth_getBlockByNumber):
if (
"result" in response
and "proofOfAuthorityData" not in response["result"]
):
response["result"] = geth_poa_cleanup(response["result"])
logger.debug(
{
"msg": "Send request using MultiHTTPProvider.",
"method": method,
"params": str(params),
"provider": self._http_providers[
self._current_provider_index
].endpoint_uri,
}
)
self._last_working_provider_index = self._current_provider_index
return response
except Exception as error: # pylint: disable=W0703
logger.warning(
{
"msg": "Provider not responding.",
"error": str(error),
"provider": self._http_providers[
self._current_provider_index
].endpoint_uri,
}
)
self._current_provider_index = (self._current_provider_index + 1) % len(
self._hosts_uri
)
if self._last_working_provider_index == self._current_provider_index:
msg = "No active provider available."
logger.error({"msg": msg})
raise NoActiveProviderError(msg) from error
return self.make_request(method, params) | web3_multi_provider/multi_http_provider.py | import logging
from typing import Any, List, Optional, Union
from eth_typing import URI
from web3 import HTTPProvider
from web3._utils.rpc_abi import RPC
from web3.middleware.geth_poa import geth_poa_cleanup
from web3.types import RPCEndpoint, RPCResponse
logger = logging.getLogger(__name__)
class NoActiveProviderError(Exception):
"""Base exception if all providers are offline"""
class MultiHTTPProvider(HTTPProvider):
"""
Provider that switches rpc endpoint if default one is broken.
Does not support subscriptions for now.
"""
_http_providers: List[HTTPProvider] = []
_current_provider_index: int = 0
_last_working_provider_index: int = 0
def __init__(
self,
endpoint_urls: List[Union[URI, str]],
request_kwargs: Optional[Any] = None,
session: Optional[Any] = None,
):
logger.info({"msg": "Initialize MultiHTTPProvider"})
self._hosts_uri = endpoint_urls
self._http_providers = [
HTTPProvider(host_uri, request_kwargs, session)
for host_uri in endpoint_urls
]
super().__init__(endpoint_urls[0], request_kwargs, session)
def make_request(self, method: RPCEndpoint, params: Any) -> RPCResponse:
try:
response = self._http_providers[self._current_provider_index].make_request(
method, params
)
if method in (RPC.eth_getBlockByHash, RPC.eth_getBlockByNumber):
if (
"result" in response
and "proofOfAuthorityData" not in response["result"]
):
response["result"] = geth_poa_cleanup(response["result"])
logger.debug(
{
"msg": "Send request using MultiHTTPProvider.",
"method": method,
"params": str(params),
"provider": self._http_providers[
self._current_provider_index
].endpoint_uri,
}
)
self._last_working_provider_index = self._current_provider_index
return response
except Exception as error: # pylint: disable=W0703
logger.warning(
{
"msg": "Provider not responding.",
"error": str(error),
"provider": self._http_providers[
self._current_provider_index
].endpoint_uri,
}
)
self._current_provider_index = (self._current_provider_index + 1) % len(
self._hosts_uri
)
if self._last_working_provider_index == self._current_provider_index:
msg = "No active provider available."
logger.error({"msg": msg})
raise NoActiveProviderError(msg) from error
return self.make_request(method, params) | 0.769124 | 0.126623 |
__author__ = 'luckydonald'
from . import encoding
from .utils import escape # validate_input
from .exceptions import ArgumentParseError
from os import path # file checking.
import logging
logger = logging.getLogger(__name__)
class Argument(object):
def __init__(self, name, optional=False, multible=False):
self.name = name
self.optional = optional
self.multible = multible
def __str__(self):
string = self.name
if self.optional:
string = "["+string+"]"
else:
string = "<"+string+">"
if self.multible:
string = string + "+"
return string
def parse(self, value):
return value
class Nothing(Argument):
def parse(self, value):
value = super(Nothing, self).parse(value)
if not value is None:
raise ArgumentParseError("Is not null.")
return value
class UnescapedUnicodeString(Argument):
"""
Used for unicodes stings which will not be escaped.
"""
pass
class UnicodeString(UnescapedUnicodeString):
"""
Used for unicodes stings which will be escaped, and wrapped in 'simple quotes'
"""
def parse(self, value):
value = super(UnicodeString, self).parse(value)
value = escape(value)
if not isinstance(value, encoding.text_type):
raise ArgumentParseError("Not a string.")
return value
class Peer(UnescapedUnicodeString):
def parse(self, value):
value = super(Peer, self).parse(value)
if " " in value:
raise ArgumentParseError("Space in peer.")
return value
class Chat(Peer):
def parse(self, value):
return super(Chat, self).parse(value)
class User(Peer):
def parse(self, value):
return super(User, self).parse(value)
class SecretChat(Peer):
def parse(self, value):
return super(SecretChat, self).parse(value)
class Number(Argument):
def parse(self, value):
super(Number, self).parse(value)
if isinstance(encoding.native_type, encoding.text_type):
return int(value)
if not isinstance(value, (int, encoding.long_int)):
raise ArgumentParseError("Not a int/long")
return value
class Double(Argument):
def parse(self, value):
value = super(Double, self).parse(value)
if not isinstance(value, float):
raise ArgumentParseError("Not a float.")
return value
class NonNegativeNumber(Number):
def parse(self, value):
value = super(NonNegativeNumber, self).parse(value)
if value < 0:
raise ArgumentParseError("Number smaller than 0.")
return value
class PositiveNumber(NonNegativeNumber):
def parse(self, value):
value = super(PositiveNumber, self).parse(value)
if value <= 0:
raise ArgumentParseError("Number must be bigger than 0.")
return value
class File(UnicodeString):
def parse(self, value):
if not path.isfile(encoding.native_type(value)):
raise ArgumentParseError("File path \"{path}\" not valid.".format(path=value))
value = super(File, self).parse(value)
return value
class MsgId(PositiveNumber):
def parse(self, value):
return super(MsgId, self).parse(value)
def validate_input(function_name, arguments, arguments_types):
logger.warn("validate_input() is deprecated!")
raise NotImplementedError()
if (len(arguments) != len(arguments_types)):
raise ValueError("Error in function {function_name}: {expected_number} paramters expected, but {given_number} were given.".format(function_name=function_name, expected_number=len(arguments_types), given_number=len(args)))
i = 0
new_args = []
for arg in arguments:
func_type = arguments_types[i]
# arg is the given one, which should be func_type.
if not func_type(arg):
raise ValueError("Error in function {function_name}: parameter {number} is not type {type}.".format(function_name=function_name, number=i, type=func_type.__name__))
if func_type == UnicodeString:
new_args.append(encoding.to_unicode(escape(arg)))
else:
new_args.append(encoding.to_unicode(str(arg)))
i += 1
# end for
return new_args | pytg2/argument_types.py | __author__ = 'luckydonald'
from . import encoding
from .utils import escape # validate_input
from .exceptions import ArgumentParseError
from os import path # file checking.
import logging
logger = logging.getLogger(__name__)
class Argument(object):
def __init__(self, name, optional=False, multible=False):
self.name = name
self.optional = optional
self.multible = multible
def __str__(self):
string = self.name
if self.optional:
string = "["+string+"]"
else:
string = "<"+string+">"
if self.multible:
string = string + "+"
return string
def parse(self, value):
return value
class Nothing(Argument):
def parse(self, value):
value = super(Nothing, self).parse(value)
if not value is None:
raise ArgumentParseError("Is not null.")
return value
class UnescapedUnicodeString(Argument):
"""
Used for unicodes stings which will not be escaped.
"""
pass
class UnicodeString(UnescapedUnicodeString):
"""
Used for unicodes stings which will be escaped, and wrapped in 'simple quotes'
"""
def parse(self, value):
value = super(UnicodeString, self).parse(value)
value = escape(value)
if not isinstance(value, encoding.text_type):
raise ArgumentParseError("Not a string.")
return value
class Peer(UnescapedUnicodeString):
def parse(self, value):
value = super(Peer, self).parse(value)
if " " in value:
raise ArgumentParseError("Space in peer.")
return value
class Chat(Peer):
def parse(self, value):
return super(Chat, self).parse(value)
class User(Peer):
def parse(self, value):
return super(User, self).parse(value)
class SecretChat(Peer):
def parse(self, value):
return super(SecretChat, self).parse(value)
class Number(Argument):
def parse(self, value):
super(Number, self).parse(value)
if isinstance(encoding.native_type, encoding.text_type):
return int(value)
if not isinstance(value, (int, encoding.long_int)):
raise ArgumentParseError("Not a int/long")
return value
class Double(Argument):
def parse(self, value):
value = super(Double, self).parse(value)
if not isinstance(value, float):
raise ArgumentParseError("Not a float.")
return value
class NonNegativeNumber(Number):
def parse(self, value):
value = super(NonNegativeNumber, self).parse(value)
if value < 0:
raise ArgumentParseError("Number smaller than 0.")
return value
class PositiveNumber(NonNegativeNumber):
def parse(self, value):
value = super(PositiveNumber, self).parse(value)
if value <= 0:
raise ArgumentParseError("Number must be bigger than 0.")
return value
class File(UnicodeString):
def parse(self, value):
if not path.isfile(encoding.native_type(value)):
raise ArgumentParseError("File path \"{path}\" not valid.".format(path=value))
value = super(File, self).parse(value)
return value
class MsgId(PositiveNumber):
def parse(self, value):
return super(MsgId, self).parse(value)
def validate_input(function_name, arguments, arguments_types):
logger.warn("validate_input() is deprecated!")
raise NotImplementedError()
if (len(arguments) != len(arguments_types)):
raise ValueError("Error in function {function_name}: {expected_number} paramters expected, but {given_number} were given.".format(function_name=function_name, expected_number=len(arguments_types), given_number=len(args)))
i = 0
new_args = []
for arg in arguments:
func_type = arguments_types[i]
# arg is the given one, which should be func_type.
if not func_type(arg):
raise ValueError("Error in function {function_name}: parameter {number} is not type {type}.".format(function_name=function_name, number=i, type=func_type.__name__))
if func_type == UnicodeString:
new_args.append(encoding.to_unicode(escape(arg)))
else:
new_args.append(encoding.to_unicode(str(arg)))
i += 1
# end for
return new_args | 0.401453 | 0.258081 |
import os
import importlib
import argparse
COLLATE_FN_REGISTRY = {}
def register_collate_fn(name):
def register_collate_fn_method(f):
if name in COLLATE_FN_REGISTRY:
raise ValueError(
"Cannot register duplicate collate function ({})".format(name)
)
COLLATE_FN_REGISTRY[name] = f
return f
return register_collate_fn_method
def arguments_collate_fn(parser: argparse.ArgumentParser):
group = parser.add_argument_group(
title="Collate function arguments", description="Collate function arguments"
)
group.add_argument(
"--dataset.collate-fn-name-train",
type=str,
default="default_collate_fn",
help="Name of collate function",
)
group.add_argument(
"--dataset.collate-fn-name-val",
type=str,
default="default_collate_fn",
help="Name of collate function",
)
group.add_argument(
"--dataset.collate-fn-name-eval",
type=str,
default=None,
help="Name of collate function used for evaluation. "
"Default is None, i.e., use PyTorch's inbuilt collate function",
)
return parser
def build_collate_fn(opts, *args, **kwargs):
collate_fn_name_train = getattr(
opts, "dataset.collate_fn_name_train", "default_collate_fn"
)
collate_fn_name_val = getattr(
opts, "dataset.collate_fn_name_val", "default_collate_fn"
)
collate_fn_train = None
if (
collate_fn_name_train is not None
and collate_fn_name_train in COLLATE_FN_REGISTRY
):
collate_fn_train = COLLATE_FN_REGISTRY[collate_fn_name_train]
collate_fn_val = None
if collate_fn_name_val is None:
collate_fn_val = collate_fn_name_train
elif collate_fn_name_val is not None and collate_fn_name_val in COLLATE_FN_REGISTRY:
collate_fn_val = COLLATE_FN_REGISTRY[collate_fn_name_val]
return collate_fn_train, collate_fn_val
def build_eval_collate_fn(opts, *args, **kwargs):
collate_fn_name_eval = getattr(opts, "dataset.collate_fn_name_eval", None)
collate_fn_eval = None
if collate_fn_name_eval is not None and collate_fn_name_eval in COLLATE_FN_REGISTRY:
collate_fn_eval = COLLATE_FN_REGISTRY[collate_fn_name_eval]
return collate_fn_eval
# automatically import the augmentations
collate_fn_dir = os.path.dirname(__file__)
for file in os.listdir(collate_fn_dir):
path = os.path.join(collate_fn_dir, file)
if (
not file.startswith("_")
and not file.startswith(".")
and (file.endswith(".py") or os.path.isdir(path))
):
collate_fn_fname = file[: file.find(".py")] if file.endswith(".py") else file
module = importlib.import_module("data.collate_fns." + collate_fn_fname) | data/collate_fns/__init__.py |
import os
import importlib
import argparse
COLLATE_FN_REGISTRY = {}
def register_collate_fn(name):
def register_collate_fn_method(f):
if name in COLLATE_FN_REGISTRY:
raise ValueError(
"Cannot register duplicate collate function ({})".format(name)
)
COLLATE_FN_REGISTRY[name] = f
return f
return register_collate_fn_method
def arguments_collate_fn(parser: argparse.ArgumentParser):
group = parser.add_argument_group(
title="Collate function arguments", description="Collate function arguments"
)
group.add_argument(
"--dataset.collate-fn-name-train",
type=str,
default="default_collate_fn",
help="Name of collate function",
)
group.add_argument(
"--dataset.collate-fn-name-val",
type=str,
default="default_collate_fn",
help="Name of collate function",
)
group.add_argument(
"--dataset.collate-fn-name-eval",
type=str,
default=None,
help="Name of collate function used for evaluation. "
"Default is None, i.e., use PyTorch's inbuilt collate function",
)
return parser
def build_collate_fn(opts, *args, **kwargs):
collate_fn_name_train = getattr(
opts, "dataset.collate_fn_name_train", "default_collate_fn"
)
collate_fn_name_val = getattr(
opts, "dataset.collate_fn_name_val", "default_collate_fn"
)
collate_fn_train = None
if (
collate_fn_name_train is not None
and collate_fn_name_train in COLLATE_FN_REGISTRY
):
collate_fn_train = COLLATE_FN_REGISTRY[collate_fn_name_train]
collate_fn_val = None
if collate_fn_name_val is None:
collate_fn_val = collate_fn_name_train
elif collate_fn_name_val is not None and collate_fn_name_val in COLLATE_FN_REGISTRY:
collate_fn_val = COLLATE_FN_REGISTRY[collate_fn_name_val]
return collate_fn_train, collate_fn_val
def build_eval_collate_fn(opts, *args, **kwargs):
collate_fn_name_eval = getattr(opts, "dataset.collate_fn_name_eval", None)
collate_fn_eval = None
if collate_fn_name_eval is not None and collate_fn_name_eval in COLLATE_FN_REGISTRY:
collate_fn_eval = COLLATE_FN_REGISTRY[collate_fn_name_eval]
return collate_fn_eval
# automatically import the augmentations
collate_fn_dir = os.path.dirname(__file__)
for file in os.listdir(collate_fn_dir):
path = os.path.join(collate_fn_dir, file)
if (
not file.startswith("_")
and not file.startswith(".")
and (file.endswith(".py") or os.path.isdir(path))
):
collate_fn_fname = file[: file.find(".py")] if file.endswith(".py") else file
module = importlib.import_module("data.collate_fns." + collate_fn_fname) | 0.374219 | 0.101679 |
import re
from pywriter.html.html_file import HtmlFile
from pywriter.model.splitter import Splitter
class HtmlProof(HtmlFile):
"""HTML proof reading file representation.
Import a manuscript with visibly tagged chapters and scenes.
"""
DESCRIPTION = 'Tagged manuscript for proofing'
SUFFIX = '_proof'
def __init__(self, filePath, **kwargs):
"""Initialize local instance variables for parsing.
Positional arguments:
filePath -- str: path to the file represented by the Novel instance.
The HTML parser works like a state machine.
A prefix for chapter and scene recognition must be saved between the transitions.
Extends the superclass constructor.
"""
super().__init__(filePath)
self._prefix = None
def _preprocess(self, text):
"""Process the html text before parsing.
Convert html formatting tags to yWriter 7 raw markup.
Overrides the superclass method.
"""
return self._convert_to_yw(text)
def _postprocess(self):
"""Parse the converted text to identify chapters and scenes.
Overrides the superclass method.
"""
sceneText = []
scId = ''
chId = ''
inScene = False
for line in self._lines:
if '[ScID' in line:
scId = re.search('[0-9]+', line).group()
self.scenes[scId] = self.SCENE_CLASS()
self.chapters[chId].srtScenes.append(scId)
inScene = True
elif '[/ScID' in line:
self.scenes[scId].sceneContent = '\n'.join(sceneText)
sceneText = []
inScene = False
elif '[ChID' in line:
chId = re.search('[0-9]+', line).group()
self.chapters[chId] = self.CHAPTER_CLASS()
self.srtChapters.append(chId)
elif '[/ChID' in line:
pass
elif inScene:
sceneText.append(line)
def handle_starttag(self, tag, attrs):
"""Recognize the paragraph's beginning.
Positional arguments:
tag -- str: name of the tag converted to lower case.
attrs -- list of (name, value) pairs containing the attributes found inside the tag’s <> brackets.
Overrides the superclass method.
"""
if tag == 'p' and self._prefix is None:
self._prefix = ''
elif tag == 'h2':
self._prefix = f'{Splitter.CHAPTER_SEPARATOR} '
elif tag == 'h1':
self._prefix = f'{Splitter.PART_SEPARATOR} '
elif tag == 'li':
self._prefix = f'{self._BULLET} '
elif tag == 'blockquote':
self._prefix = f'{self._INDENT} '
def handle_endtag(self, tag):
"""Recognize the paragraph's end.
Positional arguments:
tag -- str: name of the tag converted to lower case.
Overrides HTMLparser.handle_endtag() called by the HTML parser to handle the end tag of an element.
"""
if tag in ['p', 'h2', 'h1', 'blockquote']:
self._prefix = None
def handle_data(self, data):
"""Copy the scene paragraphs.
Positional arguments:
data -- str: text to be stored.
Overrides HTMLparser.handle_data() called by the parser to process arbitrary data.
"""
if self._prefix is not None:
self._lines.append(f'{self._prefix}{data}') | src/pywriter/html/html_proof.py | import re
from pywriter.html.html_file import HtmlFile
from pywriter.model.splitter import Splitter
class HtmlProof(HtmlFile):
"""HTML proof reading file representation.
Import a manuscript with visibly tagged chapters and scenes.
"""
DESCRIPTION = 'Tagged manuscript for proofing'
SUFFIX = '_proof'
def __init__(self, filePath, **kwargs):
"""Initialize local instance variables for parsing.
Positional arguments:
filePath -- str: path to the file represented by the Novel instance.
The HTML parser works like a state machine.
A prefix for chapter and scene recognition must be saved between the transitions.
Extends the superclass constructor.
"""
super().__init__(filePath)
self._prefix = None
def _preprocess(self, text):
"""Process the html text before parsing.
Convert html formatting tags to yWriter 7 raw markup.
Overrides the superclass method.
"""
return self._convert_to_yw(text)
def _postprocess(self):
"""Parse the converted text to identify chapters and scenes.
Overrides the superclass method.
"""
sceneText = []
scId = ''
chId = ''
inScene = False
for line in self._lines:
if '[ScID' in line:
scId = re.search('[0-9]+', line).group()
self.scenes[scId] = self.SCENE_CLASS()
self.chapters[chId].srtScenes.append(scId)
inScene = True
elif '[/ScID' in line:
self.scenes[scId].sceneContent = '\n'.join(sceneText)
sceneText = []
inScene = False
elif '[ChID' in line:
chId = re.search('[0-9]+', line).group()
self.chapters[chId] = self.CHAPTER_CLASS()
self.srtChapters.append(chId)
elif '[/ChID' in line:
pass
elif inScene:
sceneText.append(line)
def handle_starttag(self, tag, attrs):
"""Recognize the paragraph's beginning.
Positional arguments:
tag -- str: name of the tag converted to lower case.
attrs -- list of (name, value) pairs containing the attributes found inside the tag’s <> brackets.
Overrides the superclass method.
"""
if tag == 'p' and self._prefix is None:
self._prefix = ''
elif tag == 'h2':
self._prefix = f'{Splitter.CHAPTER_SEPARATOR} '
elif tag == 'h1':
self._prefix = f'{Splitter.PART_SEPARATOR} '
elif tag == 'li':
self._prefix = f'{self._BULLET} '
elif tag == 'blockquote':
self._prefix = f'{self._INDENT} '
def handle_endtag(self, tag):
"""Recognize the paragraph's end.
Positional arguments:
tag -- str: name of the tag converted to lower case.
Overrides HTMLparser.handle_endtag() called by the HTML parser to handle the end tag of an element.
"""
if tag in ['p', 'h2', 'h1', 'blockquote']:
self._prefix = None
def handle_data(self, data):
"""Copy the scene paragraphs.
Positional arguments:
data -- str: text to be stored.
Overrides HTMLparser.handle_data() called by the parser to process arbitrary data.
"""
if self._prefix is not None:
self._lines.append(f'{self._prefix}{data}') | 0.469277 | 0.155142 |
from sqlalchemy import orm
from infosystem.database import db
from infosystem.common.subsystem import entity
class TimelineEvent(entity.Entity, db.Model):
LIMIT_SEARCH = 30
attributes = ['domain_id', 'event_at', 'event_by', 'lat', 'lon',
'description', 'entity', 'entity_id']
attributes += entity.Entity.attributes
domain_id = db.Column(
db.CHAR(32), db.ForeignKey('domain.id'), nullable=False)
event_at = db.Column(db.DateTime, nullable=False, unique=False)
event_by = db.Column(db.CHAR(32), nullable=False, unique=False)
lat = db.Column(db.Numeric(14, 8), nullable=False, unique=False)
lon = db.Column(db.Numeric(14, 8), nullable=False, unique=False)
description = db.Column(db.String(500), nullable=False, unique=False)
entity = db.Column(db.String(100), nullable=True, unique=False)
entity_id = db.Column(db.CHAR(32), nullable=True, unique=False)
users = orm.relationship(
"TimelineEventUser", backref=orm.backref('timeline_event_user'),
cascade='delete,delete-orphan,save-update')
__tablename__ = 'timeline_event'
def __init__(self, id, domain_id, event_at, event_by, lat, lon,
description, entity=None, entity_id=None,
active=True, created_at=None, created_by=None,
updated_at=None, updated_by=None, tag=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by, tag)
self.id = id
self.domain_id = domain_id
self.event_at = event_at
self.event_by = event_by
self.lat = lat
self.lon = lon
self.description = description
self.entity = entity
self.entity_id = entity_id,
@classmethod
def individual(cls):
return 'timeline_event'
@classmethod
def embedded(cls):
return ['users']
class TimelineEventUser(entity.Entity, db.Model):
attributes = ['id', 'user_id']
timeline_event_id = db.Column(
db.CHAR(32), db.ForeignKey("timeline_event.id"), nullable=False)
user_id = db.Column(
db.CHAR(32), db.ForeignKey("user.id"), nullable=False)
user = orm.relationship(
'User', backref=orm.backref('timeline_event_user'))
def __init__(self, id, timeline_event_id, user_id,
active=True, created_at=None,
created_by=None, updated_at=None, updated_by=None, tag=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by, tag)
self.timeline_event_id = timeline_event_id
self.user_id = user_id
def is_stable(self):
if self.user_id is not None and self.timeline_event_id is not None:
return True
return False | infosystem/subsystem/timeline_event/resource.py | from sqlalchemy import orm
from infosystem.database import db
from infosystem.common.subsystem import entity
class TimelineEvent(entity.Entity, db.Model):
LIMIT_SEARCH = 30
attributes = ['domain_id', 'event_at', 'event_by', 'lat', 'lon',
'description', 'entity', 'entity_id']
attributes += entity.Entity.attributes
domain_id = db.Column(
db.CHAR(32), db.ForeignKey('domain.id'), nullable=False)
event_at = db.Column(db.DateTime, nullable=False, unique=False)
event_by = db.Column(db.CHAR(32), nullable=False, unique=False)
lat = db.Column(db.Numeric(14, 8), nullable=False, unique=False)
lon = db.Column(db.Numeric(14, 8), nullable=False, unique=False)
description = db.Column(db.String(500), nullable=False, unique=False)
entity = db.Column(db.String(100), nullable=True, unique=False)
entity_id = db.Column(db.CHAR(32), nullable=True, unique=False)
users = orm.relationship(
"TimelineEventUser", backref=orm.backref('timeline_event_user'),
cascade='delete,delete-orphan,save-update')
__tablename__ = 'timeline_event'
def __init__(self, id, domain_id, event_at, event_by, lat, lon,
description, entity=None, entity_id=None,
active=True, created_at=None, created_by=None,
updated_at=None, updated_by=None, tag=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by, tag)
self.id = id
self.domain_id = domain_id
self.event_at = event_at
self.event_by = event_by
self.lat = lat
self.lon = lon
self.description = description
self.entity = entity
self.entity_id = entity_id,
@classmethod
def individual(cls):
return 'timeline_event'
@classmethod
def embedded(cls):
return ['users']
class TimelineEventUser(entity.Entity, db.Model):
attributes = ['id', 'user_id']
timeline_event_id = db.Column(
db.CHAR(32), db.ForeignKey("timeline_event.id"), nullable=False)
user_id = db.Column(
db.CHAR(32), db.ForeignKey("user.id"), nullable=False)
user = orm.relationship(
'User', backref=orm.backref('timeline_event_user'))
def __init__(self, id, timeline_event_id, user_id,
active=True, created_at=None,
created_by=None, updated_at=None, updated_by=None, tag=None):
super().__init__(id, active, created_at, created_by,
updated_at, updated_by, tag)
self.timeline_event_id = timeline_event_id
self.user_id = user_id
def is_stable(self):
if self.user_id is not None and self.timeline_event_id is not None:
return True
return False | 0.58818 | 0.057493 |
import os
import re
from typing import Optional, Sequence
from magmap.io import export_regions
from magmap.settings import config
from magmap.stats import vols
_logger = config.logger.getChild(__name__)
def build_labels_diff_images(paths: Optional[Sequence[str]] = None):
"""Build labels difference images for given metrics.
Replaces each label in an atlas labels image with the value of the effect
size of the given metric.
:class:`magmap.settings.config.PlotLabels.X_COL` in
:attr:`magmap.settings.config.plot_labels` can be used to change the
metric column.
Args:
paths: Paths to volume stat files output from the R pipeline.
"""
if paths:
# set up metrics from filenames after first (image) filename;
# extract metrics from R stats filename format
path_dfs = paths
metrics = [re.search(r"vols_stats_(.*).csv", p) for p in path_dfs]
metrics = [m.group(1) if m else m for m in metrics]
else:
# set up default metrics and assume corresponding CSVs are in
# current working directory
metrics = (
vols.LabelMetrics.EdgeDistSum.name,
vols.LabelMetrics.CoefVarNuc.name,
vols.LabelMetrics.CoefVarIntens.name,
vols.LabelMetrics.NucCluster.name,
vols.LabelMetrics.NucClusNoise.name,
#vols.MetricCombos.HOMOGENEITY.value[0],
)
path_dfs = [f"vols_stats_{m}.csv" for m in metrics]
# set the measurement column
col_meas = config.plot_labels[config.PlotLabels.X_COL]
if not col_meas:
col_meas = "vals.effect"
for path_df, metric in zip(path_dfs, metrics):
if not os.path.exists(path_df):
# check for existing R stats file
_logger.warn(f"{path_df} not found, skipping")
continue
if not metric:
# check for extracted metric name
_logger.warn(f"Metric not found from {path_df}, skipping")
continue
# generate difference image
col_wt = vols.get_metric_weight_col(metric)
export_regions.make_labels_diff_img(
config.filename, path_df, col_meas, None, config.prefix,
config.show, meas_path_name=metric, col_wt=col_wt) | magmap/atlas/reg_tasks.py |
import os
import re
from typing import Optional, Sequence
from magmap.io import export_regions
from magmap.settings import config
from magmap.stats import vols
_logger = config.logger.getChild(__name__)
def build_labels_diff_images(paths: Optional[Sequence[str]] = None):
"""Build labels difference images for given metrics.
Replaces each label in an atlas labels image with the value of the effect
size of the given metric.
:class:`magmap.settings.config.PlotLabels.X_COL` in
:attr:`magmap.settings.config.plot_labels` can be used to change the
metric column.
Args:
paths: Paths to volume stat files output from the R pipeline.
"""
if paths:
# set up metrics from filenames after first (image) filename;
# extract metrics from R stats filename format
path_dfs = paths
metrics = [re.search(r"vols_stats_(.*).csv", p) for p in path_dfs]
metrics = [m.group(1) if m else m for m in metrics]
else:
# set up default metrics and assume corresponding CSVs are in
# current working directory
metrics = (
vols.LabelMetrics.EdgeDistSum.name,
vols.LabelMetrics.CoefVarNuc.name,
vols.LabelMetrics.CoefVarIntens.name,
vols.LabelMetrics.NucCluster.name,
vols.LabelMetrics.NucClusNoise.name,
#vols.MetricCombos.HOMOGENEITY.value[0],
)
path_dfs = [f"vols_stats_{m}.csv" for m in metrics]
# set the measurement column
col_meas = config.plot_labels[config.PlotLabels.X_COL]
if not col_meas:
col_meas = "vals.effect"
for path_df, metric in zip(path_dfs, metrics):
if not os.path.exists(path_df):
# check for existing R stats file
_logger.warn(f"{path_df} not found, skipping")
continue
if not metric:
# check for extracted metric name
_logger.warn(f"Metric not found from {path_df}, skipping")
continue
# generate difference image
col_wt = vols.get_metric_weight_col(metric)
export_regions.make_labels_diff_img(
config.filename, path_df, col_meas, None, config.prefix,
config.show, meas_path_name=metric, col_wt=col_wt) | 0.897746 | 0.36108 |
from __future__ import absolute_import, division
from functools import partial
from python_lib.shell_command_helper import ShellCommandHelper
from utils import get_logger
class OvsHelper:
"""Class to build OVS bridges, VxLANs and other network components"""
DEFAULT_VXLAN_PORT = 4789
VXLAN_CMD_FMT = 'ip link add %s type vxlan id %s remote %s dstport %s srcport %s %s nolearning'
def __init__(self):
self._logger = get_logger('OvsHelper')
self._run_shell = partial(ShellCommandHelper().run_cmd, capture=True)
self._run_shell_no_raise = partial(ShellCommandHelper().run_cmd, capture=True, strict=False)
def create_vxlan_endpoint(self, port, remote_ip, vni, local_ip=None):
"""Creates a VxLAN endpoint"""
interface = "vxlan%s" % port
self.remove_vxlan_endpoint(interface)
self._logger.info("Creating VxLAN endpoint %s", interface)
vxlan_cmd = 'sudo ' + self.VXLAN_CMD_FMT % (
interface, vni, remote_ip, self.DEFAULT_VXLAN_PORT,
self.DEFAULT_VXLAN_PORT, self.DEFAULT_VXLAN_PORT)
self._run_shell(vxlan_cmd)
self._run_shell('sudo ip link set %s up' % interface)
if local_ip:
self._run_shell('sudo ip addr add %s dev %s' % (local_ip, interface))
return interface
def remove_vxlan_endpoint(self, interface):
"""Clears VxLAN endpoint"""
self._logger.info('Removing vxlan interface %s', interface)
self._run_shell_no_raise('sudo ip link set %s down' % interface)
self._run_shell_no_raise('sudo ip link del %s' % interface)
self._run_shell_no_raise('sudo ovs-vsctl del-port t1sw1 %s' % interface)
def create_ovs_bridge(self, name):
"""Creates OVS bridge"""
self._logger.info('Creating OVS bridge %s', name)
self._run_shell('sudo ovs-vsctl add-br %s' % name)
def delete_ovs_bridge(self, name):
"""Delete ovs bridge"""
self._logger.info('Deleting OVS bridge %s', name)
self._run_shell_no_raise('sudo ovs-vsctl del-br %s' % name)
def add_iface_to_bridge(self, bridge, iface):
"""Add interface to OVS bridge"""
self._logger.info('Adding interface %s to bridge %s', iface, bridge)
self._run_shell('sudo ovs-vsctl add-port %s %s' % (bridge, iface))
def set_native_vlan(self, interface, vlan):
"""Set native VLAN to port on OVS bridge"""
self._logger.info('Enabling native VLAN %s on interface %s', vlan, interface)
self._run_shell('sudo ovs-vsctl set port %s tag=%s' % (interface, vlan))
def set_trunk_vlan(self, interface, vlans):
"""Takes an array of VLANs and sets them as trunk VLANs for the port on OVS bridge"""
self._logger.info('Enabling trunk VLANs %s on interface %s', vlans, interface)
vlan_str = ",".join(str(vlan) for vlan in vlans)
self._run_shell('sudo ovs-vsctl set port %s trunks=%s' % (interface, vlan_str))
def create_faux_device(self, index):
"""Creates faux docker container daq-faux-<index>"""
self._run_shell('sudo cmd/faux %s' % index)
iface = 'faux-eth0'
prefix = int(index / 256) + 1
suffix = index % 256
ip_addr = '192.168.%s.%s' % (prefix, suffix)
gateway = '192.168.1.0'
container = 'daq-faux-%s' % index
self._run_shell('ip addr flush %s' % iface, docker_container=container)
self._run_shell('ip addr add %s/16 dev %s' % (ip_addr, iface), docker_container=container)
self._run_shell('ip route add default via %s' % gateway, docker_container=container) | device_coupler/ovs_helper.py |
from __future__ import absolute_import, division
from functools import partial
from python_lib.shell_command_helper import ShellCommandHelper
from utils import get_logger
class OvsHelper:
"""Class to build OVS bridges, VxLANs and other network components"""
DEFAULT_VXLAN_PORT = 4789
VXLAN_CMD_FMT = 'ip link add %s type vxlan id %s remote %s dstport %s srcport %s %s nolearning'
def __init__(self):
self._logger = get_logger('OvsHelper')
self._run_shell = partial(ShellCommandHelper().run_cmd, capture=True)
self._run_shell_no_raise = partial(ShellCommandHelper().run_cmd, capture=True, strict=False)
def create_vxlan_endpoint(self, port, remote_ip, vni, local_ip=None):
"""Creates a VxLAN endpoint"""
interface = "vxlan%s" % port
self.remove_vxlan_endpoint(interface)
self._logger.info("Creating VxLAN endpoint %s", interface)
vxlan_cmd = 'sudo ' + self.VXLAN_CMD_FMT % (
interface, vni, remote_ip, self.DEFAULT_VXLAN_PORT,
self.DEFAULT_VXLAN_PORT, self.DEFAULT_VXLAN_PORT)
self._run_shell(vxlan_cmd)
self._run_shell('sudo ip link set %s up' % interface)
if local_ip:
self._run_shell('sudo ip addr add %s dev %s' % (local_ip, interface))
return interface
def remove_vxlan_endpoint(self, interface):
"""Clears VxLAN endpoint"""
self._logger.info('Removing vxlan interface %s', interface)
self._run_shell_no_raise('sudo ip link set %s down' % interface)
self._run_shell_no_raise('sudo ip link del %s' % interface)
self._run_shell_no_raise('sudo ovs-vsctl del-port t1sw1 %s' % interface)
def create_ovs_bridge(self, name):
"""Creates OVS bridge"""
self._logger.info('Creating OVS bridge %s', name)
self._run_shell('sudo ovs-vsctl add-br %s' % name)
def delete_ovs_bridge(self, name):
"""Delete ovs bridge"""
self._logger.info('Deleting OVS bridge %s', name)
self._run_shell_no_raise('sudo ovs-vsctl del-br %s' % name)
def add_iface_to_bridge(self, bridge, iface):
"""Add interface to OVS bridge"""
self._logger.info('Adding interface %s to bridge %s', iface, bridge)
self._run_shell('sudo ovs-vsctl add-port %s %s' % (bridge, iface))
def set_native_vlan(self, interface, vlan):
"""Set native VLAN to port on OVS bridge"""
self._logger.info('Enabling native VLAN %s on interface %s', vlan, interface)
self._run_shell('sudo ovs-vsctl set port %s tag=%s' % (interface, vlan))
def set_trunk_vlan(self, interface, vlans):
"""Takes an array of VLANs and sets them as trunk VLANs for the port on OVS bridge"""
self._logger.info('Enabling trunk VLANs %s on interface %s', vlans, interface)
vlan_str = ",".join(str(vlan) for vlan in vlans)
self._run_shell('sudo ovs-vsctl set port %s trunks=%s' % (interface, vlan_str))
def create_faux_device(self, index):
"""Creates faux docker container daq-faux-<index>"""
self._run_shell('sudo cmd/faux %s' % index)
iface = 'faux-eth0'
prefix = int(index / 256) + 1
suffix = index % 256
ip_addr = '192.168.%s.%s' % (prefix, suffix)
gateway = '192.168.1.0'
container = 'daq-faux-%s' % index
self._run_shell('ip addr flush %s' % iface, docker_container=container)
self._run_shell('ip addr add %s/16 dev %s' % (ip_addr, iface), docker_container=container)
self._run_shell('ip route add default via %s' % gateway, docker_container=container) | 0.69233 | 0.093595 |
from math import radians
import bpy
import os
from mathutils import Vector, Matrix
def get_max(ob):
mx = Vector((-1000., -1000., -1000.))
for vx in ob.data.vertices:
p = ob.matrix_world * vx.co
mx.x = max(mx.x, p.x)
mx.y = max(mx.y, p.y)
mx.z = max(mx.z, p.z)
return mx
floor = bpy.data.objects['floor']
bpy.ops.object.select_all(action="DESELECT")
for ob in bpy.data.objects:
if not ob.name.startswith('Object.'):
continue
parts = ob.name[7:].split('_')
oid = int(parts[0])
typ = parts[1]
part = parts[2]
if '-' in part:
part = part[:part.index('-')]
name_model = None
if typ == 'table':
if part != 'top':
continue
else:
name_model = 'table'
elif typ == 'couch' or typ == 'chair':
if part != 'seat':
continue
else:
name_model = typ
elif typ == 'shelf':
name_model = 'shelf'
assert name_model is not None, "Nooo: {}".format(parts)
name_model = os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.pardir, os.pardir, 'models',
'{}.obj'.format(name_model))
bpy.ops.import_scene.obj(filepath=name_model, use_split_objects=True)
model = bpy.context.selected_objects[-1]
model.name = 'Model.{}_{}'.format(parts[0], typ)
print(name_model, model)
model.location = ob.location
model.rotation_euler = ob.rotation_euler
bpy.context.scene.update()
if typ == 'shelf':
model.matrix_world *= Matrix.Rotation(radians(90), 4, 'X')
elif typ == 'couch':
# model.rotation_euler.z = 3.14159 + ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y + 0.2 # slide bwards
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x + 0.26
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.4925 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z
bpy.context.scene.update()
# compensate for backwards slide:
model.location -= model.matrix_world.col[2].xyz * 0.125
elif typ == 'chair':
# model.rotation_euler.z = ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.24 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z
elif typ == 'table':
# model.rotation_euler.z = ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.5 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z | imapper/blender/replace_objects_w_models.py | from math import radians
import bpy
import os
from mathutils import Vector, Matrix
def get_max(ob):
mx = Vector((-1000., -1000., -1000.))
for vx in ob.data.vertices:
p = ob.matrix_world * vx.co
mx.x = max(mx.x, p.x)
mx.y = max(mx.y, p.y)
mx.z = max(mx.z, p.z)
return mx
floor = bpy.data.objects['floor']
bpy.ops.object.select_all(action="DESELECT")
for ob in bpy.data.objects:
if not ob.name.startswith('Object.'):
continue
parts = ob.name[7:].split('_')
oid = int(parts[0])
typ = parts[1]
part = parts[2]
if '-' in part:
part = part[:part.index('-')]
name_model = None
if typ == 'table':
if part != 'top':
continue
else:
name_model = 'table'
elif typ == 'couch' or typ == 'chair':
if part != 'seat':
continue
else:
name_model = typ
elif typ == 'shelf':
name_model = 'shelf'
assert name_model is not None, "Nooo: {}".format(parts)
name_model = os.path.join(os.path.dirname(os.path.abspath(__file__)),
os.pardir, os.pardir, 'models',
'{}.obj'.format(name_model))
bpy.ops.import_scene.obj(filepath=name_model, use_split_objects=True)
model = bpy.context.selected_objects[-1]
model.name = 'Model.{}_{}'.format(parts[0], typ)
print(name_model, model)
model.location = ob.location
model.rotation_euler = ob.rotation_euler
bpy.context.scene.update()
if typ == 'shelf':
model.matrix_world *= Matrix.Rotation(radians(90), 4, 'X')
elif typ == 'couch':
# model.rotation_euler.z = 3.14159 + ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y + 0.2 # slide bwards
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x + 0.26
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.4925 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z
bpy.context.scene.update()
# compensate for backwards slide:
model.location -= model.matrix_world.col[2].xyz * 0.125
elif typ == 'chair':
# model.rotation_euler.z = ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.24 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z
elif typ == 'table':
# model.rotation_euler.z = ob.rotation_euler.z
model.matrix_world *= Matrix.Rotation(radians(-90), 4, 'X')
bpy.context.scene.update()
model.dimensions.z = ob.dimensions.y
bpy.context.scene.update()
model.dimensions.x = ob.dimensions.x
bpy.context.scene.update()
mx = get_max(ob)
model.dimensions.y = 0.5 / (mx.z - floor.location.z)
bpy.ops.object.select_pattern(pattern='floor', extend=True)
bpy.context.scene.objects.active = floor
bpy.ops.object.align(align_mode='OPT_3', align_axis={'Z'})
model.location.z += floor.dimensions.z | 0.466359 | 0.363816 |
import datetime
import json
import pathlib
import re
import sys
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
from vaccine_feed_ingest.utils.normalize import normalize_phone, normalize_url
logger = getLogger(__file__)
def _get_id(site: dict) -> str:
loc_id = site["Event Location Id"]
return f"nc_myspot_gov:{loc_id}"
def _get_name(site: dict) -> str:
return site["Provider Location Name"]
def _get_address(site: dict):
return schema.Address(
street1=site["Street Address"],
street2=site["Street Address 2"],
city=site["City"],
state=site["State"],
zip=site["Postal Code"],
)
def _get_location(site: dict):
if site["latitude"] == "" or site["longitude"] == "":
return None
return schema.LatLng(
latitude=float(site["latitude"]),
longitude=float(site["longitude"]),
)
def _get_contacts(site: dict):
ret = []
if site["Appointment Phone"]:
for phone in normalize_phone(site["Appointment Phone"]):
ret.append(phone)
url = site["Web Address"]
# Some URLs have multiple schemes.
valid_url = re.match(r"(https?:\/\/)*(.+)", url)
if (
url == "http://"
or url == "https://"
or url == "none"
or url == ""
or url.startswith("Please email")
):
return ret
elif valid_url is not None:
if valid_url.group(1) is None:
url = valid_url.group(2)
else:
url = f"{valid_url.group(1)}{valid_url.group(2)}"
url = normalize_url(url)
ret.append(schema.Contact(website=url))
else:
logger.warning(f"Unknown, invalid URL: {url}")
return ret
def _normalize_date(dt: str):
if dt == "":
return None
return dt[0:4] + "-" + dt[4:6] + "-" + dt[6:8]
def _get_opening_dates(site: dict):
if site["Start Date"] == "" and site["End Date"]:
return None
return [
schema.OpenDate(
opens=_normalize_date(site["Start Date"]),
closes=_normalize_date(site["End Date"]),
)
]
def _get_inventories(site: dict):
ret = []
if site["Moderna"] == "Y":
ret.append(schema.Vaccine(vaccine="moderna", supply_level="in_stock"))
if site["Pfizer"] == "Y":
ret.append(schema.Vaccine(vaccine="pfizer_biontech", supply_level="in_stock"))
if site["Janssen"] == "Y":
ret.append(
schema.Vaccine(vaccine="johnson_johnson_janssen", supply_level="in_stock")
)
if site["Moderna"] == "N":
ret.append(schema.Vaccine(vaccine="moderna", supply_level="out_of_stock"))
if site["Pfizer"] == "N":
ret.append(
schema.Vaccine(vaccine="pfizer_biontech", supply_level="out_of_stock")
)
if site["Janssen"] == "N":
ret.append(
schema.Vaccine(
vaccine="johnson_johnson_janssen", supply_level="out_of_stock"
)
)
return ret
def _get_organization(site: dict):
if site["Organization Name"] == "":
return None
if site["Organization Name"] == "Walmart, Inc.":
return schema.Organization(name=site["Organization Name"], id="walmart")
return schema.Organization(name=site["Organization Name"])
def _get_notes(site: dict):
ret = []
ret.append("cvms_scheduling__nc_specific:" + site["CVMS Scheduling"])
ret.append(
"cvms_info__nc_specific:https://covid19.ncdhhs.gov/vaccines/providers/covid-19-vaccine-management-system-cvms"
)
if site["Event Type"] != "" and site["Event Type"] != "Not Applicable":
ret.append("event_type:" + site["Event Type"])
return ret
def _get_source(site: dict, timestamp: str) -> schema.Source:
return schema.Source(
data=site,
fetched_at=timestamp,
fetched_from_uri="https://myspot.nc.gov/api/get-vaccine-locations",
id=site["Event Location Id"],
source="nc_myspot_gov",
)
def normalize(site: dict, timestamp: str) -> str:
normalized = schema.NormalizedLocation(
id=_get_id(site),
name=_get_name(site),
address=_get_address(site),
location=_get_location(site),
contact=_get_contacts(site),
opening_dates=_get_opening_dates(site),
inventory=_get_inventories(site),
parent_organization=_get_organization(site),
notes=_get_notes(site),
source=_get_source(site, timestamp),
).dict()
return normalized
parsed_at_timestamp = datetime.datetime.utcnow().isoformat()
input_dir = pathlib.Path(sys.argv[2])
input_file = input_dir / "nc_data.parsed.ndjson"
output_dir = pathlib.Path(sys.argv[1])
output_file = output_dir / "nc_data.normalized.ndjson"
with input_file.open() as parsed_lines:
with output_file.open("w") as fout:
for line in parsed_lines:
site_blob = json.loads(line)
normalized_site = normalize(site_blob, parsed_at_timestamp)
json.dump(normalized_site, fout)
fout.write("\n") | vaccine_feed_ingest/runners/nc/myspot_gov/normalize.py |
import datetime
import json
import pathlib
import re
import sys
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
from vaccine_feed_ingest.utils.normalize import normalize_phone, normalize_url
logger = getLogger(__file__)
def _get_id(site: dict) -> str:
loc_id = site["Event Location Id"]
return f"nc_myspot_gov:{loc_id}"
def _get_name(site: dict) -> str:
return site["Provider Location Name"]
def _get_address(site: dict):
return schema.Address(
street1=site["Street Address"],
street2=site["Street Address 2"],
city=site["City"],
state=site["State"],
zip=site["Postal Code"],
)
def _get_location(site: dict):
if site["latitude"] == "" or site["longitude"] == "":
return None
return schema.LatLng(
latitude=float(site["latitude"]),
longitude=float(site["longitude"]),
)
def _get_contacts(site: dict):
ret = []
if site["Appointment Phone"]:
for phone in normalize_phone(site["Appointment Phone"]):
ret.append(phone)
url = site["Web Address"]
# Some URLs have multiple schemes.
valid_url = re.match(r"(https?:\/\/)*(.+)", url)
if (
url == "http://"
or url == "https://"
or url == "none"
or url == ""
or url.startswith("Please email")
):
return ret
elif valid_url is not None:
if valid_url.group(1) is None:
url = valid_url.group(2)
else:
url = f"{valid_url.group(1)}{valid_url.group(2)}"
url = normalize_url(url)
ret.append(schema.Contact(website=url))
else:
logger.warning(f"Unknown, invalid URL: {url}")
return ret
def _normalize_date(dt: str):
if dt == "":
return None
return dt[0:4] + "-" + dt[4:6] + "-" + dt[6:8]
def _get_opening_dates(site: dict):
if site["Start Date"] == "" and site["End Date"]:
return None
return [
schema.OpenDate(
opens=_normalize_date(site["Start Date"]),
closes=_normalize_date(site["End Date"]),
)
]
def _get_inventories(site: dict):
ret = []
if site["Moderna"] == "Y":
ret.append(schema.Vaccine(vaccine="moderna", supply_level="in_stock"))
if site["Pfizer"] == "Y":
ret.append(schema.Vaccine(vaccine="pfizer_biontech", supply_level="in_stock"))
if site["Janssen"] == "Y":
ret.append(
schema.Vaccine(vaccine="johnson_johnson_janssen", supply_level="in_stock")
)
if site["Moderna"] == "N":
ret.append(schema.Vaccine(vaccine="moderna", supply_level="out_of_stock"))
if site["Pfizer"] == "N":
ret.append(
schema.Vaccine(vaccine="pfizer_biontech", supply_level="out_of_stock")
)
if site["Janssen"] == "N":
ret.append(
schema.Vaccine(
vaccine="johnson_johnson_janssen", supply_level="out_of_stock"
)
)
return ret
def _get_organization(site: dict):
if site["Organization Name"] == "":
return None
if site["Organization Name"] == "Walmart, Inc.":
return schema.Organization(name=site["Organization Name"], id="walmart")
return schema.Organization(name=site["Organization Name"])
def _get_notes(site: dict):
ret = []
ret.append("cvms_scheduling__nc_specific:" + site["CVMS Scheduling"])
ret.append(
"cvms_info__nc_specific:https://covid19.ncdhhs.gov/vaccines/providers/covid-19-vaccine-management-system-cvms"
)
if site["Event Type"] != "" and site["Event Type"] != "Not Applicable":
ret.append("event_type:" + site["Event Type"])
return ret
def _get_source(site: dict, timestamp: str) -> schema.Source:
return schema.Source(
data=site,
fetched_at=timestamp,
fetched_from_uri="https://myspot.nc.gov/api/get-vaccine-locations",
id=site["Event Location Id"],
source="nc_myspot_gov",
)
def normalize(site: dict, timestamp: str) -> str:
normalized = schema.NormalizedLocation(
id=_get_id(site),
name=_get_name(site),
address=_get_address(site),
location=_get_location(site),
contact=_get_contacts(site),
opening_dates=_get_opening_dates(site),
inventory=_get_inventories(site),
parent_organization=_get_organization(site),
notes=_get_notes(site),
source=_get_source(site, timestamp),
).dict()
return normalized
parsed_at_timestamp = datetime.datetime.utcnow().isoformat()
input_dir = pathlib.Path(sys.argv[2])
input_file = input_dir / "nc_data.parsed.ndjson"
output_dir = pathlib.Path(sys.argv[1])
output_file = output_dir / "nc_data.normalized.ndjson"
with input_file.open() as parsed_lines:
with output_file.open("w") as fout:
for line in parsed_lines:
site_blob = json.loads(line)
normalized_site = normalize(site_blob, parsed_at_timestamp)
json.dump(normalized_site, fout)
fout.write("\n") | 0.361165 | 0.183466 |
import uuid
from pyvultr.base_api import SupportHttpMethod
from pyvultr.v2 import StartupScript
from pyvultr.v2.enums import StartupScriptType
from tests.v2 import BaseTestV2
class TestStartupScript(BaseTestV2):
def test_list(self):
"""Test list scripts."""
with self._get("response/startup_scripts") as mock:
_excepted_result = mock.python_body["startup_scripts"][0]
excepted_result = StartupScript.from_dict(_excepted_result)
_real_result = self.api_v2.startup_script.list(capacity=1)
real_result: StartupScript = _real_result.first()
self.assertEqual(mock.url, "https://api.vultr.com/v2/startup-scripts")
self.assertEqual(mock.method, SupportHttpMethod.GET.value)
self.assertEqual(real_result, excepted_result)
def test_create(self):
"""Test create script."""
with self._post("response/startup_script", expected_returned=StartupScript, status_code=201) as mock:
excepted_result = mock.python_body
name = "test_name_1"
script = "test_script"
script_type = StartupScriptType.PXE
real_result: StartupScript = self.api_v2.startup_script.create(
name=name,
script=script,
script_type=script_type,
)
self.assertEqual(mock.url, "https://api.vultr.com/v2/startup-scripts")
self.assertEqual(mock.method, SupportHttpMethod.POST.value)
self.assertEqual(mock.req_json["name"], name)
self.assertEqual(mock.req_json["script"], script)
self.assertEqual(mock.req_json["type"], script_type.value)
self.assertEqual(mock.status_code, 201)
self.assertEqual(real_result, excepted_result)
def test_get(self):
"""Test get script."""
with self._get("response/startup_script", expected_returned=StartupScript) as mock:
excepted_result = mock.python_body
startup_script_id = str(uuid.uuid4())
real_result: StartupScript = self.api_v2.startup_script.get(startup_id=startup_script_id)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.GET.value)
self.assertEqual(real_result, excepted_result)
def test_update(self):
"""Test update script."""
with self._patch(status_code=204) as mock:
startup_script_id = str(uuid.uuid4())
name = "test_name_2"
real_result: StartupScript = self.api_v2.startup_script.update(startup_script_id, name=name)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.PATCH.value)
self.assertEqual(mock.req_json["name"], name)
self.assertEqual(mock.status_code, 204)
self.assertIsNone(real_result)
def test_delete(self):
"""Test delete script."""
with self._delete(status_code=204) as mock:
startup_script_id = str(uuid.uuid4())
self.api_v2.startup_script.delete(startup_id=startup_script_id)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.DELETE.value)
self.assertEqual(mock.status_code, 204) | tests/v2/test_startup_script.py | import uuid
from pyvultr.base_api import SupportHttpMethod
from pyvultr.v2 import StartupScript
from pyvultr.v2.enums import StartupScriptType
from tests.v2 import BaseTestV2
class TestStartupScript(BaseTestV2):
def test_list(self):
"""Test list scripts."""
with self._get("response/startup_scripts") as mock:
_excepted_result = mock.python_body["startup_scripts"][0]
excepted_result = StartupScript.from_dict(_excepted_result)
_real_result = self.api_v2.startup_script.list(capacity=1)
real_result: StartupScript = _real_result.first()
self.assertEqual(mock.url, "https://api.vultr.com/v2/startup-scripts")
self.assertEqual(mock.method, SupportHttpMethod.GET.value)
self.assertEqual(real_result, excepted_result)
def test_create(self):
"""Test create script."""
with self._post("response/startup_script", expected_returned=StartupScript, status_code=201) as mock:
excepted_result = mock.python_body
name = "test_name_1"
script = "test_script"
script_type = StartupScriptType.PXE
real_result: StartupScript = self.api_v2.startup_script.create(
name=name,
script=script,
script_type=script_type,
)
self.assertEqual(mock.url, "https://api.vultr.com/v2/startup-scripts")
self.assertEqual(mock.method, SupportHttpMethod.POST.value)
self.assertEqual(mock.req_json["name"], name)
self.assertEqual(mock.req_json["script"], script)
self.assertEqual(mock.req_json["type"], script_type.value)
self.assertEqual(mock.status_code, 201)
self.assertEqual(real_result, excepted_result)
def test_get(self):
"""Test get script."""
with self._get("response/startup_script", expected_returned=StartupScript) as mock:
excepted_result = mock.python_body
startup_script_id = str(uuid.uuid4())
real_result: StartupScript = self.api_v2.startup_script.get(startup_id=startup_script_id)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.GET.value)
self.assertEqual(real_result, excepted_result)
def test_update(self):
"""Test update script."""
with self._patch(status_code=204) as mock:
startup_script_id = str(uuid.uuid4())
name = "test_name_2"
real_result: StartupScript = self.api_v2.startup_script.update(startup_script_id, name=name)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.PATCH.value)
self.assertEqual(mock.req_json["name"], name)
self.assertEqual(mock.status_code, 204)
self.assertIsNone(real_result)
def test_delete(self):
"""Test delete script."""
with self._delete(status_code=204) as mock:
startup_script_id = str(uuid.uuid4())
self.api_v2.startup_script.delete(startup_id=startup_script_id)
self.assertEqual(mock.url, f"https://api.vultr.com/v2/startup-scripts/{startup_script_id}")
self.assertEqual(mock.method, SupportHttpMethod.DELETE.value)
self.assertEqual(mock.status_code, 204) | 0.68721 | 0.201833 |
# Add Kitchen assets adept_envs/ folder to the python path.
import sys
import os
parent_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(parent_dir, "kitchen_assets/adept_envs"))
import time
import numpy as np
import mujoco_py
import copy
from adept_envs.franka.kitchen_multitask_v0 import KitchenTaskRelaxV1
component_to_state_idx = {
'arm': [0, 1, 2, 3, 4, 5, 6, 7, 8],
'burner0': [9, 10],
'burner1': [11, 12],
'burner2': [13, 14],
'burner3': [15, 16],
'light_switch': [17, 18],
'slide_cabinet': [19],
'hinge_cabinet': [20, 21],
'microwave': [22],
}
# clean goal state
goal_states = np.array([[
-4.1336253e-01,
-1.6970085e+00,
1.4286385e+00,
-2.5005307e+00,
6.2198675e-01,
1.2632011e+00,
8.8903642e-01,
4.3514766e-02,
7.9217982e-03,
-5.1586074e-04,
4.8548312e-04,
-5.4527864e-06,
6.3510129e-06,
6.0837720e-05,
-3.3861103e-05,
6.6394619e-05,
-1.9801613e-05,
-1.2477605e-04,
3.8065159e-04,
-1.5148541e-04,
-9.2229841e-04,
7.2293887e-03,
6.9650509e-03,
]])
# supported_tasks = ['close_microwave', 'burner0', 'burner1', 'burner2', 'burner3', 'light_switch', 'slide_cabinet', 'hinge_cabinet']
shaped_reward_tasks = ['microwave', 'light_switch', 'slide_cabinet', 'hinge_cabinet']
initial_states = {}
def convert_to_initial_state(component_names, values):
new_init_state = goal_states[0].copy()
for name, val in zip(component_names, values):
new_init_state[component_to_state_idx[name]] = np.array(val)
return new_init_state
# states from https://github.com/rail-berkeley/d4rl/blob/master/d4rl/kitchen/kitchen_envs.py
initial_states['microwave'] = convert_to_initial_state(['microwave'], [[-0.7]])
# initial_states['burner1'] = convert_to_initial_state('burner1', [-0.88, -0.01])
# initial_states['burner3'] = convert_to_initial_state('burner3', [-0.92, -0.01])
initial_states['light_switch'] = convert_to_initial_state(['light_switch'], [[-0.69, -0.05]])
initial_states['slide_cabinet'] = convert_to_initial_state(['slide_cabinet'], [[0.37]])
initial_states['hinge_cabinet'] = convert_to_initial_state(['hinge_cabinet'], [[0., 1.45]])
initial_states['micro_hinge'] = convert_to_initial_state(['microwave', 'hinge_cabinet'], [[-0.7], [0., 1.45]])
initial_states['micro_slide'] = convert_to_initial_state(['microwave', 'slide_cabinet'], [[-0.7], [0.37]])
initial_states['micro_light'] = convert_to_initial_state(['microwave', 'light_switch'], [[-0.7], [-0.69, -0.05]])
initial_states['light_slide'] = convert_to_initial_state(['light_switch', 'slide_cabinet'], [[-0.69, -0.05], [0.37]])
initial_states['light_hinge'] = convert_to_initial_state(['light_switch', 'hinge_cabinet'], [[-0.69, -0.05], [0., 1.45]])
initial_states['slide_hinge'] = convert_to_initial_state(['slide_cabinet', 'hinge_cabinet'], [[0.37], [0., 1.45]])
initial_states['all_pairs'] = np.array([initial_states['micro_hinge'].copy(),
initial_states['micro_slide'].copy(),
initial_states['micro_light'].copy(),
initial_states['light_slide'].copy(),
initial_states['light_hinge'].copy(),
initial_states['slide_hinge'].copy()])
class Kitchen(KitchenTaskRelaxV1):
def __init__(self, task="all_pairs", reward_type="dense"):
self._initial_states = copy.deepcopy(initial_states)
self._goal_states = copy.deepcopy(goal_states)
if reward_type != 'dense':
raise ValueError("Kitchen environment only supports dense rewards.")
self._viewers = {}
self.viewer = None
self._reward_type = reward_type
self._task = task
super().__init__()
def get_task(self):
return self._task
def get_init_states(self):
return self._initial_states['all_pairs']
def _get_obs(self):
ob = super()._get_obs()
return ob
def get_next_goal(self):
return self._goal_states[0]
def reset_goal(self, goal=None):
if goal is None:
goal = self.get_next_goal()
self.set_goal(goal)
def reset_model(self):
reset_pos = self.init_qpos[:].copy()
reset_vel = self.init_qvel[:].copy()
if self._task == 'all_pairs':
random_idx = np.random.randint(initial_states['all_pairs'].shape[0])
reset_pos[9:] = self._initial_states[self._task][random_idx, 9:]
else:
reset_pos[9:] = self._initial_states[self._task][9:]
self.robot.reset(self, reset_pos, reset_vel)
for _ in range(10):
new_pos = self.midpoint_pos
self.sim.data.mocap_pos[:] = new_pos.copy()
a = np.zeros(9)
for _ in range(10):
self.robot.step(
self, a, step_duration=self.skip * self.model.opt.timestep)
self.reset_goal()
return self._get_obs()
def _get_reward_n_score(self, obs_dict):
reward_dict = {}
if isinstance(obs_dict, dict):
obs = np.append(np.append(obs_dict['qp'], obs_dict['obj_qp']), obs_dict['goal'])
else:
obs = obs_dict
task_to_site = {'microwave': 'microhandle_site',
'hinge_cabinet': 'hinge_site2',
'slide_cabinet': 'slide_site',
'burner0': 'knob1_site',
'burner1': 'knob2_site',
'burner2': 'knob3_site',
'burner3': 'knob4_site',
'light_switch': 'light_site',}
reward_dict['true_reward'] = -10 * np.linalg.norm(obs[9:23] - obs[9+23:23+23])
reaching_component = False
for key in component_to_state_idx.keys():
if key == 'arm':
continue
cur_idxs = np.array(component_to_state_idx[key])
num_idxs = len(component_to_state_idx[key])
if np.linalg.norm(obs[cur_idxs] - obs[cur_idxs + 23]) < num_idxs * 0.01:
reward_dict['true_reward'] += 1
elif not reaching_component:
reaching_component = True
reward_dict['true_reward'] += -0.5 * np.linalg.norm(self.sim.data.mocap_pos[0] - \
self.sim.data.get_site_xpos(task_to_site[key]))
reward_dict['r_total'] = reward_dict['true_reward']
score = 0.
return reward_dict, score
def compute_reward(self, obs):
return self._get_reward_n_score(obs)[0]['r_total']
def is_successful(self, obs=None):
if obs is None:
obs = self._get_obs()
return bool(np.linalg.norm(obs[9:23] - obs[9+23:23+23]) <= 0.3)
def step(self, a, b=None):
obs, reward, done, info = super().step(a, b)
return obs, reward, done, info
# functions for rendering
def viewer_setup(self):
self.viewer.cam.distance = 3.0
self.viewer.cam.elevation = -30
self.viewer.cam.azimuth = 120
def _get_viewer(self, mode):
self.viewer = self._viewers.get(mode)
if self.viewer is None:
if mode == 'human':
self.viewer = mujoco_py.MjViewer(self.sim)
if 'rgb_array' in mode:
self.viewer = mujoco_py.MjRenderContextOffscreen(self.sim)
self._viewers[mode] = self.viewer
self.viewer_setup()
return self.viewer
def render(self, mode='human', width=640, height=480):
if mode == 'human':
self._get_viewer(mode).render()
elif mode == 'rgb_array':
self._get_viewer(mode).render(width, height)
return self.viewer.read_pixels(width, height, depth=False)[::-1, :, :]
else:
raise ValueError("mode can only be either 'human' or 'rgb_array'")
def close(self):
if self.viewer is not None:
if isinstance(self.viewer, mujoco_py.MjViewer):
glfw.destroy_window(self.viewer.window)
self.viewer = None | envs/kitchen.py |
# Add Kitchen assets adept_envs/ folder to the python path.
import sys
import os
parent_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(parent_dir, "kitchen_assets/adept_envs"))
import time
import numpy as np
import mujoco_py
import copy
from adept_envs.franka.kitchen_multitask_v0 import KitchenTaskRelaxV1
component_to_state_idx = {
'arm': [0, 1, 2, 3, 4, 5, 6, 7, 8],
'burner0': [9, 10],
'burner1': [11, 12],
'burner2': [13, 14],
'burner3': [15, 16],
'light_switch': [17, 18],
'slide_cabinet': [19],
'hinge_cabinet': [20, 21],
'microwave': [22],
}
# clean goal state
goal_states = np.array([[
-4.1336253e-01,
-1.6970085e+00,
1.4286385e+00,
-2.5005307e+00,
6.2198675e-01,
1.2632011e+00,
8.8903642e-01,
4.3514766e-02,
7.9217982e-03,
-5.1586074e-04,
4.8548312e-04,
-5.4527864e-06,
6.3510129e-06,
6.0837720e-05,
-3.3861103e-05,
6.6394619e-05,
-1.9801613e-05,
-1.2477605e-04,
3.8065159e-04,
-1.5148541e-04,
-9.2229841e-04,
7.2293887e-03,
6.9650509e-03,
]])
# supported_tasks = ['close_microwave', 'burner0', 'burner1', 'burner2', 'burner3', 'light_switch', 'slide_cabinet', 'hinge_cabinet']
shaped_reward_tasks = ['microwave', 'light_switch', 'slide_cabinet', 'hinge_cabinet']
initial_states = {}
def convert_to_initial_state(component_names, values):
new_init_state = goal_states[0].copy()
for name, val in zip(component_names, values):
new_init_state[component_to_state_idx[name]] = np.array(val)
return new_init_state
# states from https://github.com/rail-berkeley/d4rl/blob/master/d4rl/kitchen/kitchen_envs.py
initial_states['microwave'] = convert_to_initial_state(['microwave'], [[-0.7]])
# initial_states['burner1'] = convert_to_initial_state('burner1', [-0.88, -0.01])
# initial_states['burner3'] = convert_to_initial_state('burner3', [-0.92, -0.01])
initial_states['light_switch'] = convert_to_initial_state(['light_switch'], [[-0.69, -0.05]])
initial_states['slide_cabinet'] = convert_to_initial_state(['slide_cabinet'], [[0.37]])
initial_states['hinge_cabinet'] = convert_to_initial_state(['hinge_cabinet'], [[0., 1.45]])
initial_states['micro_hinge'] = convert_to_initial_state(['microwave', 'hinge_cabinet'], [[-0.7], [0., 1.45]])
initial_states['micro_slide'] = convert_to_initial_state(['microwave', 'slide_cabinet'], [[-0.7], [0.37]])
initial_states['micro_light'] = convert_to_initial_state(['microwave', 'light_switch'], [[-0.7], [-0.69, -0.05]])
initial_states['light_slide'] = convert_to_initial_state(['light_switch', 'slide_cabinet'], [[-0.69, -0.05], [0.37]])
initial_states['light_hinge'] = convert_to_initial_state(['light_switch', 'hinge_cabinet'], [[-0.69, -0.05], [0., 1.45]])
initial_states['slide_hinge'] = convert_to_initial_state(['slide_cabinet', 'hinge_cabinet'], [[0.37], [0., 1.45]])
initial_states['all_pairs'] = np.array([initial_states['micro_hinge'].copy(),
initial_states['micro_slide'].copy(),
initial_states['micro_light'].copy(),
initial_states['light_slide'].copy(),
initial_states['light_hinge'].copy(),
initial_states['slide_hinge'].copy()])
class Kitchen(KitchenTaskRelaxV1):
def __init__(self, task="all_pairs", reward_type="dense"):
self._initial_states = copy.deepcopy(initial_states)
self._goal_states = copy.deepcopy(goal_states)
if reward_type != 'dense':
raise ValueError("Kitchen environment only supports dense rewards.")
self._viewers = {}
self.viewer = None
self._reward_type = reward_type
self._task = task
super().__init__()
def get_task(self):
return self._task
def get_init_states(self):
return self._initial_states['all_pairs']
def _get_obs(self):
ob = super()._get_obs()
return ob
def get_next_goal(self):
return self._goal_states[0]
def reset_goal(self, goal=None):
if goal is None:
goal = self.get_next_goal()
self.set_goal(goal)
def reset_model(self):
reset_pos = self.init_qpos[:].copy()
reset_vel = self.init_qvel[:].copy()
if self._task == 'all_pairs':
random_idx = np.random.randint(initial_states['all_pairs'].shape[0])
reset_pos[9:] = self._initial_states[self._task][random_idx, 9:]
else:
reset_pos[9:] = self._initial_states[self._task][9:]
self.robot.reset(self, reset_pos, reset_vel)
for _ in range(10):
new_pos = self.midpoint_pos
self.sim.data.mocap_pos[:] = new_pos.copy()
a = np.zeros(9)
for _ in range(10):
self.robot.step(
self, a, step_duration=self.skip * self.model.opt.timestep)
self.reset_goal()
return self._get_obs()
def _get_reward_n_score(self, obs_dict):
reward_dict = {}
if isinstance(obs_dict, dict):
obs = np.append(np.append(obs_dict['qp'], obs_dict['obj_qp']), obs_dict['goal'])
else:
obs = obs_dict
task_to_site = {'microwave': 'microhandle_site',
'hinge_cabinet': 'hinge_site2',
'slide_cabinet': 'slide_site',
'burner0': 'knob1_site',
'burner1': 'knob2_site',
'burner2': 'knob3_site',
'burner3': 'knob4_site',
'light_switch': 'light_site',}
reward_dict['true_reward'] = -10 * np.linalg.norm(obs[9:23] - obs[9+23:23+23])
reaching_component = False
for key in component_to_state_idx.keys():
if key == 'arm':
continue
cur_idxs = np.array(component_to_state_idx[key])
num_idxs = len(component_to_state_idx[key])
if np.linalg.norm(obs[cur_idxs] - obs[cur_idxs + 23]) < num_idxs * 0.01:
reward_dict['true_reward'] += 1
elif not reaching_component:
reaching_component = True
reward_dict['true_reward'] += -0.5 * np.linalg.norm(self.sim.data.mocap_pos[0] - \
self.sim.data.get_site_xpos(task_to_site[key]))
reward_dict['r_total'] = reward_dict['true_reward']
score = 0.
return reward_dict, score
def compute_reward(self, obs):
return self._get_reward_n_score(obs)[0]['r_total']
def is_successful(self, obs=None):
if obs is None:
obs = self._get_obs()
return bool(np.linalg.norm(obs[9:23] - obs[9+23:23+23]) <= 0.3)
def step(self, a, b=None):
obs, reward, done, info = super().step(a, b)
return obs, reward, done, info
# functions for rendering
def viewer_setup(self):
self.viewer.cam.distance = 3.0
self.viewer.cam.elevation = -30
self.viewer.cam.azimuth = 120
def _get_viewer(self, mode):
self.viewer = self._viewers.get(mode)
if self.viewer is None:
if mode == 'human':
self.viewer = mujoco_py.MjViewer(self.sim)
if 'rgb_array' in mode:
self.viewer = mujoco_py.MjRenderContextOffscreen(self.sim)
self._viewers[mode] = self.viewer
self.viewer_setup()
return self.viewer
def render(self, mode='human', width=640, height=480):
if mode == 'human':
self._get_viewer(mode).render()
elif mode == 'rgb_array':
self._get_viewer(mode).render(width, height)
return self.viewer.read_pixels(width, height, depth=False)[::-1, :, :]
else:
raise ValueError("mode can only be either 'human' or 'rgb_array'")
def close(self):
if self.viewer is not None:
if isinstance(self.viewer, mujoco_py.MjViewer):
glfw.destroy_window(self.viewer.window)
self.viewer = None | 0.524882 | 0.389837 |
import os, uuid, subprocess, logging, time, re
from .db_utils import DBUtils
from CTFd import utils
from .models import ADAChallenge, GlowwormContainers, GlowwormCheckLog, GlowwormAttacks
from .extensions import get_round
from CTFd.utils.logging import log
from CTFd.models import db, Users, Teams
from .extensions import get_mode, teampasswd
class DockerUtils:
@staticmethod
def get_socket():
configs = DBUtils.get_all_configs()
socket = configs.get("docker_api_url")
return socket
@staticmethod
def init_teams(counts):
platform_name = utils.get_config("ctf_name")
print(platform_name)
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
print(platformDir)
try:
for index in counts:
if not isinstance(index, Teams):
if index.type == "admin":
pass
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
print(teamDir)
if (os.path.exists(platformDir) == False):
os.mkdir(platformDir)
os.mkdir(teamDir)
elif (os.path.exists(teamDir) == False):
os.mkdir(teamDir)
return True
except Exception as e:
return False
@staticmethod
def check_env(challenge_id):
from .schedule import scheduler
with scheduler.app.app_context():
try:
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
dirname = challenge.dirname.split("/")[1]
containers = GlowwormContainers.query.filter_by(challenge_id=challenge_id).all()
for index in containers:
if mode == "users":
victim = Users.query.filter_by(id=index.user_id).first()
victim_name = victim.name
victim_id = victim.id
team_id = victim.team_id if victim.team_id else None
else:
victim = None
team = Teams.query.filter_by(id=index.user_id).first()
team_id = team.id
victim_id = team_id
victim_name = team.name
check_file = os.path.join(basePath, challenge.dirname, "conf", "check.py")
# Todo: excute check file in containers
command = "python3 '%s' %s %s" % (check_file, index.ip, index.service_port)
print(command)
# 容器Check
rq = os.popen(command).read()
r = "".join(re.findall(r'team..', rq))
if r == "":
msg = index.docker_id + " seems ok."
else:
msg = index.docker_id + " seems down."
check_log = GlowwormCheckLog(
user_id=victim_id,
team_id=team_id,
victim_user_id=victim_id,
victim_team_id=team_id,
challenge_id=challenge.id,
ip="127.0.0.1",
provided=msg,
)
check = GlowwormAttacks(
attack_id=None,
attack_name=None,
victim_id=victim_id,
victim_name=victim_name,
docker_id=index.docker_id,
envname=index.docker_id.split("_", 1)[1],
flag="",
round=get_round()
)
db.session.add(check)
db.session.add(check_log)
print(check)
print(check_log)
print(msg)
db.session.commit()
db.session.close()
return True
except Exception as e:
print(e)
return False
@staticmethod
def build_env(challenge_id):
platform_name = utils.get_config("ctf_name")
print(platform_name)
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
envPath = os.path.join(basePath, challenge.dirname)
command = 'cd ' + envPath + ' && docker build -f ' + envPath + '/Dockerfile -t ' + challenge.image_name + " ."
print(command)
try:
os.system(command)
return True
except Exception as e:
print(e)
return str(e)
@staticmethod
def gen_env(language="PHP", rootpasswd="", teamPath="", key="", teamid="", interval=300):
# "*/5 * * * * python /conf/flag.py team3_web_pyblog Unknow2Kg 300"
# f = "*/5 * * * * python /conf/flag.py %s %s %s"
# echo ${f:12}
service = {}
# PHP
service['PHP'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
chown -R web:web /var/www/html
chmod -R 777 /var/www/html
if [ -f "/conf/apache2.sh" ]; then
chmod +x /conf/apache2.sh
/conf/apache2.sh
fi
chown -R mysql:mysql /var/lib/mysql /var/run/mysqld
service mysql start;
/etc/init.d/ssh start;
sleep 2
mysql -u root < /var/www/html/*.sql
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
/bin/bash
'''
# PWN
service['PWN'] = '''#!/bin/sh
echo pwn:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
f="*/5 * * * * python /conf/flag.py %s %s %s"
# echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
'''
# Django
service['Django'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
/etc/init.d/ssh start;
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
/bin/bash
'''
# Node
service['Node'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
/etc/init.d/ssh start;
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
/bin/bash
'''
webpasswd = <PASSWORD>(key)
servicesh = service[language] % (webpasswd, rootpasswd, key, teamid, interval)
print(servicesh)
with open(os.path.join(teamPath, "conf", "service.sh"), 'w') as f:
f.write(servicesh)
return webpasswd
@staticmethod
def copy_env(source, dest):
try:
if not (os.path.exists(dest)):
# TODO: 重构
os.system("mkdir -p %s" % dest)
command = 'cp -r "%s" "%s"' % (source, dest)
print(command)
os.system(command)
return True
else:
command = 'cp -r "%s" "%s"' % (source, dest)
print(command)
os.system(command)
return True
except Exception as e:
print(e)
return False
@staticmethod
def delete_env(counts, challenge_id):
try:
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
for index in counts:
if mode == "users" and index.type == "admin":
pass
else:
dirname = challenge.dirname.split("/")[1]
envPath = os.path.join(basePath, challenge.dirname)
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
teamEnvDir = os.path.join(teamDir, dirname)
# 容器删除
name = "Team{}_{}".format(str(index.id), dirname)
print(name)
os.system("docker stop " + name)
os.system("docker rm " + name)
instance = GlowwormContainers.query.filter_by(docker_id=name).first()
if instance == None:
pass
else:
db.session.delete(instance)
db.session.commit()
# 目录删除
command = "rm -rf '%s'" % teamEnvDir
print(command)
os.system(command)
challenge.env_status = False
db.session.commit()
return True
except Exception as e:
print(e)
return False
@staticmethod
def run_env(counts, challenge_id):
try:
configs = DBUtils.get_all_configs()
interval = configs.get("per_round") if configs.get("per_round") else "300"
cpu_limit = configs.get("cpu_limit") if configs.get("cpu_limit") else "0.5"
memory_limit = configs.get("memory_limit") if configs.get("memory_limit") else "512M"
rootpwd = configs.get("containers_key") if configs.get("containers_key") else "root"
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
for index in counts:
if mode == "users" and index.type == "admin":
pass
else:
dirname = challenge.dirname.split("/")[1]
envPath = os.path.join(basePath, challenge.dirname)
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
teamEnvDir = os.path.join(teamDir, dirname)
name = "Team{}_{}".format(str(index.id), dirname)
# 目录复制
DockerUtils.copy_env(envPath, teamDir)
# 容器动态信息初始化
# save random key
key = str(<KEY>())), platform_name + str(time.time())))
print(key)
instance_pwd = DockerUtils.gen_env(language=challenge.env_language, rootpasswd=<PASSWORD>, teamPath=teamEnvDir, key=key, teamid=name, interval=interval)
# choose alive random port
if configs.get("random_port") == "1":
fixedPorts = DBUtils.get_alive_ports()
insert_service_port = fixedPorts[0]
insert_ssh_port = fixedPorts[1]
else:
fixedPorts = 100 * int(challenge.id)
insert_service_port = int(str(fixedPorts + index.id) + "80")
insert_ssh_port = int(str(fixedPorts + index.id) + "22")
env_port = challenge.env_port if challenge.env_port != "" else "80"
confPath = os.path.join(teamEnvDir, "conf")
instance = GlowwormContainers(
user_id=index.id
, challenge_id=challenge_id
, docker_id=name
, ip=configs.get("direct_address")
, service_port=insert_service_port
, ssh_port=insert_ssh_port
, ssh_key=instance_pwd
, key=key
)
db.session.add(instance)
db.session.commit()
command = """#!/bin/sh
docker run -tid --restart=on-failure:10 --privileged --name %s --cpus=%s -m %s -v "%s":"%s" -p %s:%s -p %s:%s --network h1ve_frp_containers %s "/conf/service.sh"
""" % ( name, cpu_limit, memory_limit, confPath, "/conf", insert_service_port, env_port, insert_ssh_port, "22", challenge.image_name)
print(command)
with open(os.path.join(confPath, "docker.sh"), 'w') as f:
f.write(command)
# 启动容器
command = 'cd "%s" && chmod +x ./docker.sh service.sh && ./docker.sh' % confPath
print(command)
try:
os.system(command)
msg = name + " up."
log(
"glowworm",
"[{date}] {name} {msg}",
msg=msg,
)
except Exception as e:
# print(e)
msg = name + " up error." + str(e)
log(
"glowworm",
"[{date}] {name} {msg}",
msg=msg,
)
return str(e)
challenge.env_status = True
db.session.commit()
return True
except Exception as e:
return str(e) | CTFd/plugins/ctfd_glowworm/docker_utils.py | import os, uuid, subprocess, logging, time, re
from .db_utils import DBUtils
from CTFd import utils
from .models import ADAChallenge, GlowwormContainers, GlowwormCheckLog, GlowwormAttacks
from .extensions import get_round
from CTFd.utils.logging import log
from CTFd.models import db, Users, Teams
from .extensions import get_mode, teampasswd
class DockerUtils:
@staticmethod
def get_socket():
configs = DBUtils.get_all_configs()
socket = configs.get("docker_api_url")
return socket
@staticmethod
def init_teams(counts):
platform_name = utils.get_config("ctf_name")
print(platform_name)
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
print(platformDir)
try:
for index in counts:
if not isinstance(index, Teams):
if index.type == "admin":
pass
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
print(teamDir)
if (os.path.exists(platformDir) == False):
os.mkdir(platformDir)
os.mkdir(teamDir)
elif (os.path.exists(teamDir) == False):
os.mkdir(teamDir)
return True
except Exception as e:
return False
@staticmethod
def check_env(challenge_id):
from .schedule import scheduler
with scheduler.app.app_context():
try:
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
dirname = challenge.dirname.split("/")[1]
containers = GlowwormContainers.query.filter_by(challenge_id=challenge_id).all()
for index in containers:
if mode == "users":
victim = Users.query.filter_by(id=index.user_id).first()
victim_name = victim.name
victim_id = victim.id
team_id = victim.team_id if victim.team_id else None
else:
victim = None
team = Teams.query.filter_by(id=index.user_id).first()
team_id = team.id
victim_id = team_id
victim_name = team.name
check_file = os.path.join(basePath, challenge.dirname, "conf", "check.py")
# Todo: excute check file in containers
command = "python3 '%s' %s %s" % (check_file, index.ip, index.service_port)
print(command)
# 容器Check
rq = os.popen(command).read()
r = "".join(re.findall(r'team..', rq))
if r == "":
msg = index.docker_id + " seems ok."
else:
msg = index.docker_id + " seems down."
check_log = GlowwormCheckLog(
user_id=victim_id,
team_id=team_id,
victim_user_id=victim_id,
victim_team_id=team_id,
challenge_id=challenge.id,
ip="127.0.0.1",
provided=msg,
)
check = GlowwormAttacks(
attack_id=None,
attack_name=None,
victim_id=victim_id,
victim_name=victim_name,
docker_id=index.docker_id,
envname=index.docker_id.split("_", 1)[1],
flag="",
round=get_round()
)
db.session.add(check)
db.session.add(check_log)
print(check)
print(check_log)
print(msg)
db.session.commit()
db.session.close()
return True
except Exception as e:
print(e)
return False
@staticmethod
def build_env(challenge_id):
platform_name = utils.get_config("ctf_name")
print(platform_name)
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
envPath = os.path.join(basePath, challenge.dirname)
command = 'cd ' + envPath + ' && docker build -f ' + envPath + '/Dockerfile -t ' + challenge.image_name + " ."
print(command)
try:
os.system(command)
return True
except Exception as e:
print(e)
return str(e)
@staticmethod
def gen_env(language="PHP", rootpasswd="", teamPath="", key="", teamid="", interval=300):
# "*/5 * * * * python /conf/flag.py team3_web_pyblog Unknow2Kg 300"
# f = "*/5 * * * * python /conf/flag.py %s %s %s"
# echo ${f:12}
service = {}
# PHP
service['PHP'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
chown -R web:web /var/www/html
chmod -R 777 /var/www/html
if [ -f "/conf/apache2.sh" ]; then
chmod +x /conf/apache2.sh
/conf/apache2.sh
fi
chown -R mysql:mysql /var/lib/mysql /var/run/mysqld
service mysql start;
/etc/init.d/ssh start;
sleep 2
mysql -u root < /var/www/html/*.sql
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
/bin/bash
'''
# PWN
service['PWN'] = '''#!/bin/sh
echo pwn:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
f="*/5 * * * * python /conf/flag.py %s %s %s"
# echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
'''
# Django
service['Django'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
/etc/init.d/ssh start;
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
/bin/bash
'''
# Node
service['Node'] = '''#!/bin/bash
echo web:%s | chpasswd;
echo root:%s | chpasswd;
chmod -R 700 /conf
/etc/init.d/ssh start;
f="*/5 * * * * python /conf/flag.py %s %s %s"
echo `${f:12}`
echo "$f" > /conf/cron.txt
crontab /conf/cron.txt
cron
if [ -f "/conf/extra.sh" ]; then
chmod +x /conf/extra.sh
/conf/extra.sh
fi
/bin/bash
'''
webpasswd = <PASSWORD>(key)
servicesh = service[language] % (webpasswd, rootpasswd, key, teamid, interval)
print(servicesh)
with open(os.path.join(teamPath, "conf", "service.sh"), 'w') as f:
f.write(servicesh)
return webpasswd
@staticmethod
def copy_env(source, dest):
try:
if not (os.path.exists(dest)):
# TODO: 重构
os.system("mkdir -p %s" % dest)
command = 'cp -r "%s" "%s"' % (source, dest)
print(command)
os.system(command)
return True
else:
command = 'cp -r "%s" "%s"' % (source, dest)
print(command)
os.system(command)
return True
except Exception as e:
print(e)
return False
@staticmethod
def delete_env(counts, challenge_id):
try:
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
for index in counts:
if mode == "users" and index.type == "admin":
pass
else:
dirname = challenge.dirname.split("/")[1]
envPath = os.path.join(basePath, challenge.dirname)
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
teamEnvDir = os.path.join(teamDir, dirname)
# 容器删除
name = "Team{}_{}".format(str(index.id), dirname)
print(name)
os.system("docker stop " + name)
os.system("docker rm " + name)
instance = GlowwormContainers.query.filter_by(docker_id=name).first()
if instance == None:
pass
else:
db.session.delete(instance)
db.session.commit()
# 目录删除
command = "rm -rf '%s'" % teamEnvDir
print(command)
os.system(command)
challenge.env_status = False
db.session.commit()
return True
except Exception as e:
print(e)
return False
@staticmethod
def run_env(counts, challenge_id):
try:
configs = DBUtils.get_all_configs()
interval = configs.get("per_round") if configs.get("per_round") else "300"
cpu_limit = configs.get("cpu_limit") if configs.get("cpu_limit") else "0.5"
memory_limit = configs.get("memory_limit") if configs.get("memory_limit") else "512M"
rootpwd = configs.get("containers_key") if configs.get("containers_key") else "root"
mode = utils.get_config("user_mode")
platform_name = utils.get_config("ctf_name")
basePath = os.path.abspath(os.path.dirname(__file__))
platformDir = os.path.join(basePath, platform_name)
challenge = ADAChallenge.query.filter_by(id=challenge_id).first_or_404()
for index in counts:
if mode == "users" and index.type == "admin":
pass
else:
dirname = challenge.dirname.split("/")[1]
envPath = os.path.join(basePath, challenge.dirname)
teamDir = os.path.join(basePath, platform_name, 'team' + str(index.id))
teamEnvDir = os.path.join(teamDir, dirname)
name = "Team{}_{}".format(str(index.id), dirname)
# 目录复制
DockerUtils.copy_env(envPath, teamDir)
# 容器动态信息初始化
# save random key
key = str(<KEY>())), platform_name + str(time.time())))
print(key)
instance_pwd = DockerUtils.gen_env(language=challenge.env_language, rootpasswd=<PASSWORD>, teamPath=teamEnvDir, key=key, teamid=name, interval=interval)
# choose alive random port
if configs.get("random_port") == "1":
fixedPorts = DBUtils.get_alive_ports()
insert_service_port = fixedPorts[0]
insert_ssh_port = fixedPorts[1]
else:
fixedPorts = 100 * int(challenge.id)
insert_service_port = int(str(fixedPorts + index.id) + "80")
insert_ssh_port = int(str(fixedPorts + index.id) + "22")
env_port = challenge.env_port if challenge.env_port != "" else "80"
confPath = os.path.join(teamEnvDir, "conf")
instance = GlowwormContainers(
user_id=index.id
, challenge_id=challenge_id
, docker_id=name
, ip=configs.get("direct_address")
, service_port=insert_service_port
, ssh_port=insert_ssh_port
, ssh_key=instance_pwd
, key=key
)
db.session.add(instance)
db.session.commit()
command = """#!/bin/sh
docker run -tid --restart=on-failure:10 --privileged --name %s --cpus=%s -m %s -v "%s":"%s" -p %s:%s -p %s:%s --network h1ve_frp_containers %s "/conf/service.sh"
""" % ( name, cpu_limit, memory_limit, confPath, "/conf", insert_service_port, env_port, insert_ssh_port, "22", challenge.image_name)
print(command)
with open(os.path.join(confPath, "docker.sh"), 'w') as f:
f.write(command)
# 启动容器
command = 'cd "%s" && chmod +x ./docker.sh service.sh && ./docker.sh' % confPath
print(command)
try:
os.system(command)
msg = name + " up."
log(
"glowworm",
"[{date}] {name} {msg}",
msg=msg,
)
except Exception as e:
# print(e)
msg = name + " up error." + str(e)
log(
"glowworm",
"[{date}] {name} {msg}",
msg=msg,
)
return str(e)
challenge.env_status = True
db.session.commit()
return True
except Exception as e:
return str(e) | 0.159577 | 0.050331 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import tensorflow as tf
from tf_agents.agents.dqn import dqn_agent
from tf_agents.environments import time_step as ts
from tf_agents.networks import network
from tf_agents.specs import tensor_spec
from tf_agents.utils import common
from tensorflow.python.eager import context # pylint:disable=g-direct-tensorflow-import # TF internal
from tensorflow.python.framework import test_util # pylint:disable=g-direct-tensorflow-import # TF internal
class DummyNet(network.Network):
def __init__(self, unused_observation_spec, action_spec, name=None):
super(DummyNet, self).__init__(
unused_observation_spec, state_spec=(), name=name)
action_spec = tf.nest.flatten(action_spec)[0]
num_actions = action_spec.maximum - action_spec.minimum + 1
self._layers.append(
tf.keras.layers.Dense(
num_actions,
kernel_initializer=tf.compat.v1.initializers.constant([[2, 1],
[1, 1]]),
bias_initializer=tf.compat.v1.initializers.constant([[1], [1]])))
def call(self, inputs, unused_step_type=None, network_state=()):
inputs = tf.cast(inputs[0], tf.float32)
for layer in self.layers:
inputs = layer(inputs)
return inputs, network_state
class ComputeTDTargetsTest(tf.test.TestCase):
@test_util.run_in_graph_and_eager_modes()
def testComputeTDTargets(self):
next_q_values = tf.constant([10, 20], dtype=tf.float32)
rewards = tf.constant([10, 20], dtype=tf.float32)
discounts = tf.constant([0.9, 0.9], dtype=tf.float32)
expected_td_targets = [19., 38.]
td_targets = dqn_agent.compute_td_targets(next_q_values, rewards, discounts)
self.assertAllClose(self.evaluate(td_targets), expected_td_targets)
@parameterized.named_parameters(
('.DqnAgent_graph', dqn_agent.DqnAgent, context.graph_mode),
('.DqnAgent_eager', dqn_agent.DqnAgent, context.eager_mode),
('.DdqnAgent_graph', dqn_agent.DdqnAgent, context.graph_mode),
('.DdqnAgent_eager', dqn_agent.DdqnAgent, context.eager_mode)
)
class AgentTest(tf.test.TestCase):
def setUp(self):
super(AgentTest, self).setUp()
tf.compat.v1.enable_resource_variables()
self._obs_spec = [tensor_spec.TensorSpec([2], tf.float32)]
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = [tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)]
self._observation_spec = self._time_step_spec.observation
def testCreateAgent(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
self.assertIsNotNone(agent.policy)
def testInitializeAgent(self, agent_class, run_mode):
if tf.executing_eagerly() and run_mode == context.graph_mode:
self.skipTest('b/123778560')
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
init_op = agent.initialize()
if not tf.executing_eagerly():
with self.cached_session() as sess:
common.initialize_uninitialized_variables(sess)
self.assertIsNone(sess.run(init_op))
def testCreateAgentNestSizeChecks(self, agent_class, run_mode):
with run_mode():
action_spec = [
tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1),
tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)
]
q_net = DummyNet(self._observation_spec, action_spec)
with self.assertRaisesRegexp(ValueError, '.*one dimensional.*'):
agent_class(
self._time_step_spec, action_spec, q_network=q_net, optimizer=None)
def testCreateAgentDimChecks(self, agent_class, run_mode):
with run_mode():
action_spec = [tensor_spec.BoundedTensorSpec([1, 2], tf.int32, 0, 1)]
q_net = DummyNet(self._observation_spec, action_spec)
with self.assertRaisesRegexp(ValueError, '.*one dimensional.*'):
agent_class(
self._time_step_spec, action_spec, q_network=q_net, optimizer=None)
# TODO(b/127383724): Add a test where the target network has different values.
def testLoss(self, agent_class, run_mode):
if tf.executing_eagerly() and run_mode == context.graph_mode:
self.skipTest('b/123778560')
with run_mode(), tf.compat.v2.summary.record_if(False):
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
actions = [tf.constant([[0], [1]], dtype=tf.int32)]
rewards = tf.constant([10, 20], dtype=tf.float32)
discounts = tf.constant([0.9, 0.9], dtype=tf.float32)
next_observations = [tf.constant([[5, 6], [7, 8]], dtype=tf.float32)]
next_time_steps = ts.transition(next_observations, rewards, discounts)
expected_loss = 26.0
loss, _ = agent.loss(time_steps, actions, next_time_steps)
self.evaluate(tf.compat.v1.initialize_all_variables())
self.assertAllClose(self.evaluate(loss), expected_loss)
def testPolicy(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
policy = agent.policy
action_step = policy.action(time_steps)
# Batch size 2.
self.assertAllEqual(
[2] + self._action_spec[0].shape.as_list(),
action_step.action[0].shape,
)
self.evaluate(tf.compat.v1.initialize_all_variables())
actions_ = self.evaluate(action_step.action)
self.assertTrue(all(actions_[0] <= self._action_spec[0].maximum))
self.assertTrue(all(actions_[0] >= self._action_spec[0].minimum))
def testInitializeRestoreAgent(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
policy = agent.policy
action_step = policy.action(time_steps)
self.evaluate(tf.compat.v1.initialize_all_variables())
checkpoint = tf.train.Checkpoint(agent=agent)
latest_checkpoint = tf.train.latest_checkpoint(self.get_temp_dir())
checkpoint_load_status = checkpoint.restore(latest_checkpoint)
if tf.executing_eagerly():
self.evaluate(checkpoint_load_status.initialize_or_restore())
self.assertAllEqual(self.evaluate(action_step.action), [[[0], [0]]])
else:
with self.cached_session() as sess:
checkpoint_load_status.initialize_or_restore(sess)
self.assertAllEqual(sess.run(action_step.action), [[[0], [0]]])
if __name__ == '__main__':
tf.test.main() | tf_agents/agents/dqn/dqn_agent_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import tensorflow as tf
from tf_agents.agents.dqn import dqn_agent
from tf_agents.environments import time_step as ts
from tf_agents.networks import network
from tf_agents.specs import tensor_spec
from tf_agents.utils import common
from tensorflow.python.eager import context # pylint:disable=g-direct-tensorflow-import # TF internal
from tensorflow.python.framework import test_util # pylint:disable=g-direct-tensorflow-import # TF internal
class DummyNet(network.Network):
def __init__(self, unused_observation_spec, action_spec, name=None):
super(DummyNet, self).__init__(
unused_observation_spec, state_spec=(), name=name)
action_spec = tf.nest.flatten(action_spec)[0]
num_actions = action_spec.maximum - action_spec.minimum + 1
self._layers.append(
tf.keras.layers.Dense(
num_actions,
kernel_initializer=tf.compat.v1.initializers.constant([[2, 1],
[1, 1]]),
bias_initializer=tf.compat.v1.initializers.constant([[1], [1]])))
def call(self, inputs, unused_step_type=None, network_state=()):
inputs = tf.cast(inputs[0], tf.float32)
for layer in self.layers:
inputs = layer(inputs)
return inputs, network_state
class ComputeTDTargetsTest(tf.test.TestCase):
@test_util.run_in_graph_and_eager_modes()
def testComputeTDTargets(self):
next_q_values = tf.constant([10, 20], dtype=tf.float32)
rewards = tf.constant([10, 20], dtype=tf.float32)
discounts = tf.constant([0.9, 0.9], dtype=tf.float32)
expected_td_targets = [19., 38.]
td_targets = dqn_agent.compute_td_targets(next_q_values, rewards, discounts)
self.assertAllClose(self.evaluate(td_targets), expected_td_targets)
@parameterized.named_parameters(
('.DqnAgent_graph', dqn_agent.DqnAgent, context.graph_mode),
('.DqnAgent_eager', dqn_agent.DqnAgent, context.eager_mode),
('.DdqnAgent_graph', dqn_agent.DdqnAgent, context.graph_mode),
('.DdqnAgent_eager', dqn_agent.DdqnAgent, context.eager_mode)
)
class AgentTest(tf.test.TestCase):
def setUp(self):
super(AgentTest, self).setUp()
tf.compat.v1.enable_resource_variables()
self._obs_spec = [tensor_spec.TensorSpec([2], tf.float32)]
self._time_step_spec = ts.time_step_spec(self._obs_spec)
self._action_spec = [tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)]
self._observation_spec = self._time_step_spec.observation
def testCreateAgent(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
self.assertIsNotNone(agent.policy)
def testInitializeAgent(self, agent_class, run_mode):
if tf.executing_eagerly() and run_mode == context.graph_mode:
self.skipTest('b/123778560')
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
init_op = agent.initialize()
if not tf.executing_eagerly():
with self.cached_session() as sess:
common.initialize_uninitialized_variables(sess)
self.assertIsNone(sess.run(init_op))
def testCreateAgentNestSizeChecks(self, agent_class, run_mode):
with run_mode():
action_spec = [
tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1),
tensor_spec.BoundedTensorSpec([1], tf.int32, 0, 1)
]
q_net = DummyNet(self._observation_spec, action_spec)
with self.assertRaisesRegexp(ValueError, '.*one dimensional.*'):
agent_class(
self._time_step_spec, action_spec, q_network=q_net, optimizer=None)
def testCreateAgentDimChecks(self, agent_class, run_mode):
with run_mode():
action_spec = [tensor_spec.BoundedTensorSpec([1, 2], tf.int32, 0, 1)]
q_net = DummyNet(self._observation_spec, action_spec)
with self.assertRaisesRegexp(ValueError, '.*one dimensional.*'):
agent_class(
self._time_step_spec, action_spec, q_network=q_net, optimizer=None)
# TODO(b/127383724): Add a test where the target network has different values.
def testLoss(self, agent_class, run_mode):
if tf.executing_eagerly() and run_mode == context.graph_mode:
self.skipTest('b/123778560')
with run_mode(), tf.compat.v2.summary.record_if(False):
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
actions = [tf.constant([[0], [1]], dtype=tf.int32)]
rewards = tf.constant([10, 20], dtype=tf.float32)
discounts = tf.constant([0.9, 0.9], dtype=tf.float32)
next_observations = [tf.constant([[5, 6], [7, 8]], dtype=tf.float32)]
next_time_steps = ts.transition(next_observations, rewards, discounts)
expected_loss = 26.0
loss, _ = agent.loss(time_steps, actions, next_time_steps)
self.evaluate(tf.compat.v1.initialize_all_variables())
self.assertAllClose(self.evaluate(loss), expected_loss)
def testPolicy(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
policy = agent.policy
action_step = policy.action(time_steps)
# Batch size 2.
self.assertAllEqual(
[2] + self._action_spec[0].shape.as_list(),
action_step.action[0].shape,
)
self.evaluate(tf.compat.v1.initialize_all_variables())
actions_ = self.evaluate(action_step.action)
self.assertTrue(all(actions_[0] <= self._action_spec[0].maximum))
self.assertTrue(all(actions_[0] >= self._action_spec[0].minimum))
def testInitializeRestoreAgent(self, agent_class, run_mode):
with run_mode():
q_net = DummyNet(self._observation_spec, self._action_spec)
agent = agent_class(
self._time_step_spec,
self._action_spec,
q_network=q_net,
optimizer=None)
observations = [tf.constant([[1, 2], [3, 4]], dtype=tf.float32)]
time_steps = ts.restart(observations, batch_size=2)
policy = agent.policy
action_step = policy.action(time_steps)
self.evaluate(tf.compat.v1.initialize_all_variables())
checkpoint = tf.train.Checkpoint(agent=agent)
latest_checkpoint = tf.train.latest_checkpoint(self.get_temp_dir())
checkpoint_load_status = checkpoint.restore(latest_checkpoint)
if tf.executing_eagerly():
self.evaluate(checkpoint_load_status.initialize_or_restore())
self.assertAllEqual(self.evaluate(action_step.action), [[[0], [0]]])
else:
with self.cached_session() as sess:
checkpoint_load_status.initialize_or_restore(sess)
self.assertAllEqual(sess.run(action_step.action), [[[0], [0]]])
if __name__ == '__main__':
tf.test.main() | 0.723798 | 0.308242 |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='coverage.proto',
package='resultstoresearch.v1',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x0e\x63overage.proto\x12\x14resultstoresearch.v1\"B\n\x0cLineCoverage\x12\x1a\n\x12instrumented_lines\x18\x01 \x01(\x0c\x12\x16\n\x0e\x65xecuted_lines\x18\x02 \x01(\x0c\"c\n\x0e\x42ranchCoverage\x12\x16\n\x0e\x62ranch_present\x18\x01 \x01(\x0c\x12\x18\n\x10\x62ranches_in_line\x18\x02 \x03(\x05\x12\x10\n\x08\x65xecuted\x18\x03 \x01(\x0c\x12\r\n\x05taken\x18\x04 \x01(\x0c\"\x96\x01\n\x0c\x46ileCoverage\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x39\n\rline_coverage\x18\x02 \x01(\x0b\x32\".resultstoresearch.v1.LineCoverage\x12=\n\x0f\x62ranch_coverage\x18\x03 \x01(\x0b\x32$.resultstoresearch.v1.BranchCoverage\"L\n\x0e\x41\x63tionCoverage\x12:\n\x0e\x66ile_coverages\x18\x02 \x03(\x0b\x32\".resultstoresearch.v1.FileCoverage\"O\n\x11\x41ggregateCoverage\x12:\n\x0e\x66ile_coverages\x18\x01 \x03(\x0b\x32\".resultstoresearch.v1.FileCoverageb\x06proto3'
)
_LINECOVERAGE = _descriptor.Descriptor(
name='LineCoverage',
full_name='resultstoresearch.v1.LineCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='instrumented_lines', full_name='resultstoresearch.v1.LineCoverage.instrumented_lines', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='executed_lines', full_name='resultstoresearch.v1.LineCoverage.executed_lines', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=40,
serialized_end=106,
)
_BRANCHCOVERAGE = _descriptor.Descriptor(
name='BranchCoverage',
full_name='resultstoresearch.v1.BranchCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='branch_present', full_name='resultstoresearch.v1.BranchCoverage.branch_present', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='branches_in_line', full_name='resultstoresearch.v1.BranchCoverage.branches_in_line', index=1,
number=2, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='executed', full_name='resultstoresearch.v1.BranchCoverage.executed', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='taken', full_name='resultstoresearch.v1.BranchCoverage.taken', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=108,
serialized_end=207,
)
_FILECOVERAGE = _descriptor.Descriptor(
name='FileCoverage',
full_name='resultstoresearch.v1.FileCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='path', full_name='resultstoresearch.v1.FileCoverage.path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='line_coverage', full_name='resultstoresearch.v1.FileCoverage.line_coverage', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='branch_coverage', full_name='resultstoresearch.v1.FileCoverage.branch_coverage', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=210,
serialized_end=360,
)
_ACTIONCOVERAGE = _descriptor.Descriptor(
name='ActionCoverage',
full_name='resultstoresearch.v1.ActionCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='file_coverages', full_name='resultstoresearch.v1.ActionCoverage.file_coverages', index=0,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=362,
serialized_end=438,
)
_AGGREGATECOVERAGE = _descriptor.Descriptor(
name='AggregateCoverage',
full_name='resultstoresearch.v1.AggregateCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='file_coverages', full_name='resultstoresearch.v1.AggregateCoverage.file_coverages', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=440,
serialized_end=519,
)
_FILECOVERAGE.fields_by_name['line_coverage'].message_type = _LINECOVERAGE
_FILECOVERAGE.fields_by_name['branch_coverage'].message_type = _BRANCHCOVERAGE
_ACTIONCOVERAGE.fields_by_name['file_coverages'].message_type = _FILECOVERAGE
_AGGREGATECOVERAGE.fields_by_name['file_coverages'].message_type = _FILECOVERAGE
DESCRIPTOR.message_types_by_name['LineCoverage'] = _LINECOVERAGE
DESCRIPTOR.message_types_by_name['BranchCoverage'] = _BRANCHCOVERAGE
DESCRIPTOR.message_types_by_name['FileCoverage'] = _FILECOVERAGE
DESCRIPTOR.message_types_by_name['ActionCoverage'] = _ACTIONCOVERAGE
DESCRIPTOR.message_types_by_name['AggregateCoverage'] = _AGGREGATECOVERAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
LineCoverage = _reflection.GeneratedProtocolMessageType('LineCoverage', (_message.Message,), {
'DESCRIPTOR' : _LINECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.LineCoverage)
})
_sym_db.RegisterMessage(LineCoverage)
BranchCoverage = _reflection.GeneratedProtocolMessageType('BranchCoverage', (_message.Message,), {
'DESCRIPTOR' : _BRANCHCOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.BranchCoverage)
})
_sym_db.RegisterMessage(BranchCoverage)
FileCoverage = _reflection.GeneratedProtocolMessageType('FileCoverage', (_message.Message,), {
'DESCRIPTOR' : _FILECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.FileCoverage)
})
_sym_db.RegisterMessage(FileCoverage)
ActionCoverage = _reflection.GeneratedProtocolMessageType('ActionCoverage', (_message.Message,), {
'DESCRIPTOR' : _ACTIONCOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.ActionCoverage)
})
_sym_db.RegisterMessage(ActionCoverage)
AggregateCoverage = _reflection.GeneratedProtocolMessageType('AggregateCoverage', (_message.Message,), {
'DESCRIPTOR' : _AGGREGATECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.AggregateCoverage)
})
_sym_db.RegisterMessage(AggregateCoverage)
# @@protoc_insertion_point(module_scope) | resultstoresearch/server/resultstoresearch/resultstoresearchapi/coverage_pb2.py |
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='coverage.proto',
package='resultstoresearch.v1',
syntax='proto3',
serialized_options=None,
create_key=_descriptor._internal_create_key,
serialized_pb=b'\n\x0e\x63overage.proto\x12\x14resultstoresearch.v1\"B\n\x0cLineCoverage\x12\x1a\n\x12instrumented_lines\x18\x01 \x01(\x0c\x12\x16\n\x0e\x65xecuted_lines\x18\x02 \x01(\x0c\"c\n\x0e\x42ranchCoverage\x12\x16\n\x0e\x62ranch_present\x18\x01 \x01(\x0c\x12\x18\n\x10\x62ranches_in_line\x18\x02 \x03(\x05\x12\x10\n\x08\x65xecuted\x18\x03 \x01(\x0c\x12\r\n\x05taken\x18\x04 \x01(\x0c\"\x96\x01\n\x0c\x46ileCoverage\x12\x0c\n\x04path\x18\x01 \x01(\t\x12\x39\n\rline_coverage\x18\x02 \x01(\x0b\x32\".resultstoresearch.v1.LineCoverage\x12=\n\x0f\x62ranch_coverage\x18\x03 \x01(\x0b\x32$.resultstoresearch.v1.BranchCoverage\"L\n\x0e\x41\x63tionCoverage\x12:\n\x0e\x66ile_coverages\x18\x02 \x03(\x0b\x32\".resultstoresearch.v1.FileCoverage\"O\n\x11\x41ggregateCoverage\x12:\n\x0e\x66ile_coverages\x18\x01 \x03(\x0b\x32\".resultstoresearch.v1.FileCoverageb\x06proto3'
)
_LINECOVERAGE = _descriptor.Descriptor(
name='LineCoverage',
full_name='resultstoresearch.v1.LineCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='instrumented_lines', full_name='resultstoresearch.v1.LineCoverage.instrumented_lines', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='executed_lines', full_name='resultstoresearch.v1.LineCoverage.executed_lines', index=1,
number=2, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=40,
serialized_end=106,
)
_BRANCHCOVERAGE = _descriptor.Descriptor(
name='BranchCoverage',
full_name='resultstoresearch.v1.BranchCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='branch_present', full_name='resultstoresearch.v1.BranchCoverage.branch_present', index=0,
number=1, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='branches_in_line', full_name='resultstoresearch.v1.BranchCoverage.branches_in_line', index=1,
number=2, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='executed', full_name='resultstoresearch.v1.BranchCoverage.executed', index=2,
number=3, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='taken', full_name='resultstoresearch.v1.BranchCoverage.taken', index=3,
number=4, type=12, cpp_type=9, label=1,
has_default_value=False, default_value=b"",
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=108,
serialized_end=207,
)
_FILECOVERAGE = _descriptor.Descriptor(
name='FileCoverage',
full_name='resultstoresearch.v1.FileCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='path', full_name='resultstoresearch.v1.FileCoverage.path', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=b"".decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='line_coverage', full_name='resultstoresearch.v1.FileCoverage.line_coverage', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
_descriptor.FieldDescriptor(
name='branch_coverage', full_name='resultstoresearch.v1.FileCoverage.branch_coverage', index=2,
number=3, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=210,
serialized_end=360,
)
_ACTIONCOVERAGE = _descriptor.Descriptor(
name='ActionCoverage',
full_name='resultstoresearch.v1.ActionCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='file_coverages', full_name='resultstoresearch.v1.ActionCoverage.file_coverages', index=0,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=362,
serialized_end=438,
)
_AGGREGATECOVERAGE = _descriptor.Descriptor(
name='AggregateCoverage',
full_name='resultstoresearch.v1.AggregateCoverage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
create_key=_descriptor._internal_create_key,
fields=[
_descriptor.FieldDescriptor(
name='file_coverages', full_name='resultstoresearch.v1.AggregateCoverage.file_coverages', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key),
],
extensions=[
],
nested_types=[],
enum_types=[
],
serialized_options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=440,
serialized_end=519,
)
_FILECOVERAGE.fields_by_name['line_coverage'].message_type = _LINECOVERAGE
_FILECOVERAGE.fields_by_name['branch_coverage'].message_type = _BRANCHCOVERAGE
_ACTIONCOVERAGE.fields_by_name['file_coverages'].message_type = _FILECOVERAGE
_AGGREGATECOVERAGE.fields_by_name['file_coverages'].message_type = _FILECOVERAGE
DESCRIPTOR.message_types_by_name['LineCoverage'] = _LINECOVERAGE
DESCRIPTOR.message_types_by_name['BranchCoverage'] = _BRANCHCOVERAGE
DESCRIPTOR.message_types_by_name['FileCoverage'] = _FILECOVERAGE
DESCRIPTOR.message_types_by_name['ActionCoverage'] = _ACTIONCOVERAGE
DESCRIPTOR.message_types_by_name['AggregateCoverage'] = _AGGREGATECOVERAGE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
LineCoverage = _reflection.GeneratedProtocolMessageType('LineCoverage', (_message.Message,), {
'DESCRIPTOR' : _LINECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.LineCoverage)
})
_sym_db.RegisterMessage(LineCoverage)
BranchCoverage = _reflection.GeneratedProtocolMessageType('BranchCoverage', (_message.Message,), {
'DESCRIPTOR' : _BRANCHCOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.BranchCoverage)
})
_sym_db.RegisterMessage(BranchCoverage)
FileCoverage = _reflection.GeneratedProtocolMessageType('FileCoverage', (_message.Message,), {
'DESCRIPTOR' : _FILECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.FileCoverage)
})
_sym_db.RegisterMessage(FileCoverage)
ActionCoverage = _reflection.GeneratedProtocolMessageType('ActionCoverage', (_message.Message,), {
'DESCRIPTOR' : _ACTIONCOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.ActionCoverage)
})
_sym_db.RegisterMessage(ActionCoverage)
AggregateCoverage = _reflection.GeneratedProtocolMessageType('AggregateCoverage', (_message.Message,), {
'DESCRIPTOR' : _AGGREGATECOVERAGE,
'__module__' : 'coverage_pb2'
# @@protoc_insertion_point(class_scope:resultstoresearch.v1.AggregateCoverage)
})
_sym_db.RegisterMessage(AggregateCoverage)
# @@protoc_insertion_point(module_scope) | 0.29584 | 0.113383 |
from __future__ import unicode_literals
import frappe
import erpnext
import unittest
from frappe.utils import nowdate, add_days
from erpnext.tests.utils import create_test_contact_and_address
from erpnext.stock.doctype.delivery_trip.delivery_trip import notify_customers, get_contact_and_address
class TestDeliveryTrip(unittest.TestCase):
def setUp(self):
create_driver()
create_vehicle()
create_delivery_notfication()
create_test_contact_and_address()
def test_delivery_trip(self):
contact = get_contact_and_address("_Test Customer")
if not frappe.db.exists("Delivery Trip", "TOUR-00000"):
delivery_trip = frappe.new_doc("Delivery Trip")
delivery_trip.company = erpnext.get_default_company()
delivery_trip.date = add_days(nowdate(), 5)
delivery_trip.driver = "DRIVER-00001"
delivery_trip.vehicle = "JB 007"
delivery_trip.append("delivery_stops", {
"customer": "_Test Customer",
"address": contact.shipping_address.parent,
"contact": contact.contact_person.parent
})
delivery_trip.delivery_notification = 'Delivery Notification'
delivery_trip.insert()
sender_email = frappe.db.get_value("User", frappe.session.user, "email")
notify_customers(docname=delivery_trip.name, date=delivery_trip.date, driver=delivery_trip.driver,
vehicle=delivery_trip.vehicle,
sender_email=sender_email, delivery_notification=delivery_trip.delivery_notification)
self.assertEqual(delivery_trip.get("delivery_stops")[0].notified_by_email, 0)
def create_driver():
if not frappe.db.exists("Driver", "<NAME>"):
driver = frappe.new_doc("Driver")
driver.full_name = "<NAME>"
driver.cell_number = "98343424242"
driver.license_number = "B809"
driver.insert()
def create_delivery_notfication():
if not frappe.db.exists("Standard Reply", "Delivery Notification"):
frappe.get_doc({
'doctype': 'Standard Reply',
'name': 'Delivery Notification',
'response': 'Test Delivery Trip',
'subject': 'Test Subject',
'owner': frappe.session.user
}).insert()
def create_vehicle():
if not frappe.db.exists("Vehicle", "JB 007"):
vehicle = frappe.get_doc({
"doctype": "Vehicle",
"license_plate": "JB 007",
"make": "Maruti",
"model": "PCM",
"last_odometer": 5000,
"acquisition_date": frappe.utils.nowdate(),
"location": "Mumbai",
"chassis_no": "1234ABCD",
"uom": "Litre",
"vehicle_value": frappe.utils.flt(500000)
})
vehicle.insert() | frappe-bench/apps/erpnext/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py | from __future__ import unicode_literals
import frappe
import erpnext
import unittest
from frappe.utils import nowdate, add_days
from erpnext.tests.utils import create_test_contact_and_address
from erpnext.stock.doctype.delivery_trip.delivery_trip import notify_customers, get_contact_and_address
class TestDeliveryTrip(unittest.TestCase):
def setUp(self):
create_driver()
create_vehicle()
create_delivery_notfication()
create_test_contact_and_address()
def test_delivery_trip(self):
contact = get_contact_and_address("_Test Customer")
if not frappe.db.exists("Delivery Trip", "TOUR-00000"):
delivery_trip = frappe.new_doc("Delivery Trip")
delivery_trip.company = erpnext.get_default_company()
delivery_trip.date = add_days(nowdate(), 5)
delivery_trip.driver = "DRIVER-00001"
delivery_trip.vehicle = "JB 007"
delivery_trip.append("delivery_stops", {
"customer": "_Test Customer",
"address": contact.shipping_address.parent,
"contact": contact.contact_person.parent
})
delivery_trip.delivery_notification = 'Delivery Notification'
delivery_trip.insert()
sender_email = frappe.db.get_value("User", frappe.session.user, "email")
notify_customers(docname=delivery_trip.name, date=delivery_trip.date, driver=delivery_trip.driver,
vehicle=delivery_trip.vehicle,
sender_email=sender_email, delivery_notification=delivery_trip.delivery_notification)
self.assertEqual(delivery_trip.get("delivery_stops")[0].notified_by_email, 0)
def create_driver():
if not frappe.db.exists("Driver", "<NAME>"):
driver = frappe.new_doc("Driver")
driver.full_name = "<NAME>"
driver.cell_number = "98343424242"
driver.license_number = "B809"
driver.insert()
def create_delivery_notfication():
if not frappe.db.exists("Standard Reply", "Delivery Notification"):
frappe.get_doc({
'doctype': 'Standard Reply',
'name': 'Delivery Notification',
'response': 'Test Delivery Trip',
'subject': 'Test Subject',
'owner': frappe.session.user
}).insert()
def create_vehicle():
if not frappe.db.exists("Vehicle", "JB 007"):
vehicle = frappe.get_doc({
"doctype": "Vehicle",
"license_plate": "JB 007",
"make": "Maruti",
"model": "PCM",
"last_odometer": 5000,
"acquisition_date": frappe.utils.nowdate(),
"location": "Mumbai",
"chassis_no": "1234ABCD",
"uom": "Litre",
"vehicle_value": frappe.utils.flt(500000)
})
vehicle.insert() | 0.298798 | 0.114492 |
import os
import sys
import math
import tensorflow as tf
import model_helper as _mh
from pathlib import Path
PROJECT_PATH = Path(__file__).absolute().parent
sys.path.insert(0, str(PROJECT_PATH))
from utils.log import log_info as _info
from utils.log import log_error as _error
def tranformer_model(input_tensor,
attention_mask=None,
hidden_size=1024,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=_mh.gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False,
share_parameter_across_layers=True):
"""Multi-head, multi-layer Transformer.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length, seq_length],
where 1 indicates the position can be attended and 0 indicates the position cannot be attended.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the feed forward layer.
intermediate_act_fn: activation function after feed forward layer.
hidden_dropout_prob: float.
attention_probs_dropout_prob: float.
initializer_range: float.
do_return_all_layers: bool. Return the output from all the hidden layers or just the final layer.
share_parameter_across_layers: bool. Whether share parameters across each attention layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size],
or a list contains 'num_hidden_layers' float Tensor.
"""
if hidden_size % num_attention_heads != 0:
_error('The hidden size {} cannot be divided by the number of attention heads {}'.format(hidden_size, num_attention_heads))
raise ValueError
# the hidden size for each head
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = _mh.get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# residual layer need to perform on the outputs from all layers,
# so the hidden size, i.e. the outputs from the transformer blocks
# should be the same as the input_width, at the beginning, it is input tensor,
# diffetentiate hidden_size from the intermediate_size,
# intermediate layer is before the hidden layer.
if input_width != hidden_size:
_error('The width of the input tensor {} not not equal to the hidden size {}'.format(input_width, hidden_size))
raise ValueError
# create a list to save the output from each transformer layer]
prev_output = input_tensor # [batch_size, seq_length, width]
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
if share_parameter_across_layers:
name_variable_scope = 'layer_shared'
else:
name_variable_scope = 'layer_{}'.format(layer_idx)
# share the parameter across layers when share_parameter_across_layers us True and not the first layer
with tf.variable_scope(name_variable_scope, reuse=True if (share_parameter_across_layers and layer_idx > 0) else False):
layer_input = prev_output
with tf.variable_scope('attention'):
attention_heads = []
with tf.variable_scope('self'):
attention_head = self_attention_layer(from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_output = attention_head
# perform residual layer to finish the self-attention block
with tf.variable_scope('output'):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=_mh.create_initializer(initializer_range))
attention_output = _mh.dropout(attention_output, hidden_dropout_prob)
attention_output = _mh.layer_norm(attention_output + layer_input)
# do double linear projection to enhance the context representation
with tf.variable_scope('intermediate'):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=_mh.create_initializer(initializer_range))
with tf.variable_scope('output'):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=_mh.create_initializer(initializer_range))
layer_output = _mh.dropout(layer_output, hidden_dropout_prob)
layer_output = _mh.layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
return all_layer_outputs
else:
return all_layer_outputs[-1]
def self_attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
batch_size=None,
from_seq_length=None,
to_seq_length=None):
"""Perform self-attention.
Args:
from_tensor: float Tensor of shape [batch_size, seq_length, width].
to_tensor: float Tensor of shape [batch_size, seq_length, width].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length, seq_length],
where 1 indicates the position can be attended and 0 indicates the position cannot be attended.
num_attention_heads: int. Number of attention heads in the Transformer.
size_per_head: int. Size of each attention head.
query_act: (optional) Activation function for the query transformer.
key_act: (optional) Activation function for the key transformer.
value_act: (optional) Activation function for the value transformer.
attention_probs_dropout_prob: (optional) float.
initializer_range: float.
batch_size: (optional) int.
from_seq_length: (optional) int.
to_seq_length: (optional) int.
Returns:
float Tensor of shape [batch_size, from_seq_length, width].
"""
def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
seq_length, size_per_head):
"""Change the order of axes. witdh = num_attention_heads * size_per_head.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, width].
Returns:
float Tensor of shape [batch_size, num_attention_heads, seq_length, size_per_head].
"""
output_tensor = tf.reshape(input_tensor, [batch_size, seq_length, num_attention_heads, size_per_head])
output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
return output_tensor
# check the rank
from_shape = _mh.get_shape_list(from_tensor, expected_rank=3)
to_shape = _mh.get_shape_list(to_tensor, expected_rank=3)
if len(from_shape) != len(to_shape) != 3:
_error('The rank of `from_tensor` should match the rank of `to_tensor`, and should be 3')
raise ValueError
# calculate the query, key, value
# from_tensor: [batch_size, seq_length, width] -> query_layer: [batch_size, seq_length, num_attention_heads * size_per_head]
# num_attention_heads * size_per_head == hidden_size == width
query_layer = tf.layers.dense(from_tensor,
num_attention_heads * size_per_head,
activation=query_act,
name='query',
kernel_initializer=_mh.create_initializer(initializer_range))
key_layer = tf.layers.dense(to_tensor,
num_attention_heads * size_per_head,
activation=key_act,
name='key',
kernel_initializer=_mh.create_initializer(initializer_range))
value_layer = tf.layers.dense(to_tensor,
num_attention_heads * size_per_head,
activation=value_act,
name='value',
kernel_initializer=_mh.create_initializer(initializer_range))
# [batch_size, seq_length, width] -> [batch_size, num_attention_heads, seq_length, size_per_head]
query_layer = transpose_for_scores(query_layer, batch_size,
num_attention_heads, from_seq_length,
size_per_head)
key_layer = transpose_for_scores(key_layer, batch_size,
num_attention_heads, to_seq_length,
size_per_head)
# calculate the attention scores
# [batch_size, num_attention_heads, from_seq_length, to_seq_length]
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.multiply(attention_scores, 1.0 / math.sqrt(float(size_per_head)))
if attention_mask is not None:
# [batch_size, seq_length, seq_length] -> [batch_size, 1, seq_length, seq_length]
attention_mask = tf.expand_dims(attention_mask, axis=1)
adder = (1.0 - tf.cast(attention_mask, dtype=tf.float32)) * -10000.0
attention_scores += adder
attention_probs = tf.nn.softmax(attention_scores)
attention_probs = _mh.dropout(attention_probs, attention_probs_dropout_prob)
# calculate the context layer
# [batch_size, num_attention_heads, to_seq_length, size_per_head]
value_layer = transpose_for_scores(value_layer, batch_size,
num_attention_heads, to_seq_length,
size_per_head)
context_layer = tf.matmul(attention_scores, value_layer)
# [batch_size, from_seq_length, num_attention_heads, size_per_head]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
# [batch_size, from_seq_length, width]
context_layer = tf.reshape(context_layer, [batch_size, from_seq_length, num_attention_heads * size_per_head])
return context_layer | transformer.py |
import os
import sys
import math
import tensorflow as tf
import model_helper as _mh
from pathlib import Path
PROJECT_PATH = Path(__file__).absolute().parent
sys.path.insert(0, str(PROJECT_PATH))
from utils.log import log_info as _info
from utils.log import log_error as _error
def tranformer_model(input_tensor,
attention_mask=None,
hidden_size=1024,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=_mh.gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False,
share_parameter_across_layers=True):
"""Multi-head, multi-layer Transformer.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length, seq_length],
where 1 indicates the position can be attended and 0 indicates the position cannot be attended.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the feed forward layer.
intermediate_act_fn: activation function after feed forward layer.
hidden_dropout_prob: float.
attention_probs_dropout_prob: float.
initializer_range: float.
do_return_all_layers: bool. Return the output from all the hidden layers or just the final layer.
share_parameter_across_layers: bool. Whether share parameters across each attention layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size],
or a list contains 'num_hidden_layers' float Tensor.
"""
if hidden_size % num_attention_heads != 0:
_error('The hidden size {} cannot be divided by the number of attention heads {}'.format(hidden_size, num_attention_heads))
raise ValueError
# the hidden size for each head
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = _mh.get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# residual layer need to perform on the outputs from all layers,
# so the hidden size, i.e. the outputs from the transformer blocks
# should be the same as the input_width, at the beginning, it is input tensor,
# diffetentiate hidden_size from the intermediate_size,
# intermediate layer is before the hidden layer.
if input_width != hidden_size:
_error('The width of the input tensor {} not not equal to the hidden size {}'.format(input_width, hidden_size))
raise ValueError
# create a list to save the output from each transformer layer]
prev_output = input_tensor # [batch_size, seq_length, width]
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
if share_parameter_across_layers:
name_variable_scope = 'layer_shared'
else:
name_variable_scope = 'layer_{}'.format(layer_idx)
# share the parameter across layers when share_parameter_across_layers us True and not the first layer
with tf.variable_scope(name_variable_scope, reuse=True if (share_parameter_across_layers and layer_idx > 0) else False):
layer_input = prev_output
with tf.variable_scope('attention'):
attention_heads = []
with tf.variable_scope('self'):
attention_head = self_attention_layer(from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_output = attention_head
# perform residual layer to finish the self-attention block
with tf.variable_scope('output'):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=_mh.create_initializer(initializer_range))
attention_output = _mh.dropout(attention_output, hidden_dropout_prob)
attention_output = _mh.layer_norm(attention_output + layer_input)
# do double linear projection to enhance the context representation
with tf.variable_scope('intermediate'):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=_mh.create_initializer(initializer_range))
with tf.variable_scope('output'):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=_mh.create_initializer(initializer_range))
layer_output = _mh.dropout(layer_output, hidden_dropout_prob)
layer_output = _mh.layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
return all_layer_outputs
else:
return all_layer_outputs[-1]
def self_attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
batch_size=None,
from_seq_length=None,
to_seq_length=None):
"""Perform self-attention.
Args:
from_tensor: float Tensor of shape [batch_size, seq_length, width].
to_tensor: float Tensor of shape [batch_size, seq_length, width].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length, seq_length],
where 1 indicates the position can be attended and 0 indicates the position cannot be attended.
num_attention_heads: int. Number of attention heads in the Transformer.
size_per_head: int. Size of each attention head.
query_act: (optional) Activation function for the query transformer.
key_act: (optional) Activation function for the key transformer.
value_act: (optional) Activation function for the value transformer.
attention_probs_dropout_prob: (optional) float.
initializer_range: float.
batch_size: (optional) int.
from_seq_length: (optional) int.
to_seq_length: (optional) int.
Returns:
float Tensor of shape [batch_size, from_seq_length, width].
"""
def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
seq_length, size_per_head):
"""Change the order of axes. witdh = num_attention_heads * size_per_head.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, width].
Returns:
float Tensor of shape [batch_size, num_attention_heads, seq_length, size_per_head].
"""
output_tensor = tf.reshape(input_tensor, [batch_size, seq_length, num_attention_heads, size_per_head])
output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
return output_tensor
# check the rank
from_shape = _mh.get_shape_list(from_tensor, expected_rank=3)
to_shape = _mh.get_shape_list(to_tensor, expected_rank=3)
if len(from_shape) != len(to_shape) != 3:
_error('The rank of `from_tensor` should match the rank of `to_tensor`, and should be 3')
raise ValueError
# calculate the query, key, value
# from_tensor: [batch_size, seq_length, width] -> query_layer: [batch_size, seq_length, num_attention_heads * size_per_head]
# num_attention_heads * size_per_head == hidden_size == width
query_layer = tf.layers.dense(from_tensor,
num_attention_heads * size_per_head,
activation=query_act,
name='query',
kernel_initializer=_mh.create_initializer(initializer_range))
key_layer = tf.layers.dense(to_tensor,
num_attention_heads * size_per_head,
activation=key_act,
name='key',
kernel_initializer=_mh.create_initializer(initializer_range))
value_layer = tf.layers.dense(to_tensor,
num_attention_heads * size_per_head,
activation=value_act,
name='value',
kernel_initializer=_mh.create_initializer(initializer_range))
# [batch_size, seq_length, width] -> [batch_size, num_attention_heads, seq_length, size_per_head]
query_layer = transpose_for_scores(query_layer, batch_size,
num_attention_heads, from_seq_length,
size_per_head)
key_layer = transpose_for_scores(key_layer, batch_size,
num_attention_heads, to_seq_length,
size_per_head)
# calculate the attention scores
# [batch_size, num_attention_heads, from_seq_length, to_seq_length]
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.multiply(attention_scores, 1.0 / math.sqrt(float(size_per_head)))
if attention_mask is not None:
# [batch_size, seq_length, seq_length] -> [batch_size, 1, seq_length, seq_length]
attention_mask = tf.expand_dims(attention_mask, axis=1)
adder = (1.0 - tf.cast(attention_mask, dtype=tf.float32)) * -10000.0
attention_scores += adder
attention_probs = tf.nn.softmax(attention_scores)
attention_probs = _mh.dropout(attention_probs, attention_probs_dropout_prob)
# calculate the context layer
# [batch_size, num_attention_heads, to_seq_length, size_per_head]
value_layer = transpose_for_scores(value_layer, batch_size,
num_attention_heads, to_seq_length,
size_per_head)
context_layer = tf.matmul(attention_scores, value_layer)
# [batch_size, from_seq_length, num_attention_heads, size_per_head]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
# [batch_size, from_seq_length, width]
context_layer = tf.reshape(context_layer, [batch_size, from_seq_length, num_attention_heads * size_per_head])
return context_layer | 0.756987 | 0.342091 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Drug',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9)),
('image', models.ImageField(blank=True, upload_to='')),
('displayTill', models.DateField(blank=True)),
('categorys', models.ManyToManyField(blank=True, related_name='categorys', to='patients.Category')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firstName', models.CharField(max_length=30)),
('lastName', models.CharField(max_length=30)),
('active', models.NullBooleanField()),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Encounter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('reason', models.TextField(blank=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Patient',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firstName', models.CharField(max_length=30)),
('lastName', models.CharField(max_length=30)),
('customerType', models.CharField(blank=True, choices=[('0', 'BRONZE'), ('1', 'SILVER'), ('2', 'GOLD')], max_length=1)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Prescription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notes', models.TextField(blank=True)),
('isCurrent', models.NullBooleanField()),
('encounter', models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='encounter', to='patients.Encounter')),
('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescription', to='patients.Patient')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='PrescriptionItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('qty', models.PositiveIntegerField(blank=True)),
('drug', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescriptionItem', to='patients.Drug')),
('prescription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescriptionItems', to='patients.Prescription')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Vaccination',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('review', models.TextField(blank=True)),
('rating', models.PositiveIntegerField(blank=True)),
('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaccination', to='patients.Patient')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Vaccine',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='vaccination',
name='vaccine',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaccination', to='patients.Vaccine'),
),
migrations.AddField(
model_name='encounter',
name='patient',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='encounter', to='patients.Patient'),
),
migrations.AddField(
model_name='encounter',
name='prescription',
field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='prescription', to='patients.Prescription'),
),
migrations.AddField(
model_name='category',
name='drugs',
field=models.ManyToManyField(blank=True, related_name='drugs', to='patients.Drug'),
),
migrations.AlterUniqueTogether(
name='prescriptionitem',
unique_together=set([('prescription', 'drug')]),
),
] | patients/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Drug',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
('price', models.DecimalField(blank=True, decimal_places=2, max_digits=9)),
('image', models.ImageField(blank=True, upload_to='')),
('displayTill', models.DateField(blank=True)),
('categorys', models.ManyToManyField(blank=True, related_name='categorys', to='patients.Category')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Employee',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firstName', models.CharField(max_length=30)),
('lastName', models.CharField(max_length=30)),
('active', models.NullBooleanField()),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Encounter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('reason', models.TextField(blank=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Patient',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('firstName', models.CharField(max_length=30)),
('lastName', models.CharField(max_length=30)),
('customerType', models.CharField(blank=True, choices=[('0', 'BRONZE'), ('1', 'SILVER'), ('2', 'GOLD')], max_length=1)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Prescription',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notes', models.TextField(blank=True)),
('isCurrent', models.NullBooleanField()),
('encounter', models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='encounter', to='patients.Encounter')),
('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescription', to='patients.Patient')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='PrescriptionItem',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('qty', models.PositiveIntegerField(blank=True)),
('drug', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescriptionItem', to='patients.Drug')),
('prescription', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='prescriptionItems', to='patients.Prescription')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Vaccination',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('review', models.TextField(blank=True)),
('rating', models.PositiveIntegerField(blank=True)),
('patient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaccination', to='patients.Patient')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Vaccine',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='vaccination',
name='vaccine',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='vaccination', to='patients.Vaccine'),
),
migrations.AddField(
model_name='encounter',
name='patient',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='encounter', to='patients.Patient'),
),
migrations.AddField(
model_name='encounter',
name='prescription',
field=models.OneToOneField(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='prescription', to='patients.Prescription'),
),
migrations.AddField(
model_name='category',
name='drugs',
field=models.ManyToManyField(blank=True, related_name='drugs', to='patients.Drug'),
),
migrations.AlterUniqueTogether(
name='prescriptionitem',
unique_together=set([('prescription', 'drug')]),
),
] | 0.617628 | 0.196017 |
# isort: FIRSTPARTY
from dbus_client_gen import DbusClientUniqueResultError
# isort: LOCAL
from stratis_cli import StratisCliErrorCodes
from .._misc import RUNNER, TEST_RUNNER, SimTestCase, device_name_list
_DEVICE_STRATEGY = device_name_list(1)
class ListTestCase(SimTestCase):
"""
Test listing devices for a non-existant pool.
"""
_MENU = ["--propagate", "blockdev", "list"]
_POOLNAME = "deadpool"
def test_list(self):
"""
Listing the devices must fail since the pool does not exist.
"""
command_line = self._MENU + [self._POOLNAME]
self.check_error(
DbusClientUniqueResultError, command_line, StratisCliErrorCodes.ERROR
)
def test_list_empty(self):
"""
Listing the devices should succeed without a pool name specified.
The list should be empty.
"""
command_line = self._MENU
TEST_RUNNER(command_line)
def test_list_default(self):
"""
Blockdev subcommand should default to listing all blockdevs for all
pools. The list should be empty.
"""
command_line = self._MENU[:-1]
TEST_RUNNER(command_line)
class List2TestCase(SimTestCase):
"""
Test listing devices in an existing pool.
"""
_MENU = ["--propagate", "blockdev", "list"]
_POOLNAME = "deadpool"
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
super().setUp()
command_line = ["pool", "create"] + [self._POOLNAME] + _DEVICE_STRATEGY()
RUNNER(command_line)
def test_list(self):
"""
Listing the devices should succeed.
"""
command_line = self._MENU + [self._POOLNAME]
TEST_RUNNER(command_line)
def test_list_empty(self):
"""
Listing the devices should succeed without a pool name specified.
"""
command_line = self._MENU
TEST_RUNNER(command_line)
def test_list_default(self):
"""
Blockdev subcommand should default to listing all blockdevs for all
pools.
"""
command_line = self._MENU[:-1]
TEST_RUNNER(command_line) | tests/whitebox/integration/physical/test_list.py | # isort: FIRSTPARTY
from dbus_client_gen import DbusClientUniqueResultError
# isort: LOCAL
from stratis_cli import StratisCliErrorCodes
from .._misc import RUNNER, TEST_RUNNER, SimTestCase, device_name_list
_DEVICE_STRATEGY = device_name_list(1)
class ListTestCase(SimTestCase):
"""
Test listing devices for a non-existant pool.
"""
_MENU = ["--propagate", "blockdev", "list"]
_POOLNAME = "deadpool"
def test_list(self):
"""
Listing the devices must fail since the pool does not exist.
"""
command_line = self._MENU + [self._POOLNAME]
self.check_error(
DbusClientUniqueResultError, command_line, StratisCliErrorCodes.ERROR
)
def test_list_empty(self):
"""
Listing the devices should succeed without a pool name specified.
The list should be empty.
"""
command_line = self._MENU
TEST_RUNNER(command_line)
def test_list_default(self):
"""
Blockdev subcommand should default to listing all blockdevs for all
pools. The list should be empty.
"""
command_line = self._MENU[:-1]
TEST_RUNNER(command_line)
class List2TestCase(SimTestCase):
"""
Test listing devices in an existing pool.
"""
_MENU = ["--propagate", "blockdev", "list"]
_POOLNAME = "deadpool"
def setUp(self):
"""
Start the stratisd daemon with the simulator.
"""
super().setUp()
command_line = ["pool", "create"] + [self._POOLNAME] + _DEVICE_STRATEGY()
RUNNER(command_line)
def test_list(self):
"""
Listing the devices should succeed.
"""
command_line = self._MENU + [self._POOLNAME]
TEST_RUNNER(command_line)
def test_list_empty(self):
"""
Listing the devices should succeed without a pool name specified.
"""
command_line = self._MENU
TEST_RUNNER(command_line)
def test_list_default(self):
"""
Blockdev subcommand should default to listing all blockdevs for all
pools.
"""
command_line = self._MENU[:-1]
TEST_RUNNER(command_line) | 0.421314 | 0.143848 |
from collections import OrderedDict
import os
import pathlib
import re
import xml.etree.ElementTree as et
def get_filename(element):
return element.attrib['filename']
def get_name(element):
return element.attrib['name']
def get_value(element):
return int(element.attrib['value'], 0)
def get_start(element):
return int(element.attrib['start'], 0)
base_types = [
'address',
'offset',
'int',
'uint',
'bool',
'float',
]
ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
def is_base_type(name):
return name in base_types or sfixed_pattern.match(name) or ufixed_pattern.match(name)
def add_struct_refs(items, node):
if node.tag == 'field':
if 'type' in node.attrib and not is_base_type(node.attrib['type']):
t = node.attrib['type']
items[t] = True
return
if node.tag != 'struct' and node.tag != 'group':
return
for c in node:
add_struct_refs(items, c)
class Struct(object):
def __init__(self, xml):
self.xml = xml
self.name = xml.attrib['name']
self.deps = OrderedDict()
def find_deps(self, struct_dict, enum_dict):
deps = OrderedDict()
add_struct_refs(deps, self.xml)
for d in deps.keys():
if d in struct_dict:
self.deps[d] = struct_dict[d]
else:
assert(d in enum_dict)
def add_xml(self, items):
for d in self.deps.values():
d.add_xml(items)
items[self.name] = self.xml
# ordering of the various tag attributes
genxml_desc = {
'genxml' : [ 'name', 'gen', ],
'enum' : [ 'name', 'value', 'prefix', ],
'struct' : [ 'name', 'length', ],
'field' : [ 'name', 'start', 'end', 'type', 'default', 'prefix', ],
'instruction' : [ 'name', 'bias', 'length', 'engine', ],
'value' : [ 'name', 'value', ],
'group' : [ 'count', 'start', 'size', ],
'register' : [ 'name', 'length', 'num', ],
}
space_delta = 2
def print_node(f, offset, node):
if node.tag in [ 'enum', 'struct', 'instruction', 'register' ]:
f.write('\n')
spaces = ''.rjust(offset * space_delta)
f.write('{0}<{1}'.format(spaces, node.tag))
attribs = genxml_desc[node.tag]
for a in node.attrib:
assert(a in attribs)
for a in attribs:
if a in node.attrib:
f.write(' {0}="{1}"'.format(a, node.attrib[a]))
children = list(node)
if len(children) > 0:
f.write('>\n')
for c in children:
print_node(f, offset + 1, c)
f.write('{0}</{1}>\n'.format(spaces, node.tag))
else:
f.write('/>\n')
def process(filename):
xml = et.parse(filename)
genxml = xml.getroot()
enums = sorted(genxml.findall('enum'), key=get_name)
enum_dict = {}
for e in enums:
values = e.findall('./value')
e[:] = sorted(e, key=get_value)
enum_dict[e.attrib['name']] = e
# Structs are a bit annoying because they can refer to each other. We sort
# them alphabetically and then build a graph of depedencies. Finally we go
# through the alphabetically sorted list and print out dependencies first.
structs = sorted(xml.findall('./struct'), key=get_name)
wrapped_struct_dict = {}
for s in structs:
s[:] = sorted(s, key=get_start)
ws = Struct(s)
wrapped_struct_dict[ws.name] = ws
for s in wrapped_struct_dict:
wrapped_struct_dict[s].find_deps(wrapped_struct_dict, enum_dict)
sorted_structs = OrderedDict()
for _s in structs:
s = wrapped_struct_dict[_s.attrib['name']]
s.add_xml(sorted_structs)
instructions = sorted(xml.findall('./instruction'), key=get_name)
for i in instructions:
i[:] = sorted(i, key=get_start)
registers = sorted(xml.findall('./register'), key=get_name)
for r in registers:
r[:] = sorted(r, key=get_start)
genxml[:] = enums + list(sorted_structs.values()) + instructions + registers
with open(filename, 'w') as f:
f.write('<?xml version="1.0" ?>\n')
print_node(f, 0, genxml)
if __name__ == '__main__':
folder = pathlib.Path('.')
for f in folder.glob('*.xml'):
print('Processing {}... '.format(f), end='', flush=True)
process(f)
print('done.') | src/intel/genxml/gen_sort_tags.py |
from collections import OrderedDict
import os
import pathlib
import re
import xml.etree.ElementTree as et
def get_filename(element):
return element.attrib['filename']
def get_name(element):
return element.attrib['name']
def get_value(element):
return int(element.attrib['value'], 0)
def get_start(element):
return int(element.attrib['start'], 0)
base_types = [
'address',
'offset',
'int',
'uint',
'bool',
'float',
]
ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
def is_base_type(name):
return name in base_types or sfixed_pattern.match(name) or ufixed_pattern.match(name)
def add_struct_refs(items, node):
if node.tag == 'field':
if 'type' in node.attrib and not is_base_type(node.attrib['type']):
t = node.attrib['type']
items[t] = True
return
if node.tag != 'struct' and node.tag != 'group':
return
for c in node:
add_struct_refs(items, c)
class Struct(object):
def __init__(self, xml):
self.xml = xml
self.name = xml.attrib['name']
self.deps = OrderedDict()
def find_deps(self, struct_dict, enum_dict):
deps = OrderedDict()
add_struct_refs(deps, self.xml)
for d in deps.keys():
if d in struct_dict:
self.deps[d] = struct_dict[d]
else:
assert(d in enum_dict)
def add_xml(self, items):
for d in self.deps.values():
d.add_xml(items)
items[self.name] = self.xml
# ordering of the various tag attributes
genxml_desc = {
'genxml' : [ 'name', 'gen', ],
'enum' : [ 'name', 'value', 'prefix', ],
'struct' : [ 'name', 'length', ],
'field' : [ 'name', 'start', 'end', 'type', 'default', 'prefix', ],
'instruction' : [ 'name', 'bias', 'length', 'engine', ],
'value' : [ 'name', 'value', ],
'group' : [ 'count', 'start', 'size', ],
'register' : [ 'name', 'length', 'num', ],
}
space_delta = 2
def print_node(f, offset, node):
if node.tag in [ 'enum', 'struct', 'instruction', 'register' ]:
f.write('\n')
spaces = ''.rjust(offset * space_delta)
f.write('{0}<{1}'.format(spaces, node.tag))
attribs = genxml_desc[node.tag]
for a in node.attrib:
assert(a in attribs)
for a in attribs:
if a in node.attrib:
f.write(' {0}="{1}"'.format(a, node.attrib[a]))
children = list(node)
if len(children) > 0:
f.write('>\n')
for c in children:
print_node(f, offset + 1, c)
f.write('{0}</{1}>\n'.format(spaces, node.tag))
else:
f.write('/>\n')
def process(filename):
xml = et.parse(filename)
genxml = xml.getroot()
enums = sorted(genxml.findall('enum'), key=get_name)
enum_dict = {}
for e in enums:
values = e.findall('./value')
e[:] = sorted(e, key=get_value)
enum_dict[e.attrib['name']] = e
# Structs are a bit annoying because they can refer to each other. We sort
# them alphabetically and then build a graph of depedencies. Finally we go
# through the alphabetically sorted list and print out dependencies first.
structs = sorted(xml.findall('./struct'), key=get_name)
wrapped_struct_dict = {}
for s in structs:
s[:] = sorted(s, key=get_start)
ws = Struct(s)
wrapped_struct_dict[ws.name] = ws
for s in wrapped_struct_dict:
wrapped_struct_dict[s].find_deps(wrapped_struct_dict, enum_dict)
sorted_structs = OrderedDict()
for _s in structs:
s = wrapped_struct_dict[_s.attrib['name']]
s.add_xml(sorted_structs)
instructions = sorted(xml.findall('./instruction'), key=get_name)
for i in instructions:
i[:] = sorted(i, key=get_start)
registers = sorted(xml.findall('./register'), key=get_name)
for r in registers:
r[:] = sorted(r, key=get_start)
genxml[:] = enums + list(sorted_structs.values()) + instructions + registers
with open(filename, 'w') as f:
f.write('<?xml version="1.0" ?>\n')
print_node(f, 0, genxml)
if __name__ == '__main__':
folder = pathlib.Path('.')
for f in folder.glob('*.xml'):
print('Processing {}... '.format(f), end='', flush=True)
process(f)
print('done.') | 0.584271 | 0.306177 |
import kol.Error as Error
from .GenericRequest import GenericRequest
from kol.manager import PatternManager
from kol.util import ParseResponseUtils
class CafeRequest(GenericRequest):
"Purchases items from a cafe."
CHEZ_SNOOTEE ='1'
MICROBREWERY = '2'
HELLS_KITCHEN = '3'
def __init__(self, session, cafe, item):
super(CafeRequest, self).__init__(session)
self.session = session
self.url = session.serverURL + "cafe.php"
self.requestData['pwd'] = <PASSWORD>.pwd
self.requestData['cafeid'] = cafe
self.requestData['action'] = "CONSUME!"
self.requestData['whichitem'] = item
def parseResponse(self):
notEnoughMeatPattern = PatternManager.getOrCompilePattern('noMeatForStore')
cannotGoPattern = PatternManager.getOrCompilePattern('userShouldNotBeHere')
notSoldPattern = PatternManager.getOrCompilePattern('notSoldHere')
if cannotGoPattern.search(self.responseText):
raise Error.Error("You cannot reach that cafe.", Error.INVALID_LOCATION)
if notSoldPattern.search(self.responseText):
raise Error.Error("This cafe doesn't carry that item.", Error.ITEM_NOT_FOUND)
if notEnoughMeatPattern.search(self.responseText):
raise Error.Error("You do not have enough meat to purchase the item(s).", Error.NOT_ENOUGH_MEAT)
response = {}
advResponse = ParseResponseUtils.parseAdventuresGained(self.responseText)
if advResponse > 0:
response["adventures"] = advResponse
drunkResponse = ParseResponseUtils.parseDrunkGained(self.responseText)
if drunkResponse > 0:
response["drunkeness"] = drunkResponse
subResponse = ParseResponseUtils.parseSubstatsGainedLost(self.responseText)
if len(subResponse) > 0:
response["substats"] = subResponse
statResponse = ParseResponseUtils.parseStatsGainedLost(self.responseText)
if len(statResponse) > 0:
response["statPoints"] = statResponse
levelResponse = ParseResponseUtils.parseLevelsGained(self.responseText)
if levelResponse > 0:
response["level"] = levelResponse
effectResponse = ParseResponseUtils.parseEffectsGained(self.responseText)
if len(effectResponse) > 0:
response["effects"] = effectResponse
hpResponse = ParseResponseUtils.parseHPGainedLost(self.responseText)
if hpResponse != 0:
response["hp"] = hpResponse
mpResponse = ParseResponseUtils.parseMPGainedLost(self.responseText)
if mpResponse != 0:
response["mp"] = mpResponse
self.responseData = response | kol/request/CafeConsumeRequest.py | import kol.Error as Error
from .GenericRequest import GenericRequest
from kol.manager import PatternManager
from kol.util import ParseResponseUtils
class CafeRequest(GenericRequest):
"Purchases items from a cafe."
CHEZ_SNOOTEE ='1'
MICROBREWERY = '2'
HELLS_KITCHEN = '3'
def __init__(self, session, cafe, item):
super(CafeRequest, self).__init__(session)
self.session = session
self.url = session.serverURL + "cafe.php"
self.requestData['pwd'] = <PASSWORD>.pwd
self.requestData['cafeid'] = cafe
self.requestData['action'] = "CONSUME!"
self.requestData['whichitem'] = item
def parseResponse(self):
notEnoughMeatPattern = PatternManager.getOrCompilePattern('noMeatForStore')
cannotGoPattern = PatternManager.getOrCompilePattern('userShouldNotBeHere')
notSoldPattern = PatternManager.getOrCompilePattern('notSoldHere')
if cannotGoPattern.search(self.responseText):
raise Error.Error("You cannot reach that cafe.", Error.INVALID_LOCATION)
if notSoldPattern.search(self.responseText):
raise Error.Error("This cafe doesn't carry that item.", Error.ITEM_NOT_FOUND)
if notEnoughMeatPattern.search(self.responseText):
raise Error.Error("You do not have enough meat to purchase the item(s).", Error.NOT_ENOUGH_MEAT)
response = {}
advResponse = ParseResponseUtils.parseAdventuresGained(self.responseText)
if advResponse > 0:
response["adventures"] = advResponse
drunkResponse = ParseResponseUtils.parseDrunkGained(self.responseText)
if drunkResponse > 0:
response["drunkeness"] = drunkResponse
subResponse = ParseResponseUtils.parseSubstatsGainedLost(self.responseText)
if len(subResponse) > 0:
response["substats"] = subResponse
statResponse = ParseResponseUtils.parseStatsGainedLost(self.responseText)
if len(statResponse) > 0:
response["statPoints"] = statResponse
levelResponse = ParseResponseUtils.parseLevelsGained(self.responseText)
if levelResponse > 0:
response["level"] = levelResponse
effectResponse = ParseResponseUtils.parseEffectsGained(self.responseText)
if len(effectResponse) > 0:
response["effects"] = effectResponse
hpResponse = ParseResponseUtils.parseHPGainedLost(self.responseText)
if hpResponse != 0:
response["hp"] = hpResponse
mpResponse = ParseResponseUtils.parseMPGainedLost(self.responseText)
if mpResponse != 0:
response["mp"] = mpResponse
self.responseData = response | 0.4436 | 0.063106 |
import os, sys
import subprocess
import time
from termcolor import colored
def getCol(col, line):
p1 = line.find(col)
if p1<0 : return ""
p2 = p1 + len(col) + 1
p3 = line.find('"',p2+1)
return line[p2+1:p3]
def updateCamera():
print " -> Update device rules: eye(s)..."
try:
result = subprocess.check_output("which v4l2ctrl", shell=True)
if( not "v4l2ctrl" in result):
print colored("Cannot config webcam. Please check dependencies.","red")
sys.exit()
except:
print colored("Cannot config webcam. Please check dependencies.","red")
sys.exit()
with open("/tmp/logitechConfig.txt", "w") as fw:
fw.write("""9963776: Brightness:128
9963777: Contrast:32
9963778: Saturation:28
9963788:White Balance Temperature, Auto:0
9963795: Gain:190
9963800: Power Line Frequency:2
9963802: White Balance Temperature:0
9963803: Sharpness:191
9963804: Backlight Compensation:1
10094849: Exposure, Auto:1
10094850: Exposure (Absolute):700
10094851: Exposure, Auto Priority:0
10094856: Pan (Absolute):0
10094857: Tilt (Absolute):0
168062213: LED1 Mode:2
168062214: LED1 Frequency:255
168062321: Disable video processing:0
168062322: Raw bits per pixel:0
""")
with open("/tmp/logitechConfig_off.txt", "w") as fw:
fw.write("""9963776: Brightness:128
9963777: Contrast:32
9963778: Saturation:28
9963788:White Balance Temperature, Auto:0
9963795: Gain:190
9963800: Power Line Frequency:2
9963802: White Balance Temperature:0
9963803: Sharpness:191
9963804: Backlight Compensation:1
10094849: Exposure, Auto:1
10094850: Exposure (Absolute):700
10094851: Exposure, Auto Priority:0
10094856: Pan (Absolute):0
10094857: Tilt (Absolute):0
168062213: LED1 Mode:0
168062214: LED1 Frequency:1
168062321: Disable video processing:0
168062322: Raw bits per pixel:0
""")
result = subprocess.check_output("sudo ls /dev/video*", shell=True)
devCount=0
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig_off.txt > /dev/null 2>&1")
devCount=devCount+1
if(devCount==0):
print colored("Can not find any webcam.","red")
sys.exit()
elif(devCount>2):
print colored("Reduce the number of webcams to two.","red")
sys.exit()
time.sleep(2)
print colored("Clear /etc/udev/rules.d/25-* & /etc/udev/rules.d/26-*","green")
os.system("sudo rm /etc/udev/rules.d/25-* > /dev/null 2>&1")
os.system("sudo rm /etc/udev/rules.d/26-* > /dev/null 2>&1")
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig.txt > /dev/null 2>&1")
inputStr=raw_input("%s (r/l/N) " % ("Is it right eye or left eye or None? (dev="+numberDev+")")).lower()
selectRight=False
selectLeft=False
if(inputStr=='r'):
selectRight=True
elif(inputStr=='l'):
selectLeft=True
if(not selectRight and not selectLeft):
print colored("Continue ...","white")
continue;
result = subprocess.check_output("udevadm info -a -p $(udevadm info -q path -p /class/video4linux/video"+numberDev+")|grep ATTRS{serial}", shell=True)
data=[]
toSaverule=""
itWasSuccessfull=False
for line in result.split(os.linesep):
serial = getCol("ATTRS{serial}=", line)
if len(serial)==8:
toSaverule='SUBSYSTEM=="video4linux", SUBSYSTEMS=="usb", ATTRS{idVendor}=="046d", ATTRS{idProduct}=="080a", ATTRS{serial}=="'+serial+'", SYMLINK+="eye'+("Right" if selectRight else "Left")+'"'
data.append(serial)
print "Webcam"+numberDev+" Serial = "+ serial
with open("/etc/udev/rules.d/"+("25" if selectRight else "26")+"-C905-webcam.rules", "w") as fw:
fw.write(toSaverule)
with open("/etc/udev/rules.d/"+("25" if selectRight else "26")+"-C905-webcam.rules", "r") as fr:
rule=fr.read()
if(rule ==toSaverule):
print colored(" -> Webcam "+numberDev+" as eye"+("Right" if selectRight else "Left")+" Done.","green")
itWasSuccessfull=True
else:
print colored("Can not update device rules: eye"+("Right" if selectRight else "Left"),"red")
sys.exit()
if(not itWasSuccessfull):
print colored("Can not update device rules (Was it a logitech?): eye"+("Right" if selectRight else "Left"),"red")
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig_off.txt > /dev/null 2>&1")
if __name__ == '__main__':
if not os.geteuid()==0:
print colored("You must be root to run this application.","red")
os._exit(-1)
print "----------Start------------"
updateCamera()
print "----------Finish-----------"
exit() | src/nimbro/scripts/set_camera.py | import os, sys
import subprocess
import time
from termcolor import colored
def getCol(col, line):
p1 = line.find(col)
if p1<0 : return ""
p2 = p1 + len(col) + 1
p3 = line.find('"',p2+1)
return line[p2+1:p3]
def updateCamera():
print " -> Update device rules: eye(s)..."
try:
result = subprocess.check_output("which v4l2ctrl", shell=True)
if( not "v4l2ctrl" in result):
print colored("Cannot config webcam. Please check dependencies.","red")
sys.exit()
except:
print colored("Cannot config webcam. Please check dependencies.","red")
sys.exit()
with open("/tmp/logitechConfig.txt", "w") as fw:
fw.write("""9963776: Brightness:128
9963777: Contrast:32
9963778: Saturation:28
9963788:White Balance Temperature, Auto:0
9963795: Gain:190
9963800: Power Line Frequency:2
9963802: White Balance Temperature:0
9963803: Sharpness:191
9963804: Backlight Compensation:1
10094849: Exposure, Auto:1
10094850: Exposure (Absolute):700
10094851: Exposure, Auto Priority:0
10094856: Pan (Absolute):0
10094857: Tilt (Absolute):0
168062213: LED1 Mode:2
168062214: LED1 Frequency:255
168062321: Disable video processing:0
168062322: Raw bits per pixel:0
""")
with open("/tmp/logitechConfig_off.txt", "w") as fw:
fw.write("""9963776: Brightness:128
9963777: Contrast:32
9963778: Saturation:28
9963788:White Balance Temperature, Auto:0
9963795: Gain:190
9963800: Power Line Frequency:2
9963802: White Balance Temperature:0
9963803: Sharpness:191
9963804: Backlight Compensation:1
10094849: Exposure, Auto:1
10094850: Exposure (Absolute):700
10094851: Exposure, Auto Priority:0
10094856: Pan (Absolute):0
10094857: Tilt (Absolute):0
168062213: LED1 Mode:0
168062214: LED1 Frequency:1
168062321: Disable video processing:0
168062322: Raw bits per pixel:0
""")
result = subprocess.check_output("sudo ls /dev/video*", shell=True)
devCount=0
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig_off.txt > /dev/null 2>&1")
devCount=devCount+1
if(devCount==0):
print colored("Can not find any webcam.","red")
sys.exit()
elif(devCount>2):
print colored("Reduce the number of webcams to two.","red")
sys.exit()
time.sleep(2)
print colored("Clear /etc/udev/rules.d/25-* & /etc/udev/rules.d/26-*","green")
os.system("sudo rm /etc/udev/rules.d/25-* > /dev/null 2>&1")
os.system("sudo rm /etc/udev/rules.d/26-* > /dev/null 2>&1")
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig.txt > /dev/null 2>&1")
inputStr=raw_input("%s (r/l/N) " % ("Is it right eye or left eye or None? (dev="+numberDev+")")).lower()
selectRight=False
selectLeft=False
if(inputStr=='r'):
selectRight=True
elif(inputStr=='l'):
selectLeft=True
if(not selectRight and not selectLeft):
print colored("Continue ...","white")
continue;
result = subprocess.check_output("udevadm info -a -p $(udevadm info -q path -p /class/video4linux/video"+numberDev+")|grep ATTRS{serial}", shell=True)
data=[]
toSaverule=""
itWasSuccessfull=False
for line in result.split(os.linesep):
serial = getCol("ATTRS{serial}=", line)
if len(serial)==8:
toSaverule='SUBSYSTEM=="video4linux", SUBSYSTEMS=="usb", ATTRS{idVendor}=="046d", ATTRS{idProduct}=="080a", ATTRS{serial}=="'+serial+'", SYMLINK+="eye'+("Right" if selectRight else "Left")+'"'
data.append(serial)
print "Webcam"+numberDev+" Serial = "+ serial
with open("/etc/udev/rules.d/"+("25" if selectRight else "26")+"-C905-webcam.rules", "w") as fw:
fw.write(toSaverule)
with open("/etc/udev/rules.d/"+("25" if selectRight else "26")+"-C905-webcam.rules", "r") as fr:
rule=fr.read()
if(rule ==toSaverule):
print colored(" -> Webcam "+numberDev+" as eye"+("Right" if selectRight else "Left")+" Done.","green")
itWasSuccessfull=True
else:
print colored("Can not update device rules: eye"+("Right" if selectRight else "Left"),"red")
sys.exit()
if(not itWasSuccessfull):
print colored("Can not update device rules (Was it a logitech?): eye"+("Right" if selectRight else "Left"),"red")
for line in result.split(os.linesep):
numberDev = line.replace("/dev/video", "")
if(numberDev.isdigit()):
os.system("v4l2ctrl -d /dev/video"+numberDev+" -l /tmp/logitechConfig_off.txt > /dev/null 2>&1")
if __name__ == '__main__':
if not os.geteuid()==0:
print colored("You must be root to run this application.","red")
os._exit(-1)
print "----------Start------------"
updateCamera()
print "----------Finish-----------"
exit() | 0.060218 | 0.148664 |
from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
FunctionOOP, \
FunctionOOPField, \
CompoundOOPData, \
FunctionData, \
CompoundFunctionData
DUMP_PARTIAL = [
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="addPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='addClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to set the current clothes on a ped.' ,
arguments={
"thePed": """: The ped whose clothes you want to change. """,
"clothesTexture": """: A string determining the clothes texture that will be added. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: A string determining the clothes model that will be added. See the CJ Clothes|clothes catalog. """,
"clothesType": """: A integer representing the clothes slot/type the clothes should be added to. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully added to the ped, false otherwise.' ,
),
url='addPedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="addPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='addClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to set the current clothes on a ped.' ,
arguments={
"thePed": """: The ped whose clothes you want to change. """,
"clothesTexture": """: A string determining the clothes texture that will be added. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: A string determining the clothes model that will be added. See the CJ Clothes|clothes catalog. """,
"clothesType": """: A integer representing the clothes slot/type the clothes should be added to. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully added to the ped, false otherwise.' ,
),
url='addPedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="canPedBeKnockedOffBike",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='canBeKnockedOffBike',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the given ped can fall off bikes.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped can be knocked off bikes, false if he cannot or an invalid element was passed.' ,
),
url='canPedBeKnockedOffBike',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedAmmoInClip",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAmmoInClip',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """The ped whose ammo you want to check. """,
"weaponSlot": """an integer representing the weapon slot (set to the peds currently selected slot if not specified). """
},
result='returns an int containing the amount of ammo in the specified peds currently selected or specified clip, or 0 if the ped specified is invalid.' ,
),
url='getPedAmmoInClip',
),
field=FunctionOOPField(
name='ammoInClip',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedAmmoInClip",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAmmoInClip',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """The ped whose ammo you want to check. """,
"weaponSlot": """an integer representing the weapon slot (set to the peds currently selected slot if not specified). """
},
result='returns an int containing the amount of ammo in the specified peds currently selected or specified clip, or 0 if the ped specified is invalid.' ,
),
url='getPedAmmoInClip',
),
field=FunctionOOPField(
name='ammoInClip',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Gets the animation of a player or ped that was set using setPedAnimation.' ,
arguments={
"thePed": """the player or ped you want to get the animations|animation of. """
},
result='<syntaxhighlight lang=lua>string anim, string block, int time, bool loop, bool updateposition, bool interruptable, bool freezelastframe, int blendtime, bool restoretaskonanimend</syntaxhighlight>' ,
),
url='getPedAnimation',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current armor of the specified ped.' ,
arguments={
"thePed": """The ped whose armor you want to check """
},
result='a float with the armor, false if an invalid ped was given.' ,
),
url='getPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current armor of the specified ped.' ,
arguments={
"thePed": """The ped whose armor you want to check """
},
result='a float with the armor, false if an invalid ped was given.' ,
),
url='getPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedBonePosition",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getBonePosition',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='bone',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Returns the 3D world coordinates of a specific bone of a given ped.' ,
arguments={
"thePed": """the ped you want to inspect. """,
"bone": """the number of the bone to get the position of.
<div style="border: 3px red solid; margin-bottom:3px; padding-left:5px;"> """,
"1": """BONE_PELVIS1 """,
"2": """BONE_PELVIS """,
"3": """BONE_SPINE1 """,
"4": """BONE_UPPERTORSO """,
"5": """BONE_NECK """,
"6": """BONE_HEAD2 """,
"7": """BONE_HEAD1 """,
"8": """BONE_HEAD """,
"21": """BONE_RIGHTUPPERTORSO """,
"22": """BONE_RIGHTSHOULDER """,
"23": """BONE_RIGHTELBOW """,
"24": """BONE_RIGHTWRIST """,
"25": """BONE_RIGHTHAND """,
"26": """BONE_RIGHTTHUMB """,
"31": """BONE_LEFTUPPERTORSO """,
"32": """BONE_LEFTSHOULDER """,
"33": """BONE_LEFTELBOW """,
"34": """BONE_LEFTWRIST """,
"35": """BONE_LEFTHAND """,
"36": """BONE_LEFTTHUMB """,
"41": """BONE_LEFTHIP """,
"42": """BONE_LEFTKNEE """,
"43": """BONE_LEFTANKLE """,
"44": """BONE_LEFTFOOT """,
"51": """BONE_RIGHTHIP """,
"52": """BONE_RIGHTKNEE """,
"53": """BONE_RIGHTANKLE """,
"54": """BONE_RIGHTFOOT
</div> """
},
result='returns the x, y, z world position of the bone.' ,
),
url='getPedBonePosition',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedCameraRotation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getCameraRotation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the current camera rotation of a ped.' ,
arguments={
"thePed": """the ped to retrieve the camera rotation of. """
},
result='returns the camera rotation of the ped in degrees if successful. returns false if an invalid element was passed.' ,
),
url='getPedCameraRotation',
),
field=FunctionOOPField(
name='cameraRotation',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the current clothes texture and model of a certain type on a ped.' ,
arguments={
"thePed": """The ped whose clothes you want to retrieve. """,
"clothesType": """The type/slot of clothing you want to get. """
},
result='this function returns 2 string|strings, the clothes texture and model. the first return value will be false if this players clothes type is empty or an invalid player was specified.' ,
),
url='getPedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the current clothes texture and model of a certain type on a ped.' ,
arguments={
"thePed": """The ped whose clothes you want to retrieve. """,
"clothesType": """The type/slot of clothing you want to get. """
},
result='this function returns 2 string|strings, the clothes texture and model. the first return value will be false if this players clothes type is empty or an invalid player was specified.' ,
),
url='getPedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedContactElement",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getContactElement',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function detects the element a ped is standing on. This can be a vehicle or an object.' ,
arguments={
"thePed": """The ped of which you want to get the element he is standing on. """
},
result='returns an object or a vehicle if the ped is standing on one, false if he is touching none or an invalid element was passed.' ,
),
url='getPedContactElement',
),
field=FunctionOOPField(
name='contactElement',
types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedContactElement",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getContactElement',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function detects the element a ped is standing on. This can be a vehicle or an object.' ,
arguments={
"thePed": """The ped of which you want to get the element he is standing on. """
},
result='returns an object or a vehicle if the ped is standing on one, false if he is touching none or an invalid element was passed.' ,
),
url='getPedContactElement',
),
field=FunctionOOPField(
name='contactElement',
types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedControlState",
class_name='Ped',
method=FunctionData(
signature=FunctionSignature(
name='getControlState',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='control',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether a ped or the localplayer has a certain control pressed.' ,
arguments={
"thePed": """the ped you want to check. """,
"control": """the control to get the status of. See control names for a list of valid names. """
},
result='returns true if the ped is pressing the specified control, false if not or an invalid argument was passed.' ,
),
url='getPedControlState',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedFightingStyle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getFightingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Retrieves the fighting style a player/ped is currently using.' ,
arguments={
"thePed": """the ped whose current fighting style ID you wish to retrieve. """
},
result='returns the peds current fighting style as an integer id, false if it fails to retrieve a value.' ,
),
url='getPedFightingStyle',
),
field=FunctionOOPField(
name='fightingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedFightingStyle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getFightingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Retrieves the fighting style a player/ped is currently using.' ,
arguments={
"thePed": """the ped whose current fighting style ID you wish to retrieve. """
},
result='returns the peds current fighting style as an integer id, false if it fails to retrieve a value.' ,
),
url='getPedFightingStyle',
),
field=FunctionOOPField(
name='fightingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedGravity",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getGravity',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current gravity for the specified ped. The default gravity is 0.008.' ,
arguments={
"thePed": """The ped whose gravity you want to check. """
},
result='returns a float indicating the peds gravity, or false if the ped is invalid. default value is 0.008.' ,
),
url='getPedGravity',
),
field=FunctionOOPField(
name='gravity',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="getPedOccupiedVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the vehicle that the ped is currently in or is trying to enter, if any.' ,
arguments={
"thePed": """: The ped whose vehicle youre looking up. """
},
result='returns the vehicle that the specified ped is in, or false if the ped is not in a vehicle or is an invalid ped.' ,
),
url='getPedOccupiedVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="getPedOccupiedVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the vehicle that the ped is currently in or is trying to enter, if any.' ,
arguments={
"thePed": """: The ped whose vehicle youre looking up. """
},
result='returns the vehicle that the specified ped is in, or false if the ped is not in a vehicle or is an invalid ped.' ,
),
url='getPedOccupiedVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Prior to 1.5, the variable was .occupiedVehicleSeat""",
base_function_name="getPedOccupiedVehicleSeat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicleSeat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the seat that a specific ped is sitting in in a vehicle.' ,
arguments={
"thePed": """: The ped whose vehicle seat youre looking up. """
},
result='* returns an integer containing the number of the seat that the ped is currently in:\n** 0: front-left\n** 1: front-right\n** 2: rear-left\n** 3: rear-right\nreturns false if the ped is on foot, or the ped doesnt exist.' ,
),
url='getPedOccupiedVehicleSeat',
),
field=FunctionOOPField(
name='vehicleSeat',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Prior to 1.5, the variable was .occupiedVehicleSeat""",
base_function_name="getPedOccupiedVehicleSeat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicleSeat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the seat that a specific ped is sitting in in a vehicle.' ,
arguments={
"thePed": """: The ped whose vehicle seat youre looking up. """
},
result='* returns an integer containing the number of the seat that the ped is currently in:\n** 0: front-left\n** 1: front-right\n** 2: rear-left\n** 3: rear-right\nreturns false if the ped is on foot, or the ped doesnt exist.' ,
),
url='getPedOccupiedVehicleSeat',
),
field=FunctionOOPField(
name='vehicleSeat',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedOxygenLevel",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOxygenLevel',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current oxygen level of the specified ped.' ,
arguments={
"thePed": """The ped whose oxygen level you want to check """
},
result='a float with the oxygen level, false if an invalid ped was given.' ,
),
url='getPedOxygenLevel',
),
field=FunctionOOPField(
name='oxygenLevel',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedStat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getStat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='stat',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the value of the specified statistic of a specific ped.' ,
arguments={
"thePed": """: The ped whose stat you want to retrieve. """,
"stat": """: A whole number determining the stat ID. """
},
result='returns the value of the requested statistic.' ,
),
url='getPedStat',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedStat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getStat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='stat',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the value of the specified statistic of a specific ped.' ,
arguments={
"thePed": """: The ped whose stat you want to retrieve. """,
"stat": """: A whole number determining the stat ID. """
},
result='returns the value of the requested statistic.' ,
),
url='getPedStat',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedTarget",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTarget',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the element a ped is currently targeting.' ,
arguments={
"thePed": """The ped whose target you want to retrieve. """
},
result='returns the element thats being targeted, or false if there isnt one.\nthis is only effective on physical gta elements, namely:\n* players\n* peds\n* vehicles\n* objects' ,
),
url='getPedTarget',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTarget",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTarget',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the element a ped is currently targeting.' ,
arguments={
"thePed": """The ped whose target you want to retrieve. """
},
result='returns the element thats being targeted, or false if there isnt one.\nthis is only effective on physical gta elements, namely:\n* players\n* peds\n* vehicles\n* objects' ,
),
url='getPedTarget',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTargetEnd",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTargetEnd',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='targetingPed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows retrieval of the position where a peds target range ends, when he is aiming with a weapon.' ,
arguments={
"targetingPed": """the ped who is targeting whose target end you wish to retrieve """
},
result='returns three floats, x,y,z, representing the position where the peds target ends according to his range, or false if it was unsuccessful.' ,
),
url='getPedTargetEnd',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTask",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTask',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='priority',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='taskType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get any simple or complex task of a certain type for a ped.\nIt can provide feedback on all tasks relating to a ped. For example, while jumping, getPedSimplestTask will return TASK_SIMPLE_IN_AIR. If you wanted to know specifically if the player has jumped, you would use this function. If you did you will discover that while jumping Primary task 3 is TASK_COMPLEX_JUMP.' ,
arguments={
"thePed": """: The ped whose task you want to retrieve. """,
"priority": """: A string determining which set of tasks you want to retrieve it from. This must be either primary or secondary. """,
"taskType": """: An integer value representing the task type (or slot) you want to get the task from. Types can be: """,
"PRIMARY TASKS": """ """,
"0": """TASK_SECONDARY_ATTACK """,
"1": """TASK_SECONDARY_DUCK """,
"2": """TASK_SECONDARY_SAY """,
"3": """TASK_SECONDARY_FACIAL_COMPLEX """,
"4": """TASK_SECONDARY_PARTIAL_ANIM """,
"SECONDARY TASKS": """ """,
"5": """TASK_SECONDARY_IK """
},
result='returns the name of the most complex task. see list of player tasks for valid strings. returns false if invalid arguments are specified or if there is no task of the type specified.\n<br>\nreturns between 1 and 4 strings. the first string contains the name of the most complex task, with simpler sub-tasks being named in the following strings. see list of player tasks for valid strings. returns false if invalid arguments are specified or if there is no task of the type specified.' ,
),
url='getPedTask',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedTotalAmmo",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTotalAmmo',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the total ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """: The ped whose ammo you want to check. """,
"weaponSlot": """: an integer representing the weapon slot (set to the peds current slot if not given) """
},
result='returns an int containing the total amount of ammo for the specified peds weapon, or 0 if the ped specified is invalid.' ,
),
url='getPedTotalAmmo',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTotalAmmo",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTotalAmmo',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the total ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """: The ped whose ammo you want to check. """,
"weaponSlot": """: an integer representing the weapon slot (set to the peds current slot if not given) """
},
result='returns an int containing the total amount of ammo for the specified peds weapon, or 0 if the ped specified is invalid.' ,
),
url='getPedTotalAmmo',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='getWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped whose walking style to retrieve. """
},
result='returns the walking style id if successful, false otherwise. the possible walking styles are as follows:' ,
),
url='getPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='getWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped whose walking style to retrieve. """
},
result='returns the walking style id if successful, false otherwise. the possible walking styles are as follows:' ,
),
url='getPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function tells you which weapon type is in a certain weapon|weapon slot of a ped.' ,
arguments={
"thePed": """: the ped you want to get the weapon type from. """,
"weaponSlot": """: an integer representing the weapon|weapon slot (set to the peds current slot if not given). """
},
result='returns an int indicating the type of the weapon the ped has in the specified slot. if the slot is empty, it returns 0.\nit should be noted that if a ped runs out of ammo for a weapon, it will still return the id of that weapon in the slot (even if it appears as if the ped does not have a weapon at all), though getpedtotalammo will return 0. therefore, getpedtotalammo should be used in conjunction with getpedweapon in order to check if a ped has a weapon.' ,
),
url='getPedWeapon',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function tells you which weapon type is in a certain weapon|weapon slot of a ped.' ,
arguments={
"thePed": """: the ped you want to get the weapon type from. """,
"weaponSlot": """: an integer representing the weapon|weapon slot (set to the peds current slot if not given). """
},
result='returns an int indicating the type of the weapon the ped has in the specified slot. if the slot is empty, it returns 0.\nit should be noted that if a ped runs out of ammo for a weapon, it will still return the id of that weapon in the slot (even if it appears as if the ped does not have a weapon at all), though getpedtotalammo will return 0. therefore, getpedtotalammo should be used in conjunction with getpedweapon in order to check if a ped has a weapon.' ,
),
url='getPedWeapon',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets a peds selected weapon slot.' ,
arguments={
"thePed": """the ped to get the current weapon slot of. """
},
result='returns the selected weapon slot id on success, false otherwise.' ,
),
url='getPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets a peds selected weapon slot.' ,
arguments={
"thePed": """the ped to get the current weapon slot of. """
},
result='returns the selected weapon slot id on success, false otherwise.' ,
),
url='getPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedBleeding",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isBleeding',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """The player or ped whose bleeding effect state you want to get. """
},
result='returns true if the player or ped is bleeding, false otherwise.' ,
),
url='isPedBleeding',
),
field=FunctionOOPField(
name='bleeding',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is choking (coughing) or not. This happens as a result of weapons that produce smoke - smoke grenades, fire extinguisher and the spray can.' ,
arguments={
"thePed": """: The ped you wish to check """
},
result='returns true if the ped is choking, false otherwise.' ,
),
url='isPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is choking (coughing) or not. This happens as a result of weapons that produce smoke - smoke grenades, fire extinguisher and the spray can.' ,
arguments={
"thePed": """: The ped you wish to check """
},
result='returns true if the ped is choking, false otherwise.' ,
),
url='isPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDead",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDead',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is dead or not.' ,
arguments={
"thePed": """: the ped you want to check up on. """
},
result='returns true if the ped is dead, false otherwise.' ,
),
url='isPedDead',
),
field=FunctionOOPField(
name='dead',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDead",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDead',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is dead or not.' ,
arguments={
"thePed": """: the ped you want to check up on. """
},
result='returns true if the ped is dead, false otherwise.' ,
),
url='isPedDead',
),
field=FunctionOOPField(
name='dead',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDoingGangDriveby",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDoingGangDriveby',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the ped is in the driveby state.' ,
arguments={
"thePed": """The ped element whose state is to be checked. """
},
result='returns true if the driveby state is enabled, false otherwise.' ,
),
url='isPedDoingGangDriveby',
),
field=FunctionOOPField(
name='doingGangDriveby',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDoingGangDriveby",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDoingGangDriveby',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the ped is in the driveby state.' ,
arguments={
"thePed": """The ped element whose state is to be checked. """
},
result='returns true if the driveby state is enabled, false otherwise.' ,
),
url='isPedDoingGangDriveby',
),
field=FunctionOOPField(
name='doingGangDriveby',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDucked",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDucked',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is ducked (crouched) or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is ducked, false otherwise.' ,
),
url='isPedDucked',
),
field=FunctionOOPField(
name='ducked',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDucked",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDucked',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is ducked (crouched) or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is ducked, false otherwise.' ,
),
url='isPedDucked',
),
field=FunctionOOPField(
name='ducked',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedInVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isInVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether or not a given ped is currently in a vehicle.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped is in a vehicle, false if he is on foot or an invalid element was passed.' ,
),
url='isPedInVehicle',
),
field=FunctionOOPField(
name='inVehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedInVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isInVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether or not a given ped is currently in a vehicle.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped is in a vehicle, false if he is on foot or an invalid element was passed.' ,
),
url='isPedInVehicle',
),
field=FunctionOOPField(
name='inVehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is on fire or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is on fire, false otherwise.' ,
),
url='isPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is on fire or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is on fire, false otherwise.' ,
),
url='isPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedOnGround",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnGround',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is on the ground. This is for on-foot usage only.' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is on foot and on the ground, false otherwise, even if he is in a car that stands still or on object outside world map.' ,
),
url='isPedOnGround',
),
field=FunctionOOPField(
name='onGround',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedOnGround",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnGround',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is on the ground. This is for on-foot usage only.' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is on foot and on the ground, false otherwise, even if he is in a car that stands still or on object outside world map.' ,
),
url='isPedOnGround',
),
field=FunctionOOPField(
name='onGround',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedReloadingWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isReloadingWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is currently reloading their weapon. Useful to stop certain quick reload exploits.}}' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is currently reloading a weapon, false otherwise.' ,
),
url='isPedReloadingWeapon',
),
field=FunctionOOPField(
name='reloadingWeapon',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped you want to check """
},
result='returns true if the ped is carrying a jetpack, false if he is not or an invalid element was passed.' ,
),
url='isPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped you want to check """
},
result='returns true if the ped is carrying a jetpack, false if he is not or an invalid element was passed.' ,
),
url='isPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="killPed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='kill',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theKiller',
argument_type=FunctionType(
names=['ped'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='weapon',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='bodyPart',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='stealth',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function kills the specified ped.\nFrom v1.5.3 onwards this function is now available client side. Only works on client side peds.' ,
arguments={
"thePed": """The ped to kill """,
"theKiller": """The ped responsible for the kill """,
"weapon": """The ID of the weapon or Damage Types that should appear to have killed the ped (doesnt affect how they die) """,
"bodyPart": """The ID of the body part that should appear to have been hit by the weapon (doesnt affect how they die) """,
"stealth": """Boolean value, representing whether or not this a stealth kill """
},
result='returns true if the ped was killed, false if the ped specified could not be killed or is invalid.' ,
),
url='killPed',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="killPed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='kill',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theKiller',
argument_type=FunctionType(
names=['ped'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='weapon',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='bodyPart',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='stealth',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function kills the specified ped.\nFrom v1.5.3 onwards this function is now available client side. Only works on client side peds.' ,
arguments={
"thePed": """The ped to kill """,
"theKiller": """The ped responsible for the kill """,
"weapon": """The ID of the weapon or Damage Types that should appear to have killed the ped (doesnt affect how they die) """,
"bodyPart": """The ID of the body part that should appear to have been hit by the weapon (doesnt affect how they die) """,
"stealth": """Boolean value, representing whether or not this a stealth kill """
},
result='returns true if the ped was killed, false if the ped specified could not be killed or is invalid.' ,
),
url='killPed',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="reloadPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='reloadWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function makes a pedestrian reload their weapon.' ,
arguments={
"thePed": """The ped who will reload their weapon. """
},
result='returns true if the pedestrian was made to reload, or false if invalid arguments were passed or that pedestrian has a weapon which cannot be reloaded.\nnote: this will fail but return true if\n1) the ped is crouched and moving\n2) the ped is using a weapon without clip ammo (or minigun/flamethrower/fire\nextinguisher)\n3) the ped is using his weapon (shooting/aiming)\n4) the ped moved while crouching recently\ndue to these circumstances causing problems with this function' ,
),
url='reloadPedWeapon',
),
field=None,
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="removePedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to remove the current clothes of a certain type on a ped. It will remove them if the clothesTexture and clothesModel arent specified, or if they match the current clothes on that slot.' ,
arguments={
"thePed": """: The ped you want to remove clothes from. """,
"clothesType": """: the clothes slot/type to remove. See the CJ Clothes|clothes catalog. """,
"clothesTexture": """: (Server only) A string determining the clothes texture that will be removed. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: (Server only) A string determining the clothes model that will be removed. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully removed from the ped, false otherwise.' ,
),
url='removePedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="removePedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to remove the current clothes of a certain type on a ped. It will remove them if the clothesTexture and clothesModel arent specified, or if they match the current clothes on that slot.' ,
arguments={
"thePed": """: The ped you want to remove clothes from. """,
"clothesType": """: the clothes slot/type to remove. See the CJ Clothes|clothes catalog. """,
"clothesTexture": """: (Server only) A string determining the clothes texture that will be removed. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: (Server only) A string determining the clothes model that will be removed. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully removed from the ped, false otherwise.' ,
),
url='removePedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute this function""",
base_function_name="removePedFromVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeFromVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function removes a ped from a vehicle immediately. This works for drivers and passengers. Note that this removes the ped from the vehicle and puts him in the exact position where the command was initiated.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped you wish to remove from a vehicle """
},
result='returns true if the operation was successful, false if the specified ped is not valid or if it isnt in a vehicle.' ,
),
url='removePedFromVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute this function""",
base_function_name="removePedFromVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeFromVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function removes a ped from a vehicle immediately. This works for drivers and passengers. Note that this removes the ped from the vehicle and puts him in the exact position where the command was initiated.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped you wish to remove from a vehicle """
},
result='returns true if the operation was successful, false if the specified ped is not valid or if it isnt in a vehicle.' ,
),
url='removePedFromVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='block',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='time',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='-1',
)
],
[
FunctionArgument(
name='loop',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='updatePosition',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='interruptable',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='freezeLastFrame',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='blendTime',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='250',
)
],
[
FunctionArgument(
name='retainPedState',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current Animations|animation of a player or ped. Not specifying the type of animation will automatically cancel the current one.' ,
arguments={
"thePed": """the player or ped you want to apply an Animations|animation to. """,
"block": """the Animations|animation blocks name. """,
"anim": """the name of the Animations|animation within the block. """,
"time": """how long the animation will run for in milliseconds. """,
"loop": """indicates whether or not the animation will loop. """,
"updatePosition": """will change the actual coordinates of the ped according to the animation. Use this for e.g. walking animations. """,
"interruptable": """if set to false other tasks wont be able to interupt the animation. Setting this to false also gives this function more power to override other animations that are running. For example, squatting after a jump can be terminated. """,
"freezeLastFrame": """if set to true after animation the last frame will be frozen, otherwise the animation will end and controls will return. """,
"blendTime": """how long the animation will mixed with the previous one in milliseconds. """,
"retainPedState": """will restore the task which was playing before calling this function. Useful for restoring the crouch task after animation ends. This may be extended in the future to support other states/tasks.
|16632}} """
},
result='returns true if succesful, false otherwise.' ,
),
url='setPedAnimation',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='block',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='time',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='-1',
)
],
[
FunctionArgument(
name='loop',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='updatePosition',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='interruptable',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='freezeLastFrame',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='blendTime',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='250',
)
],
[
FunctionArgument(
name='retainPedState',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current Animations|animation of a player or ped. Not specifying the type of animation will automatically cancel the current one.' ,
arguments={
"thePed": """the player or ped you want to apply an Animations|animation to. """,
"block": """the Animations|animation blocks name. """,
"anim": """the name of the Animations|animation within the block. """,
"time": """how long the animation will run for in milliseconds. """,
"loop": """indicates whether or not the animation will loop. """,
"updatePosition": """will change the actual coordinates of the ped according to the animation. Use this for e.g. walking animations. """,
"interruptable": """if set to false other tasks wont be able to interupt the animation. Setting this to false also gives this function more power to override other animations that are running. For example, squatting after a jump can be terminated. """,
"freezeLastFrame": """if set to true after animation the last frame will be frozen, otherwise the animation will end and controls will return. """,
"blendTime": """how long the animation will mixed with the previous one in milliseconds. """,
"retainPedState": """will restore the task which was playing before calling this function. Useful for restoring the crouch task after animation ends. This may be extended in the future to support other states/tasks.
|16632}} """
},
result='returns true if succesful, false otherwise.' ,
),
url='setPedAnimation',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationProgress",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationProgress',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='progress',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current animation progress of a player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation progress. """,
"anim": """the animation name currently applied to ped, if not supplied, the animation will stop """,
"progress": """current animation progress you want to apply, value from 0.0 to 1.0, if not supplied will default to 0.0 """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationProgress',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationProgress",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationProgress',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='progress',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current animation progress of a player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation progress. """,
"anim": """the animation name currently applied to ped, if not supplied, the animation will stop """,
"progress": """current animation progress you want to apply, value from 0.0 to 1.0, if not supplied will default to 0.0 """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationProgress',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationSpeed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationSpeed',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='""',
)
],
[
FunctionArgument(
name='speed',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value='1.0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the speed of a currently running animation for a particular player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation speed of. """,
"anim": """the animation name it will affect. """,
"speed": """a float containing the speed between 0.0–1.0 you want to apply to the animation. This limitation may be adjusted in the future, so do not provide speeds outside this boundary. {{New feature/item|3.0158|1.5.7|20395|The limit is now 0.0 to 10.0.}} {{Warning|Setting speed higher than 1 can cause issues with some animations.}} """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationSpeed',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationSpeed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationSpeed',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='""',
)
],
[
FunctionArgument(
name='speed',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value='1.0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the speed of a currently running animation for a particular player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation speed of. """,
"anim": """the animation name it will affect. """,
"speed": """a float containing the speed between 0.0–1.0 you want to apply to the animation. This limitation may be adjusted in the future, so do not provide speeds outside this boundary. {{New feature/item|3.0158|1.5.7|20395|The limit is now 0.0 to 10.0.}} {{Warning|Setting speed higher than 1 can cause issues with some animations.}} """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationSpeed',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='armor',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the armor value of a ped.' ,
arguments={
"thePed": """: the ped whose armor you want to modify. """,
"armor": """: the amount of armor you want to set on the ped. Valid values are from 0 to 100. """
},
result='returns true if the armor was changed succesfully. returns false if an invalid ped was specified, or the armor value specified is out of acceptable range.' ,
),
url='setPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='armor',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the armor value of a ped.' ,
arguments={
"thePed": """: the ped whose armor you want to modify. """,
"armor": """: the amount of armor you want to set on the ped. Valid values are from 0 to 100. """
},
result='returns true if the armor was changed succesfully. returns false if an invalid ped was specified, or the armor value specified is out of acceptable range.' ,
),
url='setPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedBleeding",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setBleeding',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='bleeding',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """The player or ped whose bleeding effect you want to set of. """,
"bleeding": """Boolean specifying whether the player or ped is bleeding or not. """
},
result='returns true if the bleeding state was successfully set, false otherwise.' ,
),
url='setPedBleeding',
),
field=FunctionOOPField(
name='bleeding',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedCameraRotation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setCameraRotation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='cameraRotation',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function sets the camera rotation of a ped, e.g. where its camera will look at. Dont confuse this with getCameraMatrix, because that function is designed for fixed (scripted) camera moves.' ,
arguments={
"thePed": """The ped whose camera rotation is to be changed. """,
"cameraRotation": """The new direction that the ped will walk if you set their forwards control state. If the ped is the local player, it will also change where his camera is looking at if it isnt fixed (i.e. camera target is the local player). """
},
result='returns true if the camera rotation was changed, false otherwise.' ,
),
url='setPedCameraRotation',
),
field=FunctionOOPField(
name='cameraRotation',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedCanBeKnockedOffBike",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setCanBeKnockedOffBike',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='canBeKnockedOffBike',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function controls if a ped can fall of his bike by accident - namely by banging into a wall.' ,
arguments={
"thePed": """the ped whose knockoffstatus is being changed """,
"canBeKnockedOffBike": """true or false """
},
result='' ,
),
url='setPedCanBeKnockedOffBike',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='choking',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to force the ped to do the choking (coughing) animation until he respawns or toggled off using this function. The animation can not be cancelled by a player its applied to, and he will not loose health.' ,
arguments={
"thePed": """The ped whose choking status to toggle """,
"choking": """true to make the ped choke, false to no longer force his choking animation """
},
result='returns true if successful, false otherwise (e.g. player handle is invalid)' ,
),
url='setPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedControlState",
class_name='Ped',
method=FunctionData(
signature=FunctionSignature(
name='setControlState',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='control',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='state',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function makes a ped or player press or release a certain control.' ,
arguments={
"thePed": """the ped you want to press or release a control. """,
"control": """the name of the control of which to change the state. See control names for a list of valid names. """,
"state": """the new control state. true means pressed, false is released. """
},
result='returns true if successful, false if otherwise.' ,
),
url='setPedControlState',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedGravity",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setGravity',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='gravity',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function sets the gravity level of a ped.' ,
arguments={
"thePed": """: The ped whose gravity to change. """,
"level": """: The level of gravity (default is 0.008). """
},
result='returns true if the gravity was successfully set, false otherwise' ,
),
url='setPedGravity',
),
field=FunctionOOPField(
name='gravity',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedHeadless",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setHeadless',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='headState',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='With this function, you can set if a ped has a head or not.' ,
arguments={
"thePed": """: The ped to check. """,
"headState": """: head state, use true if you want the ped be headless, use false to give back the head. """
},
result='returns true if successful, false otherwise' ,
),
url='setPedHeadless',
),
field=FunctionOOPField(
name='headless',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedHeadless",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setHeadless',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='headState',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='With this function, you can set if a ped has a head or not.' ,
arguments={
"thePed": """: The ped to check. """,
"headState": """: head state, use true if you want the ped be headless, use false to give back the head. """
},
result='returns true if successful, false otherwise' ,
),
url='setPedHeadless',
),
field=FunctionOOPField(
name='headless',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='isOnFire',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to set a ped on fire or extinguish a fire on it.' ,
arguments={
"thePed": """The ped that we want to set/unset """,
"isOnFire": """true to set the ped on fire, false to extinguish any fire on him """
},
result='returns true if successful, false otherwise' ,
),
url='setPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='isOnFire',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to set a ped on fire or extinguish a fire on it.' ,
arguments={
"thePed": """The ped that we want to set/unset """,
"isOnFire": """true to set the ped on fire, false to extinguish any fire on him """
},
result='returns true if successful, false otherwise' ,
),
url='setPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedOxygenLevel",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOxygenLevel',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='oxygen',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the oxygen level of a ped.' ,
arguments={
"thePed": """: the ped whose oxygen level you want to modify. """,
"oxygen": """: the amount of oxygen you want to set on the ped. Native values are from 0 to 1000. Each of the stamina (22) and underwater stamina (225) Template:Stats|stat maximum adds a bonus of 1500. So the maximum oxygen level is 4000. """
},
result='returns true if the oxygen level was changed succesfully. returns false if an invalid ped and/or oxygen level was specified.' ,
),
url='setPedOxygenLevel',
),
field=FunctionOOPField(
name='oxygenLevel',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedVoice",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setVoice',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='voiceType',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='voiceName',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Changes the voice of a ped.' ,
arguments={
"thePed": """the ped whose voice to change. """,
"voiceType": """the voice type. See ped voices for possible types. """,
"voiceName": """the voice name within the specified type. See ped voices for possible voices. """
},
result='returns true when the voice was successfully set, false otherwise.' ,
),
url='setPedVoice',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='setWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='style',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the walking style of a ped. A walking style consists of a set of animations that are used for walking, running etc.' ,
arguments={
"thePed": """the ped whose walking style to change. """,
"style": """the walking style to set.
The possible walking styles are: """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='setWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='style',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the walking style of a ped. A walking style consists of a set of animations that are used for walking, running etc.' ,
arguments={
"thePed": """the ped whose walking style to change. """,
"style": """the walking style to set.
The possible walking styles are: """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function changes the selected weapon slot of a ped.' ,
arguments={
"thePed": """the ped whose weapon slot you want to set. In a clientside script, this cannot be used on remote players. """,
"weaponSlot": """the weapon slot to set. """
},
result='returns true if successful in setting the peds equipped weapon slot, false otherwise.' ,
),
url='setPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function changes the selected weapon slot of a ped.' ,
arguments={
"thePed": """the ped whose weapon slot you want to set. In a clientside script, this cannot be used on remote players. """,
"weaponSlot": """the weapon slot to set. """
},
result='returns true if successful in setting the peds equipped weapon slot, false otherwise.' ,
),
url='setPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='state',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to give or take a jetpack from a ped, it wont work if the ped is in a vehicle.\nAs such, you should either expect it to fail sometimes, or repeatedly try to give a jetpack every second or so until isPedWearingJetpack returns true. Alternatively, you can force the ped into a safe position (e.g. standing on the ground) before giving the jetpack, or use a pickup to handle it.}}' ,
arguments={
"thePed": """The ped you want to give a jetpack to. """,
"state": """A boolean representing whether to give or take the jetpack. """
},
result='returns true if a jetpack was successfully set for the ped, false if setting it failed.' ,
),
url='setPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="warpPedIntoVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='warpIntoVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theVehicle',
argument_type=FunctionType(
names=['vehicle'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='seat',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to warp or force a ped into a vehicle. There are no animations involved when this happens.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped which you wish to force inside the vehicle """,
"theVehicle": """The vehicle you wish to force the ped into """,
"seat": """An integer representing the seat ID. """,
"0": """Front-left """,
"1": """Front-right """,
"2": """Rear-left """,
"3": """Rear-right """
},
result='returns true if the operation is successful, false otherwise.' ,
),
url='warpPedIntoVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="warpPedIntoVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='warpIntoVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theVehicle',
argument_type=FunctionType(
names=['vehicle'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='seat',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to warp or force a ped into a vehicle. There are no animations involved when this happens.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped which you wish to force inside the vehicle """,
"theVehicle": """The vehicle you wish to force the ped into """,
"seat": """An integer representing the seat ID. """,
"0": """Front-left """,
"1": """Front-right """,
"2": """Rear-left """,
"3": """Rear-right """
},
result='returns true if the operation is successful, false otherwise.' ,
),
url='warpPedIntoVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
)
] | oops/ped_functions.py | from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
FunctionOOP, \
FunctionOOPField, \
CompoundOOPData, \
FunctionData, \
CompoundFunctionData
DUMP_PARTIAL = [
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="addPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='addClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to set the current clothes on a ped.' ,
arguments={
"thePed": """: The ped whose clothes you want to change. """,
"clothesTexture": """: A string determining the clothes texture that will be added. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: A string determining the clothes model that will be added. See the CJ Clothes|clothes catalog. """,
"clothesType": """: A integer representing the clothes slot/type the clothes should be added to. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully added to the ped, false otherwise.' ,
),
url='addPedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="addPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='addClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to set the current clothes on a ped.' ,
arguments={
"thePed": """: The ped whose clothes you want to change. """,
"clothesTexture": """: A string determining the clothes texture that will be added. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: A string determining the clothes model that will be added. See the CJ Clothes|clothes catalog. """,
"clothesType": """: A integer representing the clothes slot/type the clothes should be added to. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully added to the ped, false otherwise.' ,
),
url='addPedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="canPedBeKnockedOffBike",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='canBeKnockedOffBike',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the given ped can fall off bikes.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped can be knocked off bikes, false if he cannot or an invalid element was passed.' ,
),
url='canPedBeKnockedOffBike',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedAmmoInClip",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAmmoInClip',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """The ped whose ammo you want to check. """,
"weaponSlot": """an integer representing the weapon slot (set to the peds currently selected slot if not specified). """
},
result='returns an int containing the amount of ammo in the specified peds currently selected or specified clip, or 0 if the ped specified is invalid.' ,
),
url='getPedAmmoInClip',
),
field=FunctionOOPField(
name='ammoInClip',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedAmmoInClip",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAmmoInClip',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """The ped whose ammo you want to check. """,
"weaponSlot": """an integer representing the weapon slot (set to the peds currently selected slot if not specified). """
},
result='returns an int containing the amount of ammo in the specified peds currently selected or specified clip, or 0 if the ped specified is invalid.' ,
),
url='getPedAmmoInClip',
),
field=FunctionOOPField(
name='ammoInClip',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Gets the animation of a player or ped that was set using setPedAnimation.' ,
arguments={
"thePed": """the player or ped you want to get the animations|animation of. """
},
result='<syntaxhighlight lang=lua>string anim, string block, int time, bool loop, bool updateposition, bool interruptable, bool freezelastframe, int blendtime, bool restoretaskonanimend</syntaxhighlight>' ,
),
url='getPedAnimation',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current armor of the specified ped.' ,
arguments={
"thePed": """The ped whose armor you want to check """
},
result='a float with the armor, false if an invalid ped was given.' ,
),
url='getPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current armor of the specified ped.' ,
arguments={
"thePed": """The ped whose armor you want to check """
},
result='a float with the armor, false if an invalid ped was given.' ,
),
url='getPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedBonePosition",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getBonePosition',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='bone',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Returns the 3D world coordinates of a specific bone of a given ped.' ,
arguments={
"thePed": """the ped you want to inspect. """,
"bone": """the number of the bone to get the position of.
<div style="border: 3px red solid; margin-bottom:3px; padding-left:5px;"> """,
"1": """BONE_PELVIS1 """,
"2": """BONE_PELVIS """,
"3": """BONE_SPINE1 """,
"4": """BONE_UPPERTORSO """,
"5": """BONE_NECK """,
"6": """BONE_HEAD2 """,
"7": """BONE_HEAD1 """,
"8": """BONE_HEAD """,
"21": """BONE_RIGHTUPPERTORSO """,
"22": """BONE_RIGHTSHOULDER """,
"23": """BONE_RIGHTELBOW """,
"24": """BONE_RIGHTWRIST """,
"25": """BONE_RIGHTHAND """,
"26": """BONE_RIGHTTHUMB """,
"31": """BONE_LEFTUPPERTORSO """,
"32": """BONE_LEFTSHOULDER """,
"33": """BONE_LEFTELBOW """,
"34": """BONE_LEFTWRIST """,
"35": """BONE_LEFTHAND """,
"36": """BONE_LEFTTHUMB """,
"41": """BONE_LEFTHIP """,
"42": """BONE_LEFTKNEE """,
"43": """BONE_LEFTANKLE """,
"44": """BONE_LEFTFOOT """,
"51": """BONE_RIGHTHIP """,
"52": """BONE_RIGHTKNEE """,
"53": """BONE_RIGHTANKLE """,
"54": """BONE_RIGHTFOOT
</div> """
},
result='returns the x, y, z world position of the bone.' ,
),
url='getPedBonePosition',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedCameraRotation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getCameraRotation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the current camera rotation of a ped.' ,
arguments={
"thePed": """the ped to retrieve the camera rotation of. """
},
result='returns the camera rotation of the ped in degrees if successful. returns false if an invalid element was passed.' ,
),
url='getPedCameraRotation',
),
field=FunctionOOPField(
name='cameraRotation',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the current clothes texture and model of a certain type on a ped.' ,
arguments={
"thePed": """The ped whose clothes you want to retrieve. """,
"clothesType": """The type/slot of clothing you want to get. """
},
result='this function returns 2 string|strings, the clothes texture and model. the first return value will be false if this players clothes type is empty or an invalid player was specified.' ,
),
url='getPedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the current clothes texture and model of a certain type on a ped.' ,
arguments={
"thePed": """The ped whose clothes you want to retrieve. """,
"clothesType": """The type/slot of clothing you want to get. """
},
result='this function returns 2 string|strings, the clothes texture and model. the first return value will be false if this players clothes type is empty or an invalid player was specified.' ,
),
url='getPedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedContactElement",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getContactElement',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function detects the element a ped is standing on. This can be a vehicle or an object.' ,
arguments={
"thePed": """The ped of which you want to get the element he is standing on. """
},
result='returns an object or a vehicle if the ped is standing on one, false if he is touching none or an invalid element was passed.' ,
),
url='getPedContactElement',
),
field=FunctionOOPField(
name='contactElement',
types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedContactElement",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getContactElement',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function detects the element a ped is standing on. This can be a vehicle or an object.' ,
arguments={
"thePed": """The ped of which you want to get the element he is standing on. """
},
result='returns an object or a vehicle if the ped is standing on one, false if he is touching none or an invalid element was passed.' ,
),
url='getPedContactElement',
),
field=FunctionOOPField(
name='contactElement',
types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedControlState",
class_name='Ped',
method=FunctionData(
signature=FunctionSignature(
name='getControlState',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='control',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether a ped or the localplayer has a certain control pressed.' ,
arguments={
"thePed": """the ped you want to check. """,
"control": """the control to get the status of. See control names for a list of valid names. """
},
result='returns true if the ped is pressing the specified control, false if not or an invalid argument was passed.' ,
),
url='getPedControlState',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedFightingStyle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getFightingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Retrieves the fighting style a player/ped is currently using.' ,
arguments={
"thePed": """the ped whose current fighting style ID you wish to retrieve. """
},
result='returns the peds current fighting style as an integer id, false if it fails to retrieve a value.' ,
),
url='getPedFightingStyle',
),
field=FunctionOOPField(
name='fightingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedFightingStyle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getFightingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Retrieves the fighting style a player/ped is currently using.' ,
arguments={
"thePed": """the ped whose current fighting style ID you wish to retrieve. """
},
result='returns the peds current fighting style as an integer id, false if it fails to retrieve a value.' ,
),
url='getPedFightingStyle',
),
field=FunctionOOPField(
name='fightingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedGravity",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getGravity',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current gravity for the specified ped. The default gravity is 0.008.' ,
arguments={
"thePed": """The ped whose gravity you want to check. """
},
result='returns a float indicating the peds gravity, or false if the ped is invalid. default value is 0.008.' ,
),
url='getPedGravity',
),
field=FunctionOOPField(
name='gravity',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="getPedOccupiedVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the vehicle that the ped is currently in or is trying to enter, if any.' ,
arguments={
"thePed": """: The ped whose vehicle youre looking up. """
},
result='returns the vehicle that the specified ped is in, or false if the ped is not in a vehicle or is an invalid ped.' ,
),
url='getPedOccupiedVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="getPedOccupiedVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the vehicle that the ped is currently in or is trying to enter, if any.' ,
arguments={
"thePed": """: The ped whose vehicle youre looking up. """
},
result='returns the vehicle that the specified ped is in, or false if the ped is not in a vehicle or is an invalid ped.' ,
),
url='getPedOccupiedVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['vehicle'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Prior to 1.5, the variable was .occupiedVehicleSeat""",
base_function_name="getPedOccupiedVehicleSeat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicleSeat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the seat that a specific ped is sitting in in a vehicle.' ,
arguments={
"thePed": """: The ped whose vehicle seat youre looking up. """
},
result='* returns an integer containing the number of the seat that the ped is currently in:\n** 0: front-left\n** 1: front-right\n** 2: rear-left\n** 3: rear-right\nreturns false if the ped is on foot, or the ped doesnt exist.' ,
),
url='getPedOccupiedVehicleSeat',
),
field=FunctionOOPField(
name='vehicleSeat',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Prior to 1.5, the variable was .occupiedVehicleSeat""",
base_function_name="getPedOccupiedVehicleSeat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOccupiedVehicleSeat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets the seat that a specific ped is sitting in in a vehicle.' ,
arguments={
"thePed": """: The ped whose vehicle seat youre looking up. """
},
result='* returns an integer containing the number of the seat that the ped is currently in:\n** 0: front-left\n** 1: front-right\n** 2: rear-left\n** 3: rear-right\nreturns false if the ped is on foot, or the ped doesnt exist.' ,
),
url='getPedOccupiedVehicleSeat',
),
field=FunctionOOPField(
name='vehicleSeat',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedOxygenLevel",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getOxygenLevel',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the current oxygen level of the specified ped.' ,
arguments={
"thePed": """The ped whose oxygen level you want to check """
},
result='a float with the oxygen level, false if an invalid ped was given.' ,
),
url='getPedOxygenLevel',
),
field=FunctionOOPField(
name='oxygenLevel',
types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedStat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getStat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='stat',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the value of the specified statistic of a specific ped.' ,
arguments={
"thePed": """: The ped whose stat you want to retrieve. """,
"stat": """: A whole number determining the stat ID. """
},
result='returns the value of the requested statistic.' ,
),
url='getPedStat',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedStat",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getStat',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='stat',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns the value of the specified statistic of a specific ped.' ,
arguments={
"thePed": """: The ped whose stat you want to retrieve. """,
"stat": """: A whole number determining the stat ID. """
},
result='returns the value of the requested statistic.' ,
),
url='getPedStat',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedTarget",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTarget',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the element a ped is currently targeting.' ,
arguments={
"thePed": """The ped whose target you want to retrieve. """
},
result='returns the element thats being targeted, or false if there isnt one.\nthis is only effective on physical gta elements, namely:\n* players\n* peds\n* vehicles\n* objects' ,
),
url='getPedTarget',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTarget",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTarget',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['element'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get the element a ped is currently targeting.' ,
arguments={
"thePed": """The ped whose target you want to retrieve. """
},
result='returns the element thats being targeted, or false if there isnt one.\nthis is only effective on physical gta elements, namely:\n* players\n* peds\n* vehicles\n* objects' ,
),
url='getPedTarget',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTargetEnd",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTargetEnd',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
),
FunctionType(
names=['float'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='targetingPed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows retrieval of the position where a peds target range ends, when he is aiming with a weapon.' ,
arguments={
"targetingPed": """the ped who is targeting whose target end you wish to retrieve """
},
result='returns three floats, x,y,z, representing the position where the peds target ends according to his range, or false if it was unsuccessful.' ,
),
url='getPedTargetEnd',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTask",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTask',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
),
FunctionType(
names=['string'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='priority',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='taskType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to get any simple or complex task of a certain type for a ped.\nIt can provide feedback on all tasks relating to a ped. For example, while jumping, getPedSimplestTask will return TASK_SIMPLE_IN_AIR. If you wanted to know specifically if the player has jumped, you would use this function. If you did you will discover that while jumping Primary task 3 is TASK_COMPLEX_JUMP.' ,
arguments={
"thePed": """: The ped whose task you want to retrieve. """,
"priority": """: A string determining which set of tasks you want to retrieve it from. This must be either primary or secondary. """,
"taskType": """: An integer value representing the task type (or slot) you want to get the task from. Types can be: """,
"PRIMARY TASKS": """ """,
"0": """TASK_SECONDARY_ATTACK """,
"1": """TASK_SECONDARY_DUCK """,
"2": """TASK_SECONDARY_SAY """,
"3": """TASK_SECONDARY_FACIAL_COMPLEX """,
"4": """TASK_SECONDARY_PARTIAL_ANIM """,
"SECONDARY TASKS": """ """,
"5": """TASK_SECONDARY_IK """
},
result='returns the name of the most complex task. see list of player tasks for valid strings. returns false if invalid arguments are specified or if there is no task of the type specified.\n<br>\nreturns between 1 and 4 strings. the first string contains the name of the most complex task, with simpler sub-tasks being named in the following strings. see list of player tasks for valid strings. returns false if invalid arguments are specified or if there is no task of the type specified.' ,
),
url='getPedTask',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedTotalAmmo",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTotalAmmo',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the total ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """: The ped whose ammo you want to check. """,
"weaponSlot": """: an integer representing the weapon slot (set to the peds current slot if not given) """
},
result='returns an int containing the total amount of ammo for the specified peds weapon, or 0 if the ped specified is invalid.' ,
),
url='getPedTotalAmmo',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedTotalAmmo",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getTotalAmmo',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function returns an integer that contains the total ammo in a specified peds weapon. See weapon|Weapon Info' ,
arguments={
"thePed": """: The ped whose ammo you want to check. """,
"weaponSlot": """: an integer representing the weapon slot (set to the peds current slot if not given) """
},
result='returns an int containing the total amount of ammo for the specified peds weapon, or 0 if the ped specified is invalid.' ,
),
url='getPedTotalAmmo',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='getWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped whose walking style to retrieve. """
},
result='returns the walking style id if successful, false otherwise. the possible walking styles are as follows:' ,
),
url='getPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='getWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped whose walking style to retrieve. """
},
result='returns the walking style id if successful, false otherwise. the possible walking styles are as follows:' ,
),
url='getPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function tells you which weapon type is in a certain weapon|weapon slot of a ped.' ,
arguments={
"thePed": """: the ped you want to get the weapon type from. """,
"weaponSlot": """: an integer representing the weapon|weapon slot (set to the peds current slot if not given). """
},
result='returns an int indicating the type of the weapon the ped has in the specified slot. if the slot is empty, it returns 0.\nit should be noted that if a ped runs out of ammo for a weapon, it will still return the id of that weapon in the slot (even if it appears as if the ped does not have a weapon at all), though getpedtotalammo will return 0. therefore, getpedtotalammo should be used in conjunction with getpedweapon in order to check if a ped has a weapon.' ,
),
url='getPedWeapon',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='current',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function tells you which weapon type is in a certain weapon|weapon slot of a ped.' ,
arguments={
"thePed": """: the ped you want to get the weapon type from. """,
"weaponSlot": """: an integer representing the weapon|weapon slot (set to the peds current slot if not given). """
},
result='returns an int indicating the type of the weapon the ped has in the specified slot. if the slot is empty, it returns 0.\nit should be noted that if a ped runs out of ammo for a weapon, it will still return the id of that weapon in the slot (even if it appears as if the ped does not have a weapon at all), though getpedtotalammo will return 0. therefore, getpedtotalammo should be used in conjunction with getpedweapon in order to check if a ped has a weapon.' ,
),
url='getPedWeapon',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="getPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets a peds selected weapon slot.' ,
arguments={
"thePed": """the ped to get the current weapon slot of. """
},
result='returns the selected weapon slot id on success, false otherwise.' ,
),
url='getPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="getPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='getWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function gets a peds selected weapon slot.' ,
arguments={
"thePed": """the ped to get the current weapon slot of. """
},
result='returns the selected weapon slot id on success, false otherwise.' ,
),
url='getPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['int'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedBleeding",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isBleeding',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """The player or ped whose bleeding effect state you want to get. """
},
result='returns true if the player or ped is bleeding, false otherwise.' ,
),
url='isPedBleeding',
),
field=FunctionOOPField(
name='bleeding',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is choking (coughing) or not. This happens as a result of weapons that produce smoke - smoke grenades, fire extinguisher and the spray can.' ,
arguments={
"thePed": """: The ped you wish to check """
},
result='returns true if the ped is choking, false otherwise.' ,
),
url='isPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is choking (coughing) or not. This happens as a result of weapons that produce smoke - smoke grenades, fire extinguisher and the spray can.' ,
arguments={
"thePed": """: The ped you wish to check """
},
result='returns true if the ped is choking, false otherwise.' ,
),
url='isPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDead",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDead',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is dead or not.' ,
arguments={
"thePed": """: the ped you want to check up on. """
},
result='returns true if the ped is dead, false otherwise.' ,
),
url='isPedDead',
),
field=FunctionOOPField(
name='dead',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDead",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDead',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is dead or not.' ,
arguments={
"thePed": """: the ped you want to check up on. """
},
result='returns true if the ped is dead, false otherwise.' ,
),
url='isPedDead',
),
field=FunctionOOPField(
name='dead',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDoingGangDriveby",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDoingGangDriveby',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the ped is in the driveby state.' ,
arguments={
"thePed": """The ped element whose state is to be checked. """
},
result='returns true if the driveby state is enabled, false otherwise.' ,
),
url='isPedDoingGangDriveby',
),
field=FunctionOOPField(
name='doingGangDriveby',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDoingGangDriveby",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDoingGangDriveby',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the ped is in the driveby state.' ,
arguments={
"thePed": """The ped element whose state is to be checked. """
},
result='returns true if the driveby state is enabled, false otherwise.' ,
),
url='isPedDoingGangDriveby',
),
field=FunctionOOPField(
name='doingGangDriveby',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedDucked",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDucked',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is ducked (crouched) or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is ducked, false otherwise.' ,
),
url='isPedDucked',
),
field=FunctionOOPField(
name='ducked',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedDucked",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isDucked',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is ducked (crouched) or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is ducked, false otherwise.' ,
),
url='isPedDucked',
),
field=FunctionOOPField(
name='ducked',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedInVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isInVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether or not a given ped is currently in a vehicle.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped is in a vehicle, false if he is on foot or an invalid element was passed.' ,
),
url='isPedInVehicle',
),
field=FunctionOOPField(
name='inVehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedInVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isInVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Checks whether or not a given ped is currently in a vehicle.' ,
arguments={
"thePed": """the ped you want to check. """
},
result='returns true if the ped is in a vehicle, false if he is on foot or an invalid element was passed.' ,
),
url='isPedInVehicle',
),
field=FunctionOOPField(
name='inVehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is on fire or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is on fire, false otherwise.' ,
),
url='isPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function checks if the specified ped is on fire or not.' ,
arguments={
"thePed": """: The ped to check. """
},
result='returns true if the ped is on fire, false otherwise.' ,
),
url='isPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedOnGround",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnGround',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is on the ground. This is for on-foot usage only.' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is on foot and on the ground, false otherwise, even if he is in a car that stands still or on object outside world map.' ,
),
url='isPedOnGround',
),
field=FunctionOOPField(
name='onGround',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedOnGround",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isOnGround',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is on the ground. This is for on-foot usage only.' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is on foot and on the ground, false otherwise, even if he is in a car that stands still or on object outside world map.' ,
),
url='isPedOnGround',
),
field=FunctionOOPField(
name='onGround',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedReloadingWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isReloadingWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to determine whether or not a ped is currently reloading their weapon. Useful to stop certain quick reload exploits.}}' ,
arguments={
"thePed": """The ped you are checking. """
},
result='returns true if the ped is currently reloading a weapon, false otherwise.' ,
),
url='isPedReloadingWeapon',
),
field=FunctionOOPField(
name='reloadingWeapon',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="isPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped you want to check """
},
result='returns true if the ped is carrying a jetpack, false if he is not or an invalid element was passed.' ,
),
url='isPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="isPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='isWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """the ped you want to check """
},
result='returns true if the ped is carrying a jetpack, false if he is not or an invalid element was passed.' ,
),
url='isPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="killPed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='kill',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theKiller',
argument_type=FunctionType(
names=['ped'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='weapon',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='bodyPart',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='stealth',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function kills the specified ped.\nFrom v1.5.3 onwards this function is now available client side. Only works on client side peds.' ,
arguments={
"thePed": """The ped to kill """,
"theKiller": """The ped responsible for the kill """,
"weapon": """The ID of the weapon or Damage Types that should appear to have killed the ped (doesnt affect how they die) """,
"bodyPart": """The ID of the body part that should appear to have been hit by the weapon (doesnt affect how they die) """,
"stealth": """Boolean value, representing whether or not this a stealth kill """
},
result='returns true if the ped was killed, false if the ped specified could not be killed or is invalid.' ,
),
url='killPed',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="killPed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='kill',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theKiller',
argument_type=FunctionType(
names=['ped'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='weapon',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='bodyPart',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='255',
)
],
[
FunctionArgument(
name='stealth',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function kills the specified ped.\nFrom v1.5.3 onwards this function is now available client side. Only works on client side peds.' ,
arguments={
"thePed": """The ped to kill """,
"theKiller": """The ped responsible for the kill """,
"weapon": """The ID of the weapon or Damage Types that should appear to have killed the ped (doesnt affect how they die) """,
"bodyPart": """The ID of the body part that should appear to have been hit by the weapon (doesnt affect how they die) """,
"stealth": """Boolean value, representing whether or not this a stealth kill """
},
result='returns true if the ped was killed, false if the ped specified could not be killed or is invalid.' ,
),
url='killPed',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="reloadPedWeapon",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='reloadWeapon',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function makes a pedestrian reload their weapon.' ,
arguments={
"thePed": """The ped who will reload their weapon. """
},
result='returns true if the pedestrian was made to reload, or false if invalid arguments were passed or that pedestrian has a weapon which cannot be reloaded.\nnote: this will fail but return true if\n1) the ped is crouched and moving\n2) the ped is using a weapon without clip ammo (or minigun/flamethrower/fire\nextinguisher)\n3) the ped is using his weapon (shooting/aiming)\n4) the ped moved while crouching recently\ndue to these circumstances causing problems with this function' ,
),
url='reloadPedWeapon',
),
field=None,
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="removePedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to remove the current clothes of a certain type on a ped. It will remove them if the clothesTexture and clothesModel arent specified, or if they match the current clothes on that slot.' ,
arguments={
"thePed": """: The ped you want to remove clothes from. """,
"clothesType": """: the clothes slot/type to remove. See the CJ Clothes|clothes catalog. """,
"clothesTexture": """: (Server only) A string determining the clothes texture that will be removed. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: (Server only) A string determining the clothes model that will be removed. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully removed from the ped, false otherwise.' ,
),
url='removePedClothes',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="removePedClothes",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeClothes',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesType',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesTexture',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='clothesModel',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to remove the current clothes of a certain type on a ped. It will remove them if the clothesTexture and clothesModel arent specified, or if they match the current clothes on that slot.' ,
arguments={
"thePed": """: The ped you want to remove clothes from. """,
"clothesType": """: the clothes slot/type to remove. See the CJ Clothes|clothes catalog. """,
"clothesTexture": """: (Server only) A string determining the clothes texture that will be removed. See the CJ Clothes|clothes catalog. """,
"clothesModel": """: (Server only) A string determining the clothes model that will be removed. See the CJ Clothes|clothes catalog. """
},
result='this function returns true if the clothes were successfully removed from the ped, false otherwise.' ,
),
url='removePedClothes',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute this function""",
base_function_name="removePedFromVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeFromVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function removes a ped from a vehicle immediately. This works for drivers and passengers. Note that this removes the ped from the vehicle and puts him in the exact position where the command was initiated.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped you wish to remove from a vehicle """
},
result='returns true if the operation was successful, false if the specified ped is not valid or if it isnt in a vehicle.' ,
),
url='removePedFromVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute this function""",
base_function_name="removePedFromVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='removeFromVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function removes a ped from a vehicle immediately. This works for drivers and passengers. Note that this removes the ped from the vehicle and puts him in the exact position where the command was initiated.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped you wish to remove from a vehicle """
},
result='returns true if the operation was successful, false if the specified ped is not valid or if it isnt in a vehicle.' ,
),
url='removePedFromVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='block',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='time',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='-1',
)
],
[
FunctionArgument(
name='loop',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='updatePosition',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='interruptable',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='freezeLastFrame',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='blendTime',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='250',
)
],
[
FunctionArgument(
name='retainPedState',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current Animations|animation of a player or ped. Not specifying the type of animation will automatically cancel the current one.' ,
arguments={
"thePed": """the player or ped you want to apply an Animations|animation to. """,
"block": """the Animations|animation blocks name. """,
"anim": """the name of the Animations|animation within the block. """,
"time": """how long the animation will run for in milliseconds. """,
"loop": """indicates whether or not the animation will loop. """,
"updatePosition": """will change the actual coordinates of the ped according to the animation. Use this for e.g. walking animations. """,
"interruptable": """if set to false other tasks wont be able to interupt the animation. Setting this to false also gives this function more power to override other animations that are running. For example, squatting after a jump can be terminated. """,
"freezeLastFrame": """if set to true after animation the last frame will be frozen, otherwise the animation will end and controls will return. """,
"blendTime": """how long the animation will mixed with the previous one in milliseconds. """,
"retainPedState": """will restore the task which was playing before calling this function. Useful for restoring the crouch task after animation ends. This may be extended in the future to support other states/tasks.
|16632}} """
},
result='returns true if succesful, false otherwise.' ,
),
url='setPedAnimation',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='block',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='nil',
)
],
[
FunctionArgument(
name='time',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='-1',
)
],
[
FunctionArgument(
name='loop',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='updatePosition',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='interruptable',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='freezeLastFrame',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='true',
)
],
[
FunctionArgument(
name='blendTime',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='250',
)
],
[
FunctionArgument(
name='retainPedState',
argument_type=FunctionType(
names=['bool'],
is_optional=True,
),
default_value='false',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current Animations|animation of a player or ped. Not specifying the type of animation will automatically cancel the current one.' ,
arguments={
"thePed": """the player or ped you want to apply an Animations|animation to. """,
"block": """the Animations|animation blocks name. """,
"anim": """the name of the Animations|animation within the block. """,
"time": """how long the animation will run for in milliseconds. """,
"loop": """indicates whether or not the animation will loop. """,
"updatePosition": """will change the actual coordinates of the ped according to the animation. Use this for e.g. walking animations. """,
"interruptable": """if set to false other tasks wont be able to interupt the animation. Setting this to false also gives this function more power to override other animations that are running. For example, squatting after a jump can be terminated. """,
"freezeLastFrame": """if set to true after animation the last frame will be frozen, otherwise the animation will end and controls will return. """,
"blendTime": """how long the animation will mixed with the previous one in milliseconds. """,
"retainPedState": """will restore the task which was playing before calling this function. Useful for restoring the crouch task after animation ends. This may be extended in the future to support other states/tasks.
|16632}} """
},
result='returns true if succesful, false otherwise.' ,
),
url='setPedAnimation',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationProgress",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationProgress',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='progress',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current animation progress of a player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation progress. """,
"anim": """the animation name currently applied to ped, if not supplied, the animation will stop """,
"progress": """current animation progress you want to apply, value from 0.0 to 1.0, if not supplied will default to 0.0 """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationProgress',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationProgress",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationProgress',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value=None,
)
],
[
FunctionArgument(
name='progress',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the current animation progress of a player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation progress. """,
"anim": """the animation name currently applied to ped, if not supplied, the animation will stop """,
"progress": """current animation progress you want to apply, value from 0.0 to 1.0, if not supplied will default to 0.0 """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationProgress',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationSpeed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationSpeed',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='""',
)
],
[
FunctionArgument(
name='speed',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value='1.0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the speed of a currently running animation for a particular player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation speed of. """,
"anim": """the animation name it will affect. """,
"speed": """a float containing the speed between 0.0–1.0 you want to apply to the animation. This limitation may be adjusted in the future, so do not provide speeds outside this boundary. {{New feature/item|3.0158|1.5.7|20395|The limit is now 0.0 to 10.0.}} {{Warning|Setting speed higher than 1 can cause issues with some animations.}} """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationSpeed',
),
field=None,
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedAnimationSpeed",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setAnimationSpeed',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='anim',
argument_type=FunctionType(
names=['string'],
is_optional=True,
),
default_value='""',
)
],
[
FunctionArgument(
name='speed',
argument_type=FunctionType(
names=['float'],
is_optional=True,
),
default_value='1.0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the speed of a currently running animation for a particular player or ped.' ,
arguments={
"thePed": """the player or ped you want to change animation speed of. """,
"anim": """the animation name it will affect. """,
"speed": """a float containing the speed between 0.0–1.0 you want to apply to the animation. This limitation may be adjusted in the future, so do not provide speeds outside this boundary. {{New feature/item|3.0158|1.5.7|20395|The limit is now 0.0 to 10.0.}} {{Warning|Setting speed higher than 1 can cause issues with some animations.}} """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedAnimationSpeed',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='armor',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the armor value of a ped.' ,
arguments={
"thePed": """: the ped whose armor you want to modify. """,
"armor": """: the amount of armor you want to set on the ped. Valid values are from 0 to 100. """
},
result='returns true if the armor was changed succesfully. returns false if an invalid ped was specified, or the armor value specified is out of acceptable range.' ,
),
url='setPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedArmor",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setArmor',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='armor',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the armor value of a ped.' ,
arguments={
"thePed": """: the ped whose armor you want to modify. """,
"armor": """: the amount of armor you want to set on the ped. Valid values are from 0 to 100. """
},
result='returns true if the armor was changed succesfully. returns false if an invalid ped was specified, or the armor value specified is out of acceptable range.' ,
),
url='setPedArmor',
),
field=FunctionOOPField(
name='armor',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedBleeding",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setBleeding',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='bleeding',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='' ,
arguments={
"thePed": """The player or ped whose bleeding effect you want to set of. """,
"bleeding": """Boolean specifying whether the player or ped is bleeding or not. """
},
result='returns true if the bleeding state was successfully set, false otherwise.' ,
),
url='setPedBleeding',
),
field=FunctionOOPField(
name='bleeding',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedCameraRotation",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setCameraRotation',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='cameraRotation',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function sets the camera rotation of a ped, e.g. where its camera will look at. Dont confuse this with getCameraMatrix, because that function is designed for fixed (scripted) camera moves.' ,
arguments={
"thePed": """The ped whose camera rotation is to be changed. """,
"cameraRotation": """The new direction that the ped will walk if you set their forwards control state. If the ped is the local player, it will also change where his camera is looking at if it isnt fixed (i.e. camera target is the local player). """
},
result='returns true if the camera rotation was changed, false otherwise.' ,
),
url='setPedCameraRotation',
),
field=FunctionOOPField(
name='cameraRotation',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedCanBeKnockedOffBike",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setCanBeKnockedOffBike',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='canBeKnockedOffBike',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function controls if a ped can fall of his bike by accident - namely by banging into a wall.' ,
arguments={
"thePed": """the ped whose knockoffstatus is being changed """,
"canBeKnockedOffBike": """true or false """
},
result='' ,
),
url='setPedCanBeKnockedOffBike',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedChoking",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setChoking',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='choking',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to force the ped to do the choking (coughing) animation until he respawns or toggled off using this function. The animation can not be cancelled by a player its applied to, and he will not loose health.' ,
arguments={
"thePed": """The ped whose choking status to toggle """,
"choking": """true to make the ped choke, false to no longer force his choking animation """
},
result='returns true if successful, false otherwise (e.g. player handle is invalid)' ,
),
url='setPedChoking',
),
field=FunctionOOPField(
name='choking',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedControlState",
class_name='Ped',
method=FunctionData(
signature=FunctionSignature(
name='setControlState',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='control',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='state',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function makes a ped or player press or release a certain control.' ,
arguments={
"thePed": """the ped you want to press or release a control. """,
"control": """the name of the control of which to change the state. See control names for a list of valid names. """,
"state": """the new control state. true means pressed, false is released. """
},
result='returns true if successful, false if otherwise.' ,
),
url='setPedControlState',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedGravity",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setGravity',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='gravity',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function sets the gravity level of a ped.' ,
arguments={
"thePed": """: The ped whose gravity to change. """,
"level": """: The level of gravity (default is 0.008). """
},
result='returns true if the gravity was successfully set, false otherwise' ,
),
url='setPedGravity',
),
field=FunctionOOPField(
name='gravity',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedHeadless",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setHeadless',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='headState',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='With this function, you can set if a ped has a head or not.' ,
arguments={
"thePed": """: The ped to check. """,
"headState": """: head state, use true if you want the ped be headless, use false to give back the head. """
},
result='returns true if successful, false otherwise' ,
),
url='setPedHeadless',
),
field=FunctionOOPField(
name='headless',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedHeadless",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setHeadless',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='headState',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='With this function, you can set if a ped has a head or not.' ,
arguments={
"thePed": """: The ped to check. """,
"headState": """: head state, use true if you want the ped be headless, use false to give back the head. """
},
result='returns true if successful, false otherwise' ,
),
url='setPedHeadless',
),
field=FunctionOOPField(
name='headless',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='isOnFire',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to set a ped on fire or extinguish a fire on it.' ,
arguments={
"thePed": """The ped that we want to set/unset """,
"isOnFire": """true to set the ped on fire, false to extinguish any fire on him """
},
result='returns true if successful, false otherwise' ,
),
url='setPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedOnFire",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOnFire',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='isOnFire',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function can be used to set a ped on fire or extinguish a fire on it.' ,
arguments={
"thePed": """The ped that we want to set/unset """,
"isOnFire": """true to set the ped on fire, false to extinguish any fire on him """
},
result='returns true if successful, false otherwise' ,
),
url='setPedOnFire',
),
field=FunctionOOPField(
name='onFire',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedOxygenLevel",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setOxygenLevel',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='oxygen',
argument_type=FunctionType(
names=['float'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function allows you to set the oxygen level of a ped.' ,
arguments={
"thePed": """: the ped whose oxygen level you want to modify. """,
"oxygen": """: the amount of oxygen you want to set on the ped. Native values are from 0 to 1000. Each of the stamina (22) and underwater stamina (225) Template:Stats|stat maximum adds a bonus of 1500. So the maximum oxygen level is 4000. """
},
result='returns true if the oxygen level was changed succesfully. returns false if an invalid ped and/or oxygen level was specified.' ,
),
url='setPedOxygenLevel',
),
field=FunctionOOPField(
name='oxygenLevel',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
],
),
CompoundOOPData(
server=[
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedVoice",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setVoice',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='voiceType',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='voiceName',
argument_type=FunctionType(
names=['string'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Changes the voice of a ped.' ,
arguments={
"thePed": """the ped whose voice to change. """,
"voiceType": """the voice type. See ped voices for possible types. """,
"voiceName": """the voice name within the specified type. See ped voices for possible voices. """
},
result='returns true when the voice was successfully set, false otherwise.' ,
),
url='setPedVoice',
),
field=None,
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='setWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='style',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the walking style of a ped. A walking style consists of a set of animations that are used for walking, running etc.' ,
arguments={
"thePed": """the ped whose walking style to change. """,
"style": """the walking style to set.
The possible walking styles are: """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedWalkingStyle",
class_name='Ped|ped',
method=FunctionData(
signature=FunctionSignature(
name='setWalkingStyle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='style',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='Sets the walking style of a ped. A walking style consists of a set of animations that are used for walking, running etc.' ,
arguments={
"thePed": """the ped whose walking style to change. """,
"style": """the walking style to set.
The possible walking styles are: """
},
result='returns true if successful, false otherwise.' ,
),
url='setPedWalkingStyle',
),
field=FunctionOOPField(
name='walkingStyle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function changes the selected weapon slot of a ped.' ,
arguments={
"thePed": """the ped whose weapon slot you want to set. In a clientside script, this cannot be used on remote players. """,
"weaponSlot": """the weapon slot to set. """
},
result='returns true if successful in setting the peds equipped weapon slot, false otherwise.' ,
),
url='setPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description=None,
base_function_name="setPedWeaponSlot",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWeaponSlot',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='weaponSlot',
argument_type=FunctionType(
names=['int'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function changes the selected weapon slot of a ped.' ,
arguments={
"thePed": """the ped whose weapon slot you want to set. In a clientside script, this cannot be used on remote players. """,
"weaponSlot": """the weapon slot to set. """
},
result='returns true if successful in setting the peds equipped weapon slot, false otherwise.' ,
),
url='setPedWeaponSlot',
),
field=FunctionOOPField(
name='weaponSlot',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
),
CompoundOOPData(
server=[
FunctionOOP(
description=None,
base_function_name="setPedWearingJetpack",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='setWearingJetpack',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='state',
argument_type=FunctionType(
names=['bool'],
is_optional=False,
),
default_value=None,
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to give or take a jetpack from a ped, it wont work if the ped is in a vehicle.\nAs such, you should either expect it to fail sometimes, or repeatedly try to give a jetpack every second or so until isPedWearingJetpack returns true. Alternatively, you can force the ped into a safe position (e.g. standing on the ground) before giving the jetpack, or use a pickup to handle it.}}' ,
arguments={
"thePed": """The ped you want to give a jetpack to. """,
"state": """A boolean representing whether to give or take the jetpack. """
},
result='returns true if a jetpack was successfully set for the ped, false if setting it failed.' ,
),
url='setPedWearingJetpack',
),
field=FunctionOOPField(
name='jetpack',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
],
),
CompoundOOPData(
server=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="warpPedIntoVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='warpIntoVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theVehicle',
argument_type=FunctionType(
names=['vehicle'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='seat',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to warp or force a ped into a vehicle. There are no animations involved when this happens.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped which you wish to force inside the vehicle """,
"theVehicle": """The vehicle you wish to force the ped into """,
"seat": """An integer representing the seat ID. """,
"0": """Front-left """,
"1": """Front-right """,
"2": """Rear-left """,
"3": """Rear-right """
},
result='returns true if the operation is successful, false otherwise.' ,
),
url='warpPedIntoVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
client=[
FunctionOOP(
description="""Set the variable to nil to execute [[removePedFromVehicle]]""",
base_function_name="warpPedIntoVehicle",
class_name='ped',
method=FunctionData(
signature=FunctionSignature(
name='warpIntoVehicle',
return_types=FunctionReturnTypes(
return_types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
variable_length=False,
),
arguments=FunctionArgumentValues(
arguments=[
[
FunctionArgument(
name='thePed',
argument_type=FunctionType(
names=['ped'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='theVehicle',
argument_type=FunctionType(
names=['vehicle'],
is_optional=False,
),
default_value=None,
)
],
[
FunctionArgument(
name='seat',
argument_type=FunctionType(
names=['int'],
is_optional=True,
),
default_value='0',
)
]
],
variable_length=False,
),
generic_types=[
],
),
docs=FunctionDoc(
description='This function is used to warp or force a ped into a vehicle. There are no animations involved when this happens.\nAvailable client side from 1.3.1 (It will only work with client side vehicles and peds)' ,
arguments={
"thePed": """The ped which you wish to force inside the vehicle """,
"theVehicle": """The vehicle you wish to force the ped into """,
"seat": """An integer representing the seat ID. """,
"0": """Front-left """,
"1": """Front-right """,
"2": """Rear-left """,
"3": """Rear-right """
},
result='returns true if the operation is successful, false otherwise.' ,
),
url='warpPedIntoVehicle',
),
field=FunctionOOPField(
name='vehicle',
types=[
FunctionType(
names=['bool'],
is_optional=False,
)
],
),
is_static=False,
)
],
)
] | 0.698741 | 0.438424 |
import json
import os
import pkgutil
import tempfile
import dataset
import jsonpointer
from flattentool import unflatten
from jsonschema import FormatChecker
from jsonschema.validators import Draft4Validator, RefResolver
from ocdsmerge.util import get_release_schema_url, get_tags
from scrapy.exceptions import DropItem
from kingfisher_scrapy.items import File, FileItem, PluckedItem, ReleaseDataItem
from transform.transform import transform
def _json_loads(basename):
return json.loads(pkgutil.get_data('kingfisher_scrapy', f'item_schema/{basename}.json'))
class PgPipeline(object):
def __init__(self, **kwargs):
self.args = kwargs
@classmethod
def from_crawler(cls, crawler):
args = crawler.settings.get('PG_PIPELINE', {})
return cls(**args)
def close_spider(self, spider):
transform(self.db, spider.schema)
def open_spider(self, spider):
if self.args.get('connection'):
self.db = dataset.connect(self.args.get('connection'), schema=spider.schema)
self.table = self.db[self.args.get('table_name')]
self.pkey = self.args.get('pkey')
self.types = self.args.get('types', {})
self.ignore_identical = self.args.get('ignore_identical')
self.table.create_index([self.pkey])
self.table.create_index(self.ignore_identical)
self.onconflict = self.args.get('onconflict', 'ignore')
def process_item(self, item, spider):
if not isinstance(item, File):
return item
for release in _get_releases_data(item):
if self.onconflict == 'ignore':
self.table.insert(
release, types=self.types)
elif self.onconflict == 'upsert':
self.table.upsert(
release, self.ignore_identical, types=self.types)
elif self.onconflict == 'non-null':
row, res = self.table._upsert_pre_check(
release, self.ignore_identical, None)
selected = release
if res is not None:
# remove keys with none value
selected = dict((k, v) for k, v in release.iteritems() if v)
self.table.upsert(
selected, self.ignore_identical, types=self.types)
else:
self.table.insert(
selected, self.ignore_identical, types=self.types)
else:
raise Exception("no such strategy: %s" % (self.onconflict))
return item
def _get_releases_data(item):
releases = []
data = json.loads(item['data'])
if item['data_type'] == 'record_package':
for record in data['records']:
releases.append(ReleaseDataItem({
'data': record['compiledRelease'],
'release_id': record['compiledRelease']['id'],
'ocid': record['compiledRelease']['ocid']
}))
if item['data_type'] == 'release_package':
for release in data['releases']:
releases.append(ReleaseDataItem({
'data': release,
'release_id': release['id'],
'ocid': release['ocid']
}))
return releases
class Validate:
def __init__(self):
self.validators = {}
self.files = set()
self.file_items = set()
resolver = RefResolver.from_schema(_json_loads('item'))
checker = FormatChecker()
for item in ('File', 'FileError', 'FileItem'):
self.validators[item] = Draft4Validator(_json_loads(item), resolver=resolver, format_checker=checker)
def process_item(self, item, spider):
if hasattr(item, 'validate'):
self.validators.get(item.__class__.__name__).validate(dict(item))
if isinstance(item, FileItem):
key = (item['file_name'], item['number'])
if key in self.file_items:
spider.logger.warning('Duplicate FileItem: %r', key)
self.file_items.add(key)
elif isinstance(item, File):
key = item['file_name']
if key in self.files:
spider.logger.warning('Duplicate File: %r', key)
self.files.add(key)
return item
class Sample:
"""
Drop items and close the spider once the sample size is reached.
"""
def __init__(self):
self.item_count = 0
def process_item(self, item, spider):
if not spider.sample:
return item
# Drop FileError items, so that we keep trying to get data.
if not isinstance(item, (File, FileItem)):
raise DropItem('Item is not a File or FileItem')
if self.item_count >= spider.sample:
spider.crawler.engine.close_spider(spider, 'sample')
raise DropItem('Maximum sample size reached')
self.item_count += 1
return item
def open_spider(self, spider):
if spider.sample:
spider.crawler.engine.downloader.total_concurrency = 1
class Pluck:
def process_item(self, item, spider):
if not spider.pluck:
return item
value = None
if spider.package_pointer:
try:
package = _get_package(item)
except NotImplementedError as e:
value = f'error: {e}'
else:
value = _resolve_pointer(package, spider.package_pointer)
else: # spider.release_pointer
if item['data_type'] in ('release_package', 'release_package_list', 'release_package_list_in_results',
'release_list', 'release'):
data = _get_releases(item)
if data:
value = max(_resolve_pointer(r, spider.release_pointer) for r in data)
elif item['data_type'] in ('record_package', 'record_package_list', 'record_package_list_in_results',
'record'):
data = _get_records(item)
if data:
# This assumes that the first record in the record package has the desired value.
data = data[0]
if 'releases' in data:
value = max(_resolve_pointer(r, spider.release_pointer) for r in data['releases'])
elif 'compiledRelease' in data:
value = _resolve_pointer(data['compiledRelease'], spider.release_pointer)
if value and spider.truncate:
value = value[:spider.truncate]
return PluckedItem({'value': value})
class Unflatten:
def process_item(self, item, spider):
if not spider.unflatten or not isinstance(item, (File, FileItem)):
return item
input_name = item['file_name']
if input_name.endswith('.csv'):
item['file_name'] = item['file_name'][:-4] + '.json'
input_format = 'csv'
elif input_name.endswith('.xlsx'):
item['file_name'] = item['file_name'][:-5] + '.json'
input_format = 'xlsx'
else:
raise NotImplementedError(f"the file '{input_name}' has no extension or is not CSV or XLSX, "
f"obtained from: {item['url']}")
spider_ocds_version = spider.ocds_version.replace('.', '__')
for tag in reversed(get_tags()):
if tag.startswith(spider_ocds_version):
schema = get_release_schema_url(tag)
break
else:
raise NotImplementedError(f"no schema found for '{spider_ocds_version}'")
with tempfile.TemporaryDirectory() as directory:
input_path = os.path.join(directory, input_name)
output_name = os.path.join(directory, item['file_name'])
if input_format == 'csv':
input_name = directory
elif input_format == 'xlsx':
input_name = input_path
with open(input_path, 'wb') as f:
f.write(item['data'])
unflatten(
input_name,
root_list_path='releases',
root_id='ocid',
schema=schema,
input_format=input_format,
output_name=output_name
)
with open(output_name, 'r') as f:
item['data'] = f.read()
return item
def _resolve_pointer(data, pointer):
try:
return jsonpointer.resolve_pointer(data, pointer)
except jsonpointer.JsonPointerException:
return f'error: {pointer} not found'
def _get_package(item):
data = json.loads(item['data'])
if item['data_type'] in ('release_package', 'record_package'):
return data
# This assumes that the first package in the list has the desired value.
elif item['data_type'] in ('release_package_list', 'record_package_list'):
return data[0]
elif item['data_type'] in ('release_package_list_in_results', 'record_package_list_in_results'):
return data['results'][0]
raise NotImplementedError(f"no package for data_type: {item['data_type']}")
def _get_releases(item):
data = json.loads(item['data'])
if item['data_type'] == 'release_package':
return data['releases']
# This assumes that the first package in the list has the desired value.
elif item['data_type'] == 'release_package_list':
return data[0]['releases']
elif item['data_type'] == 'release_package_list_in_results':
return data['results'][0]['releases']
elif item['data_type'] == 'release_list':
return data
elif item['data_type'] == 'release':
return [data]
raise NotImplementedError(f"unhandled data_type: {item['data_type']}")
def _get_records(item):
data = json.loads(item['data'])
if item['data_type'] == 'record_package':
return data['records']
# This assumes that the first package in the list has the desired value.
elif item['data_type'] == 'record_package_list':
return data[0]['records']
elif item['data_type'] == 'record_package_list_in_results':
return data['results'][0]['records']
elif item['data_type'] == 'record':
return [data]
raise NotImplementedError(f"unhandled data_type: {item['data_type']}") | kingfisher_scrapy/pipelines.py | import json
import os
import pkgutil
import tempfile
import dataset
import jsonpointer
from flattentool import unflatten
from jsonschema import FormatChecker
from jsonschema.validators import Draft4Validator, RefResolver
from ocdsmerge.util import get_release_schema_url, get_tags
from scrapy.exceptions import DropItem
from kingfisher_scrapy.items import File, FileItem, PluckedItem, ReleaseDataItem
from transform.transform import transform
def _json_loads(basename):
return json.loads(pkgutil.get_data('kingfisher_scrapy', f'item_schema/{basename}.json'))
class PgPipeline(object):
def __init__(self, **kwargs):
self.args = kwargs
@classmethod
def from_crawler(cls, crawler):
args = crawler.settings.get('PG_PIPELINE', {})
return cls(**args)
def close_spider(self, spider):
transform(self.db, spider.schema)
def open_spider(self, spider):
if self.args.get('connection'):
self.db = dataset.connect(self.args.get('connection'), schema=spider.schema)
self.table = self.db[self.args.get('table_name')]
self.pkey = self.args.get('pkey')
self.types = self.args.get('types', {})
self.ignore_identical = self.args.get('ignore_identical')
self.table.create_index([self.pkey])
self.table.create_index(self.ignore_identical)
self.onconflict = self.args.get('onconflict', 'ignore')
def process_item(self, item, spider):
if not isinstance(item, File):
return item
for release in _get_releases_data(item):
if self.onconflict == 'ignore':
self.table.insert(
release, types=self.types)
elif self.onconflict == 'upsert':
self.table.upsert(
release, self.ignore_identical, types=self.types)
elif self.onconflict == 'non-null':
row, res = self.table._upsert_pre_check(
release, self.ignore_identical, None)
selected = release
if res is not None:
# remove keys with none value
selected = dict((k, v) for k, v in release.iteritems() if v)
self.table.upsert(
selected, self.ignore_identical, types=self.types)
else:
self.table.insert(
selected, self.ignore_identical, types=self.types)
else:
raise Exception("no such strategy: %s" % (self.onconflict))
return item
def _get_releases_data(item):
releases = []
data = json.loads(item['data'])
if item['data_type'] == 'record_package':
for record in data['records']:
releases.append(ReleaseDataItem({
'data': record['compiledRelease'],
'release_id': record['compiledRelease']['id'],
'ocid': record['compiledRelease']['ocid']
}))
if item['data_type'] == 'release_package':
for release in data['releases']:
releases.append(ReleaseDataItem({
'data': release,
'release_id': release['id'],
'ocid': release['ocid']
}))
return releases
class Validate:
def __init__(self):
self.validators = {}
self.files = set()
self.file_items = set()
resolver = RefResolver.from_schema(_json_loads('item'))
checker = FormatChecker()
for item in ('File', 'FileError', 'FileItem'):
self.validators[item] = Draft4Validator(_json_loads(item), resolver=resolver, format_checker=checker)
def process_item(self, item, spider):
if hasattr(item, 'validate'):
self.validators.get(item.__class__.__name__).validate(dict(item))
if isinstance(item, FileItem):
key = (item['file_name'], item['number'])
if key in self.file_items:
spider.logger.warning('Duplicate FileItem: %r', key)
self.file_items.add(key)
elif isinstance(item, File):
key = item['file_name']
if key in self.files:
spider.logger.warning('Duplicate File: %r', key)
self.files.add(key)
return item
class Sample:
"""
Drop items and close the spider once the sample size is reached.
"""
def __init__(self):
self.item_count = 0
def process_item(self, item, spider):
if not spider.sample:
return item
# Drop FileError items, so that we keep trying to get data.
if not isinstance(item, (File, FileItem)):
raise DropItem('Item is not a File or FileItem')
if self.item_count >= spider.sample:
spider.crawler.engine.close_spider(spider, 'sample')
raise DropItem('Maximum sample size reached')
self.item_count += 1
return item
def open_spider(self, spider):
if spider.sample:
spider.crawler.engine.downloader.total_concurrency = 1
class Pluck:
def process_item(self, item, spider):
if not spider.pluck:
return item
value = None
if spider.package_pointer:
try:
package = _get_package(item)
except NotImplementedError as e:
value = f'error: {e}'
else:
value = _resolve_pointer(package, spider.package_pointer)
else: # spider.release_pointer
if item['data_type'] in ('release_package', 'release_package_list', 'release_package_list_in_results',
'release_list', 'release'):
data = _get_releases(item)
if data:
value = max(_resolve_pointer(r, spider.release_pointer) for r in data)
elif item['data_type'] in ('record_package', 'record_package_list', 'record_package_list_in_results',
'record'):
data = _get_records(item)
if data:
# This assumes that the first record in the record package has the desired value.
data = data[0]
if 'releases' in data:
value = max(_resolve_pointer(r, spider.release_pointer) for r in data['releases'])
elif 'compiledRelease' in data:
value = _resolve_pointer(data['compiledRelease'], spider.release_pointer)
if value and spider.truncate:
value = value[:spider.truncate]
return PluckedItem({'value': value})
class Unflatten:
def process_item(self, item, spider):
if not spider.unflatten or not isinstance(item, (File, FileItem)):
return item
input_name = item['file_name']
if input_name.endswith('.csv'):
item['file_name'] = item['file_name'][:-4] + '.json'
input_format = 'csv'
elif input_name.endswith('.xlsx'):
item['file_name'] = item['file_name'][:-5] + '.json'
input_format = 'xlsx'
else:
raise NotImplementedError(f"the file '{input_name}' has no extension or is not CSV or XLSX, "
f"obtained from: {item['url']}")
spider_ocds_version = spider.ocds_version.replace('.', '__')
for tag in reversed(get_tags()):
if tag.startswith(spider_ocds_version):
schema = get_release_schema_url(tag)
break
else:
raise NotImplementedError(f"no schema found for '{spider_ocds_version}'")
with tempfile.TemporaryDirectory() as directory:
input_path = os.path.join(directory, input_name)
output_name = os.path.join(directory, item['file_name'])
if input_format == 'csv':
input_name = directory
elif input_format == 'xlsx':
input_name = input_path
with open(input_path, 'wb') as f:
f.write(item['data'])
unflatten(
input_name,
root_list_path='releases',
root_id='ocid',
schema=schema,
input_format=input_format,
output_name=output_name
)
with open(output_name, 'r') as f:
item['data'] = f.read()
return item
def _resolve_pointer(data, pointer):
try:
return jsonpointer.resolve_pointer(data, pointer)
except jsonpointer.JsonPointerException:
return f'error: {pointer} not found'
def _get_package(item):
data = json.loads(item['data'])
if item['data_type'] in ('release_package', 'record_package'):
return data
# This assumes that the first package in the list has the desired value.
elif item['data_type'] in ('release_package_list', 'record_package_list'):
return data[0]
elif item['data_type'] in ('release_package_list_in_results', 'record_package_list_in_results'):
return data['results'][0]
raise NotImplementedError(f"no package for data_type: {item['data_type']}")
def _get_releases(item):
data = json.loads(item['data'])
if item['data_type'] == 'release_package':
return data['releases']
# This assumes that the first package in the list has the desired value.
elif item['data_type'] == 'release_package_list':
return data[0]['releases']
elif item['data_type'] == 'release_package_list_in_results':
return data['results'][0]['releases']
elif item['data_type'] == 'release_list':
return data
elif item['data_type'] == 'release':
return [data]
raise NotImplementedError(f"unhandled data_type: {item['data_type']}")
def _get_records(item):
data = json.loads(item['data'])
if item['data_type'] == 'record_package':
return data['records']
# This assumes that the first package in the list has the desired value.
elif item['data_type'] == 'record_package_list':
return data[0]['records']
elif item['data_type'] == 'record_package_list_in_results':
return data['results'][0]['records']
elif item['data_type'] == 'record':
return [data]
raise NotImplementedError(f"unhandled data_type: {item['data_type']}") | 0.439507 | 0.095983 |
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Dict, TYPE_CHECKING
from reamber.base.Map import Map
from reamber.base.lists import TimedList
from reamber.sm.SMBpm import SMBpm
from reamber.sm.SMConst import SMConst
from reamber.sm.SMFake import SMFake
from reamber.sm.SMHit import SMHit
from reamber.sm.SMHold import SMHold
from reamber.sm.SMKeySound import SMKeySound
from reamber.sm.SMLift import SMLift
from reamber.sm.SMMapMeta import SMMapMeta, SMMapChartTypes
from reamber.sm.SMMine import SMMine
from reamber.sm.SMRoll import SMRoll
from reamber.sm.SMStop import SMStop
from reamber.sm.lists.SMBpmList import SMBpmList
from reamber.sm.lists.SMNotePkg import SMNotePkg
if TYPE_CHECKING:
from reamber.sm.SMMapSet import SMMapSet
from numpy import gcd
import logging
log = logging.getLogger(__name__)
@dataclass
class SMMap(Map, SMMapMeta):
""" If you're trying to load using this, use SMMapSet. """
_SNAP_ERROR_BUFFER = 0.001
notes: SMNotePkg = field(default_factory=lambda: SMNotePkg())
bpms: SMBpmList = field(default_factory=lambda: SMBpmList())
def data(self) -> Dict[str, TimedList]:
""" Gets the notes and bpms as a dictionary """
return {'notes': self.notes,
'bpms': self.bpms}
@staticmethod
def readString(noteStr: str, bpms: List[SMBpm], stops: List[SMStop]) -> SMMap:
""" Reads the Note part of the SM Map
That means including the // Comment, and anything below
:param noteStr: The note part
:param bpms: BPMs to help sync notes
:param stops: Stops to help sync notes
:return:
"""
spl = noteStr.split(":")
noteStr = SMMap()
noteStr._readNoteMetadata(spl[1:6]) # These contain the metadata
# Splits measures by \n and filters out blank + comment entries
measures: List[List[str]] =\
[[snap for snap in measure.split("\n")
if "//" not in snap and len(snap) > 0] for measure in spl[-1].split(",")]
noteStr._readNotes(measures, bpms=bpms, stops=stops)
return noteStr
def writeString(self) -> List[str]:
""" Write an exportable String List to be passed to SMMapset for writing.
:return: Exportable String List
"""
# Tried to use a BPM
log.info("StepMania writeString is not stable on MultiBpm cases!")
log.info("Start Parsing File")
header = [
f"//------{self.chartType}[{self.difficultyVal} {self.difficulty}]------",
"#NOTES:",
f"\t{self.chartType}:",
f"\t{self.description}:",
f"\t{self.difficulty}:",
f"\t{self.difficultyVal}:",
"\t" + ",".join(map(str, self.grooveRadar)) + ":"
]
log.info(f"Header {header}")
bpmBeats = SMBpm.getBeats(self.bpms, self.bpms)
# -------- We will grab all required notes here --------
# List[Tuple[Beat, Column], Char]]
notes: List[List[float, int, str]] = []
for snap, ho in zip(SMBpm.getBeats(self.notes.hits(), self.bpms), self.notes.hits()):
notes.append([snap, ho.column, SMConst.HIT_STRING])
holdHeads = []
holdTails = []
for head, tail in zip(self.notes.holds().sorted().offsets(),self.notes.holds().sorted().tailOffsets()):
holdHeads.append(head)
holdTails.append(tail)
for snap, ho in zip(SMBpm.getBeats(holdHeads, self.bpms), self.notes.holds()):
if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_HEAD])
elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_HEAD])
for snap, ho in zip(SMBpm.getBeats(holdTails, self.bpms), self.notes.holds()):
if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_TAIL])
elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_TAIL])
del holdHeads, holdTails
notes.sort(key=lambda x: x[0])
# -------- Loop through Bpm --------
# This is where notes are slot into the BPM beats
# We loop through the BPMs and find which notes fit
# We then remove the fitted notes and repeat
# BPM Beat 1 , BPM Beat 2 ...
# List[List[Beat, Column, Char]], List[List[Beat, Column, Char]]
notesByBpm: List[List[float, int, str]] = []
for bpmBeatIndex in range(len(bpmBeats)):
# If we are at the end, we use infinity as the upper bound
bpmBeatLower = bpmBeats[bpmBeatIndex]
bpmBeatUpper = bpmBeats[bpmBeatIndex + 1] if bpmBeatIndex < len(bpmBeats) - 1 else float("inf")
# Filter out placement for this bpm beat
noteByBpm: List[List[float, int, str]] = []
noteIndexToRemove = []
for noteIndex, note in enumerate(notes):
# We exclude the any notes are that close to the lower BPM Beat else they will repeat
if bpmBeatLower - self._SNAP_ERROR_BUFFER <= note[0] < bpmBeatUpper + self._SNAP_ERROR_BUFFER:
log.info(f"Write Note: Beat {round(note[0], 2)}, Column {note[1]}, Char {note[2]} set in "
f"{round(bpmBeatLower, 1)} - {round(bpmBeatUpper, 1)}")
noteByBpm.append(note)
noteIndexToRemove.append(noteIndex)
# Remove filtered out objects
noteIndexToRemove.reverse() # We need to reverse the list to retain correct indexes
for index in noteIndexToRemove:
del notes[index] # faster than pop
# Zeros the measure and converts it into snap units
noteByBpm = [[round(m * 48), c, ch] for m, c, ch in noteByBpm]
notesByBpm += noteByBpm
del noteByBpm, notes, bpmBeatIndex, bpmBeatUpper, bpmBeatLower, note, noteIndexToRemove, index
notesByBpm.sort(key=lambda item: item[0])
# -------- Fit into Measures --------
# After finding which notes belong to which BPM
# We cut them into measures then slot them in
# Note that we want to have the smallest size template before slotting
# That's where GCD comes in handy.
measures = [[] for _ in range(int(notesByBpm[-1][0] / 192) + 1)]
keys = SMMapChartTypes.getKeys(self.chartType)
for note in notesByBpm:
measures[int(note[0] / 192)].append(note)
measuresStr = []
for measureIndex, measure in enumerate(measures):
log.info(f"Parse Measure {measureIndex}\t{measure}")
measure = [[snap % 192, col, char] for snap, col, char in measure]
log.info(f"Zero Measure\t\t{measure}")
if len(measure) != 0:
# Using GCD, we can determine the smallest template to use
gcd_ = gcd.reduce([x[0] for x in measure])
if gcd_ == 0: snapsReq: int = 4
else: snapsReq: int = int(192 / gcd_)
log.info(f"Calc Snaps Req.\t{int(snapsReq)}")
if snapsReq == 3: snapsReq = 6 # Min 6 snaps to represent
if snapsReq < 4: snapsReq = 4 # Min 4 snaps to represent
log.info(f"Final Snaps Req.\t{int(snapsReq)}")
# This the template created to slot in notes
measure = [[int(snap/(192/snapsReq)), col, char] for snap, col, char in measure]
measureStr = [['0' for _key in range(keys)] for _snaps in range(int(snapsReq))]
log.info(f"Write Measure Input \t\t{measure}")
# Note: [Snap, Column, Char]
for note in measure: measureStr[note[0]][note[1]] = note[2]
else:
measureStr = [['0' for _key in range(keys)] for _snaps in range(4)]
measuresStr.append("\n".join(["".join(snap) for snap in measureStr]))
log.info(f"Finished Parsing Measure")
log.info(f"Finished Parsing Notes")
return header + ["\n,\n".join(measuresStr)] + [";\n\n"]
def _readNotes(self, measures: List[List[str]], bpms: List[SMBpm], stops: List[SMStop]):
""" Reads notes from split measures
We expect a format of [['0000',...]['0100',...]]
:param measures: Measures as 2D List
:param bpms: BPMs to help sync
:param stops: Stops to help Sync
"""
globalBeatIndex: float = 0.0 # This will help sync the bpm used
currentBpmIndex: int = 0
currentStopIndex: int = -1
offset = bpms[0].offset
stopOffsetSum = 0
bpmBeats = SMBpm.getBeats(bpms, bpms)
stopBeats = SMBpm.getBeats(stops, bpms)
# The buffer is used to find the head and tails
# If we find the head, we throw it in here {Col, HeadOffset}
# If we find the tail, we extract ^ and clear the Dict then form the Hold/Roll
holdBuffer: Dict[int, float] = {}
rollBuffer: Dict[int, float] = {}
for measure in measures:
for beatIndex in range(4):
# Grabs the first beat in the measure
beat = measure[int(beatIndex * len(measure) / 4): int((beatIndex + 1) * len(measure) / 4)]
# Loop through the beat
for snapIndex, snap in enumerate(beat):
for columnIndex, columnChar in enumerate(snap):
# "Switch" statement for character found
if columnChar == "0":
continue
elif columnChar == SMConst.HIT_STRING:
self.notes.hits().append(SMHit(offset + stopOffsetSum, column=columnIndex))
log.info(f"Read Hit at \t\t{round(offset + stopOffsetSum)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.MINE_STRING:
self.notes.hits().append(SMMine(offset + stopOffsetSum, column=columnIndex))
log.info(f"Read Mine at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.HOLD_STRING_HEAD:
holdBuffer[columnIndex] = offset
log.info(f"Read HoldHead at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.ROLL_STRING_HEAD:
rollBuffer[columnIndex] = offset
log.info(f"Read RollHead at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.ROLL_STRING_TAIL: # ROLL and HOLD tail is the same
# Flush out hold/roll buffer
if columnIndex in holdBuffer.keys():
startOffset = holdBuffer.pop(columnIndex)
self.notes.holds().append(SMHold(startOffset + stopOffsetSum,
column=columnIndex,
_length=offset - startOffset))
log.info(f"Read HoldTail at \t{round(startOffset + stopOffsetSum, 2)} "
f"of length {round(offset - startOffset, 2)} "
f"at Column {columnIndex}")
elif columnIndex in rollBuffer.keys():
startOffset = rollBuffer.pop(columnIndex)
self.notes.holds().append(SMRoll(startOffset + stopOffsetSum,
column=columnIndex,
_length=offset - startOffset))
log.info(f"Read RollTail at \t{round(startOffset + stopOffsetSum, 2)} "
f"of length {round(offset - startOffset, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.LIFT_STRING:
self.notes.hits().append(SMLift(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read Lift at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.FAKE_STRING:
self.notes.hits().append(SMFake(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read Fake at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.KEYSOUND_STRING:
self.notes.hits().append(SMKeySound(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read KeySound at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
globalBeatIndex += 4.0 / len(measure)
offset += bpms[currentBpmIndex].beatLength() / len(beat)
# <- Fraction -> <- Length of Beat ->
# Length of Snap
# Check if next index exists & check if current beat index is outdated
while currentBpmIndex + 1 != len(bpms) and \
globalBeatIndex > bpmBeats[currentBpmIndex + 1] - self._SNAP_ERROR_BUFFER:
globalBeatIndex = bpmBeats[currentBpmIndex + 1]
currentBpmIndex += 1
# Add stop offsets to current offset sum
while currentStopIndex + 1 != len(stops) and \
globalBeatIndex > stopBeats[currentStopIndex + 1]:
stopOffsetSum += stops[currentStopIndex + 1].length
currentStopIndex += 1
# Deal with rounding issues
globalBeatIndex = round(globalBeatIndex)
# noinspection PyMethodOverriding
# Class requires set to operate
def metadata(self, s: SMMapSet, unicode=True) -> str:
""" Grabs the map metadata
:param s: The Map Set Object, required for additional metadata info.
:param unicode: Whether to try to find the unicode or non-unicode. \
This doesn't try to convert unicode to ascii, it just looks for if there's an available translation.
:return:
"""
def formatting(artist, title, difficulty, creator):
return f"{artist} - {title}, {difficulty} ({creator})"
if unicode:
return formatting(s.artist if len(s.artist.strip()) > 0 else s.artistTranslit,
s.title if len(s.title.strip()) > 0 else s.titleTranslit,
self.difficulty, s.credit)
else:
return formatting(s.artistTranslit if len(s.artistTranslit.strip()) > 0 else s.artist,
s.titleTranslit if len(s.titleTranslit.strip()) > 0 else s.title,
self.difficulty, s.credit)
# noinspection PyMethodOverriding
def describe(self, s:SMMapSet, rounding: int = 2, unicode: bool = False) -> None:
""" Describes the map's attributes as a short summary
:param s: The Map Set Object, required for additional metadata info.
:param rounding: The decimal rounding
:param unicode: Whether to attempt to get the non-unicode or unicode. \
Doesn't attempt to translate.
"""
super(SMMap, self).describe(rounding=rounding, unicode=unicode, s=s)
def rate(self, by: float, inplace:bool = False):
""" Changes the rate of the map. Note that you need to do rate on the mapset to correctly affect the sm output
:param by: The value to rate it by. 1.1x speeds up the song by 10%. Hence 10/11 of the length.
:param inplace: Whether to perform the operation in place. Returns a copy if False
"""
# Sample start and length aren't changed here.
return super(SMMap, self).rate(by=by, inplace=inplace) | reamber/sm/SMMap.py | from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Dict, TYPE_CHECKING
from reamber.base.Map import Map
from reamber.base.lists import TimedList
from reamber.sm.SMBpm import SMBpm
from reamber.sm.SMConst import SMConst
from reamber.sm.SMFake import SMFake
from reamber.sm.SMHit import SMHit
from reamber.sm.SMHold import SMHold
from reamber.sm.SMKeySound import SMKeySound
from reamber.sm.SMLift import SMLift
from reamber.sm.SMMapMeta import SMMapMeta, SMMapChartTypes
from reamber.sm.SMMine import SMMine
from reamber.sm.SMRoll import SMRoll
from reamber.sm.SMStop import SMStop
from reamber.sm.lists.SMBpmList import SMBpmList
from reamber.sm.lists.SMNotePkg import SMNotePkg
if TYPE_CHECKING:
from reamber.sm.SMMapSet import SMMapSet
from numpy import gcd
import logging
log = logging.getLogger(__name__)
@dataclass
class SMMap(Map, SMMapMeta):
""" If you're trying to load using this, use SMMapSet. """
_SNAP_ERROR_BUFFER = 0.001
notes: SMNotePkg = field(default_factory=lambda: SMNotePkg())
bpms: SMBpmList = field(default_factory=lambda: SMBpmList())
def data(self) -> Dict[str, TimedList]:
""" Gets the notes and bpms as a dictionary """
return {'notes': self.notes,
'bpms': self.bpms}
@staticmethod
def readString(noteStr: str, bpms: List[SMBpm], stops: List[SMStop]) -> SMMap:
""" Reads the Note part of the SM Map
That means including the // Comment, and anything below
:param noteStr: The note part
:param bpms: BPMs to help sync notes
:param stops: Stops to help sync notes
:return:
"""
spl = noteStr.split(":")
noteStr = SMMap()
noteStr._readNoteMetadata(spl[1:6]) # These contain the metadata
# Splits measures by \n and filters out blank + comment entries
measures: List[List[str]] =\
[[snap for snap in measure.split("\n")
if "//" not in snap and len(snap) > 0] for measure in spl[-1].split(",")]
noteStr._readNotes(measures, bpms=bpms, stops=stops)
return noteStr
def writeString(self) -> List[str]:
""" Write an exportable String List to be passed to SMMapset for writing.
:return: Exportable String List
"""
# Tried to use a BPM
log.info("StepMania writeString is not stable on MultiBpm cases!")
log.info("Start Parsing File")
header = [
f"//------{self.chartType}[{self.difficultyVal} {self.difficulty}]------",
"#NOTES:",
f"\t{self.chartType}:",
f"\t{self.description}:",
f"\t{self.difficulty}:",
f"\t{self.difficultyVal}:",
"\t" + ",".join(map(str, self.grooveRadar)) + ":"
]
log.info(f"Header {header}")
bpmBeats = SMBpm.getBeats(self.bpms, self.bpms)
# -------- We will grab all required notes here --------
# List[Tuple[Beat, Column], Char]]
notes: List[List[float, int, str]] = []
for snap, ho in zip(SMBpm.getBeats(self.notes.hits(), self.bpms), self.notes.hits()):
notes.append([snap, ho.column, SMConst.HIT_STRING])
holdHeads = []
holdTails = []
for head, tail in zip(self.notes.holds().sorted().offsets(),self.notes.holds().sorted().tailOffsets()):
holdHeads.append(head)
holdTails.append(tail)
for snap, ho in zip(SMBpm.getBeats(holdHeads, self.bpms), self.notes.holds()):
if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_HEAD])
elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_HEAD])
for snap, ho in zip(SMBpm.getBeats(holdTails, self.bpms), self.notes.holds()):
if isinstance(ho, SMHold): notes.append([snap, ho.column, SMConst.HOLD_STRING_TAIL])
elif isinstance(ho, SMRoll): notes.append([snap, ho.column, SMConst.ROLL_STRING_TAIL])
del holdHeads, holdTails
notes.sort(key=lambda x: x[0])
# -------- Loop through Bpm --------
# This is where notes are slot into the BPM beats
# We loop through the BPMs and find which notes fit
# We then remove the fitted notes and repeat
# BPM Beat 1 , BPM Beat 2 ...
# List[List[Beat, Column, Char]], List[List[Beat, Column, Char]]
notesByBpm: List[List[float, int, str]] = []
for bpmBeatIndex in range(len(bpmBeats)):
# If we are at the end, we use infinity as the upper bound
bpmBeatLower = bpmBeats[bpmBeatIndex]
bpmBeatUpper = bpmBeats[bpmBeatIndex + 1] if bpmBeatIndex < len(bpmBeats) - 1 else float("inf")
# Filter out placement for this bpm beat
noteByBpm: List[List[float, int, str]] = []
noteIndexToRemove = []
for noteIndex, note in enumerate(notes):
# We exclude the any notes are that close to the lower BPM Beat else they will repeat
if bpmBeatLower - self._SNAP_ERROR_BUFFER <= note[0] < bpmBeatUpper + self._SNAP_ERROR_BUFFER:
log.info(f"Write Note: Beat {round(note[0], 2)}, Column {note[1]}, Char {note[2]} set in "
f"{round(bpmBeatLower, 1)} - {round(bpmBeatUpper, 1)}")
noteByBpm.append(note)
noteIndexToRemove.append(noteIndex)
# Remove filtered out objects
noteIndexToRemove.reverse() # We need to reverse the list to retain correct indexes
for index in noteIndexToRemove:
del notes[index] # faster than pop
# Zeros the measure and converts it into snap units
noteByBpm = [[round(m * 48), c, ch] for m, c, ch in noteByBpm]
notesByBpm += noteByBpm
del noteByBpm, notes, bpmBeatIndex, bpmBeatUpper, bpmBeatLower, note, noteIndexToRemove, index
notesByBpm.sort(key=lambda item: item[0])
# -------- Fit into Measures --------
# After finding which notes belong to which BPM
# We cut them into measures then slot them in
# Note that we want to have the smallest size template before slotting
# That's where GCD comes in handy.
measures = [[] for _ in range(int(notesByBpm[-1][0] / 192) + 1)]
keys = SMMapChartTypes.getKeys(self.chartType)
for note in notesByBpm:
measures[int(note[0] / 192)].append(note)
measuresStr = []
for measureIndex, measure in enumerate(measures):
log.info(f"Parse Measure {measureIndex}\t{measure}")
measure = [[snap % 192, col, char] for snap, col, char in measure]
log.info(f"Zero Measure\t\t{measure}")
if len(measure) != 0:
# Using GCD, we can determine the smallest template to use
gcd_ = gcd.reduce([x[0] for x in measure])
if gcd_ == 0: snapsReq: int = 4
else: snapsReq: int = int(192 / gcd_)
log.info(f"Calc Snaps Req.\t{int(snapsReq)}")
if snapsReq == 3: snapsReq = 6 # Min 6 snaps to represent
if snapsReq < 4: snapsReq = 4 # Min 4 snaps to represent
log.info(f"Final Snaps Req.\t{int(snapsReq)}")
# This the template created to slot in notes
measure = [[int(snap/(192/snapsReq)), col, char] for snap, col, char in measure]
measureStr = [['0' for _key in range(keys)] for _snaps in range(int(snapsReq))]
log.info(f"Write Measure Input \t\t{measure}")
# Note: [Snap, Column, Char]
for note in measure: measureStr[note[0]][note[1]] = note[2]
else:
measureStr = [['0' for _key in range(keys)] for _snaps in range(4)]
measuresStr.append("\n".join(["".join(snap) for snap in measureStr]))
log.info(f"Finished Parsing Measure")
log.info(f"Finished Parsing Notes")
return header + ["\n,\n".join(measuresStr)] + [";\n\n"]
def _readNotes(self, measures: List[List[str]], bpms: List[SMBpm], stops: List[SMStop]):
""" Reads notes from split measures
We expect a format of [['0000',...]['0100',...]]
:param measures: Measures as 2D List
:param bpms: BPMs to help sync
:param stops: Stops to help Sync
"""
globalBeatIndex: float = 0.0 # This will help sync the bpm used
currentBpmIndex: int = 0
currentStopIndex: int = -1
offset = bpms[0].offset
stopOffsetSum = 0
bpmBeats = SMBpm.getBeats(bpms, bpms)
stopBeats = SMBpm.getBeats(stops, bpms)
# The buffer is used to find the head and tails
# If we find the head, we throw it in here {Col, HeadOffset}
# If we find the tail, we extract ^ and clear the Dict then form the Hold/Roll
holdBuffer: Dict[int, float] = {}
rollBuffer: Dict[int, float] = {}
for measure in measures:
for beatIndex in range(4):
# Grabs the first beat in the measure
beat = measure[int(beatIndex * len(measure) / 4): int((beatIndex + 1) * len(measure) / 4)]
# Loop through the beat
for snapIndex, snap in enumerate(beat):
for columnIndex, columnChar in enumerate(snap):
# "Switch" statement for character found
if columnChar == "0":
continue
elif columnChar == SMConst.HIT_STRING:
self.notes.hits().append(SMHit(offset + stopOffsetSum, column=columnIndex))
log.info(f"Read Hit at \t\t{round(offset + stopOffsetSum)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.MINE_STRING:
self.notes.hits().append(SMMine(offset + stopOffsetSum, column=columnIndex))
log.info(f"Read Mine at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.HOLD_STRING_HEAD:
holdBuffer[columnIndex] = offset
log.info(f"Read HoldHead at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.ROLL_STRING_HEAD:
rollBuffer[columnIndex] = offset
log.info(f"Read RollHead at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.ROLL_STRING_TAIL: # ROLL and HOLD tail is the same
# Flush out hold/roll buffer
if columnIndex in holdBuffer.keys():
startOffset = holdBuffer.pop(columnIndex)
self.notes.holds().append(SMHold(startOffset + stopOffsetSum,
column=columnIndex,
_length=offset - startOffset))
log.info(f"Read HoldTail at \t{round(startOffset + stopOffsetSum, 2)} "
f"of length {round(offset - startOffset, 2)} "
f"at Column {columnIndex}")
elif columnIndex in rollBuffer.keys():
startOffset = rollBuffer.pop(columnIndex)
self.notes.holds().append(SMRoll(startOffset + stopOffsetSum,
column=columnIndex,
_length=offset - startOffset))
log.info(f"Read RollTail at \t{round(startOffset + stopOffsetSum, 2)} "
f"of length {round(offset - startOffset, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.LIFT_STRING:
self.notes.hits().append(SMLift(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read Lift at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.FAKE_STRING:
self.notes.hits().append(SMFake(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read Fake at \t\t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
elif columnChar == SMConst.KEYSOUND_STRING:
self.notes.hits().append(SMKeySound(offset=offset + stopOffsetSum,
column=columnIndex))
log.info(f"Read KeySound at \t{round(offset + stopOffsetSum, 2)} "
f"at Column {columnIndex}")
globalBeatIndex += 4.0 / len(measure)
offset += bpms[currentBpmIndex].beatLength() / len(beat)
# <- Fraction -> <- Length of Beat ->
# Length of Snap
# Check if next index exists & check if current beat index is outdated
while currentBpmIndex + 1 != len(bpms) and \
globalBeatIndex > bpmBeats[currentBpmIndex + 1] - self._SNAP_ERROR_BUFFER:
globalBeatIndex = bpmBeats[currentBpmIndex + 1]
currentBpmIndex += 1
# Add stop offsets to current offset sum
while currentStopIndex + 1 != len(stops) and \
globalBeatIndex > stopBeats[currentStopIndex + 1]:
stopOffsetSum += stops[currentStopIndex + 1].length
currentStopIndex += 1
# Deal with rounding issues
globalBeatIndex = round(globalBeatIndex)
# noinspection PyMethodOverriding
# Class requires set to operate
def metadata(self, s: SMMapSet, unicode=True) -> str:
""" Grabs the map metadata
:param s: The Map Set Object, required for additional metadata info.
:param unicode: Whether to try to find the unicode or non-unicode. \
This doesn't try to convert unicode to ascii, it just looks for if there's an available translation.
:return:
"""
def formatting(artist, title, difficulty, creator):
return f"{artist} - {title}, {difficulty} ({creator})"
if unicode:
return formatting(s.artist if len(s.artist.strip()) > 0 else s.artistTranslit,
s.title if len(s.title.strip()) > 0 else s.titleTranslit,
self.difficulty, s.credit)
else:
return formatting(s.artistTranslit if len(s.artistTranslit.strip()) > 0 else s.artist,
s.titleTranslit if len(s.titleTranslit.strip()) > 0 else s.title,
self.difficulty, s.credit)
# noinspection PyMethodOverriding
def describe(self, s:SMMapSet, rounding: int = 2, unicode: bool = False) -> None:
""" Describes the map's attributes as a short summary
:param s: The Map Set Object, required for additional metadata info.
:param rounding: The decimal rounding
:param unicode: Whether to attempt to get the non-unicode or unicode. \
Doesn't attempt to translate.
"""
super(SMMap, self).describe(rounding=rounding, unicode=unicode, s=s)
def rate(self, by: float, inplace:bool = False):
""" Changes the rate of the map. Note that you need to do rate on the mapset to correctly affect the sm output
:param by: The value to rate it by. 1.1x speeds up the song by 10%. Hence 10/11 of the length.
:param inplace: Whether to perform the operation in place. Returns a copy if False
"""
# Sample start and length aren't changed here.
return super(SMMap, self).rate(by=by, inplace=inplace) | 0.814459 | 0.361756 |
import pyecharts.options as opts
from pyecharts.charts import Line, Page
from pyecharts.commons.utils import JsCode
from pyecharts.faker import Collector, Faker
C = Collector()
@C.funcs
def line_base() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values())
.add_yaxis("商家B", Faker.values())
.set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
)
return c
@C.funcs
def line_connect_null() -> Line:
y = Faker.values()
y[3], y[5] = None, None
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", y, is_connect_nones=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-连接空数据"))
)
return c
@C.funcs
def line_smooth() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_smooth=True)
.add_yaxis("商家B", Faker.values(), is_smooth=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-smooth"))
)
return c
@C.funcs
def line_areastyle() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
)
.add_yaxis(
"商家B", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-面积图"))
)
return c
@C.funcs
def line_areastyle_boundary_gap() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_smooth=True)
.add_yaxis("商家B", Faker.values(), is_smooth=True)
.set_series_opts(
areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Line-面积图(紧贴 Y 轴)"),
xaxis_opts=opts.AxisOpts(
axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
is_scale=False,
boundary_gap=False,
),
)
)
return c
@C.funcs
def line_yaxis_log() -> Line:
c = (
Line()
.add_xaxis(xaxis_data=["一", "二", "三", "四", "五", "六", "七", "八", "九"])
.add_yaxis(
"2 的指数",
y_axis=[1, 2, 4, 8, 16, 32, 64, 128, 256],
linestyle_opts=opts.LineStyleOpts(width=2),
)
.add_yaxis(
"3 的指数",
y_axis=[1, 3, 9, 27, 81, 247, 741, 2223, 6669],
linestyle_opts=opts.LineStyleOpts(width=2),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Line-对数轴示例"),
xaxis_opts=opts.AxisOpts(name="x"),
yaxis_opts=opts.AxisOpts(
type_="log",
name="y",
splitline_opts=opts.SplitLineOpts(is_show=True),
is_scale=True,
),
)
)
return c
@C.funcs
def line_markpoint_custom() -> Line:
x, y = Faker.choose(), Faker.values()
c = (
Line()
.add_xaxis(x)
.add_yaxis(
"商家A",
y,
markpoint_opts=opts.MarkPointOpts(
data=[opts.MarkPointItem(name="自定义标记点", coord=[x[2], y[2]], value=y[2])]
),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkPoint(自定义)"))
)
return c
@C.funcs
def line_markpoint() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min")]),
)
.add_yaxis(
"商家B",
Faker.values(),
markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkPoint"))
)
return c
@C.funcs
def line_markline() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
)
.add_yaxis(
"商家B",
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkLine"))
)
return c
@C.funcs
def line_step() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_step=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-阶梯图"))
)
return c
@C.funcs
def line_itemstyle() -> Line:
c = (
Line()
.add_xaxis(xaxis_data=Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
symbol="triangle",
symbol_size=20,
linestyle_opts=opts.LineStyleOpts(color="green", width=4, type_="dashed"),
itemstyle_opts=opts.ItemStyleOpts(
border_width=3, border_color="yellow", color="blue"
),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-ItemStyle"))
)
return c
@C.funcs
def line_color_with_js_func() -> Line:
x_data = ["14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]
y_data = [393, 438, 485, 631, 689, 824, 987, 1000, 1100, 1200]
background_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
)
area_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)"
)
c = (
Line(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js)))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="注册总量",
y_axis=y_data,
is_smooth=True,
is_symbol_show=True,
symbol="circle",
symbol_size=6,
linestyle_opts=opts.LineStyleOpts(color="#fff"),
label_opts=opts.LabelOpts(is_show=True, position="top", color="white"),
itemstyle_opts=opts.ItemStyleOpts(
color="red", border_color="#fff", border_width=3
),
tooltip_opts=opts.TooltipOpts(is_show=False),
areastyle_opts=opts.AreaStyleOpts(color=JsCode(area_color_js), opacity=1),
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="OCTOBER 2015",
pos_bottom="5%",
pos_left="center",
title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16),
),
xaxis_opts=opts.AxisOpts(
type_="category",
boundary_gap=False,
axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(is_show=False),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=25,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
),
),
yaxis_opts=opts.AxisOpts(
type_="value",
position="right",
axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(
linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")
),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=15,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
),
),
legend_opts=opts.LegendOpts(is_show=False),
)
)
return c
Page().add(*[fn() for fn, _ in C.charts]).render() | example/line_example.py | import pyecharts.options as opts
from pyecharts.charts import Line, Page
from pyecharts.commons.utils import JsCode
from pyecharts.faker import Collector, Faker
C = Collector()
@C.funcs
def line_base() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values())
.add_yaxis("商家B", Faker.values())
.set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
)
return c
@C.funcs
def line_connect_null() -> Line:
y = Faker.values()
y[3], y[5] = None, None
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", y, is_connect_nones=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-连接空数据"))
)
return c
@C.funcs
def line_smooth() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_smooth=True)
.add_yaxis("商家B", Faker.values(), is_smooth=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-smooth"))
)
return c
@C.funcs
def line_areastyle() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
)
.add_yaxis(
"商家B", Faker.values(), areastyle_opts=opts.AreaStyleOpts(opacity=0.5)
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-面积图"))
)
return c
@C.funcs
def line_areastyle_boundary_gap() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_smooth=True)
.add_yaxis("商家B", Faker.values(), is_smooth=True)
.set_series_opts(
areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Line-面积图(紧贴 Y 轴)"),
xaxis_opts=opts.AxisOpts(
axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
is_scale=False,
boundary_gap=False,
),
)
)
return c
@C.funcs
def line_yaxis_log() -> Line:
c = (
Line()
.add_xaxis(xaxis_data=["一", "二", "三", "四", "五", "六", "七", "八", "九"])
.add_yaxis(
"2 的指数",
y_axis=[1, 2, 4, 8, 16, 32, 64, 128, 256],
linestyle_opts=opts.LineStyleOpts(width=2),
)
.add_yaxis(
"3 的指数",
y_axis=[1, 3, 9, 27, 81, 247, 741, 2223, 6669],
linestyle_opts=opts.LineStyleOpts(width=2),
)
.set_global_opts(
title_opts=opts.TitleOpts(title="Line-对数轴示例"),
xaxis_opts=opts.AxisOpts(name="x"),
yaxis_opts=opts.AxisOpts(
type_="log",
name="y",
splitline_opts=opts.SplitLineOpts(is_show=True),
is_scale=True,
),
)
)
return c
@C.funcs
def line_markpoint_custom() -> Line:
x, y = Faker.choose(), Faker.values()
c = (
Line()
.add_xaxis(x)
.add_yaxis(
"商家A",
y,
markpoint_opts=opts.MarkPointOpts(
data=[opts.MarkPointItem(name="自定义标记点", coord=[x[2], y[2]], value=y[2])]
),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkPoint(自定义)"))
)
return c
@C.funcs
def line_markpoint() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="min")]),
)
.add_yaxis(
"商家B",
Faker.values(),
markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max")]),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkPoint"))
)
return c
@C.funcs
def line_markline() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
)
.add_yaxis(
"商家B",
Faker.values(),
markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(type_="average")]),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-MarkLine"))
)
return c
@C.funcs
def line_step() -> Line:
c = (
Line()
.add_xaxis(Faker.choose())
.add_yaxis("商家A", Faker.values(), is_step=True)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-阶梯图"))
)
return c
@C.funcs
def line_itemstyle() -> Line:
c = (
Line()
.add_xaxis(xaxis_data=Faker.choose())
.add_yaxis(
"商家A",
Faker.values(),
symbol="triangle",
symbol_size=20,
linestyle_opts=opts.LineStyleOpts(color="green", width=4, type_="dashed"),
itemstyle_opts=opts.ItemStyleOpts(
border_width=3, border_color="yellow", color="blue"
),
)
.set_global_opts(title_opts=opts.TitleOpts(title="Line-ItemStyle"))
)
return c
@C.funcs
def line_color_with_js_func() -> Line:
x_data = ["14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]
y_data = [393, 438, 485, 631, 689, 824, 987, 1000, 1100, 1200]
background_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)"
)
area_color_js = (
"new echarts.graphic.LinearGradient(0, 0, 0, 1, "
"[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)"
)
c = (
Line(init_opts=opts.InitOpts(bg_color=JsCode(background_color_js)))
.add_xaxis(xaxis_data=x_data)
.add_yaxis(
series_name="注册总量",
y_axis=y_data,
is_smooth=True,
is_symbol_show=True,
symbol="circle",
symbol_size=6,
linestyle_opts=opts.LineStyleOpts(color="#fff"),
label_opts=opts.LabelOpts(is_show=True, position="top", color="white"),
itemstyle_opts=opts.ItemStyleOpts(
color="red", border_color="#fff", border_width=3
),
tooltip_opts=opts.TooltipOpts(is_show=False),
areastyle_opts=opts.AreaStyleOpts(color=JsCode(area_color_js), opacity=1),
)
.set_global_opts(
title_opts=opts.TitleOpts(
title="OCTOBER 2015",
pos_bottom="5%",
pos_left="center",
title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16),
),
xaxis_opts=opts.AxisOpts(
type_="category",
boundary_gap=False,
axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(is_show=False),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=25,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
),
),
yaxis_opts=opts.AxisOpts(
type_="value",
position="right",
axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"),
axisline_opts=opts.AxisLineOpts(
linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")
),
axistick_opts=opts.AxisTickOpts(
is_show=True,
length=15,
linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"),
),
splitline_opts=opts.SplitLineOpts(
is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")
),
),
legend_opts=opts.LegendOpts(is_show=False),
)
)
return c
Page().add(*[fn() for fn, _ in C.charts]).render() | 0.431345 | 0.245469 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from hubspot.automation.actions.api_client import ApiClient
from hubspot.automation.actions.exceptions import ApiTypeError, ApiValueError # noqa: F401
class FunctionsApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def archive(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.archive_with_http_info(definition_id, function_type, function_id, app_id, **kwargs) # noqa: E501
def archive_with_http_info(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_with_http_info(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method archive" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `archive`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `archive`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `archive`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `archive`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"DELETE",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def archive_by_function_type(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_by_function_type(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.archive_by_function_type_with_http_info(definition_id, function_type, app_id, **kwargs) # noqa: E501
def archive_by_function_type_with_http_info(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_by_function_type_with_http_info(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method archive_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `archive_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `archive_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `archive_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"DELETE",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def create_or_replace(self, definition_id, function_type, function_id, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace(definition_id, function_type, function_id, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunctionIdentifier
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.create_or_replace_with_http_info(definition_id, function_type, function_id, app_id, body, **kwargs) # noqa: E501
def create_or_replace_with_http_info(self, definition_id, function_type, function_id, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_with_http_info(definition_id, function_type, function_id, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunctionIdentifier, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id", "body"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_or_replace" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ("body" not in local_var_params or local_var_params["body"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_or_replace`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "body" in local_var_params:
body_params = local_var_params["body"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# HTTP header `Content-Type`
header_params["Content-Type"] = self.api_client.select_header_content_type(["text/plain"]) # noqa: E501 # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"PUT",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunctionIdentifier", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def create_or_replace_by_function_type(self, definition_id, function_type, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_by_function_type(definition_id, function_type, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunctionIdentifier
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.create_or_replace_by_function_type_with_http_info(definition_id, function_type, app_id, body, **kwargs) # noqa: E501
def create_or_replace_by_function_type_with_http_info(self, definition_id, function_type, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_by_function_type_with_http_info(definition_id, function_type, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunctionIdentifier, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id", "body"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_or_replace_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ("body" not in local_var_params or local_var_params["body"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_or_replace_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "body" in local_var_params:
body_params = local_var_params["body"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# HTTP header `Content-Type`
header_params["Content-Type"] = self.api_client.select_header_content_type(["text/plain"]) # noqa: E501 # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"PUT",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunctionIdentifier", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_by_function_type(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_function_type(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunction
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_by_function_type_with_http_info(definition_id, function_type, app_id, **kwargs) # noqa: E501
def get_by_function_type_with_http_info(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_function_type_with_http_info(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunction, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `get_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunction", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_by_id(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_id(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunction
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_by_id_with_http_info(definition_id, function_type, function_id, app_id, **kwargs) # noqa: E501
def get_by_id_with_http_info(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_id_with_http_info(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunction, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_by_id" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_by_id`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunction", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_page(self, definition_id, app_id, **kwargs): # noqa: E501
"""Get all custom action functions # noqa: E501
Returns a list of all functions that are associated with the given custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_page(definition_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CollectionResponseActionFunctionIdentifierNoPaging
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_page_with_http_info(definition_id, app_id, **kwargs) # noqa: E501
def get_page_with_http_info(self, definition_id, app_id, **kwargs): # noqa: E501
"""Get all custom action functions # noqa: E501
Returns a list of all functions that are associated with the given custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_page_with_http_info(definition_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CollectionResponseActionFunctionIdentifierNoPaging, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_page" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_page`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_page`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="CollectionResponseActionFunctionIdentifierNoPaging", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
) | hubspot/automation/actions/api/functions_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from hubspot.automation.actions.api_client import ApiClient
from hubspot.automation.actions.exceptions import ApiTypeError, ApiValueError # noqa: F401
class FunctionsApi(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def archive(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.archive_with_http_info(definition_id, function_type, function_id, app_id, **kwargs) # noqa: E501
def archive_with_http_info(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_with_http_info(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method archive" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `archive`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `archive`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `archive`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `archive`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"DELETE",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def archive_by_function_type(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_by_function_type(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.archive_by_function_type_with_http_info(definition_id, function_type, app_id, **kwargs) # noqa: E501
def archive_by_function_type_with_http_info(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Delete a custom action function # noqa: E501
Delete a function for a custom workflow action. This will remove the function itself as well as removing the association between the function and the custom action. This can't be undone. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.archive_by_function_type_with_http_info(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method archive_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `archive_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `archive_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `archive_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"DELETE",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def create_or_replace(self, definition_id, function_type, function_id, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace(definition_id, function_type, function_id, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunctionIdentifier
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.create_or_replace_with_http_info(definition_id, function_type, function_id, app_id, body, **kwargs) # noqa: E501
def create_or_replace_with_http_info(self, definition_id, function_type, function_id, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_with_http_info(definition_id, function_type, function_id, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunctionIdentifier, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id", "body"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_or_replace" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `create_or_replace`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ("body" not in local_var_params or local_var_params["body"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_or_replace`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "body" in local_var_params:
body_params = local_var_params["body"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# HTTP header `Content-Type`
header_params["Content-Type"] = self.api_client.select_header_content_type(["text/plain"]) # noqa: E501 # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"PUT",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunctionIdentifier", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def create_or_replace_by_function_type(self, definition_id, function_type, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_by_function_type(definition_id, function_type, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunctionIdentifier
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.create_or_replace_by_function_type_with_http_info(definition_id, function_type, app_id, body, **kwargs) # noqa: E501
def create_or_replace_by_function_type_with_http_info(self, definition_id, function_type, app_id, body, **kwargs): # noqa: E501
"""Create or replace a custom action function # noqa: E501
Creates or replaces a function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_or_replace_by_function_type_with_http_info(definition_id, function_type, app_id, body, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param str body: The function source code. Must be valid JavaScript code. (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunctionIdentifier, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id", "body"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method create_or_replace_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `create_or_replace_by_function_type`") # noqa: E501
# verify the required parameter 'body' is set
if self.api_client.client_side_validation and ("body" not in local_var_params or local_var_params["body"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `body` when calling `create_or_replace_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if "body" in local_var_params:
body_params = local_var_params["body"]
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# HTTP header `Content-Type`
header_params["Content-Type"] = self.api_client.select_header_content_type(["text/plain"]) # noqa: E501 # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"PUT",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunctionIdentifier", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_by_function_type(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_function_type(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunction
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_by_function_type_with_http_info(definition_id, function_type, app_id, **kwargs) # noqa: E501
def get_by_function_type_with_http_info(self, definition_id, function_type, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_function_type_with_http_info(definition_id, function_type, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunction, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_by_function_type" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_by_function_type`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `get_by_function_type`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_by_function_type`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunction", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_by_id(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_id(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: ActionFunction
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_by_id_with_http_info(definition_id, function_type, function_id, app_id, **kwargs) # noqa: E501
def get_by_id_with_http_info(self, definition_id, function_type, function_id, app_id, **kwargs): # noqa: E501
"""Get a custom action function # noqa: E501
Returns the given function for a custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_by_id_with_http_info(definition_id, function_type, function_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param str function_type: The type of function. This determines when the function will be called. (required)
:param str function_id: The ID qualifier for the function. This is used to specify which input field a function is associated with for `PRE_FETCH_OPTIONS` and `POST_FETCH_OPTIONS` function types. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(ActionFunction, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "function_type", "function_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_by_id" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'function_type' is set
if self.api_client.client_side_validation and ("function_type" not in local_var_params or local_var_params["function_type"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_type` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'function_id' is set
if self.api_client.client_side_validation and ("function_id" not in local_var_params or local_var_params["function_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `function_id` when calling `get_by_id`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_by_id`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "function_type" in local_var_params:
path_params["functionType"] = local_var_params["function_type"] # noqa: E501
if "function_id" in local_var_params:
path_params["functionId"] = local_var_params["function_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions/{functionType}/{functionId}",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="ActionFunction", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
)
def get_page(self, definition_id, app_id, **kwargs): # noqa: E501
"""Get all custom action functions # noqa: E501
Returns a list of all functions that are associated with the given custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_page(definition_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param int app_id: (required)
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: CollectionResponseActionFunctionIdentifierNoPaging
If the method is called asynchronously,
returns the request thread.
"""
kwargs["_return_http_data_only"] = True
return self.get_page_with_http_info(definition_id, app_id, **kwargs) # noqa: E501
def get_page_with_http_info(self, definition_id, app_id, **kwargs): # noqa: E501
"""Get all custom action functions # noqa: E501
Returns a list of all functions that are associated with the given custom workflow action. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_page_with_http_info(definition_id, app_id, async_req=True)
>>> result = thread.get()
:param async_req bool: execute request asynchronously
:param str definition_id: The ID of the custom workflow action. (required)
:param int app_id: (required)
:param _return_http_data_only: response data without head status code
and headers
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:return: tuple(CollectionResponseActionFunctionIdentifierNoPaging, status_code(int), headers(HTTPHeaderDict))
If the method is called asynchronously,
returns the request thread.
"""
local_var_params = locals()
all_params = ["definition_id", "app_id"]
all_params.extend(["async_req", "_return_http_data_only", "_preload_content", "_request_timeout"])
for key, val in six.iteritems(local_var_params["kwargs"]):
if key not in all_params:
raise ApiTypeError("Got an unexpected keyword argument '%s'" " to method get_page" % key)
local_var_params[key] = val
del local_var_params["kwargs"]
# verify the required parameter 'definition_id' is set
if self.api_client.client_side_validation and ("definition_id" not in local_var_params or local_var_params["definition_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `definition_id` when calling `get_page`") # noqa: E501
# verify the required parameter 'app_id' is set
if self.api_client.client_side_validation and ("app_id" not in local_var_params or local_var_params["app_id"] is None): # noqa: E501 # noqa: E501
raise ApiValueError("Missing the required parameter `app_id` when calling `get_page`") # noqa: E501
collection_formats = {}
path_params = {}
if "definition_id" in local_var_params:
path_params["definitionId"] = local_var_params["definition_id"] # noqa: E501
if "app_id" in local_var_params:
path_params["appId"] = local_var_params["app_id"] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params["Accept"] = self.api_client.select_header_accept(["application/json", "*/*"]) # noqa: E501
# Authentication setting
auth_settings = ["developer_hapikey"] # noqa: E501
return self.api_client.call_api(
"/automation/v4/actions/{appId}/{definitionId}/functions",
"GET",
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type="CollectionResponseActionFunctionIdentifierNoPaging", # noqa: E501
auth_settings=auth_settings,
async_req=local_var_params.get("async_req"),
_return_http_data_only=local_var_params.get("_return_http_data_only"), # noqa: E501
_preload_content=local_var_params.get("_preload_content", True),
_request_timeout=local_var_params.get("_request_timeout"),
collection_formats=collection_formats,
) | 0.764584 | 0.06832 |
from os import access, R_OK
from django.core.management.base import BaseCommand
from canary_log_api.models import CanaryLogItem
from canary_utils.lib.util import SSLVerify, print_error
class Command(BaseCommand):
help = "Check certificate validity."
def add_arguments(self, parser):
parser.add_argument('-l', '--local-certificate', type=str,
help='Path to a local certificate.')
parser.add_argument('--ip', type=str,
help='Remote ip for certificate check.')
parser.add_argument('--port', type=int,
help='Remote port where SSL server is running on.')
def handle(self, **options):
ip = options.get('ip')
port = options.get('port')
local = options.get('local_certificate')
if not ip and not port and not local:
print_error('--- Please specify an argument')
return False
if ip and port and local:
print_error('--- Cannot specify ip / port combination and '
'local certificate!')
return False
if ip and port:
self._verify_remote_certificates(ip, port)
if local and access(local, R_OK):
self._verify_local_certificate(local)
def _verify_local_certificate(self, local):
expired, expiring = SSLVerify.is_local_certificate_valid(local)
if expired:
msg = f"[SSL WARNING] Certificate {local} is expired!"
CanaryLogItem.log_message(None, None, msg)
elif expiring:
msg = f"[SSL WARNING] Certificate {local} is expiring soon!"
CanaryLogItem.log_message(None, None, msg)
def _verify_remote_certificates(self, ip, port):
expired, expiring = SSLVerify.is_remote_certificate_valid(ip, port)
if expired:
msg = f"[SSL WARNING] Certificate at {ip}:{port} is expired!"
CanaryLogItem.log_message(None, None, msg)
elif expiring:
msg = f"[SSL WARNING] Certificate at {ip}:{port} is expiring soon!"
CanaryLogItem.log_message(None, None, msg) | toucan/canary_utils/management/commands/ssl_check.py | from os import access, R_OK
from django.core.management.base import BaseCommand
from canary_log_api.models import CanaryLogItem
from canary_utils.lib.util import SSLVerify, print_error
class Command(BaseCommand):
help = "Check certificate validity."
def add_arguments(self, parser):
parser.add_argument('-l', '--local-certificate', type=str,
help='Path to a local certificate.')
parser.add_argument('--ip', type=str,
help='Remote ip for certificate check.')
parser.add_argument('--port', type=int,
help='Remote port where SSL server is running on.')
def handle(self, **options):
ip = options.get('ip')
port = options.get('port')
local = options.get('local_certificate')
if not ip and not port and not local:
print_error('--- Please specify an argument')
return False
if ip and port and local:
print_error('--- Cannot specify ip / port combination and '
'local certificate!')
return False
if ip and port:
self._verify_remote_certificates(ip, port)
if local and access(local, R_OK):
self._verify_local_certificate(local)
def _verify_local_certificate(self, local):
expired, expiring = SSLVerify.is_local_certificate_valid(local)
if expired:
msg = f"[SSL WARNING] Certificate {local} is expired!"
CanaryLogItem.log_message(None, None, msg)
elif expiring:
msg = f"[SSL WARNING] Certificate {local} is expiring soon!"
CanaryLogItem.log_message(None, None, msg)
def _verify_remote_certificates(self, ip, port):
expired, expiring = SSLVerify.is_remote_certificate_valid(ip, port)
if expired:
msg = f"[SSL WARNING] Certificate at {ip}:{port} is expired!"
CanaryLogItem.log_message(None, None, msg)
elif expiring:
msg = f"[SSL WARNING] Certificate at {ip}:{port} is expiring soon!"
CanaryLogItem.log_message(None, None, msg) | 0.364551 | 0.090977 |
import os
import sys
import textwrap
from typing import Set, List, Optional
from extract_wheels.lib import wheel
def pkg_resources_style_namespace_packages(wheel_dir: str) -> Set[str]:
"""Discovers namespace packages implemented using the 'pkg_resources-style namespace packages' method.
"While this approach is no longer recommended, it is widely present in most existing namespace packages." - PyPA
See https://packaging.python.org/guides/packaging-namespace-packages/#pkg-resources-style-namespace-packages
"""
namespace_pkg_dirs = set()
dist_info = wheel.get_dist_info(wheel_dir)
namespace_packages_record_file = os.path.join(dist_info, "namespace_packages.txt")
if os.path.exists(namespace_packages_record_file):
with open(namespace_packages_record_file) as nspkg:
for line in nspkg.readlines():
namespace = line.strip().replace(".", os.sep)
if namespace:
namespace_pkg_dirs.add(os.path.join(wheel_dir, namespace))
return namespace_pkg_dirs
def native_namespace_packages_supported() -> bool:
"""Returns true if this version of Python supports native namespace packages."""
return (sys.version_info.major, sys.version_info.minor) >= (3, 3)
def implicit_namespace_packages(
directory: str, ignored_dirnames: Optional[List[str]] = None
) -> Set[str]:
"""Discovers namespace packages implemented using the 'native namespace packages' method.
AKA 'implicit namespace packages', which has been supported since Python 3.3.
See: https://packaging.python.org/guides/packaging-namespace-packages/#native-namespace-packages
Args:
directory: The root directory to recursively find packages in.
ignored_dirnames: A list of directories to exclude from the search
Returns:
The set of directories found under root to be packages using the native namespace method.
"""
namespace_pkg_dirs = set()
for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
# We are only interested in dirs with no __init__.py file
if "__init__.py" in filenames:
dirnames[:] = [] # Remove dirnames from search
continue
for ignored_dir in ignored_dirnames or []:
if ignored_dir in dirnames:
dirnames.remove(ignored_dir)
non_empty_directory = dirnames or filenames
if (
non_empty_directory
and
# The root of the directory should never be an implicit namespace
dirpath != directory
):
namespace_pkg_dirs.add(dirpath)
return namespace_pkg_dirs
def add_pkgutil_style_namespace_pkg_init(dir_path: str) -> None:
"""Adds 'pkgutil-style namespace packages' init file to the given directory
See: https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
Args:
dir_path: The directory to create an __init__.py for.
Raises:
ValueError: If the directory already contains an __init__.py file
"""
ns_pkg_init_filepath = os.path.join(dir_path, "__init__.py")
if os.path.isfile(ns_pkg_init_filepath):
raise ValueError("%s already contains an __init__.py file." % dir_path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
with open(ns_pkg_init_filepath, "w") as ns_pkg_init_f:
# See https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
ns_pkg_init_f.write(
textwrap.dedent(
"""\
# __path__ manipulation added by rules_python_external to support namespace pkgs.
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
"""
)
) | extract_wheels/lib/namespace_pkgs.py | import os
import sys
import textwrap
from typing import Set, List, Optional
from extract_wheels.lib import wheel
def pkg_resources_style_namespace_packages(wheel_dir: str) -> Set[str]:
"""Discovers namespace packages implemented using the 'pkg_resources-style namespace packages' method.
"While this approach is no longer recommended, it is widely present in most existing namespace packages." - PyPA
See https://packaging.python.org/guides/packaging-namespace-packages/#pkg-resources-style-namespace-packages
"""
namespace_pkg_dirs = set()
dist_info = wheel.get_dist_info(wheel_dir)
namespace_packages_record_file = os.path.join(dist_info, "namespace_packages.txt")
if os.path.exists(namespace_packages_record_file):
with open(namespace_packages_record_file) as nspkg:
for line in nspkg.readlines():
namespace = line.strip().replace(".", os.sep)
if namespace:
namespace_pkg_dirs.add(os.path.join(wheel_dir, namespace))
return namespace_pkg_dirs
def native_namespace_packages_supported() -> bool:
"""Returns true if this version of Python supports native namespace packages."""
return (sys.version_info.major, sys.version_info.minor) >= (3, 3)
def implicit_namespace_packages(
directory: str, ignored_dirnames: Optional[List[str]] = None
) -> Set[str]:
"""Discovers namespace packages implemented using the 'native namespace packages' method.
AKA 'implicit namespace packages', which has been supported since Python 3.3.
See: https://packaging.python.org/guides/packaging-namespace-packages/#native-namespace-packages
Args:
directory: The root directory to recursively find packages in.
ignored_dirnames: A list of directories to exclude from the search
Returns:
The set of directories found under root to be packages using the native namespace method.
"""
namespace_pkg_dirs = set()
for dirpath, dirnames, filenames in os.walk(directory, topdown=True):
# We are only interested in dirs with no __init__.py file
if "__init__.py" in filenames:
dirnames[:] = [] # Remove dirnames from search
continue
for ignored_dir in ignored_dirnames or []:
if ignored_dir in dirnames:
dirnames.remove(ignored_dir)
non_empty_directory = dirnames or filenames
if (
non_empty_directory
and
# The root of the directory should never be an implicit namespace
dirpath != directory
):
namespace_pkg_dirs.add(dirpath)
return namespace_pkg_dirs
def add_pkgutil_style_namespace_pkg_init(dir_path: str) -> None:
"""Adds 'pkgutil-style namespace packages' init file to the given directory
See: https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
Args:
dir_path: The directory to create an __init__.py for.
Raises:
ValueError: If the directory already contains an __init__.py file
"""
ns_pkg_init_filepath = os.path.join(dir_path, "__init__.py")
if os.path.isfile(ns_pkg_init_filepath):
raise ValueError("%s already contains an __init__.py file." % dir_path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
with open(ns_pkg_init_filepath, "w") as ns_pkg_init_f:
# See https://packaging.python.org/guides/packaging-namespace-packages/#pkgutil-style-namespace-packages
ns_pkg_init_f.write(
textwrap.dedent(
"""\
# __path__ manipulation added by rules_python_external to support namespace pkgs.
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
"""
)
) | 0.753648 | 0.216198 |
from datetime import date, datetime
import jsonpickle
from bson import ObjectId
from cryptodataaccess.Transactions.TransactionRepository import TransactionRepository
from cryptodataaccess.Transactions.TransactionMongoStore import TransactionMongoStore
from cryptodataaccess.Users.UsersMongoStore import UsersMongoStore
from cryptodataaccess.Users.UsersRepository import UsersRepository
from cryptodataaccess.helpers import do_connect, convert_to_int_timestamp
from cryptomodel.cryptomodel import exchange_rates, prices
from cryptomodel.cryptostore import user_transaction, user_settings
from CryptoCalculatorService.BalanceService import BalanceService
from CryptoCalculatorService.config import config, configure_app
from CryptoCalculatorService.tests.Scedhuler_test import mock_log
from CryptoCalculatorService.tests.helpers import insert_prices_record, insert_exchange_record, \
insert_prices_2020731_record
DATE_FORMAT = '%Y-%m-%d'
def test_compute_with_non_existing_key():
config, trans_repo, users_repo = delete_data_and_setup_repositories()
cs = BalanceService(config)
trans_repo.add_transaction(1, 1, 'OXT', 1, 1, "EUR", date(year=2020,month=1, day=1), "kraken",
source_id=ObjectId('666f6f2d6261722d71757578'), transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 1)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
out = jsonpickle.decode(cs.compute_balance(1))
assert (out.transactions[0].is_valid == False) # OXT does not exist
def delete_data_and_setup_repositories():
user_transaction.objects.all().delete()
exchange_rates.objects.all().delete()
prices.objects.all().delete()
user_settings.objects.all().delete()
insert_prices_record()
insert_exchange_record()
config = configure_app()
store = TransactionMongoStore(config, mock_log)
trans_repo = TransactionRepository(store)
users_store = UsersMongoStore(config, mock_log)
users_repo = UsersRepository(users_store)
do_connect(config)
return config, trans_repo, users_repo
def test_compute_with_existing_key():
config, trans_repo, users_repo = delete_data_and_setup_repositories()
insert_prices_record()
insert_exchange_record()
cs = BalanceService(config)
trans_repo.add_transaction(1, 1, 'BTC', 1, 1, "EUR", date(year=2020, month=1,day=1), "kraken",
source_id=ObjectId('666f6f2d6261722d71757578'), transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 1)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
out = jsonpickle.decode(cs.compute_balance(1))
assert (out.transactions[0].is_valid == True) # OXT does not exist
def test_four_transactions_same_symbol():
user_transaction.objects.all().delete()
exchange_rates.objects.all().delete()
prices.objects.all().delete()
insert_prices_2020731_record()
insert_exchange_record()
config = configure_app()
cs = BalanceService(config)
store = TransactionMongoStore(config, mock_log)
trans_repo = TransactionRepository(store)
users_store = UsersMongoStore(config, mock_log)
users_repo = UsersRepository(users_store)
do_connect(config)
user_transaction.objects.all().delete()
user_settings.objects.all().delete()
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-30", volume=1000.71140621,
value=211, symbol="XRP",
price=0.21085, source="kraken",transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-29", volume=245.08602519,
value=50, symbol="XRP",
price=0.20401, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-29", volume=487.16324840,
value=99.93179, symbol="XRP",
price=0.20527, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-28", volume=500, value=96.70500,
symbol="XRP",
price=0.19344, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 4)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
tdt = date(year=2020,month=8,day=1)
sdt = convert_to_int_timestamp( datetime(year=2030,month=8,day=1))
out = jsonpickle.decode(cs.compute_balance_with_upperbound_dates(1, upper_bound_symbol_rates_date=sdt,
upper_bound_transaction_date=tdt))
assert (len(out.transactions) == 4)
assert (out.converted_value == 0.2134997315708581 * (500 + 487.16324840 + 245.08602519 + 1000.71140621)) | CryptoCalculatorService/tests/BalanceService_test.py | from datetime import date, datetime
import jsonpickle
from bson import ObjectId
from cryptodataaccess.Transactions.TransactionRepository import TransactionRepository
from cryptodataaccess.Transactions.TransactionMongoStore import TransactionMongoStore
from cryptodataaccess.Users.UsersMongoStore import UsersMongoStore
from cryptodataaccess.Users.UsersRepository import UsersRepository
from cryptodataaccess.helpers import do_connect, convert_to_int_timestamp
from cryptomodel.cryptomodel import exchange_rates, prices
from cryptomodel.cryptostore import user_transaction, user_settings
from CryptoCalculatorService.BalanceService import BalanceService
from CryptoCalculatorService.config import config, configure_app
from CryptoCalculatorService.tests.Scedhuler_test import mock_log
from CryptoCalculatorService.tests.helpers import insert_prices_record, insert_exchange_record, \
insert_prices_2020731_record
DATE_FORMAT = '%Y-%m-%d'
def test_compute_with_non_existing_key():
config, trans_repo, users_repo = delete_data_and_setup_repositories()
cs = BalanceService(config)
trans_repo.add_transaction(1, 1, 'OXT', 1, 1, "EUR", date(year=2020,month=1, day=1), "kraken",
source_id=ObjectId('666f6f2d6261722d71757578'), transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 1)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
out = jsonpickle.decode(cs.compute_balance(1))
assert (out.transactions[0].is_valid == False) # OXT does not exist
def delete_data_and_setup_repositories():
user_transaction.objects.all().delete()
exchange_rates.objects.all().delete()
prices.objects.all().delete()
user_settings.objects.all().delete()
insert_prices_record()
insert_exchange_record()
config = configure_app()
store = TransactionMongoStore(config, mock_log)
trans_repo = TransactionRepository(store)
users_store = UsersMongoStore(config, mock_log)
users_repo = UsersRepository(users_store)
do_connect(config)
return config, trans_repo, users_repo
def test_compute_with_existing_key():
config, trans_repo, users_repo = delete_data_and_setup_repositories()
insert_prices_record()
insert_exchange_record()
cs = BalanceService(config)
trans_repo.add_transaction(1, 1, 'BTC', 1, 1, "EUR", date(year=2020, month=1,day=1), "kraken",
source_id=ObjectId('666f6f2d6261722d71757578'), transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 1)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
out = jsonpickle.decode(cs.compute_balance(1))
assert (out.transactions[0].is_valid == True) # OXT does not exist
def test_four_transactions_same_symbol():
user_transaction.objects.all().delete()
exchange_rates.objects.all().delete()
prices.objects.all().delete()
insert_prices_2020731_record()
insert_exchange_record()
config = configure_app()
cs = BalanceService(config)
store = TransactionMongoStore(config, mock_log)
trans_repo = TransactionRepository(store)
users_store = UsersMongoStore(config, mock_log)
users_repo = UsersRepository(users_store)
do_connect(config)
user_transaction.objects.all().delete()
user_settings.objects.all().delete()
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-30", volume=1000.71140621,
value=211, symbol="XRP",
price=0.21085, source="kraken",transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-29", volume=245.08602519,
value=50, symbol="XRP",
price=0.20401, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-29", volume=487.16324840,
value=99.93179, symbol="XRP",
price=0.20527, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.add_transaction(user_id=1, source_id=None, currency="EUR", date="2020-07-28", volume=500, value=96.70500,
symbol="XRP",
price=0.19344, source="kraken", transaction_type="TRADE", order_type="BUY")
trans_repo.commit()
assert (len(user_transaction.objects) == 4)
user_settings.objects.all().delete()
users_repo.add_user_settings(user_id=1, preferred_currency='EUR', source_id=ObjectId('666f6f2d6261722d71757578'))
users_repo.commit()
tdt = date(year=2020,month=8,day=1)
sdt = convert_to_int_timestamp( datetime(year=2030,month=8,day=1))
out = jsonpickle.decode(cs.compute_balance_with_upperbound_dates(1, upper_bound_symbol_rates_date=sdt,
upper_bound_transaction_date=tdt))
assert (len(out.transactions) == 4)
assert (out.converted_value == 0.2134997315708581 * (500 + 487.16324840 + 245.08602519 + 1000.71140621)) | 0.513912 | 0.131062 |
import unittest
import os
import json
import sppas
from sppas import sppasTypeError, u
from ..fileref import sppasAttribute, FileReference
from ..filedata import FileData
from ..filebase import States
# ---------------------------------------------------------------------------
class TestsppasAttribute(unittest.TestCase):
def setUp(self):
self.valint = sppasAttribute('age', '12', 'int', 'speaker\'s age')
self.valfloat = sppasAttribute('freq', '0.002', 'float', 'word appearance frequency')
self.valbool = sppasAttribute('adult', 'false', 'bool', 'speaker is minor')
self.valstr = sppasAttribute('utf', 'Hi everyone !', None, u('первый токен'))
def testInt(self):
self.assertTrue(isinstance(self.valint.get_typed_value(), int))
self.assertEqual('12', self.valint.get_value())
def testFloat(self):
self.assertTrue(isinstance(self.valfloat.get_typed_value(), float))
self.assertNotEqual(0.002, self.valfloat.get_value())
def testBool(self):
self.assertFalse(self.valbool.get_typed_value())
def testStr(self):
self.assertEqual('Hi everyone !', self.valstr.get_typed_value())
self.assertEqual('Hi everyone !', self.valstr.get_value())
def testRepr(self):
self.assertEqual(u('age, 12, speaker\'s age'), str(self.valint))
def testSetTypeValue(self):
with self.assertRaises(sppasTypeError) as error:
self.valbool.set_value_type('sppasAttribute')
self.assertTrue(isinstance(error.exception, sppasTypeError))
def testGetValuetype(self):
self.assertEqual('str', self.valstr.get_value_type())
# ---------------------------------------------------------------------------
class TestReferences(unittest.TestCase):
def setUp(self):
self.micros = FileReference('microphone')
self.att = sppasAttribute('mic1', 'Bird UM1', None, '最初のインタビューで使えていましたマイク')
self.micros.append(self.att)
self.micros.add('mic2', 'AKG D5')
def testGetItem(self):
self.assertEqual(u('最初のインタビューで使えていましたマイク'),
self.micros.att('mic1').get_description())
def testsppasAttribute(self):
self.assertFalse(isinstance(self.micros.att('mic2').get_typed_value(), int))
def testAddKey(self):
with self.assertRaises(ValueError) as AsciiError:
self.micros.add('i', 'Blue Yeti')
self.assertTrue(isinstance(AsciiError.exception, ValueError))
def testPopKey(self):
self.micros.pop('mic1')
self.assertEqual(1, len(self.micros))
self.micros.append(self.att)
self.micros.pop(self.att)
self.assertEqual(1, len(self.micros))
# ----------------------------------------------------------------------------
class TestFileData(unittest.TestCase):
def setUp(self):
self.data = FileData()
self.data.add_file(__file__)
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-fra', 'AC track_0379.PitchTier'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-fra', 'AC track_0379.TextGrid'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-jpn', 'JPA_M16_JPA_T02.TextGrid'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-cat', 'TB-FE1-H1_phrase1.TextGrid'))
self.r1 = FileReference('SpeakerAB')
self.r1.set_type('SPEAKER')
self.r1.append(sppasAttribute('initials', 'AB'))
self.r1.append(sppasAttribute('sex', 'F'))
self.r2 = FileReference('SpeakerCM')
self.r2.set_type('SPEAKER')
self.r2.append(sppasAttribute('initials', 'CM'))
self.r2.append(sppasAttribute('sex', 'F'))
self.r3 = FileReference('Dialog1')
self.r3.set_type('INTERACTION')
self.r3.append(sppasAttribute('when', '2003', 'int', 'Year of recording'))
self.r3.append(sppasAttribute('where', 'Aix-en-Provence', descr='Place of recording'))
def test_init(self):
data = FileData()
self.assertEqual(36, len(data.id))
self.assertEqual(0, len(data))
def test_save(self):
self.data.add_ref(self.r1)
self.data.add_ref(self.r2)
self.data.add_ref(self.r3)
current_file_list = list()
saved_file_list = list()
self.data.save(os.path.join(sppas.paths.sppas, 'src', 'files', 'test', 'save.json'))
for fp in self.data:
for fr in fp:
for fn in fr:
current_file_list.append(fn)
data = FileData.load(os.path.join(sppas.paths.sppas, 'src', 'files', 'test', 'save.json'))
for fp in data:
for fr in fp:
for fn in fr:
saved_file_list.append(fn)
self.assertEqual(len(current_file_list), len(saved_file_list))
for f1, f2 in zip(current_file_list, saved_file_list):
self.assertEqual(f1, f2)
def test_state(self):
self.data.set_object_state(States().LOCKED)
self.assertEqual(States().LOCKED, self.data.get_object_state(self.data[0]))
def test_ref(self):
self.data.add_ref(self.r1)
self.assertEqual(1, len(self.data.get_refs()))
self.data.add_ref(self.r2)
self.assertEqual(2, len(self.data.get_refs()))
self.r1.set_state(States().CHECKED)
self.r2.set_state(States().CHECKED)
self.data.remove_refs(States().CHECKED)
self.assertEqual(0, len(self.data.get_refs()))
def test_assocations(self):
self.data.add_ref(self.r1)
self.data.set_object_state(States().CHECKED)
for ref in self.data.get_refs():
self.data.set_object_state(States().CHECKED, ref)
self.data.associate()
for fp in self.data:
for fr in fp:
self.assertTrue(self.r1 in fr.get_references())
self.data.dissociate()
for fp in self.data:
for fr in fp:
self.assertEqual(0, len(fr.get_references()))
def test_serialize(self):
d = self.data.serialize()
jsondata = json.dumps(d, indent=4, separators=(',', ': '))
jsondict = json.loads(jsondata)
self.assertEqual(d, jsondict)
def test_parse(self):
self.data.add_ref(self.r1)
self.data.add_ref(self.r2)
self.data.add_ref(self.r3)
d = self.data.serialize()
data = self.data.parse(d)
self.assertEqual(len(data), len(self.data))
self.assertEqual(len(data.get_refs()), len(self.data.get_refs()))
dd = data.serialize()
self.assertEqual(d, dd) | sppas/sppas/src/files/tests/test_filedata.py | import unittest
import os
import json
import sppas
from sppas import sppasTypeError, u
from ..fileref import sppasAttribute, FileReference
from ..filedata import FileData
from ..filebase import States
# ---------------------------------------------------------------------------
class TestsppasAttribute(unittest.TestCase):
def setUp(self):
self.valint = sppasAttribute('age', '12', 'int', 'speaker\'s age')
self.valfloat = sppasAttribute('freq', '0.002', 'float', 'word appearance frequency')
self.valbool = sppasAttribute('adult', 'false', 'bool', 'speaker is minor')
self.valstr = sppasAttribute('utf', 'Hi everyone !', None, u('первый токен'))
def testInt(self):
self.assertTrue(isinstance(self.valint.get_typed_value(), int))
self.assertEqual('12', self.valint.get_value())
def testFloat(self):
self.assertTrue(isinstance(self.valfloat.get_typed_value(), float))
self.assertNotEqual(0.002, self.valfloat.get_value())
def testBool(self):
self.assertFalse(self.valbool.get_typed_value())
def testStr(self):
self.assertEqual('Hi everyone !', self.valstr.get_typed_value())
self.assertEqual('Hi everyone !', self.valstr.get_value())
def testRepr(self):
self.assertEqual(u('age, 12, speaker\'s age'), str(self.valint))
def testSetTypeValue(self):
with self.assertRaises(sppasTypeError) as error:
self.valbool.set_value_type('sppasAttribute')
self.assertTrue(isinstance(error.exception, sppasTypeError))
def testGetValuetype(self):
self.assertEqual('str', self.valstr.get_value_type())
# ---------------------------------------------------------------------------
class TestReferences(unittest.TestCase):
def setUp(self):
self.micros = FileReference('microphone')
self.att = sppasAttribute('mic1', 'Bird UM1', None, '最初のインタビューで使えていましたマイク')
self.micros.append(self.att)
self.micros.add('mic2', 'AKG D5')
def testGetItem(self):
self.assertEqual(u('最初のインタビューで使えていましたマイク'),
self.micros.att('mic1').get_description())
def testsppasAttribute(self):
self.assertFalse(isinstance(self.micros.att('mic2').get_typed_value(), int))
def testAddKey(self):
with self.assertRaises(ValueError) as AsciiError:
self.micros.add('i', 'Blue Yeti')
self.assertTrue(isinstance(AsciiError.exception, ValueError))
def testPopKey(self):
self.micros.pop('mic1')
self.assertEqual(1, len(self.micros))
self.micros.append(self.att)
self.micros.pop(self.att)
self.assertEqual(1, len(self.micros))
# ----------------------------------------------------------------------------
class TestFileData(unittest.TestCase):
def setUp(self):
self.data = FileData()
self.data.add_file(__file__)
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-fra', 'AC track_0379.PitchTier'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-fra', 'AC track_0379.TextGrid'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-jpn', 'JPA_M16_JPA_T02.TextGrid'))
self.data.add_file(os.path.join(sppas.paths.samples, 'samples-cat', 'TB-FE1-H1_phrase1.TextGrid'))
self.r1 = FileReference('SpeakerAB')
self.r1.set_type('SPEAKER')
self.r1.append(sppasAttribute('initials', 'AB'))
self.r1.append(sppasAttribute('sex', 'F'))
self.r2 = FileReference('SpeakerCM')
self.r2.set_type('SPEAKER')
self.r2.append(sppasAttribute('initials', 'CM'))
self.r2.append(sppasAttribute('sex', 'F'))
self.r3 = FileReference('Dialog1')
self.r3.set_type('INTERACTION')
self.r3.append(sppasAttribute('when', '2003', 'int', 'Year of recording'))
self.r3.append(sppasAttribute('where', 'Aix-en-Provence', descr='Place of recording'))
def test_init(self):
data = FileData()
self.assertEqual(36, len(data.id))
self.assertEqual(0, len(data))
def test_save(self):
self.data.add_ref(self.r1)
self.data.add_ref(self.r2)
self.data.add_ref(self.r3)
current_file_list = list()
saved_file_list = list()
self.data.save(os.path.join(sppas.paths.sppas, 'src', 'files', 'test', 'save.json'))
for fp in self.data:
for fr in fp:
for fn in fr:
current_file_list.append(fn)
data = FileData.load(os.path.join(sppas.paths.sppas, 'src', 'files', 'test', 'save.json'))
for fp in data:
for fr in fp:
for fn in fr:
saved_file_list.append(fn)
self.assertEqual(len(current_file_list), len(saved_file_list))
for f1, f2 in zip(current_file_list, saved_file_list):
self.assertEqual(f1, f2)
def test_state(self):
self.data.set_object_state(States().LOCKED)
self.assertEqual(States().LOCKED, self.data.get_object_state(self.data[0]))
def test_ref(self):
self.data.add_ref(self.r1)
self.assertEqual(1, len(self.data.get_refs()))
self.data.add_ref(self.r2)
self.assertEqual(2, len(self.data.get_refs()))
self.r1.set_state(States().CHECKED)
self.r2.set_state(States().CHECKED)
self.data.remove_refs(States().CHECKED)
self.assertEqual(0, len(self.data.get_refs()))
def test_assocations(self):
self.data.add_ref(self.r1)
self.data.set_object_state(States().CHECKED)
for ref in self.data.get_refs():
self.data.set_object_state(States().CHECKED, ref)
self.data.associate()
for fp in self.data:
for fr in fp:
self.assertTrue(self.r1 in fr.get_references())
self.data.dissociate()
for fp in self.data:
for fr in fp:
self.assertEqual(0, len(fr.get_references()))
def test_serialize(self):
d = self.data.serialize()
jsondata = json.dumps(d, indent=4, separators=(',', ': '))
jsondict = json.loads(jsondata)
self.assertEqual(d, jsondict)
def test_parse(self):
self.data.add_ref(self.r1)
self.data.add_ref(self.r2)
self.data.add_ref(self.r3)
d = self.data.serialize()
data = self.data.parse(d)
self.assertEqual(len(data), len(self.data))
self.assertEqual(len(data.get_refs()), len(self.data.get_refs()))
dd = data.serialize()
self.assertEqual(d, dd) | 0.445288 | 0.369969 |
from noOD import No
class ListaLigada:
def __init__(self):
self.cabeca = None
self._tamanho = 0
def append(self, cdX, cdY, IDpessoa):
if self.cabeca:
atual = self.cabeca
while atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
if IDpessoa not in atual.frequentadores: # Tira IDPessoas repetidas no local
atual.frequentadores.append(IDpessoa)
elif atual.prox is None:
print("Criando local", cdX, cdY)
atual.prox = No(cdX, cdY, IDpessoa)
self._tamanho += 1
else:
print("Criando local na cabeça", cdX, cdY)
self.cabeca = No(cdX, cdY, IDpessoa)
self._tamanho += 1
def __len__(self):
return self._tamanho
# get por index
def __getitem__(self, index):
atual = self.cabeca
for i in range(index):
if atual:
atual = atual.prox
else:
return IndexError('List index out of range')
if atual:
return "{0},{1},{2}".format(atual.coordenada_dX, atual.coordenada_dY, len(atual.frequentadores))
return IndexError('List index out of range')
# get por coordenada
def getItem(self, cdX, cdY):
atual = self.cabeca
i = 0
while atual:
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
return "{0},{1},{2},{3}".format(atual.coordenada_dX, atual.coordenada_dY, len(atual.frequentadores), i)
if atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
i += 1
else:
return ValueError('X:{0}, Y:{1} is not in list'.format(cdX, cdY))
# Retorna quantidade de frequentadores em uma coordenada
def contarFreq(self, cdX, cdY):
atual = self.cabeca
while atual:
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
return len(atual.frequentadores)
if atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
else:
return ValueError('X:{0}, Y:{1} is not in list'.format(cdX, cdY))
# Retorna quantidade de frequentadores em um index
def contFreqIndex(self, index):
atual = self.cabeca
for i in range(index):
if atual:
atual = atual.prox
else:
return IndexError('List index out of range')
if atual:
return len(atual.frequentadores)
return IndexError('List index out of range') | Algoritmos e Estruturas de Dados II/EP1/ListaODsimples.py | from noOD import No
class ListaLigada:
def __init__(self):
self.cabeca = None
self._tamanho = 0
def append(self, cdX, cdY, IDpessoa):
if self.cabeca:
atual = self.cabeca
while atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
if IDpessoa not in atual.frequentadores: # Tira IDPessoas repetidas no local
atual.frequentadores.append(IDpessoa)
elif atual.prox is None:
print("Criando local", cdX, cdY)
atual.prox = No(cdX, cdY, IDpessoa)
self._tamanho += 1
else:
print("Criando local na cabeça", cdX, cdY)
self.cabeca = No(cdX, cdY, IDpessoa)
self._tamanho += 1
def __len__(self):
return self._tamanho
# get por index
def __getitem__(self, index):
atual = self.cabeca
for i in range(index):
if atual:
atual = atual.prox
else:
return IndexError('List index out of range')
if atual:
return "{0},{1},{2}".format(atual.coordenada_dX, atual.coordenada_dY, len(atual.frequentadores))
return IndexError('List index out of range')
# get por coordenada
def getItem(self, cdX, cdY):
atual = self.cabeca
i = 0
while atual:
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
return "{0},{1},{2},{3}".format(atual.coordenada_dX, atual.coordenada_dY, len(atual.frequentadores), i)
if atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
i += 1
else:
return ValueError('X:{0}, Y:{1} is not in list'.format(cdX, cdY))
# Retorna quantidade de frequentadores em uma coordenada
def contarFreq(self, cdX, cdY):
atual = self.cabeca
while atual:
if atual.coordenada_dX == cdX and atual.coordenada_dY == cdY:
return len(atual.frequentadores)
if atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY):
atual = atual.prox
else:
return ValueError('X:{0}, Y:{1} is not in list'.format(cdX, cdY))
# Retorna quantidade de frequentadores em um index
def contFreqIndex(self, index):
atual = self.cabeca
for i in range(index):
if atual:
atual = atual.prox
else:
return IndexError('List index out of range')
if atual:
return len(atual.frequentadores)
return IndexError('List index out of range') | 0.318485 | 0.519826 |
import sys
sys.path.append('../')
def ImportAriesByScenario(scenarioName, start_date, end_date, Area, CorpID = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
#Create ODS and EDW objects
Success = True
Messages = []
combined_df = pd.DataFrame()
try:
ODSobj = bpxdb.GetDBEnvironment('ProdODS', 'OVERRIDE')
EDWobj = bpxdb.GetDBEnvironment('ProdEDW', 'OVERRIDE')
scenario_query = qf.ScenarioQuery(scenarioName, CorpID, start_date, end_date)
results = ODSobj.Query(scenario_query)
#Extract APINumbers from the results and concatenate into an 'IN' sql clause
corpid_list = []
for result in results[0]:
if not result['CorpID'] in corpid_list:
corpid_list.append(result['CorpID'])
if None in corpid_list:
corpid_list.remove(None)
key_query = qf.EDWKeyQueryFromCorpID(corpid_list, Area)
key_results = EDWobj.Query(key_query)
#Join the key_results to the Aries results
combined_df = pd.merge(results[1], key_results[1], on='CorpID', how='right')
except Exception as ex:
Messages.append('Error on Import from Aries. ' + str(ex))
Success = False
return combined_df, Success, Messages
def ImportActuals(corpID_list, start_date, end_date, LEName = ''):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
from Model import ModelLayer as m
from datetime import datetime
import pandas as pd
Success = True
Messages = []
Actuals = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
EDWobj = bpxdb.GetDBEnvironment('ProdEDW', 'OVERRIDE')
query = qf.GetActualsFromDB(corpID_list, start_date, end_date)
results = EDWobj.Query(query)
Actuals = results[1]
#ToDo: Add optional parameter of LE Name. Scan the production adjustments table for any overrides of
#potentially incorrect production values from the EDH/EDW tables
if LEName:
ProdAdjObj = m.ProductionAdjustments('', [LEName], [], [])
ProdAdjsRows, Success, Message = ProdAdjObj.ReadTable()
if not Success:
Messages.append(Message)
#Query the production adjustments and see if there is any well entries for the given LE
if len(ProdAdjsRows) > 0:
#Loop through the results of the above query.
for row in ProdAdjsRows:
#Query the Actuals dataframe for the well and the dates and then update the production value (as long as value is not null)
date = row.Date_Key.date()
ActualsRow = Actuals.query('CorpID == @row.CorpID and Date_Key == @date')
if not ActualsRow.empty:
idx = ActualsRow.index.values[0]
if row.AdjustedGasProduction:
Actuals.loc[idx, 'Gas'] = row.AdjustedGasProduction
if row.AdjustedOilProduction:
Actuals.loc[idx, 'Oil'] = row.AdjustedOilProduction
if row.AdjustedWaterProduction:
Actuals.loc[idx, 'Water'] = row.AdjustedWaterProduction
except Exception as ex:
Messages.append('Error during query for actuals data. ' + str(ex))
Success = False
return Actuals, Success, Messages
def ImportForecastFromExcel(file, sheetname, IDstart_row, corpId_col, wellName_col, date_row, date_startcol, date_endcol, Phase, OilNF, GasNF, IDs = ['ALL']):
import openpyxl as xl
import pandas as pd
Success = True
Messages = []
return_df = pd.DataFrame()
try:
workbook = xl.load_workbook(file, data_only=True)
worksheet = workbook[sheetname]
if corpId_col:
id_col = corpId_col
else:
id_col = wellName_col
#Get integer value of parsed Range
max_row_count = worksheet.max_row
for row in worksheet.iter_rows(min_row = IDstart_row):
if corpId_col:
CorpID = row[id_col -1].value
WellName = ''
else:
WellName = row[id_col -1].value
CorpID = ''
wedge = row[id_col].value
for col in worksheet.iter_cols(min_col = date_startcol, max_col = date_endcol):
#Add a row to dataframe
if Phase == 'Gas':
Oil = 0
Water = 0
Gas = worksheet[col[0].column_letter + str(row[0].row)].value
else:
Oil = worksheet[col[0].column_letter + str(row[0].row)].value
Water = 0
Gas = 0
Date = worksheet[col[0].column_letter + str(date_row)].value
return_df = return_df.append({'CorpID': CorpID , 'WellName':WellName, 'Wedge':wedge, 'Date': Date, 'Gas': Gas, 'Oil':Oil, 'Water':Water, 'OilNF' : OilNF, 'GasNF' :GasNF}, ignore_index = True)
except Exception as ex:
Messages.append('Error during read from specified LE Spreadsheet. ' + str(ex))
Success = False
return return_df, Success, Messages
def ImportGFOFromDB2019(start_date, end_date, WellName_FieldName = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
from datetime import datetime
return_df = pd.DataFrame()
Success = True
Messages = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
TeamOpsObj = bpxdb.GetDBEnvironment('OnPrem', 'OVERRIDE')
query = qf.GetGFOFromEastDB2019(WellName_FieldName, start_date, end_date)
results = TeamOpsObj.Query(query)
return_df = results[1]
except Exception as ex:
Messages.append('Error retrieving the GFO data from the desired table. ' + str(ex))
Success = False
return return_df, Success, Messages
def ImportGFOFromDB2018(start_date, end_date, WellFlac = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
from datetime import datetime
return_df = pd.DataFrame()
Success = True
Messages = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
TeamOpsObj = bpxdb.GetDBEnvironment('OnPrem', 'OVERRIDE')
query = qf.GetGFOFromEastDB2018(WellFlac, start_date, end_date)
results = TeamOpsObj.Query(query)
return_df = results[1]
except Exception as ex:
Messages.append('Error retrieving the GFO data from the desired table. ' + str(ex))
Success = False
return return_df, Success, Messages
def GetWellandCorpID(WellName, CorpID):
from Model import QueryFile as qf
from Model import BPXDatabase as bpx
#Check CorpID if Wellname is passed
if not CorpID and WellName:
CorpID_query = qf.EDWKeyQueryFromWellName([WellName])
EDWObj = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE')
res, res_df = EDWObj.Query(CorpID_query)
if not res_df.empty:
CorpID = res_df['CorpID'].values[0]
#Check WellName if CorpID not passed
if not WellName and CorpID:
WellName_Query = qf.EDWKeyQueryFromCorpID([CorpID], '')
EDWObj = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE')
res, res_df = EDWObj.Query(WellName_Query)
if not res_df.empty:
WellName = res_df['WellName'].values[0]
return WellName, CorpID
def GetWedgeData(CorpID, SuppressMessages):
from Model import QueryFile as qf
from Model import BPXDatabase as bpx
from datetime import datetime, timedelta
import pandas as pd
Messages = []
#Get Wedge from First Production Date
#If an area is passed in as an aggregate, the first production date will be the oldest first production date of its associated well list.
well_list = GetFullWellList([CorpID])
first_sales_date_query = qf.FirstProductionDateQuery(well_list)
first_results = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE').Query(first_sales_date_query)
msg = 'Skipped input due to lack of first production date.' + CorpID
Wedge = ''
if not first_results[1].empty:
#check current year and determine if the year of the first production is last year, this year, or base (anything prior to last year)
prod_date = first_results[1]['FirstProductionDate'].values[0]
prod_date = pd.to_datetime(prod_date)
if prod_date:
prod_year = prod_date.year
this_year = datetime.now().year
last_year = (datetime.now() - timedelta(days = 365)).year
if prod_year == this_year:
Wedge = str(this_year) + ' NWD'
elif prod_year == last_year:
Wedge = str(last_year) + ' NWD'
else:
Wedge = 'Base'
else:
if not SuppressMessages:
print(msg)
Messages.append(msg)
else:
Messages.append(msg)
if not SuppressMessages:
print(msg)
return Wedge, Messages
def GetFullWellList(well_list):
from Model import ModelLayer as m
import pandas as pd
#Check each item to see if an entry exists as an Area table and return a complete list
new_list = []
for well in well_list:
AreaObj = m.AreaAggregation('', [well], [], [])
Rows, Success, Message = AreaObj.ReadTable()
if len(Rows) > 0:
Rows = pd.DataFrame([vars(s) for s in Rows])
new_wells = Rows['CorpID'].unique()
if len(list(new_wells)) == 0:
print('No wells in Area: ' + well)
new_list.extend(list(new_wells))
else:
new_list.append(well)
return new_list | local/Model/ImportUtility.py | import sys
sys.path.append('../')
def ImportAriesByScenario(scenarioName, start_date, end_date, Area, CorpID = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
#Create ODS and EDW objects
Success = True
Messages = []
combined_df = pd.DataFrame()
try:
ODSobj = bpxdb.GetDBEnvironment('ProdODS', 'OVERRIDE')
EDWobj = bpxdb.GetDBEnvironment('ProdEDW', 'OVERRIDE')
scenario_query = qf.ScenarioQuery(scenarioName, CorpID, start_date, end_date)
results = ODSobj.Query(scenario_query)
#Extract APINumbers from the results and concatenate into an 'IN' sql clause
corpid_list = []
for result in results[0]:
if not result['CorpID'] in corpid_list:
corpid_list.append(result['CorpID'])
if None in corpid_list:
corpid_list.remove(None)
key_query = qf.EDWKeyQueryFromCorpID(corpid_list, Area)
key_results = EDWobj.Query(key_query)
#Join the key_results to the Aries results
combined_df = pd.merge(results[1], key_results[1], on='CorpID', how='right')
except Exception as ex:
Messages.append('Error on Import from Aries. ' + str(ex))
Success = False
return combined_df, Success, Messages
def ImportActuals(corpID_list, start_date, end_date, LEName = ''):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
from Model import ModelLayer as m
from datetime import datetime
import pandas as pd
Success = True
Messages = []
Actuals = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
EDWobj = bpxdb.GetDBEnvironment('ProdEDW', 'OVERRIDE')
query = qf.GetActualsFromDB(corpID_list, start_date, end_date)
results = EDWobj.Query(query)
Actuals = results[1]
#ToDo: Add optional parameter of LE Name. Scan the production adjustments table for any overrides of
#potentially incorrect production values from the EDH/EDW tables
if LEName:
ProdAdjObj = m.ProductionAdjustments('', [LEName], [], [])
ProdAdjsRows, Success, Message = ProdAdjObj.ReadTable()
if not Success:
Messages.append(Message)
#Query the production adjustments and see if there is any well entries for the given LE
if len(ProdAdjsRows) > 0:
#Loop through the results of the above query.
for row in ProdAdjsRows:
#Query the Actuals dataframe for the well and the dates and then update the production value (as long as value is not null)
date = row.Date_Key.date()
ActualsRow = Actuals.query('CorpID == @row.CorpID and Date_Key == @date')
if not ActualsRow.empty:
idx = ActualsRow.index.values[0]
if row.AdjustedGasProduction:
Actuals.loc[idx, 'Gas'] = row.AdjustedGasProduction
if row.AdjustedOilProduction:
Actuals.loc[idx, 'Oil'] = row.AdjustedOilProduction
if row.AdjustedWaterProduction:
Actuals.loc[idx, 'Water'] = row.AdjustedWaterProduction
except Exception as ex:
Messages.append('Error during query for actuals data. ' + str(ex))
Success = False
return Actuals, Success, Messages
def ImportForecastFromExcel(file, sheetname, IDstart_row, corpId_col, wellName_col, date_row, date_startcol, date_endcol, Phase, OilNF, GasNF, IDs = ['ALL']):
import openpyxl as xl
import pandas as pd
Success = True
Messages = []
return_df = pd.DataFrame()
try:
workbook = xl.load_workbook(file, data_only=True)
worksheet = workbook[sheetname]
if corpId_col:
id_col = corpId_col
else:
id_col = wellName_col
#Get integer value of parsed Range
max_row_count = worksheet.max_row
for row in worksheet.iter_rows(min_row = IDstart_row):
if corpId_col:
CorpID = row[id_col -1].value
WellName = ''
else:
WellName = row[id_col -1].value
CorpID = ''
wedge = row[id_col].value
for col in worksheet.iter_cols(min_col = date_startcol, max_col = date_endcol):
#Add a row to dataframe
if Phase == 'Gas':
Oil = 0
Water = 0
Gas = worksheet[col[0].column_letter + str(row[0].row)].value
else:
Oil = worksheet[col[0].column_letter + str(row[0].row)].value
Water = 0
Gas = 0
Date = worksheet[col[0].column_letter + str(date_row)].value
return_df = return_df.append({'CorpID': CorpID , 'WellName':WellName, 'Wedge':wedge, 'Date': Date, 'Gas': Gas, 'Oil':Oil, 'Water':Water, 'OilNF' : OilNF, 'GasNF' :GasNF}, ignore_index = True)
except Exception as ex:
Messages.append('Error during read from specified LE Spreadsheet. ' + str(ex))
Success = False
return return_df, Success, Messages
def ImportGFOFromDB2019(start_date, end_date, WellName_FieldName = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
from datetime import datetime
return_df = pd.DataFrame()
Success = True
Messages = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
TeamOpsObj = bpxdb.GetDBEnvironment('OnPrem', 'OVERRIDE')
query = qf.GetGFOFromEastDB2019(WellName_FieldName, start_date, end_date)
results = TeamOpsObj.Query(query)
return_df = results[1]
except Exception as ex:
Messages.append('Error retrieving the GFO data from the desired table. ' + str(ex))
Success = False
return return_df, Success, Messages
def ImportGFOFromDB2018(start_date, end_date, WellFlac = ['ALL']):
from Model import BPXDatabase as bpxdb
from Model import QueryFile as qf
import pandas as pd
from datetime import datetime
return_df = pd.DataFrame()
Success = True
Messages = []
try:
if isinstance(start_date, datetime):
start_date = '\'' + start_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
if isinstance(end_date, datetime):
end_date = '\'' + end_date.strftime('%Y-%m-%d %H:%M:%S') + '\''
TeamOpsObj = bpxdb.GetDBEnvironment('OnPrem', 'OVERRIDE')
query = qf.GetGFOFromEastDB2018(WellFlac, start_date, end_date)
results = TeamOpsObj.Query(query)
return_df = results[1]
except Exception as ex:
Messages.append('Error retrieving the GFO data from the desired table. ' + str(ex))
Success = False
return return_df, Success, Messages
def GetWellandCorpID(WellName, CorpID):
from Model import QueryFile as qf
from Model import BPXDatabase as bpx
#Check CorpID if Wellname is passed
if not CorpID and WellName:
CorpID_query = qf.EDWKeyQueryFromWellName([WellName])
EDWObj = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE')
res, res_df = EDWObj.Query(CorpID_query)
if not res_df.empty:
CorpID = res_df['CorpID'].values[0]
#Check WellName if CorpID not passed
if not WellName and CorpID:
WellName_Query = qf.EDWKeyQueryFromCorpID([CorpID], '')
EDWObj = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE')
res, res_df = EDWObj.Query(WellName_Query)
if not res_df.empty:
WellName = res_df['WellName'].values[0]
return WellName, CorpID
def GetWedgeData(CorpID, SuppressMessages):
from Model import QueryFile as qf
from Model import BPXDatabase as bpx
from datetime import datetime, timedelta
import pandas as pd
Messages = []
#Get Wedge from First Production Date
#If an area is passed in as an aggregate, the first production date will be the oldest first production date of its associated well list.
well_list = GetFullWellList([CorpID])
first_sales_date_query = qf.FirstProductionDateQuery(well_list)
first_results = bpx.GetDBEnvironment('ProdEDW', 'OVERRIDE').Query(first_sales_date_query)
msg = 'Skipped input due to lack of first production date.' + CorpID
Wedge = ''
if not first_results[1].empty:
#check current year and determine if the year of the first production is last year, this year, or base (anything prior to last year)
prod_date = first_results[1]['FirstProductionDate'].values[0]
prod_date = pd.to_datetime(prod_date)
if prod_date:
prod_year = prod_date.year
this_year = datetime.now().year
last_year = (datetime.now() - timedelta(days = 365)).year
if prod_year == this_year:
Wedge = str(this_year) + ' NWD'
elif prod_year == last_year:
Wedge = str(last_year) + ' NWD'
else:
Wedge = 'Base'
else:
if not SuppressMessages:
print(msg)
Messages.append(msg)
else:
Messages.append(msg)
if not SuppressMessages:
print(msg)
return Wedge, Messages
def GetFullWellList(well_list):
from Model import ModelLayer as m
import pandas as pd
#Check each item to see if an entry exists as an Area table and return a complete list
new_list = []
for well in well_list:
AreaObj = m.AreaAggregation('', [well], [], [])
Rows, Success, Message = AreaObj.ReadTable()
if len(Rows) > 0:
Rows = pd.DataFrame([vars(s) for s in Rows])
new_wells = Rows['CorpID'].unique()
if len(list(new_wells)) == 0:
print('No wells in Area: ' + well)
new_list.extend(list(new_wells))
else:
new_list.append(well)
return new_list | 0.247351 | 0.136177 |
from itertools import chain
from logzero import logger
import pandas as pd
from intervaltree import Interval, IntervalTree
import pysam
from . import data, genes, settings
from .exceptions import ExcovisException
from .cache import cache
@cache.memoize()
def load_all_data():
"""Load all meta data information from ``settings.DATA_SOURCES``.
A data source can either be a URL to a file ending on ``.bam`` or a directory that contains ``.bam`` files.
"""
result = []
if settings.FAKE_DATA:
result.append(data.fake_data())
for url in settings.DATA_SOURCES:
if url.scheme in data.PYFS_SCHEMES:
if url.path.endswith(".bam"): # one file
result.append(data.load_data(url))
else:
curr_fs = data.make_fs(url)
for match in curr_fs.glob("**/*.bam"):
x = url._replace(path=url.path + match.path)
result.append(data.load_data(x))
return result
@cache.memoize()
def load_data(id):
for data in load_all_data():
if data.id == id:
return data
raise ExcovisException("Unknown dataset %d" % id)
def _load_fake_coverage(sample, chrom, tree):
def padded_range(a, b, padding):
return range(a - padding, b + padding)
def fn(lst):
return list(sorted(set(chain(*lst))))
positions = fn([padded_range(itv.begin, itv.end, settings.MAX_EXON_PADDING) for itv in tree])
n = len(positions)
return pd.DataFrame(
data=[
{"chrom": chrom, "pos": pos, sample: int(50.0 * i / n)}
for i, pos in enumerate(positions)
],
columns=["chrom", "pos", sample],
)
@cache.memoize()
def load_coverage(sample_id, chrom, tree, transcript):
"""Load coverage for all positions in ``tree`` from ``chrom``."""
if sample_id == data.FAKE_DATA_ID: # short-circuit for fake data
return _load_fake_coverage(sample_id, chrom, tree)
datasets = load_all_data()
for dataset in datasets:
if dataset.id == sample_id:
break
else:
logger.info("Could not locate sample %s in %s", sample_id, [ds.id for ds in datasets])
raise ExcovisException("Unknown sample %s" % sample_id)
logger.info("dataset = %s", dataset)
pad = settings.MAX_EXON_PADDING
rows = []
with pysam.AlignmentFile(dataset.path, "rb") as samfile:
for i, itv in enumerate(sorted(tree, key=lambda exon: exon.begin)):
if transcript.strand == "+":
exon_no = i + 1
else:
exon_no = len(transcript.exons) - i
seen = set()
for align_col in samfile.pileup(chrom, itv.begin - pad, itv.end + pad):
pos = align_col.reference_pos
if pos not in seen and itv.begin - pad <= pos < itv.end + pad:
seen.add(pos)
rows.append(
{
"chrom": chrom,
"pos": pos + 1,
"exon_no": exon_no,
dataset.sample: align_col.get_num_aligned(),
}
)
for pos in range(itv.begin - pad, itv.end + pad):
if pos not in seen:
rows.append(
{"chrom": chrom, "pos": pos + 1, "exon_no": exon_no, dataset.sample: 0}
)
result = pd.DataFrame(data=rows, columns=["chrom", "pos", "exon_no", dataset.sample])
result.sort_values("pos", inplace=True)
return result
@cache.memoize()
def load_coverage_df(exon_padding, tx_accession, samples):
transcript = genes.load_transcripts()[tx_accession]
tree = IntervalTree([Interval(exon.begin, exon.end) for exon in transcript.exons])
ds = [load_coverage(sample, transcript.chrom, tree, transcript) for sample in samples]
df_coverage = pd.concat(
[ds[0]["chrom"], ds[0]["pos"], ds[0]["exon_no"]] + [d.iloc[:, 3] for d in ds],
axis="columns",
)
df_coverage.sort_values("pos", inplace=True)
return df_coverage | excovis/store.py | from itertools import chain
from logzero import logger
import pandas as pd
from intervaltree import Interval, IntervalTree
import pysam
from . import data, genes, settings
from .exceptions import ExcovisException
from .cache import cache
@cache.memoize()
def load_all_data():
"""Load all meta data information from ``settings.DATA_SOURCES``.
A data source can either be a URL to a file ending on ``.bam`` or a directory that contains ``.bam`` files.
"""
result = []
if settings.FAKE_DATA:
result.append(data.fake_data())
for url in settings.DATA_SOURCES:
if url.scheme in data.PYFS_SCHEMES:
if url.path.endswith(".bam"): # one file
result.append(data.load_data(url))
else:
curr_fs = data.make_fs(url)
for match in curr_fs.glob("**/*.bam"):
x = url._replace(path=url.path + match.path)
result.append(data.load_data(x))
return result
@cache.memoize()
def load_data(id):
for data in load_all_data():
if data.id == id:
return data
raise ExcovisException("Unknown dataset %d" % id)
def _load_fake_coverage(sample, chrom, tree):
def padded_range(a, b, padding):
return range(a - padding, b + padding)
def fn(lst):
return list(sorted(set(chain(*lst))))
positions = fn([padded_range(itv.begin, itv.end, settings.MAX_EXON_PADDING) for itv in tree])
n = len(positions)
return pd.DataFrame(
data=[
{"chrom": chrom, "pos": pos, sample: int(50.0 * i / n)}
for i, pos in enumerate(positions)
],
columns=["chrom", "pos", sample],
)
@cache.memoize()
def load_coverage(sample_id, chrom, tree, transcript):
"""Load coverage for all positions in ``tree`` from ``chrom``."""
if sample_id == data.FAKE_DATA_ID: # short-circuit for fake data
return _load_fake_coverage(sample_id, chrom, tree)
datasets = load_all_data()
for dataset in datasets:
if dataset.id == sample_id:
break
else:
logger.info("Could not locate sample %s in %s", sample_id, [ds.id for ds in datasets])
raise ExcovisException("Unknown sample %s" % sample_id)
logger.info("dataset = %s", dataset)
pad = settings.MAX_EXON_PADDING
rows = []
with pysam.AlignmentFile(dataset.path, "rb") as samfile:
for i, itv in enumerate(sorted(tree, key=lambda exon: exon.begin)):
if transcript.strand == "+":
exon_no = i + 1
else:
exon_no = len(transcript.exons) - i
seen = set()
for align_col in samfile.pileup(chrom, itv.begin - pad, itv.end + pad):
pos = align_col.reference_pos
if pos not in seen and itv.begin - pad <= pos < itv.end + pad:
seen.add(pos)
rows.append(
{
"chrom": chrom,
"pos": pos + 1,
"exon_no": exon_no,
dataset.sample: align_col.get_num_aligned(),
}
)
for pos in range(itv.begin - pad, itv.end + pad):
if pos not in seen:
rows.append(
{"chrom": chrom, "pos": pos + 1, "exon_no": exon_no, dataset.sample: 0}
)
result = pd.DataFrame(data=rows, columns=["chrom", "pos", "exon_no", dataset.sample])
result.sort_values("pos", inplace=True)
return result
@cache.memoize()
def load_coverage_df(exon_padding, tx_accession, samples):
transcript = genes.load_transcripts()[tx_accession]
tree = IntervalTree([Interval(exon.begin, exon.end) for exon in transcript.exons])
ds = [load_coverage(sample, transcript.chrom, tree, transcript) for sample in samples]
df_coverage = pd.concat(
[ds[0]["chrom"], ds[0]["pos"], ds[0]["exon_no"]] + [d.iloc[:, 3] for d in ds],
axis="columns",
)
df_coverage.sort_values("pos", inplace=True)
return df_coverage | 0.616012 | 0.409693 |
import base64
import os
import re
import subprocess
import yaml
SHELF = os.path.expanduser('~/.config/easy2fa/accounts')
TYPES = ['counter', 'timer']
class AccountStorage(object):
def __init__(self, filename=SHELF):
self.filename = filename
self._safety_check()
self.shelf = None
self.accounts = None
self._load()
@property
def list(self):
return sorted(self.accounts.keys())
@property
def default(self):
return self.shelf.get('default')
@default.setter
def default(self, name):
assert(name in self.accounts)
self.shelf['default'] = name
self._save_shelf()
def add(self, name, secret, type_):
assert(name not in self.accounts)
assert(type_ in TYPES)
if type_ != 'timer':
# start the counter at zero
type_ = 0
self.accounts[name] = (AccountStorage.__normalize_secret(secret),
type_)
self._update_default()
self._save_shelf()
def remove(self, name):
assert(name in self.accounts)
del self.accounts[name]
self._update_default()
self._save_shelf()
def generate(self, name):
assert(name in self.accounts)
secret, type_ = self.accounts[name]
opts = '--totp'
if type_ != 'timer':
opts = "--counter=%s" % str(type_)
type_ += 1
try:
otp = subprocess.check_output(
['oathtool', '-b', opts, secret]).decode().strip()
except:
print("Unable to create one time password")
raise
self.accounts[name] = secret, type_
self._save_shelf()
return otp
def _update_default(self, account=None):
if self.shelf.get('default') in self.accounts:
return
if 'default' in self.shelf and not self.accounts:
del self.shelf['default']
return
self.shelf['default'] = sorted(self.accounts.keys())[0]
def _save_shelf(self):
with open(self.filename, 'w') as fd:
yaml.dump(self.shelf, fd)
def _safety_check(self):
dirname = os.path.dirname(self.filename)
if os.path.isfile(self.filename):
try:
assert(os.stat(self.filename).st_uid == os.geteuid())
assert(os.stat(self.filename).st_gid == os.getegid())
assert(os.stat(self.filename).st_mode == 0o100600)
assert(os.stat(dirname).st_uid == os.geteuid())
assert(os.stat(dirname).st_gid == os.getegid())
assert(os.stat(dirname).st_mode == 0o040755)
# TODO: extend checks to be more discerning
except AssertionError:
print("Aborting: Safety checks not met for %s" % self.filename)
raise
else:
try:
os.makedirs(dirname, 0o755)
except:
pass
os.open(self.filename, os.O_WRONLY | os.O_CREAT, 0o600)
def _load(self):
with open(self.filename, 'r') as fd:
self.shelf = yaml.load(fd)
if self.shelf is None:
self.shelf = {'accounts': {}}
assert(isinstance(self.shelf, dict))
assert('accounts' in self.shelf)
self.accounts = self.shelf['accounts']
assert(isinstance(self.accounts, dict))
try:
for account, info in self.accounts.items():
assert(isinstance(account, str))
assert(len(info) == 2)
assert(info[1] == 'timer' or isinstance(info[1], int))
except AssertionError:
print("Aborting: Format checks not met for %s" % self.filename)
raise
@staticmethod
def __normalize_secret(secret):
secret = re.sub(r"\s+", "", secret, flags=re.UNICODE)
try:
secret = base64.b32encode(bytes.fromhex(secret))
except ValueError:
pass
return secret | easy2fa/storage.py |
import base64
import os
import re
import subprocess
import yaml
SHELF = os.path.expanduser('~/.config/easy2fa/accounts')
TYPES = ['counter', 'timer']
class AccountStorage(object):
def __init__(self, filename=SHELF):
self.filename = filename
self._safety_check()
self.shelf = None
self.accounts = None
self._load()
@property
def list(self):
return sorted(self.accounts.keys())
@property
def default(self):
return self.shelf.get('default')
@default.setter
def default(self, name):
assert(name in self.accounts)
self.shelf['default'] = name
self._save_shelf()
def add(self, name, secret, type_):
assert(name not in self.accounts)
assert(type_ in TYPES)
if type_ != 'timer':
# start the counter at zero
type_ = 0
self.accounts[name] = (AccountStorage.__normalize_secret(secret),
type_)
self._update_default()
self._save_shelf()
def remove(self, name):
assert(name in self.accounts)
del self.accounts[name]
self._update_default()
self._save_shelf()
def generate(self, name):
assert(name in self.accounts)
secret, type_ = self.accounts[name]
opts = '--totp'
if type_ != 'timer':
opts = "--counter=%s" % str(type_)
type_ += 1
try:
otp = subprocess.check_output(
['oathtool', '-b', opts, secret]).decode().strip()
except:
print("Unable to create one time password")
raise
self.accounts[name] = secret, type_
self._save_shelf()
return otp
def _update_default(self, account=None):
if self.shelf.get('default') in self.accounts:
return
if 'default' in self.shelf and not self.accounts:
del self.shelf['default']
return
self.shelf['default'] = sorted(self.accounts.keys())[0]
def _save_shelf(self):
with open(self.filename, 'w') as fd:
yaml.dump(self.shelf, fd)
def _safety_check(self):
dirname = os.path.dirname(self.filename)
if os.path.isfile(self.filename):
try:
assert(os.stat(self.filename).st_uid == os.geteuid())
assert(os.stat(self.filename).st_gid == os.getegid())
assert(os.stat(self.filename).st_mode == 0o100600)
assert(os.stat(dirname).st_uid == os.geteuid())
assert(os.stat(dirname).st_gid == os.getegid())
assert(os.stat(dirname).st_mode == 0o040755)
# TODO: extend checks to be more discerning
except AssertionError:
print("Aborting: Safety checks not met for %s" % self.filename)
raise
else:
try:
os.makedirs(dirname, 0o755)
except:
pass
os.open(self.filename, os.O_WRONLY | os.O_CREAT, 0o600)
def _load(self):
with open(self.filename, 'r') as fd:
self.shelf = yaml.load(fd)
if self.shelf is None:
self.shelf = {'accounts': {}}
assert(isinstance(self.shelf, dict))
assert('accounts' in self.shelf)
self.accounts = self.shelf['accounts']
assert(isinstance(self.accounts, dict))
try:
for account, info in self.accounts.items():
assert(isinstance(account, str))
assert(len(info) == 2)
assert(info[1] == 'timer' or isinstance(info[1], int))
except AssertionError:
print("Aborting: Format checks not met for %s" % self.filename)
raise
@staticmethod
def __normalize_secret(secret):
secret = re.sub(r"\s+", "", secret, flags=re.UNICODE)
try:
secret = base64.b32encode(bytes.fromhex(secret))
except ValueError:
pass
return secret | 0.320396 | 0.223631 |
from F2x.parser import tree
class VarDecl(tree.VarDecl):
"""
A variable declaration.
The following properties are available:
- name: The symbolic name of the variable.
- type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any
other type like arrays, derived types or strings.
- pytype, cstype: The type to be used by Python or C# respectively.
- intent: May be 'IN', 'OUT' or 'INOUT'.
- getter: This indicates whether the generated getter should be a 'function' or 'subroutine'.
- setter (opt): This indicates whether a 'subroutine' should be generated as setter.
- ftype (opt): The name of the derived type.
- strlen (opt): The length of the string.
- kind (opt): The kind specifier if available.
- dynamic (opt): Indicates whether the variable is 'ALLOCATABLE' or a 'POINTER'.
- dims (opt): For an array contains a list with the sizes per dimension.
"""
_PYTYPES = {
"REAL": "ctypes.c_double",
"INTEGER": "ctypes.c_int",
"LOGICAL": "ctypes.c_bool",
"TYPE(C_PTR)": "ctypes.c_void_p",
}
_CSTYPES = {
"REAL": "Double",
"INTEGER": "Int32",
"LOGICAL": "Int32",
"TYPE(C_PTR)": "IntPtr",
}
def _init_children(self):
self["name"] = self._ast.select1("name").tail[0]
# Identify FORTRAN type and store properties accordingly
full_spec = self._ast.parent().parent()
type_spec = full_spec.select1("declaration_type_spec")
try:
self["ftype"] = type_spec.select1("derived_type_spec name").tail[0]
self["type"] = "TYPE(C_PTR)"
self["getter"] = "function"
self["dynamic"] = False
except ValueError:
try:
self["strlen"] = int(type_spec.select1("char_selector int_literal_constant").tail[0])
self["intent"] = "IN"
self["type"] = "TYPE(C_PTR)"
self["pytype"] = "ctypes.c_char_p"
self["cstype"] = "String"
self["getter"] = "subroutine"
self["setter"] = "subroutine"
except ValueError:
try:
self["strlen"] = type_spec.select1("char_selector /(\*|:)/")
self["intent"] = "IN"
self["type"] = "TYPE(C_PTR)"
self["pytype"] = "ctypes.c_char_p"
self["cstype"] = "String"
self["getter"] = "subroutine"
self["setter"] = "subroutine"
except ValueError:
self["type"] = type_spec.select1("intrinsic_type_kind").tail[0]
self["getter"] = "function"
self["setter"] = "subroutine"
for attr in full_spec.select(self._prefix + "attr_spec"):
if 'ALLOCATABLE' in attr.tail:
self["dynamic"] = 'ALLOCATABLE'
elif 'POINTER' in attr.tail:
self["dynamic"] = 'POINTER'
# Identify array dimensions
for ast in (self._ast, full_spec):
dim_nodes = ast.select(self._prefix + "array_spec array_spec_element")
if not dim_nodes:
continue
dims = []
for node in dim_nodes:
dim = node.select("int_literal_constant")
if dim:
dims.append(dim[0].tail[0])
continue
dim = node.select("part_ref")
if dim:
dims.append(dim[0].tail[0])
break
dims.append(0)
if dims:
self["dims"] = dims
if "dims" in self \
and "strlen" not in self:
if "setter" in self:
del self["setter"]
if "pytype" not in self \
and self["type"].upper() in self._PYTYPES:
self["pytype"] = self._PYTYPES[self["type"].upper()]
if "cstype" not in self \
and self["type"].upper() in self._CSTYPES:
self["cstype"] = self._CSTYPES[self["type"].upper()]
try:
kind_selector = type_spec.select1("kind_selector int_literal_constant")
self["kind"] = int(kind_selector.tail[0])
except ValueError:
try:
kind_selector = type_spec.select1("kind_selector part_ref")
self["kind"] = kind_selector.tail[0]
except ValueError:
pass
try:
intent_spec = type_spec.parent().select1("intent_spec")
self["intent"] = intent_spec.tail[0]
except ValueError:
self["intent"] = 'IN'
# No setter for PARAMETERs
if "setter" in self \
and len(full_spec.select("attr_spec /PARAMETER/")) > 0:
del self["setter"]
def with_intent(self, intent):
self["intent"] = intent
return self
class TypeDef(tree.TypeDef):
def _init_children(self):
self["name"] = self._ast.select1("derived_type_stmt name").tail[0]
try:
self["public"] = (self._ast.select1("access_spec").tail[0].upper() == 'PUBLIC')
except ValueError:
self["public"] = False
self["fields"] = [
VarDecl(decl, 'component_') # See documentation of VarDecl.__init__
for decl in self._ast.select("component_decl")
]
for field in self["fields"]:
del field["intent"]
class SubDef(tree.SubDef):
_PREFIX = "subroutine"
def _init_children(self):
self["name"] = self._ast.select(self._PREFIX + "_stmt name")[0].tail[0]
# Two-stage argument extraction:
# First, identify all variables declared and the dummy argument list.
dummy_args = [arg.tail[0] for arg in self._ast.select("dummy_arg name")]
var_specs = dict(
(argdecl.select1("name").tail[0], VarDecl(argdecl))
for argdecl in self._ast.select("entity_decl")
)
# Fill up self["args"] based on dummy argument list order.
self["args"] = [var_specs[argname] for argname in dummy_args]
return var_specs # to be re-used in child classes.
class FuncDef(SubDef):
_PREFIX = "function"
def _init_children(self):
var_specs = super(FuncDef, self)._init_children()
# Capture return type of function for return value.
res_name = self._ast.select("result_name name")
if res_name:
self["ret"] = var_specs[res_name[0].tail[0]]
else:
try:
self["ret"] = var_specs[self["name"] + "_VALUE"]
except KeyError:
self["ret"] = var_specs[self["name"]]
if "dims" in self["ret"]:
self["ret"]["getter"] = "subroutine"
self["ret"]["intent"] = "OUT"
class Module(tree.Module):
def _init_children(self):
self["name"] = self._ast.select1("module_stmt name").tail[0]
self["uses"] = [use.tail[0] for use in self._ast.select("use_stmt name")]
self["types"] = [
TypeDef(typedef)
for typedef in self._ast.select("derived_type_def")
]
self["globals"] = [
VarDecl(var)
for var in self._ast.select("module > specification_part type_declaration_stmt entity_decl")
if len(var.parent().parent().select("access_spec /PUBLIC/")) > 0
]
# def export_methods(self, config):
def export_methods(self, src):
config = src.config
if config.has_section("export"):
export_items = [key for key, _ in config.items("export")]
else:
export_items = None
methods = []
for funcdef in self._ast.select("function_subprogram") :
if export_items is None or funcdef.select("function_stmt name")[0].tail[0].lower() in export_items:
method = FuncDef(funcdef)
method["export_name"] = config.get("export", method["name"].lower(), fallback=f'{self["name"]}_{method["name"]}')
if "ret" in method:
if "dims" in method["ret"]:
l_line = [line for line in src.source_lines if method["ret"]["name"] in line and "ALLOCATE" in line]
if len(l_line) == 1:
#ok, it is a dynamic array, find the size variable of the array
l_aux_line = l_line[0][l_line[0].find(method["ret"]["name"]):-2]
l_size_var = l_aux_line[len(method["ret"]["name"])+1:-1].split(',')
method["ret"]["dims"] = l_size_var
if method["ret"]["getter"] == "subroutine":
if method["ret"]["name"] == method["name"]:
method["ret"]["name"] = method["export_name"].upper() + '_OUT'
method["ret"]["intent"] = "OUT"
else:
method["ret"]["name"] = method["export_name"].upper() + '_RESULT'
del method["ret"]["intent"]
methods.append(method)
for subdef in self._ast.select("subroutine_subprogram") :
if export_items is None or subdef.select("subroutine_stmt name")[0].tail[0].lower() in export_items:
method = SubDef(subdef)
method["export_name"] = config.get("export", method["name"].lower(), fallback=f'{self["name"]}_{method["name"]}')
l_array_args = [ l_arg for l_arg in method["args"] if "dims" in l_arg ]
if len(l_array_args) > 0:
#okay, we have arguments of array type
sub_start, sub_end = self._get_subroutine(method["name"], src.source_lines)
for arg in l_array_args:
self._set_array_size(arg, src.source_lines[sub_start: sub_end])
if "ret" in method:
method["ret"]["name"] = method["export_name"].upper() + '_OUT'
method["ret"]["intent"] = "OUT"
methods.append(method)
self["methods"] = methods
for method in methods:
section_key = "{0}:Cleanup".format(method["name"])
if config.has_section(section_key):
if "ret" in method: print("FREE", section_key, method["ret"]["name"])
if "ret" in method and config.has_option(section_key, method["ret"]["name"]):
method["ret"]["free"] = config.get(section_key, method["ret"]["name"])
for var in method["args"]:
if config.has_option(section_key, var["name"]):
var["free"] = config.get(section_key, var["name"])
def _set_array_size(self, a_argument, a_src):
l_arg = a_argument["name"]
l_arg_len = len(l_arg)
l_key_len = 8 # keyword "ALLOCATE"
for index, line in enumerate(a_src) :
# to do: skip the comments
l_line = line[line.find("::")+2 : ].strip()
# this is the declaration line
if l_line.startswith(l_arg+'(') :
l_declare = l_line.split('!')
l_array_var = l_declare[0].strip()
l_size_var = l_array_var[l_arg_len+1:-1].split(',')
if l_size_var[0] == ':':
# check if the array is dynamically allocated within the function/subroutine body
for line in a_src[index:] :
line = line.strip()
if line.startswith("ALLOCATE") :
# skip comment
l_alloc = line.split('!')[0].strip()
l_line = l_alloc[l_key_len:].strip()[1:-1]
l_alloc_list = l_line.split('),')
# check if more than one variables are allocated
if len(l_alloc_list) > 1 :
for l_alloc in l_alloc_list :
l_alloc = l_alloc.strip()
if l_alloc.startswith(l_arg + '(') :
l_aux_line = ''
if l_alloc.endswith(')') :
l_aux_line = l_alloc[l_arg_len+1:-1].strip()
else :
l_aux_line = l_alloc[l_arg_len+1:].strip()
l_size_var = l_aux_line.split(',')
a_argument["dims"] = l_size_var
break
else :
l_alloc = l_alloc_list[0].strip()
if l_alloc.startswith(l_arg + '(') :
l_aux_line = l_alloc[l_arg_len+1:-1].strip()
l_size_var = l_aux_line.split(',')
a_argument["dims"] = l_size_var
else :
# okay, no size variable is found. It could be "IN" or "INOUT" type,
if len(l_declare) == 2 :
l_comment = l_declare[1].strip()
l_f2x_markup='@F2x=>'
if l_comment.startswith(l_f2x_markup) :
l_vars = l_comment.split(l_f2x_markup+l_arg)[1]
l_size_var = l_vars[1:-1].split(',')
a_argument["dims"] = l_size_var
else :
# Attention: no information is provided, code is not reliable !!
# But at leaset make sure the dimension is correctly set
n = len(l_size_var)
a_argument["dims"] = [ 0 if x == ':' else x for x in l_size_var ]
else :
# Same problem as above !!
n = len(l_size_var)
a_argument["dims"] = [ 0 if x == ':' else x for x in l_size_var ]
else :
# size variables are set explicitly
a_argument["dims"] = l_size_var
break
def _get_subroutine(self,a_argument, a_src):
startIndex = 0
stopIndex =0
for i in range(len(a_src)):
l_str = a_src[i].strip()
if l_str.startswith("SUBROUTINE") and a_argument in l_str :
startIndex = i
for j, line in enumerate(a_src[i:]):
line = line.strip()
if line.startswith("END SUBROUTINE") :
stopIndex = i + j
break
break
else:
# should not happend
pass
return (startIndex, stopIndex) | src/F2x/parser/plyplus/tree.py | from F2x.parser import tree
class VarDecl(tree.VarDecl):
"""
A variable declaration.
The following properties are available:
- name: The symbolic name of the variable.
- type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any
other type like arrays, derived types or strings.
- pytype, cstype: The type to be used by Python or C# respectively.
- intent: May be 'IN', 'OUT' or 'INOUT'.
- getter: This indicates whether the generated getter should be a 'function' or 'subroutine'.
- setter (opt): This indicates whether a 'subroutine' should be generated as setter.
- ftype (opt): The name of the derived type.
- strlen (opt): The length of the string.
- kind (opt): The kind specifier if available.
- dynamic (opt): Indicates whether the variable is 'ALLOCATABLE' or a 'POINTER'.
- dims (opt): For an array contains a list with the sizes per dimension.
"""
_PYTYPES = {
"REAL": "ctypes.c_double",
"INTEGER": "ctypes.c_int",
"LOGICAL": "ctypes.c_bool",
"TYPE(C_PTR)": "ctypes.c_void_p",
}
_CSTYPES = {
"REAL": "Double",
"INTEGER": "Int32",
"LOGICAL": "Int32",
"TYPE(C_PTR)": "IntPtr",
}
def _init_children(self):
self["name"] = self._ast.select1("name").tail[0]
# Identify FORTRAN type and store properties accordingly
full_spec = self._ast.parent().parent()
type_spec = full_spec.select1("declaration_type_spec")
try:
self["ftype"] = type_spec.select1("derived_type_spec name").tail[0]
self["type"] = "TYPE(C_PTR)"
self["getter"] = "function"
self["dynamic"] = False
except ValueError:
try:
self["strlen"] = int(type_spec.select1("char_selector int_literal_constant").tail[0])
self["intent"] = "IN"
self["type"] = "TYPE(C_PTR)"
self["pytype"] = "ctypes.c_char_p"
self["cstype"] = "String"
self["getter"] = "subroutine"
self["setter"] = "subroutine"
except ValueError:
try:
self["strlen"] = type_spec.select1("char_selector /(\*|:)/")
self["intent"] = "IN"
self["type"] = "TYPE(C_PTR)"
self["pytype"] = "ctypes.c_char_p"
self["cstype"] = "String"
self["getter"] = "subroutine"
self["setter"] = "subroutine"
except ValueError:
self["type"] = type_spec.select1("intrinsic_type_kind").tail[0]
self["getter"] = "function"
self["setter"] = "subroutine"
for attr in full_spec.select(self._prefix + "attr_spec"):
if 'ALLOCATABLE' in attr.tail:
self["dynamic"] = 'ALLOCATABLE'
elif 'POINTER' in attr.tail:
self["dynamic"] = 'POINTER'
# Identify array dimensions
for ast in (self._ast, full_spec):
dim_nodes = ast.select(self._prefix + "array_spec array_spec_element")
if not dim_nodes:
continue
dims = []
for node in dim_nodes:
dim = node.select("int_literal_constant")
if dim:
dims.append(dim[0].tail[0])
continue
dim = node.select("part_ref")
if dim:
dims.append(dim[0].tail[0])
break
dims.append(0)
if dims:
self["dims"] = dims
if "dims" in self \
and "strlen" not in self:
if "setter" in self:
del self["setter"]
if "pytype" not in self \
and self["type"].upper() in self._PYTYPES:
self["pytype"] = self._PYTYPES[self["type"].upper()]
if "cstype" not in self \
and self["type"].upper() in self._CSTYPES:
self["cstype"] = self._CSTYPES[self["type"].upper()]
try:
kind_selector = type_spec.select1("kind_selector int_literal_constant")
self["kind"] = int(kind_selector.tail[0])
except ValueError:
try:
kind_selector = type_spec.select1("kind_selector part_ref")
self["kind"] = kind_selector.tail[0]
except ValueError:
pass
try:
intent_spec = type_spec.parent().select1("intent_spec")
self["intent"] = intent_spec.tail[0]
except ValueError:
self["intent"] = 'IN'
# No setter for PARAMETERs
if "setter" in self \
and len(full_spec.select("attr_spec /PARAMETER/")) > 0:
del self["setter"]
def with_intent(self, intent):
self["intent"] = intent
return self
class TypeDef(tree.TypeDef):
def _init_children(self):
self["name"] = self._ast.select1("derived_type_stmt name").tail[0]
try:
self["public"] = (self._ast.select1("access_spec").tail[0].upper() == 'PUBLIC')
except ValueError:
self["public"] = False
self["fields"] = [
VarDecl(decl, 'component_') # See documentation of VarDecl.__init__
for decl in self._ast.select("component_decl")
]
for field in self["fields"]:
del field["intent"]
class SubDef(tree.SubDef):
_PREFIX = "subroutine"
def _init_children(self):
self["name"] = self._ast.select(self._PREFIX + "_stmt name")[0].tail[0]
# Two-stage argument extraction:
# First, identify all variables declared and the dummy argument list.
dummy_args = [arg.tail[0] for arg in self._ast.select("dummy_arg name")]
var_specs = dict(
(argdecl.select1("name").tail[0], VarDecl(argdecl))
for argdecl in self._ast.select("entity_decl")
)
# Fill up self["args"] based on dummy argument list order.
self["args"] = [var_specs[argname] for argname in dummy_args]
return var_specs # to be re-used in child classes.
class FuncDef(SubDef):
_PREFIX = "function"
def _init_children(self):
var_specs = super(FuncDef, self)._init_children()
# Capture return type of function for return value.
res_name = self._ast.select("result_name name")
if res_name:
self["ret"] = var_specs[res_name[0].tail[0]]
else:
try:
self["ret"] = var_specs[self["name"] + "_VALUE"]
except KeyError:
self["ret"] = var_specs[self["name"]]
if "dims" in self["ret"]:
self["ret"]["getter"] = "subroutine"
self["ret"]["intent"] = "OUT"
class Module(tree.Module):
def _init_children(self):
self["name"] = self._ast.select1("module_stmt name").tail[0]
self["uses"] = [use.tail[0] for use in self._ast.select("use_stmt name")]
self["types"] = [
TypeDef(typedef)
for typedef in self._ast.select("derived_type_def")
]
self["globals"] = [
VarDecl(var)
for var in self._ast.select("module > specification_part type_declaration_stmt entity_decl")
if len(var.parent().parent().select("access_spec /PUBLIC/")) > 0
]
# def export_methods(self, config):
def export_methods(self, src):
config = src.config
if config.has_section("export"):
export_items = [key for key, _ in config.items("export")]
else:
export_items = None
methods = []
for funcdef in self._ast.select("function_subprogram") :
if export_items is None or funcdef.select("function_stmt name")[0].tail[0].lower() in export_items:
method = FuncDef(funcdef)
method["export_name"] = config.get("export", method["name"].lower(), fallback=f'{self["name"]}_{method["name"]}')
if "ret" in method:
if "dims" in method["ret"]:
l_line = [line for line in src.source_lines if method["ret"]["name"] in line and "ALLOCATE" in line]
if len(l_line) == 1:
#ok, it is a dynamic array, find the size variable of the array
l_aux_line = l_line[0][l_line[0].find(method["ret"]["name"]):-2]
l_size_var = l_aux_line[len(method["ret"]["name"])+1:-1].split(',')
method["ret"]["dims"] = l_size_var
if method["ret"]["getter"] == "subroutine":
if method["ret"]["name"] == method["name"]:
method["ret"]["name"] = method["export_name"].upper() + '_OUT'
method["ret"]["intent"] = "OUT"
else:
method["ret"]["name"] = method["export_name"].upper() + '_RESULT'
del method["ret"]["intent"]
methods.append(method)
for subdef in self._ast.select("subroutine_subprogram") :
if export_items is None or subdef.select("subroutine_stmt name")[0].tail[0].lower() in export_items:
method = SubDef(subdef)
method["export_name"] = config.get("export", method["name"].lower(), fallback=f'{self["name"]}_{method["name"]}')
l_array_args = [ l_arg for l_arg in method["args"] if "dims" in l_arg ]
if len(l_array_args) > 0:
#okay, we have arguments of array type
sub_start, sub_end = self._get_subroutine(method["name"], src.source_lines)
for arg in l_array_args:
self._set_array_size(arg, src.source_lines[sub_start: sub_end])
if "ret" in method:
method["ret"]["name"] = method["export_name"].upper() + '_OUT'
method["ret"]["intent"] = "OUT"
methods.append(method)
self["methods"] = methods
for method in methods:
section_key = "{0}:Cleanup".format(method["name"])
if config.has_section(section_key):
if "ret" in method: print("FREE", section_key, method["ret"]["name"])
if "ret" in method and config.has_option(section_key, method["ret"]["name"]):
method["ret"]["free"] = config.get(section_key, method["ret"]["name"])
for var in method["args"]:
if config.has_option(section_key, var["name"]):
var["free"] = config.get(section_key, var["name"])
def _set_array_size(self, a_argument, a_src):
l_arg = a_argument["name"]
l_arg_len = len(l_arg)
l_key_len = 8 # keyword "ALLOCATE"
for index, line in enumerate(a_src) :
# to do: skip the comments
l_line = line[line.find("::")+2 : ].strip()
# this is the declaration line
if l_line.startswith(l_arg+'(') :
l_declare = l_line.split('!')
l_array_var = l_declare[0].strip()
l_size_var = l_array_var[l_arg_len+1:-1].split(',')
if l_size_var[0] == ':':
# check if the array is dynamically allocated within the function/subroutine body
for line in a_src[index:] :
line = line.strip()
if line.startswith("ALLOCATE") :
# skip comment
l_alloc = line.split('!')[0].strip()
l_line = l_alloc[l_key_len:].strip()[1:-1]
l_alloc_list = l_line.split('),')
# check if more than one variables are allocated
if len(l_alloc_list) > 1 :
for l_alloc in l_alloc_list :
l_alloc = l_alloc.strip()
if l_alloc.startswith(l_arg + '(') :
l_aux_line = ''
if l_alloc.endswith(')') :
l_aux_line = l_alloc[l_arg_len+1:-1].strip()
else :
l_aux_line = l_alloc[l_arg_len+1:].strip()
l_size_var = l_aux_line.split(',')
a_argument["dims"] = l_size_var
break
else :
l_alloc = l_alloc_list[0].strip()
if l_alloc.startswith(l_arg + '(') :
l_aux_line = l_alloc[l_arg_len+1:-1].strip()
l_size_var = l_aux_line.split(',')
a_argument["dims"] = l_size_var
else :
# okay, no size variable is found. It could be "IN" or "INOUT" type,
if len(l_declare) == 2 :
l_comment = l_declare[1].strip()
l_f2x_markup='@F2x=>'
if l_comment.startswith(l_f2x_markup) :
l_vars = l_comment.split(l_f2x_markup+l_arg)[1]
l_size_var = l_vars[1:-1].split(',')
a_argument["dims"] = l_size_var
else :
# Attention: no information is provided, code is not reliable !!
# But at leaset make sure the dimension is correctly set
n = len(l_size_var)
a_argument["dims"] = [ 0 if x == ':' else x for x in l_size_var ]
else :
# Same problem as above !!
n = len(l_size_var)
a_argument["dims"] = [ 0 if x == ':' else x for x in l_size_var ]
else :
# size variables are set explicitly
a_argument["dims"] = l_size_var
break
def _get_subroutine(self,a_argument, a_src):
startIndex = 0
stopIndex =0
for i in range(len(a_src)):
l_str = a_src[i].strip()
if l_str.startswith("SUBROUTINE") and a_argument in l_str :
startIndex = i
for j, line in enumerate(a_src[i:]):
line = line.strip()
if line.startswith("END SUBROUTINE") :
stopIndex = i + j
break
break
else:
# should not happend
pass
return (startIndex, stopIndex) | 0.475118 | 0.217691 |
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame, Series
def get_expression_value_fracs(expression: np.ndarray, max_val: int = 10, round: int = 3):
expression = np.array(expression)
n_transcripts_per_gene = expression.flatten().astype(int)
n_transcripts_per_gene = n_transcripts_per_gene[n_transcripts_per_gene > 0]
n_transcripts_per_gene[n_transcripts_per_gene > max_val] = max_val
n_transcripts_per_gene = n_transcripts_per_gene.astype(str)
n_transcripts_per_gene[n_transcripts_per_gene == str(max_val)] = ">={}".format(max_val)
return (Series.value_counts(n_transcripts_per_gene).sort_index() / n_transcripts_per_gene.size * 100).round(
round).map("{}%".format)
def paired_hist(vals1, vals2, ax, xlabel, ylabel, xlim=None, legend_loc='upper right', do_paired=True):
if xlim is not None:
vals1 = vals1[vals1 < xlim]
vals2 = vals2[vals2 < xlim]
if do_paired:
ax.hist(np.array(vals1), bins=50, label=">1")
ax.hist(np.array(vals2), bins=50, alpha=0.5, label="All")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if legend_loc is not None and do_paired:
ax.legend(loc=legend_loc)
if xlim is not None:
ax.set_xlim(0, xlim)
def plot_expression_metrics(expression: np.ndarray, xlim1=None, xlim2=None, xlim3=None, figsize=(15, 3), do_paired=True):
expression = np.array(expression)
fig, axes = plt.subplots(ncols=3, figsize=figsize)
edf = np.array(expression)
edf[edf == 1] = 0
paired_hist(edf.sum(axis=1), expression.sum(axis=1),
axes[0], xlabel="#Transcripts per cell", ylabel="#Cells", xlim=xlim1, do_paired=do_paired)
paired_hist((expression > 1).sum(axis=1), (expression > 0).sum(axis=1),
axes[1], xlabel="#Genes per cell", ylabel="#Cells", xlim=xlim2, do_paired=do_paired)
paired_hist((expression > 1).sum(axis=0), (expression > 0).sum(axis=0),
axes[2], xlabel="#Cells per gene", ylabel="#Genes", xlim=xlim3, do_paired=do_paired)
plt.tight_layout()
return fig
def get_scalar_metrics(expression: np.ndarray):
expression = np.array(expression)
return DataFrame({"Sparsity Level": [(expression == 0).mean()],
"#Cells": [expression.shape[0]],
"#Genes": [expression.shape[1]],
"#Transcripts": [expression.sum()]}) | src/count_matrix_metrics.py | import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame, Series
def get_expression_value_fracs(expression: np.ndarray, max_val: int = 10, round: int = 3):
expression = np.array(expression)
n_transcripts_per_gene = expression.flatten().astype(int)
n_transcripts_per_gene = n_transcripts_per_gene[n_transcripts_per_gene > 0]
n_transcripts_per_gene[n_transcripts_per_gene > max_val] = max_val
n_transcripts_per_gene = n_transcripts_per_gene.astype(str)
n_transcripts_per_gene[n_transcripts_per_gene == str(max_val)] = ">={}".format(max_val)
return (Series.value_counts(n_transcripts_per_gene).sort_index() / n_transcripts_per_gene.size * 100).round(
round).map("{}%".format)
def paired_hist(vals1, vals2, ax, xlabel, ylabel, xlim=None, legend_loc='upper right', do_paired=True):
if xlim is not None:
vals1 = vals1[vals1 < xlim]
vals2 = vals2[vals2 < xlim]
if do_paired:
ax.hist(np.array(vals1), bins=50, label=">1")
ax.hist(np.array(vals2), bins=50, alpha=0.5, label="All")
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if legend_loc is not None and do_paired:
ax.legend(loc=legend_loc)
if xlim is not None:
ax.set_xlim(0, xlim)
def plot_expression_metrics(expression: np.ndarray, xlim1=None, xlim2=None, xlim3=None, figsize=(15, 3), do_paired=True):
expression = np.array(expression)
fig, axes = plt.subplots(ncols=3, figsize=figsize)
edf = np.array(expression)
edf[edf == 1] = 0
paired_hist(edf.sum(axis=1), expression.sum(axis=1),
axes[0], xlabel="#Transcripts per cell", ylabel="#Cells", xlim=xlim1, do_paired=do_paired)
paired_hist((expression > 1).sum(axis=1), (expression > 0).sum(axis=1),
axes[1], xlabel="#Genes per cell", ylabel="#Cells", xlim=xlim2, do_paired=do_paired)
paired_hist((expression > 1).sum(axis=0), (expression > 0).sum(axis=0),
axes[2], xlabel="#Cells per gene", ylabel="#Genes", xlim=xlim3, do_paired=do_paired)
plt.tight_layout()
return fig
def get_scalar_metrics(expression: np.ndarray):
expression = np.array(expression)
return DataFrame({"Sparsity Level": [(expression == 0).mean()],
"#Cells": [expression.shape[0]],
"#Genes": [expression.shape[1]],
"#Transcripts": [expression.sum()]}) | 0.543833 | 0.745422 |
import torch
import torch.nn as nn
from onmt.Models import EncoderBase, RNNDecoderBase, NMTModel
def multimodal_model_class_by_key(key):
d = {
'hsm': HiddenStateMergeLayerMMM,
'fvtl': FirstViewThenListenMMM,
'gm': GeneratorMergeMMM,
'fvtl+gm': FirstViewThenListenFinallyViewMMM
}
return d[key]
class MultiModalModel(nn.Module):
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
"""
Create new MultiModalModel.
:param encoder: text encoder to use
:param second_encoder: second modality encoder to use. Its output should be a tensor of
size [batch x second_dim]
:param second_dim: output dimension of second_encoder
:param decoder: decoder to use
:param generator: generator to use
"""
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.generator = generator
self.second_encoder = second_encoder
self.second_dim = second_dim
def forward(self, src, second_src, tgt, lengths, dec_state=None):
"""
Run a forward pass on the MultiModalModel. This takes the same arguments as NMTModel,
but additionally requires a second_src tensor as expected by this MMM's second_encoder.
:param src: the src text tensor as expected by encoder
:param second_src: the second src tensor as expected by the second_encoder
:param tgt: the tgt text tensor as expected by decoder
:param lengths: src lengths pre-padding as expected by encoder
:param dec_state: initial decoder state as expected by decoder
:return: see NMTModel
"""
tgt = tgt[:-1] # exclude last target from inputs
_, memory_bank, enc_state = self.run_encoder_to_decoder_state(src, second_src, lengths)
decoder_outputs, dec_state, attns = \
self.run_decoder(tgt, memory_bank,
enc_state if dec_state is None
else dec_state,
lengths, second_src)
return decoder_outputs, attns, dec_state
def run_encoder_to_decoder_state(self, src, second_src, lengths):
"""
Forward the given src and second_src up to the initial decoder state.
:param src: the src tensor
:param second_src: the second_src tensor
:param lengths: the src lengths
:return: (enc_final, memory_bank, dec_state) triple, containing the final encoder state,
the final encoder memory bank and the initial state to use for the decoder.
"""
raise NotImplementedError
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
return self.decoder(tgt, memory_bank, dec_init,
memory_lengths=memory_lengths)
class HiddenStateMergeLayerMMM(MultiModalModel):
"""
Implementation of MultiModalModel merging the primary and secondary sources at their
hidden representations between the encoder and decoder.
Therefore, this model uses linear layer which gets the final encoder state and the
second_encoder output and generates the initial decoder state to use.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
super().__init__(encoder, second_encoder, second_dim, decoder, generator)
directions = 2 if self.decoder.bidirectional_encoder else 1
enc_output_size = self.encoder.rnn.hidden_size * directions
self.enc_pad_layer = nn.ConstantPad1d((0, self.second_dim), 0)
self.second_pad_layer = nn.ConstantPad1d((enc_output_size, 0), 0)
self.merge_layer = nn.Linear(enc_output_size + self.second_dim,
self.decoder.hidden_size, bias=True)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
enc_final, memory_bank = self.encoder(src, lengths)
enc_final = tuple([self._fix_enc_hidden(h) for h in enc_final])
# enc_final is now layers x batch x enc_final_dim.
# Throw in the second modality for each batch sample
# => layers x batch x (dim + secondDim)
# apply merge layer to reduce to dim expected by decoder
second_modality = self.second_encoder(second_src)
decoder_input = [None, None]
for i, enc in enumerate(enc_final):
padded_final = self.enc_pad_layer(enc)
padded_second = self.second_pad_layer(second_modality)
concatenated = padded_final + padded_second.expand_as(padded_final)
decoder_input[i] = self.merge_layer(concatenated)
decoder_input = tuple([self._refix_dec_init(h) for h in decoder_input])
dec_state = \
self.decoder.init_decoder_state(src, memory_bank, decoder_input)
return enc_final, memory_bank, dec_state
def _fix_enc_hidden(self, h):
# The encoder hidden is (layers*directions) x batch x dim.
# We need to convert it to layers x batch x (directions*dim).
if self.decoder.bidirectional_encoder:
h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2)
return h
def _refix_dec_init(self, h):
# The decoder expects its init_decoder_state input to be (layers*directions) x batch x dim
# We already fixed it above (to layers x batch x directions*dim), so need to revert it now
if self.decoder.bidirectional_encoder:
dim = h.size(2) // 2
h_even, h_odd = torch.split(h, dim, 2)
h_in_order = [x[i] for i in range(h_even.size(0)) for x in (h_even, h_odd)]
h = torch.cat([x.unsqueeze(0) for x in h_in_order], dim=0)
return h
class FirstViewThenListenMMM(MultiModalModel):
"""
Implementation of MultiModalModel using the (encoded) second modality as initial
cell state for the RNNEncoder. Thereby, the second_encoder returns a Tensor of size
[batch, second_dim] while the rnn needs a [num_layers * num_directions, batch, hidden_size]
cell state, so a linear layer changing the last dimension from second_dim to hidden_size is used
while the first dimension of size (num_layers * num_directions) is simply expanded.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
super().__init__(encoder, second_encoder, second_dim, decoder, generator)
self.convert_to_enc_init_layer = nn.Linear(second_dim, self.encoder.rnn.hidden_size)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
second_encoded = self.second_encoder(second_src) # [batch x second_dim]
converted: torch.Tensor = self.convert_to_enc_init_layer(second_encoded) # [batch x hidden_size]
converted = converted.unsqueeze(0) # [1 x batch x hidden_size]
first_dim = self.encoder.rnn.num_layers * (2 if self.encoder.rnn.bidirectional else 1)
encoder_init = converted.expand(first_dim, -1, -1) # [first_dim x batch x hidden_size]
encoder_init = encoder_init.contiguous()
if isinstance(self.encoder.rnn, nn.LSTM):
encoder_init = (encoder_init, encoder_init) # Use it as initial hidden and cell state
enc_final, memory_bank = self.encoder(src, lengths, encoder_state=encoder_init)
dec_state = \
self.decoder.init_decoder_state(src, memory_bank, enc_final)
return enc_final, memory_bank, dec_state
class GeneratorMergeMMM(MultiModalModel):
"""
Implementation of MultiModalModel using the (encoded) second modality solely as additional
input to the generator. This means, the output of the second encoder is simply concatenated
to the output of the decoder.
Note: A fitting generator must be used with this model so that dimensions match!
"""
def run_encoder_to_decoder_state(self, src, second_src, lengths):
return NMTModel.run_encoder_to_decoder_state(self, src, lengths)
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
second_encoded: torch.Tensor = self.second_encoder(second_src)
out, state, attn = super().run_decoder(tgt, memory_bank, dec_init,
memory_lengths, second_src)
# decoder output is [len x batch x rnn_size]
# second encoded is [batch x second_dim]
# concat it to [len x batch x (rnn_size + second_dim)]
length = out.size(0)
unsqueezed = second_encoded.unsqueeze(0) # [1 x batch x rnn_size]
second_expanded = unsqueezed.expand(length, -1, -1) # [len x batch x rnn_size]
concat = torch.cat((out, second_expanded), dim=2)
return concat, state, attn
class FirstViewThenListenFinallyViewMMM(FirstViewThenListenMMM, GeneratorMergeMMM):
"""
Combination of FirstViewThenListenMMM and GeneratorMergeMMM.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module, second_dim: int,
decoder: RNNDecoderBase, generator):
FirstViewThenListenMMM.__init__(self, encoder, second_encoder,
second_dim, decoder, generator)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
return FirstViewThenListenMMM.run_encoder_to_decoder_state(
self, src, second_src, lengths)
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
return GeneratorMergeMMM.run_decoder(self, tgt, memory_bank, dec_init,
memory_lengths, second_src) | onmt/modules/MultiModalModel.py | import torch
import torch.nn as nn
from onmt.Models import EncoderBase, RNNDecoderBase, NMTModel
def multimodal_model_class_by_key(key):
d = {
'hsm': HiddenStateMergeLayerMMM,
'fvtl': FirstViewThenListenMMM,
'gm': GeneratorMergeMMM,
'fvtl+gm': FirstViewThenListenFinallyViewMMM
}
return d[key]
class MultiModalModel(nn.Module):
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
"""
Create new MultiModalModel.
:param encoder: text encoder to use
:param second_encoder: second modality encoder to use. Its output should be a tensor of
size [batch x second_dim]
:param second_dim: output dimension of second_encoder
:param decoder: decoder to use
:param generator: generator to use
"""
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.generator = generator
self.second_encoder = second_encoder
self.second_dim = second_dim
def forward(self, src, second_src, tgt, lengths, dec_state=None):
"""
Run a forward pass on the MultiModalModel. This takes the same arguments as NMTModel,
but additionally requires a second_src tensor as expected by this MMM's second_encoder.
:param src: the src text tensor as expected by encoder
:param second_src: the second src tensor as expected by the second_encoder
:param tgt: the tgt text tensor as expected by decoder
:param lengths: src lengths pre-padding as expected by encoder
:param dec_state: initial decoder state as expected by decoder
:return: see NMTModel
"""
tgt = tgt[:-1] # exclude last target from inputs
_, memory_bank, enc_state = self.run_encoder_to_decoder_state(src, second_src, lengths)
decoder_outputs, dec_state, attns = \
self.run_decoder(tgt, memory_bank,
enc_state if dec_state is None
else dec_state,
lengths, second_src)
return decoder_outputs, attns, dec_state
def run_encoder_to_decoder_state(self, src, second_src, lengths):
"""
Forward the given src and second_src up to the initial decoder state.
:param src: the src tensor
:param second_src: the second_src tensor
:param lengths: the src lengths
:return: (enc_final, memory_bank, dec_state) triple, containing the final encoder state,
the final encoder memory bank and the initial state to use for the decoder.
"""
raise NotImplementedError
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
return self.decoder(tgt, memory_bank, dec_init,
memory_lengths=memory_lengths)
class HiddenStateMergeLayerMMM(MultiModalModel):
"""
Implementation of MultiModalModel merging the primary and secondary sources at their
hidden representations between the encoder and decoder.
Therefore, this model uses linear layer which gets the final encoder state and the
second_encoder output and generates the initial decoder state to use.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
super().__init__(encoder, second_encoder, second_dim, decoder, generator)
directions = 2 if self.decoder.bidirectional_encoder else 1
enc_output_size = self.encoder.rnn.hidden_size * directions
self.enc_pad_layer = nn.ConstantPad1d((0, self.second_dim), 0)
self.second_pad_layer = nn.ConstantPad1d((enc_output_size, 0), 0)
self.merge_layer = nn.Linear(enc_output_size + self.second_dim,
self.decoder.hidden_size, bias=True)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
enc_final, memory_bank = self.encoder(src, lengths)
enc_final = tuple([self._fix_enc_hidden(h) for h in enc_final])
# enc_final is now layers x batch x enc_final_dim.
# Throw in the second modality for each batch sample
# => layers x batch x (dim + secondDim)
# apply merge layer to reduce to dim expected by decoder
second_modality = self.second_encoder(second_src)
decoder_input = [None, None]
for i, enc in enumerate(enc_final):
padded_final = self.enc_pad_layer(enc)
padded_second = self.second_pad_layer(second_modality)
concatenated = padded_final + padded_second.expand_as(padded_final)
decoder_input[i] = self.merge_layer(concatenated)
decoder_input = tuple([self._refix_dec_init(h) for h in decoder_input])
dec_state = \
self.decoder.init_decoder_state(src, memory_bank, decoder_input)
return enc_final, memory_bank, dec_state
def _fix_enc_hidden(self, h):
# The encoder hidden is (layers*directions) x batch x dim.
# We need to convert it to layers x batch x (directions*dim).
if self.decoder.bidirectional_encoder:
h = torch.cat([h[0:h.size(0):2], h[1:h.size(0):2]], 2)
return h
def _refix_dec_init(self, h):
# The decoder expects its init_decoder_state input to be (layers*directions) x batch x dim
# We already fixed it above (to layers x batch x directions*dim), so need to revert it now
if self.decoder.bidirectional_encoder:
dim = h.size(2) // 2
h_even, h_odd = torch.split(h, dim, 2)
h_in_order = [x[i] for i in range(h_even.size(0)) for x in (h_even, h_odd)]
h = torch.cat([x.unsqueeze(0) for x in h_in_order], dim=0)
return h
class FirstViewThenListenMMM(MultiModalModel):
"""
Implementation of MultiModalModel using the (encoded) second modality as initial
cell state for the RNNEncoder. Thereby, the second_encoder returns a Tensor of size
[batch, second_dim] while the rnn needs a [num_layers * num_directions, batch, hidden_size]
cell state, so a linear layer changing the last dimension from second_dim to hidden_size is used
while the first dimension of size (num_layers * num_directions) is simply expanded.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module,
second_dim: int, decoder: RNNDecoderBase, generator):
super().__init__(encoder, second_encoder, second_dim, decoder, generator)
self.convert_to_enc_init_layer = nn.Linear(second_dim, self.encoder.rnn.hidden_size)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
second_encoded = self.second_encoder(second_src) # [batch x second_dim]
converted: torch.Tensor = self.convert_to_enc_init_layer(second_encoded) # [batch x hidden_size]
converted = converted.unsqueeze(0) # [1 x batch x hidden_size]
first_dim = self.encoder.rnn.num_layers * (2 if self.encoder.rnn.bidirectional else 1)
encoder_init = converted.expand(first_dim, -1, -1) # [first_dim x batch x hidden_size]
encoder_init = encoder_init.contiguous()
if isinstance(self.encoder.rnn, nn.LSTM):
encoder_init = (encoder_init, encoder_init) # Use it as initial hidden and cell state
enc_final, memory_bank = self.encoder(src, lengths, encoder_state=encoder_init)
dec_state = \
self.decoder.init_decoder_state(src, memory_bank, enc_final)
return enc_final, memory_bank, dec_state
class GeneratorMergeMMM(MultiModalModel):
"""
Implementation of MultiModalModel using the (encoded) second modality solely as additional
input to the generator. This means, the output of the second encoder is simply concatenated
to the output of the decoder.
Note: A fitting generator must be used with this model so that dimensions match!
"""
def run_encoder_to_decoder_state(self, src, second_src, lengths):
return NMTModel.run_encoder_to_decoder_state(self, src, lengths)
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
second_encoded: torch.Tensor = self.second_encoder(second_src)
out, state, attn = super().run_decoder(tgt, memory_bank, dec_init,
memory_lengths, second_src)
# decoder output is [len x batch x rnn_size]
# second encoded is [batch x second_dim]
# concat it to [len x batch x (rnn_size + second_dim)]
length = out.size(0)
unsqueezed = second_encoded.unsqueeze(0) # [1 x batch x rnn_size]
second_expanded = unsqueezed.expand(length, -1, -1) # [len x batch x rnn_size]
concat = torch.cat((out, second_expanded), dim=2)
return concat, state, attn
class FirstViewThenListenFinallyViewMMM(FirstViewThenListenMMM, GeneratorMergeMMM):
"""
Combination of FirstViewThenListenMMM and GeneratorMergeMMM.
"""
def __init__(self, encoder: EncoderBase, second_encoder: nn.Module, second_dim: int,
decoder: RNNDecoderBase, generator):
FirstViewThenListenMMM.__init__(self, encoder, second_encoder,
second_dim, decoder, generator)
def run_encoder_to_decoder_state(self, src, second_src, lengths):
return FirstViewThenListenMMM.run_encoder_to_decoder_state(
self, src, second_src, lengths)
def run_decoder(self, tgt, memory_bank, dec_init, memory_lengths, second_src):
return GeneratorMergeMMM.run_decoder(self, tgt, memory_bank, dec_init,
memory_lengths, second_src) | 0.961858 | 0.633977 |
import pytest
from MusicXMLSynthesizer.utils import parse_notes_meta_to_list
from MusicXMLSynthesizer.Synthesizer import Synthesizer
from utility.testHelper import create_synthesizer
import numpy as np
from lxml import etree as ET
#
# Naming convention: test_[CLASS_NAME]_[FUNCTION_NAME]_[CONDITION]
#
def test_Synthesizer_calculate_beat_duration():
MOCKED_DURATION = 0.25
# setup
synthesizer = create_synthesizer('input_mock/bend/')
downbeats_list = parse_notes_meta_to_list(
"input_mock/bend/downbeats.txt")
beat_duration = synthesizer.calculate_beat_duration(
"mode", synthesizer.extract_to_nparray(downbeats_list, [0])
)
assert beat_duration == MOCKED_DURATION
def test_Synthesizer_get_first_downbeats():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
# setup
synthesizer = create_synthesizer('input_mock/bend/')
downbeats_list = parse_notes_meta_to_list(
"input_mock/bend/downbeats.txt")
result = synthesizer.get_first_downbeat_edges(downbeats_list)
assert result == MOCKED_FIRST_DOWNBEAT_LIST
def test_Synthesizer_get_tech_and_notes_nparray():
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
synthesizer = create_synthesizer('input_mock/bend/')
techs_and_notes_list = parse_notes_meta_to_list(
"input_mock/bend/FinalNotes.txt")
result = synthesizer.get_tech_and_notes_nparray(techs_and_notes_list)
assert np.alltrue(result == MOCKED_SOLOLA_OUTPUT)
# TODO: need more test input
def test_Synthesizer_annotate_start_end_edge_and_group_by_bar():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
MOCKED_DURATION = 0.25
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.annotate_start_end_edge_and_group_by_bar(
MOCKED_SOLOLA_OUTPUT, MOCKED_FIRST_DOWNBEAT_LIST, MOCKED_DURATION)
assert result == [[[0.0, 'BS'], [0.0, 'NS'], [0.25, 'NE'], [0.25, 'NS'], [0.5, 'NE'], [0.5, 'NS'], [0.75, 'NE'], [0.75, 'NS'], [1.0, 'NE'], [1.0, 'BE']],
[[1.0, 'BS'], [1.0, 'NS'], [1.25, 'NE'], [1.25, 'NS'], [1.5, 'NE'], [
1.5, 'NS'], [1.75, 'NE'], [1.75, 'NS'], [2.0, 'NE'], [2.0, 'BE']],
[[2.0, 'BS'], [2.0, 'NS'], [2.25, 'NE'], [2.25, 'NS'], [2.5, 'NE'], [3.0, 'BE']]]
def test_Synthesizer_annotate_rest_and_technique():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
MOCKED_DURATION = 0.25
EDGE_ANNOTATED = [[[0.0, 'BS'], [0.0, 'NS'], [0.25, 'NE'], [0.25, 'NS'], [0.5, 'NE'], [0.5, 'NS'], [0.75, 'NE'], [0.75, 'NS'], [1.0, 'NE'], [1.0, 'BE']],
[[1.0, 'BS'], [1.0, 'NS'], [1.25, 'NE'], [1.25, 'NS'], [1.5, 'NE'], [
1.5, 'NS'], [1.75, 'NE'], [1.75, 'NS'], [2.0, 'NE'], [2.0, 'BE']],
[[2.0, 'BS'], [2.0, 'NS'], [2.25, 'NE'], [2.25, 'NS'], [2.5, 'NE'], [3.0, 'BE']]]
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.annotate_rest_and_technique(
EDGE_ANNOTATED, MOCKED_SOLOLA_OUTPUT, MOCKED_FIRST_DOWNBEAT_LIST, MOCKED_DURATION)
assert result == [[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]],
[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]],
[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0,[2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [8.0, 'r']]]
# @pytest.mark.skip(reason="under debugging with unit test")
def test_Synthesize_solola_to_xml():
ANNOTATED_DATA = [[[4.0, 'n', 58.0, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0,[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [8.0, 'r']]]
EXPECTED_RESULT = '''<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 3.1 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">
<score-partwise version="3.1">
<work>
<work-title>solo</work-title>
</work>
<part-list>
<score-part id="P1">
<part-name>Music</part-name>
</score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>16</divisions>
<key>
<fifths>0</fifths>
</key>
<time>
<beats>4</beats>
<beat-type>4</beat-type>
</time>
<clef>
<sign>G</sign>
<line>2</line>
</clef>
</attributes>
<note>
<pitch>
<step>A</step>
<alter>1</alter>
<octave>3</octave>
</pitch>
<voice>1</voice>
<duration>4.0</duration>
<type>quarter</type>
</note>
<note>
<pitch>
<step>A</step>
<alter>1</alter>
<octave>3</octave>
</pitch>
<voice>1</voice>
<duration>4.0</duration>
<type>quarter</type>
</note>
<note>
<rest/>
<voice>1</voice>
<duration>8.0</duration>
<type>half</type>
</note>
</measure>
</part>
</score-partwise>
'''
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.solola_to_xml(ANNOTATED_DATA)
assert result == EXPECTED_RESULT
def test_Synthesize_createDurationType_standard_type():
NOTE_El = ET.Element('note')
DURATION = '4.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>quarter</type></note>'
def test_Synthesize_createDurationType_dot_type():
NOTE_El = ET.Element('note')
DURATION = '3.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>eighth</type><dot/></note>'
def test_Synthesize_createDurationType_abnormal_type():
NOTE_El = ET.Element('note')
DURATION = '15.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>non-standard</type></note>'
def test_Synthesize_add_technique_prebend():
NOTE_El = ET.Element('note')
TECHNIQUE = [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter><pre-bend/></bend></technical></notations></note>'
def test_Synthesize_add_technique_bend():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter></bend></technical></notations></note>'
def test_Synthesize_add_technique_release():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter><release/></bend></technical></notations></note>'
def test_Synthesize_add_technique_pull_off_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><pull-off type="start">P</pull-off></technical></notations></note>'
def test_Synthesize_add_technique_pull_off_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><pull-off type="stop">P</pull-off></technical></notations></note>'
def test_Synthesize_add_technique_hammer_on_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><hammer-on type="start">H</hammer-on></technical></notations></note>'
def test_Synthesize_add_technique_hammer_on_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><hammer-on type="stop">H</hammer-on></technical></notations></note>'
def test_Synthesize_add_technique_vibrato():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><vibrato extent-level="1"/></other-technical></technical></notations></note>'
def test_Synthesize_add_technique_slide_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><slide type="start" line-type="solid"/></technical></notations></note>'
def test_Synthesize_add_technique_slide_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><slide type="stop" line-type="solid"/></technical></notations></note>'
def test_Synthesize_add_technique_slidein():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><slide-in from="below"/></other-technical></technical></notations></note>'
def test_Synthesize_add_technique_slideout():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><slide-out direction="downward"/></other-technical></technical></notations></note>' | tests/test_unit_Synthesizer.py | import pytest
from MusicXMLSynthesizer.utils import parse_notes_meta_to_list
from MusicXMLSynthesizer.Synthesizer import Synthesizer
from utility.testHelper import create_synthesizer
import numpy as np
from lxml import etree as ET
#
# Naming convention: test_[CLASS_NAME]_[FUNCTION_NAME]_[CONDITION]
#
def test_Synthesizer_calculate_beat_duration():
MOCKED_DURATION = 0.25
# setup
synthesizer = create_synthesizer('input_mock/bend/')
downbeats_list = parse_notes_meta_to_list(
"input_mock/bend/downbeats.txt")
beat_duration = synthesizer.calculate_beat_duration(
"mode", synthesizer.extract_to_nparray(downbeats_list, [0])
)
assert beat_duration == MOCKED_DURATION
def test_Synthesizer_get_first_downbeats():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
# setup
synthesizer = create_synthesizer('input_mock/bend/')
downbeats_list = parse_notes_meta_to_list(
"input_mock/bend/downbeats.txt")
result = synthesizer.get_first_downbeat_edges(downbeats_list)
assert result == MOCKED_FIRST_DOWNBEAT_LIST
def test_Synthesizer_get_tech_and_notes_nparray():
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
synthesizer = create_synthesizer('input_mock/bend/')
techs_and_notes_list = parse_notes_meta_to_list(
"input_mock/bend/FinalNotes.txt")
result = synthesizer.get_tech_and_notes_nparray(techs_and_notes_list)
assert np.alltrue(result == MOCKED_SOLOLA_OUTPUT)
# TODO: need more test input
def test_Synthesizer_annotate_start_end_edge_and_group_by_bar():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
MOCKED_DURATION = 0.25
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.annotate_start_end_edge_and_group_by_bar(
MOCKED_SOLOLA_OUTPUT, MOCKED_FIRST_DOWNBEAT_LIST, MOCKED_DURATION)
assert result == [[[0.0, 'BS'], [0.0, 'NS'], [0.25, 'NE'], [0.25, 'NS'], [0.5, 'NE'], [0.5, 'NS'], [0.75, 'NE'], [0.75, 'NS'], [1.0, 'NE'], [1.0, 'BE']],
[[1.0, 'BS'], [1.0, 'NS'], [1.25, 'NE'], [1.25, 'NS'], [1.5, 'NE'], [
1.5, 'NS'], [1.75, 'NE'], [1.75, 'NS'], [2.0, 'NE'], [2.0, 'BE']],
[[2.0, 'BS'], [2.0, 'NS'], [2.25, 'NE'], [2.25, 'NS'], [2.5, 'NE'], [3.0, 'BE']]]
def test_Synthesizer_annotate_rest_and_technique():
MOCKED_FIRST_DOWNBEAT_LIST = [0.0, 1.0, 2.0, 3.0]
MOCKED_SOLOLA_OUTPUT = np.array([
[58, 0., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 0.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.5, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 1.75, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2., 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ],
[58, 2.25, 0.25, 2, 0, 0, 0, 0, 0, 0, 0, 0, ], ])
MOCKED_DURATION = 0.25
EDGE_ANNOTATED = [[[0.0, 'BS'], [0.0, 'NS'], [0.25, 'NE'], [0.25, 'NS'], [0.5, 'NE'], [0.5, 'NS'], [0.75, 'NE'], [0.75, 'NS'], [1.0, 'NE'], [1.0, 'BE']],
[[1.0, 'BS'], [1.0, 'NS'], [1.25, 'NE'], [1.25, 'NS'], [1.5, 'NE'], [
1.5, 'NS'], [1.75, 'NE'], [1.75, 'NS'], [2.0, 'NE'], [2.0, 'BE']],
[[2.0, 'BS'], [2.0, 'NS'], [2.25, 'NE'], [2.25, 'NS'], [2.5, 'NE'], [3.0, 'BE']]]
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.annotate_rest_and_technique(
EDGE_ANNOTATED, MOCKED_SOLOLA_OUTPUT, MOCKED_FIRST_DOWNBEAT_LIST, MOCKED_DURATION)
assert result == [[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]],
[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]],
[[4.0, 'n', 58.0, [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0,[2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [8.0, 'r']]]
# @pytest.mark.skip(reason="under debugging with unit test")
def test_Synthesize_solola_to_xml():
ANNOTATED_DATA = [[[4.0, 'n', 58.0, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [4.0, 'n', 58.0,[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], [8.0, 'r']]]
EXPECTED_RESULT = '''<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 3.1 Partwise//EN" "http://www.musicxml.org/dtds/partwise.dtd">
<score-partwise version="3.1">
<work>
<work-title>solo</work-title>
</work>
<part-list>
<score-part id="P1">
<part-name>Music</part-name>
</score-part>
</part-list>
<part id="P1">
<measure number="1">
<attributes>
<divisions>16</divisions>
<key>
<fifths>0</fifths>
</key>
<time>
<beats>4</beats>
<beat-type>4</beat-type>
</time>
<clef>
<sign>G</sign>
<line>2</line>
</clef>
</attributes>
<note>
<pitch>
<step>A</step>
<alter>1</alter>
<octave>3</octave>
</pitch>
<voice>1</voice>
<duration>4.0</duration>
<type>quarter</type>
</note>
<note>
<pitch>
<step>A</step>
<alter>1</alter>
<octave>3</octave>
</pitch>
<voice>1</voice>
<duration>4.0</duration>
<type>quarter</type>
</note>
<note>
<rest/>
<voice>1</voice>
<duration>8.0</duration>
<type>half</type>
</note>
</measure>
</part>
</score-partwise>
'''
synthesizer = create_synthesizer('input_mock/bend/')
result = synthesizer.solola_to_xml(ANNOTATED_DATA)
assert result == EXPECTED_RESULT
def test_Synthesize_createDurationType_standard_type():
NOTE_El = ET.Element('note')
DURATION = '4.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>quarter</type></note>'
def test_Synthesize_createDurationType_dot_type():
NOTE_El = ET.Element('note')
DURATION = '3.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>eighth</type><dot/></note>'
def test_Synthesize_createDurationType_abnormal_type():
NOTE_El = ET.Element('note')
DURATION = '15.0'
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_duration_type(NOTE_El, DURATION)
assert ET.tostring(NOTE_El, encoding="unicode") == '<note><type>non-standard</type></note>'
def test_Synthesize_add_technique_prebend():
NOTE_El = ET.Element('note')
TECHNIQUE = [2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter><pre-bend/></bend></technical></notations></note>'
def test_Synthesize_add_technique_bend():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter></bend></technical></notations></note>'
def test_Synthesize_add_technique_release():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><bend><bend-alter>2</bend-alter><release/></bend></technical></notations></note>'
def test_Synthesize_add_technique_pull_off_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><pull-off type="start">P</pull-off></technical></notations></note>'
def test_Synthesize_add_technique_pull_off_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><pull-off type="stop">P</pull-off></technical></notations></note>'
def test_Synthesize_add_technique_hammer_on_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><hammer-on type="start">H</hammer-on></technical></notations></note>'
def test_Synthesize_add_technique_hammer_on_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><hammer-on type="stop">H</hammer-on></technical></notations></note>'
def test_Synthesize_add_technique_vibrato():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><vibrato extent-level="1"/></other-technical></technical></notations></note>'
def test_Synthesize_add_technique_slide_start():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><slide type="start" line-type="solid"/></technical></notations></note>'
def test_Synthesize_add_technique_slide_stop():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><slide type="stop" line-type="solid"/></technical></notations></note>'
def test_Synthesize_add_technique_slidein():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><slide-in from="below"/></other-technical></technical></notations></note>'
def test_Synthesize_add_technique_slideout():
NOTE_El = ET.Element('note')
TECHNIQUE = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]
synthesizer = create_synthesizer('input_mock/bend/')
synthesizer.add_technique(NOTE_El, TECHNIQUE)
assert ET.tostring(NOTE_El,encoding="unicode") == '<note><notations><technical><other-technical><slide-out direction="downward"/></other-technical></technical></notations></note>' | 0.272702 | 0.399548 |
import os
import requests
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import Version, InvalidVersion
DL_ZIPBALL = "https://github.com/{0}/{1}/archive/{2}.zip"
API_RELEASES = "https://api.github.com/repos/{0}/{1}/releases"
COMMIT_RELEASES = "https://api.github.com/repos/{0}/{1}/commits"
HEADERS = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "LambentLight Metadata Generator (+https://github.com/LambentLight/Metadata)"
}
if "GITHUB_TOKEN" in os.environ:
HEADERS["Authorization"] = "token " + os.environ["GITHUB_TOKEN"]
def get_commits(**kwargs):
"""
Gets the specified number of commits from a GitHub repository.
"""
# Get the parts that we need
owner = kwargs.get("owner")
repo = kwargs.get("repo")
count = kwargs.get("commits")
patch = kwargs.get("patches")["*"]
# Create a place for storing the releases
releases = []
# Make the GET request
get = requests.get(COMMIT_RELEASES.format(owner, repo), headers=HEADERS)
# If the request is not 200, return the empty list
if get.status_code != 200:
return releases
# If is 200, iterate over the commits
for commit in get.json():
# Create the object with the information
data = {
"version": commit["sha"],
"download": DL_ZIPBALL.format(owner, repo, commit["sha"]),
"path": patch["path"].format(commit["sha"])
}
# And add the new version into the list
releases.append(data)
# Finally, return the list with the releases
return releases
def get_releases(**kwargs):
"""
Gets a list of releases from a GitHub Repository.
"""
# Get the parts that we need
owner = kwargs.get("owner")
repo = kwargs.get("repo")
patches = kwargs.get("patches", {})
skip = kwargs.get("skip", [])
# Create a place for storing the releases
releases = []
# Make the GET request
get = requests.get(API_RELEASES.format(owner, repo), headers=HEADERS)
# If the request is not 200, return the empty list
if get.status_code != 200:
return releases
# If is 200, iterate over the releases
for release in get.json():
# If this tag is on the excluded list, skip this iteration
if release["tag_name"] in skip:
continue
# Create a temporary set of patches
patch = {}
# Try to parse the version on the tag without the trailing V
try:
version = Version(release["tag_name"].strip("v"))
except InvalidVersion:
version = None
# Select the correct set of manual patches
for key, item in patches.items():
# Try to parse the specifier
try:
specifier = SpecifierSet(key)
except InvalidSpecifier:
specifier = None
# If the specifier and version are valids and the later is compatible with the specifier
if specifier and version and version in specifier:
patch = item
break
# If there is no patches set, let's use the generic set of patches if is available
if not patch and "*" in patches:
patch = patches["*"]
# If assets is empty or this resource requires the zip, set it as the file
if not release["assets"] or ("zip_only" in patch and patch["zip_only"]):
download = DL_ZIPBALL.format(owner, repo, release["tag_name"])
# If there is a released file, save the first one it
else:
download = release["assets"][0]["browser_download_url"]
# Create the object with the version information
data = {
"version": release["tag_name"].strip("v"),
"download": download
}
# If there is a path to format, use it
if "path" in patch:
data["path"] = patch["path"].format(data["version"])
# And add the release onto the list
releases.append(data)
# Finally, return the new list of releases
return releases | lambentlight/github.py | import os
import requests
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import Version, InvalidVersion
DL_ZIPBALL = "https://github.com/{0}/{1}/archive/{2}.zip"
API_RELEASES = "https://api.github.com/repos/{0}/{1}/releases"
COMMIT_RELEASES = "https://api.github.com/repos/{0}/{1}/commits"
HEADERS = {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "LambentLight Metadata Generator (+https://github.com/LambentLight/Metadata)"
}
if "GITHUB_TOKEN" in os.environ:
HEADERS["Authorization"] = "token " + os.environ["GITHUB_TOKEN"]
def get_commits(**kwargs):
"""
Gets the specified number of commits from a GitHub repository.
"""
# Get the parts that we need
owner = kwargs.get("owner")
repo = kwargs.get("repo")
count = kwargs.get("commits")
patch = kwargs.get("patches")["*"]
# Create a place for storing the releases
releases = []
# Make the GET request
get = requests.get(COMMIT_RELEASES.format(owner, repo), headers=HEADERS)
# If the request is not 200, return the empty list
if get.status_code != 200:
return releases
# If is 200, iterate over the commits
for commit in get.json():
# Create the object with the information
data = {
"version": commit["sha"],
"download": DL_ZIPBALL.format(owner, repo, commit["sha"]),
"path": patch["path"].format(commit["sha"])
}
# And add the new version into the list
releases.append(data)
# Finally, return the list with the releases
return releases
def get_releases(**kwargs):
"""
Gets a list of releases from a GitHub Repository.
"""
# Get the parts that we need
owner = kwargs.get("owner")
repo = kwargs.get("repo")
patches = kwargs.get("patches", {})
skip = kwargs.get("skip", [])
# Create a place for storing the releases
releases = []
# Make the GET request
get = requests.get(API_RELEASES.format(owner, repo), headers=HEADERS)
# If the request is not 200, return the empty list
if get.status_code != 200:
return releases
# If is 200, iterate over the releases
for release in get.json():
# If this tag is on the excluded list, skip this iteration
if release["tag_name"] in skip:
continue
# Create a temporary set of patches
patch = {}
# Try to parse the version on the tag without the trailing V
try:
version = Version(release["tag_name"].strip("v"))
except InvalidVersion:
version = None
# Select the correct set of manual patches
for key, item in patches.items():
# Try to parse the specifier
try:
specifier = SpecifierSet(key)
except InvalidSpecifier:
specifier = None
# If the specifier and version are valids and the later is compatible with the specifier
if specifier and version and version in specifier:
patch = item
break
# If there is no patches set, let's use the generic set of patches if is available
if not patch and "*" in patches:
patch = patches["*"]
# If assets is empty or this resource requires the zip, set it as the file
if not release["assets"] or ("zip_only" in patch and patch["zip_only"]):
download = DL_ZIPBALL.format(owner, repo, release["tag_name"])
# If there is a released file, save the first one it
else:
download = release["assets"][0]["browser_download_url"]
# Create the object with the version information
data = {
"version": release["tag_name"].strip("v"),
"download": download
}
# If there is a path to format, use it
if "path" in patch:
data["path"] = patch["path"].format(data["version"])
# And add the release onto the list
releases.append(data)
# Finally, return the new list of releases
return releases | 0.432183 | 0.214671 |
from accounts.models import Role, User, UserRole
class TestData(object):
public_users = []
core_members = []
collaborators = []
public_users_usernames = [
'public_user_1',
'public_user_2',
'public_user_3',
]
core_members_usernames = [
'core_member_1',
'core_member_2',
'core_member_3',
]
collaborators_usernames = [
'collaborator_1',
'collaborator_2',
'collaborator_3',
]
def create_public_users(self):
if self.public_users:
return
role = Role.objects.get(name=Role.PUBLIC)
for username in self.public_users_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} Last Name'.format(username),
email='{}<EMAIL>'.format(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.public_users.append(user)
def create_collaborators(self):
if self.collaborators:
return
role = Role.objects.get(name=Role.COLLABORATOR)
for username in self.collaborators_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} Last Name'.format(username),
email='{}<EMAIL>'.format(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.collaborators.append(user)
def create_core_members(self):
if self.core_members:
return
role = Role.objects.get(name=Role.CORE_MEMBER)
for username in self.core_members_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} <NAME>'.format(username),
email='{}<EMAIL>'.<EMAIL>(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.core_members.append(user) | dwfcommon/tests/utils.py | from accounts.models import Role, User, UserRole
class TestData(object):
public_users = []
core_members = []
collaborators = []
public_users_usernames = [
'public_user_1',
'public_user_2',
'public_user_3',
]
core_members_usernames = [
'core_member_1',
'core_member_2',
'core_member_3',
]
collaborators_usernames = [
'collaborator_1',
'collaborator_2',
'collaborator_3',
]
def create_public_users(self):
if self.public_users:
return
role = Role.objects.get(name=Role.PUBLIC)
for username in self.public_users_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} Last Name'.format(username),
email='{}<EMAIL>'.format(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.public_users.append(user)
def create_collaborators(self):
if self.collaborators:
return
role = Role.objects.get(name=Role.COLLABORATOR)
for username in self.collaborators_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} Last Name'.format(username),
email='{}<EMAIL>'.format(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.collaborators.append(user)
def create_core_members(self):
if self.core_members:
return
role = Role.objects.get(name=Role.CORE_MEMBER)
for username in self.core_members_usernames:
user = User.objects.create(
username=username,
first_name='{} First Name'.format(username),
last_name='{} <NAME>'.format(username),
email='{}<EMAIL>'.<EMAIL>(username),
)
UserRole.objects.update_or_create(
user=user,
defaults={
'role': role,
}
)
self.core_members.append(user) | 0.516595 | 0.169819 |
from aiogram import types
from state_manager import Depends
from state_manager.models.dependencys.aiogram import AiogramStateManager
from state_manager.routes.aiogram import AiogramRouter
from app.db.enum import City, Representation
from app.db.repositories.settings import SettingsRepository
from app.db.repositories.user import UserRepository
from app.depends import get_locale
from app.keybords.keybords import start_keyboard, representation_keyboard, menu_keyboard
from app.keybords.raw_text import city_raw_text, representation_raw_text
from app.utils.utils import find_value_in_enum
start_state = AiogramRouter()
@start_state.message_handler()
async def start(
msg: types.Message,
state_manager: AiogramStateManager,
user_rep: UserRepository,
settings_rep: SettingsRepository,
locale=Depends(get_locale),
):
user_obj = msg.from_user
if not await user_rep.exist(user_obj.id):
settings_id = await settings_rep.create(
number_of_posts=15, city=City.brest.value, representation=Representation.text.value
)
await user_rep.create(telegram_id=user_obj.id, username=(user_obj.username or "NONE"), settings_id=settings_id)
await state_manager.set_next_state("city_choice")
await msg.reply(locale.start_msg, reply_markup=start_keyboard(locale))
@start_state.message_handler()
async def city_choice(msg: types.Message, state_manager: AiogramStateManager, locale=Depends(get_locale)):
lower_text = msg.text.lower()
if lower_text in [text.lower() for text in city_raw_text(locale)]:
city = find_value_in_enum(msg.text, City, locale)
await state_manager.set_next_state("representation_choice", data={"city": city})
await msg.reply(locale.representation_msg, reply_markup=representation_keyboard(locale))
else:
await msg.reply(locale.failed_start_msg, reply_markup=start_keyboard(locale))
@start_state.message_handler()
async def representation_choice(
msg: types.Message, state_manager: AiogramStateManager, user_rep: UserRepository, locale=Depends(get_locale)
):
if msg.text.lower() in [text.lower() for text in representation_raw_text(locale)]:
city = (await state_manager.data)["city"]
representation = find_value_in_enum(msg.text, Representation, locale)
await user_rep.update_settings_by_telegram_id(telegram_id=msg.from_user.id, city=city, representation=representation)
await state_manager.set_next_state("main_menu")
await msg.answer(locale.main_menu, reply_markup=menu_keyboard(locale))
else:
await msg.reply(
locale.failed_representation_msg, reply_markup=representation_keyboard(locale),
) | app/handlers/start.py | from aiogram import types
from state_manager import Depends
from state_manager.models.dependencys.aiogram import AiogramStateManager
from state_manager.routes.aiogram import AiogramRouter
from app.db.enum import City, Representation
from app.db.repositories.settings import SettingsRepository
from app.db.repositories.user import UserRepository
from app.depends import get_locale
from app.keybords.keybords import start_keyboard, representation_keyboard, menu_keyboard
from app.keybords.raw_text import city_raw_text, representation_raw_text
from app.utils.utils import find_value_in_enum
start_state = AiogramRouter()
@start_state.message_handler()
async def start(
msg: types.Message,
state_manager: AiogramStateManager,
user_rep: UserRepository,
settings_rep: SettingsRepository,
locale=Depends(get_locale),
):
user_obj = msg.from_user
if not await user_rep.exist(user_obj.id):
settings_id = await settings_rep.create(
number_of_posts=15, city=City.brest.value, representation=Representation.text.value
)
await user_rep.create(telegram_id=user_obj.id, username=(user_obj.username or "NONE"), settings_id=settings_id)
await state_manager.set_next_state("city_choice")
await msg.reply(locale.start_msg, reply_markup=start_keyboard(locale))
@start_state.message_handler()
async def city_choice(msg: types.Message, state_manager: AiogramStateManager, locale=Depends(get_locale)):
lower_text = msg.text.lower()
if lower_text in [text.lower() for text in city_raw_text(locale)]:
city = find_value_in_enum(msg.text, City, locale)
await state_manager.set_next_state("representation_choice", data={"city": city})
await msg.reply(locale.representation_msg, reply_markup=representation_keyboard(locale))
else:
await msg.reply(locale.failed_start_msg, reply_markup=start_keyboard(locale))
@start_state.message_handler()
async def representation_choice(
msg: types.Message, state_manager: AiogramStateManager, user_rep: UserRepository, locale=Depends(get_locale)
):
if msg.text.lower() in [text.lower() for text in representation_raw_text(locale)]:
city = (await state_manager.data)["city"]
representation = find_value_in_enum(msg.text, Representation, locale)
await user_rep.update_settings_by_telegram_id(telegram_id=msg.from_user.id, city=city, representation=representation)
await state_manager.set_next_state("main_menu")
await msg.answer(locale.main_menu, reply_markup=menu_keyboard(locale))
else:
await msg.reply(
locale.failed_representation_msg, reply_markup=representation_keyboard(locale),
) | 0.439026 | 0.165897 |
import time
class TransactionListener:
def __init__(self, client, blockchain_mode=None,
start_block=None, end_block=None,
only_ops=True):
self.client = client
self.blockchain_mode = blockchain_mode or "irreversible"
self.start_block = start_block
self.end_block = end_block
self.only_ops = only_ops
def get_last_block_height(self):
props = self.client.get_dynamic_global_properties()
if self.blockchain_mode == "irreversible":
return props['last_irreversible_block_num']
elif self.blockchain_mode == "head":
return props['head_block_number']
else:
raise ValueError(
"Invalid blockchain mode. It can be irreversible or head.")
def get_ops(self, block_num):
self.client.logger.info("Getting ops on %s", block_num)
return block_num, self.client.get_ops_in_block(block_num, False)
def get_block(self, block_num):
self.client.logger.info("Getting block: %s", block_num)
block_data = self.client.get_block(block_num)
return block_data
def listen(self, ops=True):
current_block = self.start_block
if not current_block:
current_block = self.get_last_block_height()
while True:
while (self.get_last_block_height() - current_block) > 0:
if self.end_block and current_block > self.end_block:
return
if ops:
block_num, ops = self.get_ops(current_block)
for op in ops:
yield op
else:
yield self.get_block(current_block)
current_block += 1
time.sleep(3)
def listen_blocks(self):
return self.listen(ops=False)
class EventListener:
def __init__(self, client, blockchain_mode=None,
start_block=None, end_block=None):
self.client = client
self.transaction_listener = TransactionListener(
self.client,
blockchain_mode=blockchain_mode,
start_block=start_block,
end_block=end_block,
)
def on(self, op_type, filter_by=None, condition=None):
# magically turn the op_type to a list if it's a single string.
op_types = op_type if isinstance(op_type, list) else [op_type, ]
for op_data in self.transaction_listener.listen():
if 'op' not in op_data:
continue
operation_type, operation_value = op_data["op"][0:2]
if operation_type not in op_types:
continue
# filter_by is a generic dict that can be changed on every op.
if filter_by and not filter_by.items() <= operation_value.items():
continue
# condition result should be True, otherwise continue
# and search for other operations.
if condition and not condition(operation_value):
continue
yield op_data
def stream_operations(self):
for op_data in self.transaction_listener.listen():
yield op_data
def stream_blocks(self):
for block in self.transaction_listener.listen_blocks():
yield block | lightsteem/helpers/event_listener.py | import time
class TransactionListener:
def __init__(self, client, blockchain_mode=None,
start_block=None, end_block=None,
only_ops=True):
self.client = client
self.blockchain_mode = blockchain_mode or "irreversible"
self.start_block = start_block
self.end_block = end_block
self.only_ops = only_ops
def get_last_block_height(self):
props = self.client.get_dynamic_global_properties()
if self.blockchain_mode == "irreversible":
return props['last_irreversible_block_num']
elif self.blockchain_mode == "head":
return props['head_block_number']
else:
raise ValueError(
"Invalid blockchain mode. It can be irreversible or head.")
def get_ops(self, block_num):
self.client.logger.info("Getting ops on %s", block_num)
return block_num, self.client.get_ops_in_block(block_num, False)
def get_block(self, block_num):
self.client.logger.info("Getting block: %s", block_num)
block_data = self.client.get_block(block_num)
return block_data
def listen(self, ops=True):
current_block = self.start_block
if not current_block:
current_block = self.get_last_block_height()
while True:
while (self.get_last_block_height() - current_block) > 0:
if self.end_block and current_block > self.end_block:
return
if ops:
block_num, ops = self.get_ops(current_block)
for op in ops:
yield op
else:
yield self.get_block(current_block)
current_block += 1
time.sleep(3)
def listen_blocks(self):
return self.listen(ops=False)
class EventListener:
def __init__(self, client, blockchain_mode=None,
start_block=None, end_block=None):
self.client = client
self.transaction_listener = TransactionListener(
self.client,
blockchain_mode=blockchain_mode,
start_block=start_block,
end_block=end_block,
)
def on(self, op_type, filter_by=None, condition=None):
# magically turn the op_type to a list if it's a single string.
op_types = op_type if isinstance(op_type, list) else [op_type, ]
for op_data in self.transaction_listener.listen():
if 'op' not in op_data:
continue
operation_type, operation_value = op_data["op"][0:2]
if operation_type not in op_types:
continue
# filter_by is a generic dict that can be changed on every op.
if filter_by and not filter_by.items() <= operation_value.items():
continue
# condition result should be True, otherwise continue
# and search for other operations.
if condition and not condition(operation_value):
continue
yield op_data
def stream_operations(self):
for op_data in self.transaction_listener.listen():
yield op_data
def stream_blocks(self):
for block in self.transaction_listener.listen_blocks():
yield block | 0.562537 | 0.113432 |
quotes = [
{
"headline": "<NAME> über schlechte Chancen",
"content": "Wenn etwas wichtig genug ist, dann mach es, auch wenn alle Chancen gegen dich stehen."
},
{
"headline": "<NAME> über den Aufbau einer Firma",
"content": "Eine Firma aufzubauen ist wie Kuchen backen. Man braucht von allen Zutaten genau die richtige Menge."
},
{
"headline": "<NAME> über Geduld",
"content": "Geduld ist eine Tugend und ich erlerne sie gerade. Es ist eine harte Lehre."
},
{
"headline": "<NAME> über Ziele",
"content": "Menschen arbeiten besser, wenn sie wissen für welches Ziel und warum. Es ist wichtig, dass die Leute sich darauf freuen, morgens in die Arbeit zu kommen, und ihnen das Arbeiten Spaß macht."
},
{
"headline": "<NAME> über großartige Unternehmen",
"content": "Großartige Unternehmen sind auf großartigen Produkten aufgebaut."
},
{
"headline": "<NAME> über Innovation",
"content": "Wie entsteht innovatives Denken? Es ist eine Geisteshaltung, für die man sich entscheiden muss."
},
{
"headline": "<NAME> über komplizierte Aufgaben",
"content": "Es ist ein Fehler, eine große Anzahl an Leuten einzustellen, um eine komplizierte Aufgabe zu lösen. Viele können niemals Talent wettmachen, wenn es darum geht, die richtige Lösung zu finden (zwei Menschen, die etwas nicht wissen, sind nicht besser als einer). Sie werden den Fortschritt aufhalten und unglaublich teuer machen."
},
{
"headline": "<NAME> über Unternehmertum",
"content": "Unternehmer zu sein ist wie Glas zu essen und in den Abgrund des Todes zu starren."
},
{
"headline": "<NAME> über Selbstzufriedenheit",
"content": "Denk immer darüber nach, wie du Dinge besser machen kannst, und hinterfrage dich."
},
{
"headline": "<NAME> über seinen größten Fehler",
"content": "Mein größter Fehler ist vermutlich, zu viel Wert auf das Talent von jemanden zu legen und nicht auf seine Persönlichkeit. Ich denke es ist wichtig, dass jemand ein gutes Herz hat."
},
{
"headline": "<NAME> über die Vergangenheit",
"content": "Wenn irgendwer lieber in der Vergangenheit leben will, dann kennt er sich mit Geschichte nicht besonders gut aus. Das Leben in früheren Zeiten war zum Kotzen. Die Menschen wussten sehr wenig und man wäre wahrscheinlich in einem jungen Alter an einer furchtbaren Krankheit gestorben. Man hätte jetzt wahrscheinlich keine Zähne mehr. Als Frau wäre es besonders schlimm."
},
{
"headline": "<NAME> über die Zukunft",
"content": "Wenn du morgens aufwachst und denkst, dass die Zukunft besser sein wird, ist das ein schöner Tag. Ansonsten ist er es nicht."
}
] | skill/quotes.py | quotes = [
{
"headline": "<NAME> über schlechte Chancen",
"content": "Wenn etwas wichtig genug ist, dann mach es, auch wenn alle Chancen gegen dich stehen."
},
{
"headline": "<NAME> über den Aufbau einer Firma",
"content": "Eine Firma aufzubauen ist wie Kuchen backen. Man braucht von allen Zutaten genau die richtige Menge."
},
{
"headline": "<NAME> über Geduld",
"content": "Geduld ist eine Tugend und ich erlerne sie gerade. Es ist eine harte Lehre."
},
{
"headline": "<NAME> über Ziele",
"content": "Menschen arbeiten besser, wenn sie wissen für welches Ziel und warum. Es ist wichtig, dass die Leute sich darauf freuen, morgens in die Arbeit zu kommen, und ihnen das Arbeiten Spaß macht."
},
{
"headline": "<NAME> über großartige Unternehmen",
"content": "Großartige Unternehmen sind auf großartigen Produkten aufgebaut."
},
{
"headline": "<NAME> über Innovation",
"content": "Wie entsteht innovatives Denken? Es ist eine Geisteshaltung, für die man sich entscheiden muss."
},
{
"headline": "<NAME> über komplizierte Aufgaben",
"content": "Es ist ein Fehler, eine große Anzahl an Leuten einzustellen, um eine komplizierte Aufgabe zu lösen. Viele können niemals Talent wettmachen, wenn es darum geht, die richtige Lösung zu finden (zwei Menschen, die etwas nicht wissen, sind nicht besser als einer). Sie werden den Fortschritt aufhalten und unglaublich teuer machen."
},
{
"headline": "<NAME> über Unternehmertum",
"content": "Unternehmer zu sein ist wie Glas zu essen und in den Abgrund des Todes zu starren."
},
{
"headline": "<NAME> über Selbstzufriedenheit",
"content": "Denk immer darüber nach, wie du Dinge besser machen kannst, und hinterfrage dich."
},
{
"headline": "<NAME> über seinen größten Fehler",
"content": "Mein größter Fehler ist vermutlich, zu viel Wert auf das Talent von jemanden zu legen und nicht auf seine Persönlichkeit. Ich denke es ist wichtig, dass jemand ein gutes Herz hat."
},
{
"headline": "<NAME> über die Vergangenheit",
"content": "Wenn irgendwer lieber in der Vergangenheit leben will, dann kennt er sich mit Geschichte nicht besonders gut aus. Das Leben in früheren Zeiten war zum Kotzen. Die Menschen wussten sehr wenig und man wäre wahrscheinlich in einem jungen Alter an einer furchtbaren Krankheit gestorben. Man hätte jetzt wahrscheinlich keine Zähne mehr. Als Frau wäre es besonders schlimm."
},
{
"headline": "<NAME> über die Zukunft",
"content": "Wenn du morgens aufwachst und denkst, dass die Zukunft besser sein wird, ist das ein schöner Tag. Ansonsten ist er es nicht."
}
] | 0.233706 | 0.298794 |
import netCDF4 as nc4
def create_monthly_file(writefile,vars_out_salin,vars_out_non_salin,salinity_values,parameters):
'''Creates netCDF dataset for monthly mean output data with all required variables and dimensions. Output variables have two dimensions: a record dimension (with associated month, year and buoy number variables) and a salinity dimension, as salinity affects most of the output fluxes strongly via conductivity and heat capacity'''
ncid_out = nc4.Dataset(writefile,'w')
record_dim = ncid_out.createDimension('record_number')
record_var = ncid_out.createVariable('record_number','int',dimensions=('record_number',))
buoy_var = ncid_out.createVariable('buoy_number','int',dimensions=('record_number',))
month_var = ncid_out.createVariable('month','int',dimensions=('record_number',))
month = ncid_out.createVariable('year','int',dimensions=('record_number',))
start_record = 0
salinity_dim = ncid_out.createDimension('salinity',salinity_values.shape[0])
salinity_var = ncid_out.createVariable('salinity','float64',\
dimensions=('salinity',))
salinity_var[:] = salinity_values
for var in vars_out_non_salin:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number',))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number',))
for var in vars_out_salin:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number','salinity'))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number','salinity'))
for key in dir(parameters):
if key[:2] != '__':
ncid_out.setncattr(key,getattr(parameters,key))
return ncid_out
def create_daily_file(writefile,vars_out,salinity_values):
ncid_out = nc4.Dataset(writefile,'w')
record_dim = ncid_out.createDimension('record_number')
record_var = ncid_out.createVariable('record_number','int',dimensions=('record_number',))
buoy_var = ncid_out.createVariable('buoy_number','int',dimensions=('record_number',))
day_var = ncid_out.createVariable('day','int',dimensions=('record_number',))
month_var = ncid_out.createVariable('month','int',dimensions=('record_number',))
year_var = ncid_out.createVariable('year','int',dimensions=('record_number',))
start_record = 0
salinity_dim = ncid_out.createDimension('salinity',salinity_values.shape[0])
salinity_var = ncid_out.createVariable('salinity','float64',\
dimensions=('salinity',))
salinity_var[:] = salinity_values
for var in vars_out:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number','salinity'))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number','salinity'))
return ncid_out | nc_functions.py |
import netCDF4 as nc4
def create_monthly_file(writefile,vars_out_salin,vars_out_non_salin,salinity_values,parameters):
'''Creates netCDF dataset for monthly mean output data with all required variables and dimensions. Output variables have two dimensions: a record dimension (with associated month, year and buoy number variables) and a salinity dimension, as salinity affects most of the output fluxes strongly via conductivity and heat capacity'''
ncid_out = nc4.Dataset(writefile,'w')
record_dim = ncid_out.createDimension('record_number')
record_var = ncid_out.createVariable('record_number','int',dimensions=('record_number',))
buoy_var = ncid_out.createVariable('buoy_number','int',dimensions=('record_number',))
month_var = ncid_out.createVariable('month','int',dimensions=('record_number',))
month = ncid_out.createVariable('year','int',dimensions=('record_number',))
start_record = 0
salinity_dim = ncid_out.createDimension('salinity',salinity_values.shape[0])
salinity_var = ncid_out.createVariable('salinity','float64',\
dimensions=('salinity',))
salinity_var[:] = salinity_values
for var in vars_out_non_salin:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number',))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number',))
for var in vars_out_salin:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number','salinity'))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number','salinity'))
for key in dir(parameters):
if key[:2] != '__':
ncid_out.setncattr(key,getattr(parameters,key))
return ncid_out
def create_daily_file(writefile,vars_out,salinity_values):
ncid_out = nc4.Dataset(writefile,'w')
record_dim = ncid_out.createDimension('record_number')
record_var = ncid_out.createVariable('record_number','int',dimensions=('record_number',))
buoy_var = ncid_out.createVariable('buoy_number','int',dimensions=('record_number',))
day_var = ncid_out.createVariable('day','int',dimensions=('record_number',))
month_var = ncid_out.createVariable('month','int',dimensions=('record_number',))
year_var = ncid_out.createVariable('year','int',dimensions=('record_number',))
start_record = 0
salinity_dim = ncid_out.createDimension('salinity',salinity_values.shape[0])
salinity_var = ncid_out.createVariable('salinity','float64',\
dimensions=('salinity',))
salinity_var[:] = salinity_values
for var in vars_out:
output_var = ncid_out.createVariable(var,'float64',dimensions=('record_number','salinity'))
output_var_err = ncid_out.createVariable(var+'_err','int',dimensions=('record_number','salinity'))
return ncid_out | 0.399812 | 0.384854 |
import twitter
from .config import CONSUMER_KEY, CONSUMER_SECRET
class twitter_api:
def request_token(self, hosturl, token_filename=None, open_browser=True):
oc = hosturl + 'oauth_callback'
tw = twitter.Twitter(
auth=twitter.OAuth('', '', CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
a = tw.oauth.request_token(oauth_callback=oc)
oauth_token, oauth_secret = self.parse_oauth_tokens(
a)
oauth_url = ('https://api.twitter.com/oauth/authenticate?'
+ 'oauth_token=' + oauth_token)
return oauth_url, oauth_token, oauth_secret
def get_oauth_token(self, oauth_token, oauth_secret, oauth_verifier):
tw = twitter.Twitter(
auth=twitter.OAuth(
oauth_token, oauth_secret,
CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
oauth_token, oauth_secret = self.parse_oauth_tokens(
tw.oauth.access_token(oauth_verifier=oauth_verifier))
return oauth_token, oauth_secret
def parse_oauth_tokens(self, result):
for r in result.split('&'):
k, v = r.split('=')
if k == 'oauth_token':
oauth_token = v
elif k == 'oauth_token_secret':
oauth_token_secret = v
return oauth_token, oauth_token_secret
def login_twitter_oauth(self, oauth_token, oauth_secret):
self.api = twitter.Twitter(
auth=twitter.OAuth(oauth_token, oauth_secret,
CONSUMER_KEY, CONSUMER_SECRET))
def get_account(self):
status = self.api.account.verify_credentials(skip_status=True)
return status['screen_name'], status['profile_image_url_https']
def login_twitter(self):
# 読み取りだけなのでOAuth2
bearer_token = twitter.oauth2_dance(
CONSUMER_KEY, CONSUMER_SECRET)
self.api = twitter.Twitter(
auth=twitter.OAuth2(bearer_token=bearer_token), retry=True)
def get_self_conversation(self, name, root_twid, mode='thread'):
tweets = []
# ツイート3200件取得
for i in range(1, 17):
gets = self.api.statuses.user_timeline(
id=name, count=200, include_rts=False, page=i)
if(len(gets) == 0):
break
tweets += gets
twid = root_twid
tweet_list = []
while True:
twid_tmp = twid
for i, tweet in enumerate(tweets):
if(mode == 'thread'):
# 対象ツイートにリプライを送っているツイートを取得
if(tweet['in_reply_to_status_id'] != twid):
continue
t = tweet
elif(mode == 'quote'):
# 引用でないツイートは無視
if('quoted_status_id' not in tweet):
continue
if(tweet['quoted_status_id'] != twid):
continue
t = self.get_tweet(tweet['in_reply_to_status_id'])
# 取得したツイートに画像がない場合は無視
if('extended_entities' not in t):
continue
if('media' not in t['extended_entities']):
continue
tweet_list.append(t)
twid = t['id']
if(twid_tmp == twid):
break
return tweet_list
def get_tweet(self, twid):
status = self.api.statuses.show(
id=twid, include_entities=True)
return status
def get_api_status(self):
status = self.api.application.rate_limit_status()
for s in status['resources'].values():
for n, lim in s.items():
if(lim['limit'] != lim['remaining']):
print(n, ' - ', lim['limit'], ' : ', lim['remaining'])
# end of class twitter_api | view/twmng.py | import twitter
from .config import CONSUMER_KEY, CONSUMER_SECRET
class twitter_api:
def request_token(self, hosturl, token_filename=None, open_browser=True):
oc = hosturl + 'oauth_callback'
tw = twitter.Twitter(
auth=twitter.OAuth('', '', CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
a = tw.oauth.request_token(oauth_callback=oc)
oauth_token, oauth_secret = self.parse_oauth_tokens(
a)
oauth_url = ('https://api.twitter.com/oauth/authenticate?'
+ 'oauth_token=' + oauth_token)
return oauth_url, oauth_token, oauth_secret
def get_oauth_token(self, oauth_token, oauth_secret, oauth_verifier):
tw = twitter.Twitter(
auth=twitter.OAuth(
oauth_token, oauth_secret,
CONSUMER_KEY, CONSUMER_SECRET),
format='', api_version=None)
oauth_token, oauth_secret = self.parse_oauth_tokens(
tw.oauth.access_token(oauth_verifier=oauth_verifier))
return oauth_token, oauth_secret
def parse_oauth_tokens(self, result):
for r in result.split('&'):
k, v = r.split('=')
if k == 'oauth_token':
oauth_token = v
elif k == 'oauth_token_secret':
oauth_token_secret = v
return oauth_token, oauth_token_secret
def login_twitter_oauth(self, oauth_token, oauth_secret):
self.api = twitter.Twitter(
auth=twitter.OAuth(oauth_token, oauth_secret,
CONSUMER_KEY, CONSUMER_SECRET))
def get_account(self):
status = self.api.account.verify_credentials(skip_status=True)
return status['screen_name'], status['profile_image_url_https']
def login_twitter(self):
# 読み取りだけなのでOAuth2
bearer_token = twitter.oauth2_dance(
CONSUMER_KEY, CONSUMER_SECRET)
self.api = twitter.Twitter(
auth=twitter.OAuth2(bearer_token=bearer_token), retry=True)
def get_self_conversation(self, name, root_twid, mode='thread'):
tweets = []
# ツイート3200件取得
for i in range(1, 17):
gets = self.api.statuses.user_timeline(
id=name, count=200, include_rts=False, page=i)
if(len(gets) == 0):
break
tweets += gets
twid = root_twid
tweet_list = []
while True:
twid_tmp = twid
for i, tweet in enumerate(tweets):
if(mode == 'thread'):
# 対象ツイートにリプライを送っているツイートを取得
if(tweet['in_reply_to_status_id'] != twid):
continue
t = tweet
elif(mode == 'quote'):
# 引用でないツイートは無視
if('quoted_status_id' not in tweet):
continue
if(tweet['quoted_status_id'] != twid):
continue
t = self.get_tweet(tweet['in_reply_to_status_id'])
# 取得したツイートに画像がない場合は無視
if('extended_entities' not in t):
continue
if('media' not in t['extended_entities']):
continue
tweet_list.append(t)
twid = t['id']
if(twid_tmp == twid):
break
return tweet_list
def get_tweet(self, twid):
status = self.api.statuses.show(
id=twid, include_entities=True)
return status
def get_api_status(self):
status = self.api.application.rate_limit_status()
for s in status['resources'].values():
for n, lim in s.items():
if(lim['limit'] != lim['remaining']):
print(n, ' - ', lim['limit'], ' : ', lim['remaining'])
# end of class twitter_api | 0.150465 | 0.083516 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Workspace',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=200)),
('created_at', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('workspace_id', models.CharField(max_length=16, null=True)),
('public_key', models.CharField(editable=False, max_length=64, null=True)),
('status', models.CharField(choices=[('active', 'Active'), ('archived', 'Archived'), ('deleted', 'Deleted')], default='active', max_length=25)),
('created_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='WorkspaceUser',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('status', models.CharField(choices=[('active', 'Active'), ('archived', 'Archived'), ('deleted', 'Deleted')], default='active', max_length=25)),
('role', models.CharField(choices=[('admin', 'Admin'), ('user', 'User')], default='user', max_length=25)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('workspace', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='workspaces.workspace')),
],
),
] | workspaces/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Workspace',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=200)),
('created_at', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('workspace_id', models.CharField(max_length=16, null=True)),
('public_key', models.CharField(editable=False, max_length=64, null=True)),
('status', models.CharField(choices=[('active', 'Active'), ('archived', 'Archived'), ('deleted', 'Deleted')], default='active', max_length=25)),
('created_user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='WorkspaceUser',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('status', models.CharField(choices=[('active', 'Active'), ('archived', 'Archived'), ('deleted', 'Deleted')], default='active', max_length=25)),
('role', models.CharField(choices=[('admin', 'Admin'), ('user', 'User')], default='user', max_length=25)),
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('workspace', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='workspaces.workspace')),
],
),
] | 0.523177 | 0.135346 |
import cv2
import numpy as np
from PIL import Image
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
import os
class fragile(object):
class Break(Exception):
"""Break out of the with statement"""
def __init__(self, value):
self.value = value
def __enter__(self):
return self.value.__enter__()
def __exit__(self, etype, value, traceback):
error = self.value.__exit__(etype, value, traceback)
if etype == self.Break:
return True
return error
class draw:
def text_image(text_path, font_path=None, font_size=45):
"""
Convert .txt file to image
input: text_path (path to .txt file)
font_path (path to font file; default=FreeMono.ttf builtin font)
font_size (ASCII font size in image; default=45)
return: Pillow image
"""
PIXEL_ON = 0
PIXEL_OFF = 255
grayscale = 'L'
with open(text_path) as text_file:
lines = tuple(l.rstrip() for l in text_file.readlines())
try:
font = PIL.ImageFont.truetype(font_path, size=font_size)
except:
font = PIL.ImageFont.truetype("FreeMono.ttf", size=font_size, layout_engine=PIL.ImageFont.LAYOUT_RAQM)
pt2px = lambda pt: int(round(pt * 96.0 / 72))
max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
max_height = pt2px(font.getsize(test_string)[1])
max_width = pt2px(font.getsize(max_width_line)[0])
height = max_height * len(lines)
width = int(round(max_width + 40))
image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF)
draw = PIL.ImageDraw.Draw(image)
vertical_position = 5
horizontal_position = 5
line_spacing = int(round(max_height * 0.8))
for line in lines:
draw.text((horizontal_position, vertical_position),
line, fill=PIXEL_ON, font=font)
vertical_position += line_spacing
c_box = PIL.ImageOps.invert(image).getbbox()
image = image.crop(c_box)
return image
def scale_image(image, new_width=100):
"""
Resizes an image preserving the aspect ratio
input: image (Pillow image)
new_width (Scale image smaller for ease; default=100)
return: Pillow image
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
new_image = image.resize((new_width, new_height))
return new_image
@staticmethod
def mk_ascii(image, ASCII=["A","B","C","D","E","F","I","J","K","N","P","R","S","V","Y","2","3","4","5","6","7","8","9"], fontpath=None, fontsize=45):
"""
Turn image into colorized ASCII art
input: image (3D numpy array uint8)
ASCII (ASCII list of string chars to build image; default=longlist)
font_path (path to font file; default=FreeMono.ttf builtin font)
font_size (ASCII font size in image; default=45)
return: 3D numpy array uint8
"""
lower = np.array([0, 0, 0])
upper = np.array([254,254,254])
gray = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
gray = draw.scale_image(gray)
gray = gray.convert("L")
width, height = gray.size
pixels = gray.getdata()
try:
characters = "".join([ASCII[pixel//len(ASCII)] for pixel in pixels])
except:
ASCII=["A","B","C","D","E","F","I","J","K","N","P","R","S","V","Y","2","3","4","5","6","7","8","9"]
characters = "".join([ASCII[pixel//len(ASCII)] for pixel in pixels])
pix_count = len(characters)
ascii_image = "\n".join([characters[i:(i+width)] for i in range(0, pix_count,width)])
with fragile(open("ascii_image.txt", "w")) as f:
f.write(ascii_image)
f.close()
raise fragile.Break
im = draw.text_image('ascii_image.txt', fontpath, fontsize)
gray = cv2.resize(np.asarray(im), (image.shape[1], image.shape[0]))
gray = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
mask = cv2.inRange(gray, lower, upper)
gray[mask!=0] = image[mask!=0]
gray[mask==0] = [0,0,0]
return gray | ascii_art.py | import cv2
import numpy as np
from PIL import Image
import PIL.Image
import PIL.ImageFont
import PIL.ImageOps
import PIL.ImageDraw
import os
class fragile(object):
class Break(Exception):
"""Break out of the with statement"""
def __init__(self, value):
self.value = value
def __enter__(self):
return self.value.__enter__()
def __exit__(self, etype, value, traceback):
error = self.value.__exit__(etype, value, traceback)
if etype == self.Break:
return True
return error
class draw:
def text_image(text_path, font_path=None, font_size=45):
"""
Convert .txt file to image
input: text_path (path to .txt file)
font_path (path to font file; default=FreeMono.ttf builtin font)
font_size (ASCII font size in image; default=45)
return: Pillow image
"""
PIXEL_ON = 0
PIXEL_OFF = 255
grayscale = 'L'
with open(text_path) as text_file:
lines = tuple(l.rstrip() for l in text_file.readlines())
try:
font = PIL.ImageFont.truetype(font_path, size=font_size)
except:
font = PIL.ImageFont.truetype("FreeMono.ttf", size=font_size, layout_engine=PIL.ImageFont.LAYOUT_RAQM)
pt2px = lambda pt: int(round(pt * 96.0 / 72))
max_width_line = max(lines, key=lambda s: font.getsize(s)[0])
test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
max_height = pt2px(font.getsize(test_string)[1])
max_width = pt2px(font.getsize(max_width_line)[0])
height = max_height * len(lines)
width = int(round(max_width + 40))
image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF)
draw = PIL.ImageDraw.Draw(image)
vertical_position = 5
horizontal_position = 5
line_spacing = int(round(max_height * 0.8))
for line in lines:
draw.text((horizontal_position, vertical_position),
line, fill=PIXEL_ON, font=font)
vertical_position += line_spacing
c_box = PIL.ImageOps.invert(image).getbbox()
image = image.crop(c_box)
return image
def scale_image(image, new_width=100):
"""
Resizes an image preserving the aspect ratio
input: image (Pillow image)
new_width (Scale image smaller for ease; default=100)
return: Pillow image
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
new_image = image.resize((new_width, new_height))
return new_image
@staticmethod
def mk_ascii(image, ASCII=["A","B","C","D","E","F","I","J","K","N","P","R","S","V","Y","2","3","4","5","6","7","8","9"], fontpath=None, fontsize=45):
"""
Turn image into colorized ASCII art
input: image (3D numpy array uint8)
ASCII (ASCII list of string chars to build image; default=longlist)
font_path (path to font file; default=FreeMono.ttf builtin font)
font_size (ASCII font size in image; default=45)
return: 3D numpy array uint8
"""
lower = np.array([0, 0, 0])
upper = np.array([254,254,254])
gray = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
gray = draw.scale_image(gray)
gray = gray.convert("L")
width, height = gray.size
pixels = gray.getdata()
try:
characters = "".join([ASCII[pixel//len(ASCII)] for pixel in pixels])
except:
ASCII=["A","B","C","D","E","F","I","J","K","N","P","R","S","V","Y","2","3","4","5","6","7","8","9"]
characters = "".join([ASCII[pixel//len(ASCII)] for pixel in pixels])
pix_count = len(characters)
ascii_image = "\n".join([characters[i:(i+width)] for i in range(0, pix_count,width)])
with fragile(open("ascii_image.txt", "w")) as f:
f.write(ascii_image)
f.close()
raise fragile.Break
im = draw.text_image('ascii_image.txt', fontpath, fontsize)
gray = cv2.resize(np.asarray(im), (image.shape[1], image.shape[0]))
gray = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB)
mask = cv2.inRange(gray, lower, upper)
gray[mask!=0] = image[mask!=0]
gray[mask==0] = [0,0,0]
return gray | 0.439026 | 0.164449 |
import socket
import sys
import getopt
import threading
import subprocess
import getpass
from textwrap import dedent
from typing import Tuple, Union, List
class Helpers:
"""Static functions, to use as helpers"""
@staticmethod
def send_data(to_socket: socket.socket, data_stream: bytes,
send_timeout=2) -> None:
"""
Centralised function to handle sending data stream to receive data. Sends data in consistent
buffer sizes
Args:
to_socket:
Socket to send stream to
data_stream:
Data stream to send
send_timeout:
Set timeout for to_socket
"""
to_socket.settimeout(send_timeout)
try:
data_fragments = []
for i in range(0, len(data_stream), 4096):
# Break data stream into byte sized bites
data_fragments.append(data_stream[i:i + 4096])
if data_fragments[-1] == 4096:
# Make sure last fragment isn't BUFFER bytes long
data_fragments.append(b'\n')
for frag in data_fragments:
to_socket.send(frag)
except TimeoutError:
pass
@staticmethod
def receive_data(from_socket: socket.socket,
from_timeout=2) -> bytes:
"""
Centralised fuction to handle receiving one or more packet buffers from TCP socket
Args:
from_socket:
Socket sending stream to this instance.
from_timeout:
Set timeout for from_socket
Returns:
Complete binary stream from socket
"""
from_socket.settimeout(from_timeout)
fragments: List[bytes] = []
try:
stream = from_socket.recv(4096)
fragments.append(stream)
while True:
if len(stream) < 4096:
break
else:
stream = from_socket.recv(4096)
fragments.append(stream)
except TimeoutError:
pass
return b''.join(fragments)
@staticmethod
def bin_join(*to_join: Union[str, bytes]) -> bytes:
"""
Funnel function to reliably concatenate binary and strings into binaries. Can also be used
to ensure a single item is bytes string
Args:
to_join: Item/s to join together. Either bytes or regular strings
Return:
Properly concatenated bytes string
"""
binary_bytes = []
for item in to_join:
if not item:
pass
elif isinstance(item, int):
binary_bytes.append(str(item).encode())
elif isinstance(item, str):
binary_bytes.append(item.encode())
else:
binary_bytes.append(item)
return b''.join(binary_bytes)
@staticmethod
def bin_print(*to_display, end='\n'):
"""
Funnel function to reliably print binary or regular strings.
Args:
to_display:
Item/s to join together. Either bytes or regular strings
end:
default print end arg
"""
for item in to_display:
try:
print(item.decode(), end=end)
except AttributeError:
print(item, end=end)
class SshcAttributes:
"""Dataclass-like, used to host running SSHCustom's running attributes"""
# Carries defaults
@staticmethod
def usage():
"""Module docstring doubles as --help"""
print(__doc__)
exit()
def __init__(self):
if __name__ == '__main__' and len(sys.argv) == 1:
self.usage()
try:
opts, args = getopt.getopt(sys.argv[1:], "ht:p:k:bci:u:lw:e:sv",
['help', 'target=', 'port=', 'user=', 'pass=', 'banner'
'connect', 'initial=', 'upload=',
'listen', 'write=', 'execute=', 'shell', 'verbose'])
for opt, arg in opts:
if opt in ('-h', '--help'):
self.usage()
elif opt in ('-t', '--target'):
# self.target = arg
self.__setattr__('target', arg)
elif opt in ('-p', '--port'):
# self.port = arg
self.__setattr__('port', int(arg))
elif opt in ('-c', '--connecting'):
# self.connecting = True
self.__setattr__('connecting', True)
elif opt == 'k':
# self.known_hosts = arg
self.__setattr__('known_hosts', arg)
elif opt == 'user':
# self.user = arg
self.__setattr__('user', arg)
elif opt in ('b', '--banner'):
# self.banner = True
self.__setattr__('banner', True)
elif opt == 'pass':
# self.password = arg
self.__setattr__('password', arg)
elif opt in ('-u', '--upload'):
# self.upload = arg
self.__setattr__('upload', arg)
elif opt in ('-l', '--listen'):
# self.listening = True
self.__setattr__('upload', True)
elif opt in ('-w', '--write'):
# self.write_to = arg
self.__setattr__('write_to', arg)
elif opt in ('-e', '--execute'):
# self.execute = arg
self.__setattr__('execute', arg)
elif opt in ('-s', '--shell'):
# self.shell = True
self.__setattr__('shell', True)
elif opt in ('-v', '--verbose'):
# self.verbose = True
self.__setattr__('verbose', True)
elif not self.target or not self.port:
raise SyntaxError("Must explicitly state target IP and Port!")
elif True not in [not self.connecting or not self.listening]:
input((not self.connecting or not self.listening))
raise SyntaxError("Must explicitly state connecting or listening function!")
else:
raise SyntaxError(f"Unhandled option: {opt}")
except (getopt.GetoptError, SyntaxError) as err:
print(err)
self.usage()
target: str = '127.0.0.1'
"""Target IP"""
port: int = 9999
"""Target port"""
known_hosts = ''
"""Optional key support, using absolute path to .ssh/known_hosts"""
user: str = getpass.getuser()
"""Username to pass to custom server"""
password: str = None
"""password to sign in with"""
# Connecting functions
connecting: bool = False
"""Bool to connect to listening server on [host]:[port]"""
# Listening functions
listening: bool = False
"""Bool to listen on [host]:[port] for incoming connections"""
shell: bool = False
"""Initialize a shell loop, to run one-off commands by connecting clients"""
close_connection: str = 'bhpquit'
"""Specific command to disconnect connected client"""
shutdown_listening: str = 'bhpshutdown'
"""Specific command to shutdown listening script"""
listening_active: bool = False
"""Boolean used to keep server alive"""
timeout: int = 60
"""Listening server's Timeout value"""
verbose = True
""" """
class ShutdownServer(socket.error):
"""Custom error used to shutdown listening server"""
class ShutdownClient(socket.error):
"""Custom error used to safely disconnect connecting client"""
class SSHCustom:
"""
Dedicated SSH client and server, designed specifically for windows implementations
(Note that it's usefullness is arguably lessened by the lastest Win10's built in SSH port)
See --help for more information
"""
def __init__(self):
"""
Custom SSH Client/Server built on Paramiko API. Can be imported or run from command line.
See Readme or --help for more information
"""
self.atts: SshcAttributes = SshcAttributes()
"""Attributes module"""
self.help = Helpers()
"""Helper static functions"""
def verprint(self, *to_print) -> None:
"""
Default check against verbosity attribute, to see if allowed to print
Args:
*to_print: emulation of print *args. pass as normal
"""
if self.atts.verbose:
for item in to_print:
self.help.bin_print(item, end=' ')
print()
def main(self):
"""
Primary logic loop. After init, builds listening post or starts connecting client
"""
if self.atts.listening:
# Time to listen, potentially upload items, execute commands, and drop a shell back
child = SSHServer()
child.server()
else:
# Try connecting to target, send a potential starting command
child = SSHClient()
child.client()
class SSHServer(SSHCustom, paramiko.ServerInterface):
"""Custom SSH client, using Paramiko API wrapper"""
def __init__(self):
super(SSHServer, self).__init__()
# Extension to super init, name spacing an Event
self.event = threading.Event()
def server(self):
"""
Start a TCP server socket, spool threads to handle incoming clients
"""
self.verprint(f"[*] Listening on {self.atts.target}:{self.atts.port}")
try:
# Spool main SSH server
server = socket.socket()
# Bind socket settings
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((self.atts.target, self.atts.port))
server.listen(5)
while self.atts.listening_active:
server_acceptance = server.accept() # Tuple containing client_socket and addr
if self.atts.listening_active:
client_thread = threading.Thread(target=self.handle_connects,
args=(server_acceptance,))
client_thread.start()
except ShutdownServer:
print("")
except Exception as err:
closing = dedent(f"""
--[*] Unexpected error: {err}
----- Closing server""")
self.verprint(closing)
def handle_connects(self, connected_client: Tuple[socket.socket, any]):
"""
Called by server socket for each connection
Args:
connected_client:
Returns:
"""
# Identify target TCP connection
client_socket, addr = connected_client
client_socket.settimeout(self.atts.timeout)
self.verprint(f'--[*] Accepted connection, handler spooled for {addr[0]}:{addr[1]}')
closing = ''
try:
# Create SSH transport object over client_socket
ssh_session = paramiko.Transport(client_socket)
ssh_session.add_server_key(self.rsa_key)
ssh_session.start_server()
ssh_channel = ssh_session.accept(20)
buffer_stream = self.help.receive_data(ssh_channel)
"""Received buffer stream from connecting client"""
response = b''
"""First response to send to connecting client"""
# Determine if server set to init shell or not. Respond either way
if not self.atts.shell:
response = self.help.bin_join(
response, f"\nClosing connection to {self.atts.target}:{self.atts.port}")
self.help.send_data(to_socket=ssh_channel, data_stream=response)
else:
self.shell_loop(ssh_channel, response)
# # # Exception Handling
except ShutdownClient:
closing = dedent(f"""
--[*] Client requested connection close
----- Closing handler {addr[0]}:{addr[1]}
""")
except ShutdownServer:
closing = dedent(f"""
--[*] Client {addr[0]}:{addr[1]} requested shutdown listening post
----- Shutting down
""")
# self.atts.listening_active = False
raise ShutdownServer
except Exception as err:
closing = dedent(f"""
--[*] Unexpected error: {err}
----- Closing handler {addr[0]}:{addr[1]}
""")
finally:
self.verprint(closing)
# Low effort try to send to connected client
try:
self.help.send_data(to_socket=ssh_channel,
data_stream=self.help.bin_join(closing))
# client_socket.shutdown(socket.SHUT_RDWR)
# client_socket.close()
ssh_channel.close()
except Exception as err:
self.verprint(f"Unexpected error while closing handler {addr[0]}:{addr[1]} : ")
self.verprint(err)
def check_for_commands(self, stream: bytes):
"""
Given a datastream, check if a closing command is in it. Raise appropriate handling error
Args:
stream: bytes stream sent from connecting client, to check for bhp commands
"""
# Catch bhp specific commands in stream
if self.atts.close_connection in str(stream):
raise ShutdownClient
if self.atts.shutdown_listening in str(stream):
raise ShutdownServer
def write_file(self, data_buffer) -> bytes:
"""
If allowed, Extension to write a caught data_buffer to local file (self.write_to)
Return feedback to calling functions
Args:
data_buffer: handle_connects's received data stream from it's client_socket.
Returns:
File write feedback, either successful or failure with error
if write_to is None (i.e. not set) return empty bytes string
"""
send_feedback = ''
if self.atts.write_to:
try:
with open(self.atts.write_to, "wb") as file:
file.write(data_buffer)
send_feedback = f"Successfully saved file to {self.atts.write_to}\r\n"
except Exception as err:
send_feedback = f"""Failed to save file to {self.atts.write_to}\r\n{err}\r\n"""
return self.help.bin_join(send_feedback)
def run_command(self, command: Union[str, bytes, None]) -> bytes:
"""
Locally run given command using subprocess, and return results as bytes string
Args:
command: given command to run
"""
if not command:
command_run = ''
elif isinstance(command, bytes):
command_run = command.decode()
else:
command_run = command
try:
output = subprocess.check_output(command_run, stderr=subprocess.STDOUT, shell=True)
except Exception as err:
output = dedent(f"""
Failed to execute command
Command : {command_run}
Error : {err}\r\n""")
return self.help.bin_join(output)
def shell_loop(self, client_socket: socket.socket, initial_response: bytes):
"""
Function to handle one off commands from connecting client. Loops until connection broken.
Args:
client_socket: Answered socket to accept shell commands from
initial_response: Initial response from handle_connects' steps, if any.
Passed here so shell loop can return, with prompt characters
"""
response = initial_response
prompt = f'\n<BHP@{self.atts.target}:{self.atts.port}>#'
while True:
# Loop is broken by explicit errors or commands
self.help.send_data(to_socket=client_socket,
data_stream=self.help.bin_join(response, prompt))
try:
cmd_buffer = self.help.receive_data(from_socket=client_socket)
self.check_for_commands(cmd_buffer)
response = self.run_command(cmd_buffer)
except TimeoutError:
raise TimeoutError("Listening server timeout reached")
except Exception as err:
raise err
class SSHClient(SSHCustom):
"""Custom SSH Client, , using paramiko API wrapper"""
def client(self):
"""
Spool up TCP socket, catch return data, prompt for new to_send. Rinse and repeat
"""
self.verprint(f"Connecting to {self.atts.target}:{self.atts.port}...")
# Bind new SSH client
client = paramiko.SSHClient()
try:
# Optional key support
if self.atts.known_hosts:
client.load_host_keys(self.atts.known_hosts)
# Auto add missing keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect
client.connect(self.atts.target, port=self.atts.port,
username=self.atts.user, password=<PASSWORD>)
# request session channel to server
ssh_session = client.get_transport().open_session()
# Catch banner
if self.atts.banner:
banner = self.help.receive_data(ssh_session)
self.help.bin_print(banner)
# Build initial data to send
if self.atts.upload:
to_send = self.file_stream()
else:
to_send = self.help.bin_join(self.atts.initial_cmd, '\n')
# Primary running loop
while True:
self.help.send_data(ssh_session, to_send)
server_response = self.help.receive_data(ssh_session)
self.help.bin_print('\n', server_response, end=' ')
to_send = input() + '\n'
# # # Exception Handling
except KeyboardInterrupt:
self.verprint("Disconnecting")
pass
except ConnectionRefusedError:
self.verprint('Cannot connect, is listening active?')
except ConnectionAbortedError:
# Socket closed by listener
self.verprint("Closing connection...")
except ConnectionResetError:
self.verprint("Connection prematurely closed. Did server shutdown?")
except Exception as err:
self.verprint("Unknown error!\n", err, "\nDisconnecting")
finally:
try:
# client.shutdown(socket.SHUT_RDWR)
# ssh_session.close()
client.close()
except Exception as err:
self.verprint(
f"Unexpected error when disconnecting from {self.atts.target}:{self.atts.port}")
self.verprint(err)
def file_stream(self):
"""
Targets file at upload and converts to binary stream, to send to listening server
Returns:
Single binary stream of indicated file
"""
file_stream = b''
with open(self.atts.upload, 'rb') as file:
for ndx, line in enumerate(file):
file_stream = self.help.bin_join(file_stream, line)
return file_stream + b'\r\n'
if __name__ == '__main__':
nc = SSHCustom()
nc.main() | _netcat.py | import socket
import sys
import getopt
import threading
import subprocess
import getpass
from textwrap import dedent
from typing import Tuple, Union, List
class Helpers:
"""Static functions, to use as helpers"""
@staticmethod
def send_data(to_socket: socket.socket, data_stream: bytes,
send_timeout=2) -> None:
"""
Centralised function to handle sending data stream to receive data. Sends data in consistent
buffer sizes
Args:
to_socket:
Socket to send stream to
data_stream:
Data stream to send
send_timeout:
Set timeout for to_socket
"""
to_socket.settimeout(send_timeout)
try:
data_fragments = []
for i in range(0, len(data_stream), 4096):
# Break data stream into byte sized bites
data_fragments.append(data_stream[i:i + 4096])
if data_fragments[-1] == 4096:
# Make sure last fragment isn't BUFFER bytes long
data_fragments.append(b'\n')
for frag in data_fragments:
to_socket.send(frag)
except TimeoutError:
pass
@staticmethod
def receive_data(from_socket: socket.socket,
from_timeout=2) -> bytes:
"""
Centralised fuction to handle receiving one or more packet buffers from TCP socket
Args:
from_socket:
Socket sending stream to this instance.
from_timeout:
Set timeout for from_socket
Returns:
Complete binary stream from socket
"""
from_socket.settimeout(from_timeout)
fragments: List[bytes] = []
try:
stream = from_socket.recv(4096)
fragments.append(stream)
while True:
if len(stream) < 4096:
break
else:
stream = from_socket.recv(4096)
fragments.append(stream)
except TimeoutError:
pass
return b''.join(fragments)
@staticmethod
def bin_join(*to_join: Union[str, bytes]) -> bytes:
"""
Funnel function to reliably concatenate binary and strings into binaries. Can also be used
to ensure a single item is bytes string
Args:
to_join: Item/s to join together. Either bytes or regular strings
Return:
Properly concatenated bytes string
"""
binary_bytes = []
for item in to_join:
if not item:
pass
elif isinstance(item, int):
binary_bytes.append(str(item).encode())
elif isinstance(item, str):
binary_bytes.append(item.encode())
else:
binary_bytes.append(item)
return b''.join(binary_bytes)
@staticmethod
def bin_print(*to_display, end='\n'):
"""
Funnel function to reliably print binary or regular strings.
Args:
to_display:
Item/s to join together. Either bytes or regular strings
end:
default print end arg
"""
for item in to_display:
try:
print(item.decode(), end=end)
except AttributeError:
print(item, end=end)
class SshcAttributes:
"""Dataclass-like, used to host running SSHCustom's running attributes"""
# Carries defaults
@staticmethod
def usage():
"""Module docstring doubles as --help"""
print(__doc__)
exit()
def __init__(self):
if __name__ == '__main__' and len(sys.argv) == 1:
self.usage()
try:
opts, args = getopt.getopt(sys.argv[1:], "ht:p:k:bci:u:lw:e:sv",
['help', 'target=', 'port=', 'user=', 'pass=', 'banner'
'connect', 'initial=', 'upload=',
'listen', 'write=', 'execute=', 'shell', 'verbose'])
for opt, arg in opts:
if opt in ('-h', '--help'):
self.usage()
elif opt in ('-t', '--target'):
# self.target = arg
self.__setattr__('target', arg)
elif opt in ('-p', '--port'):
# self.port = arg
self.__setattr__('port', int(arg))
elif opt in ('-c', '--connecting'):
# self.connecting = True
self.__setattr__('connecting', True)
elif opt == 'k':
# self.known_hosts = arg
self.__setattr__('known_hosts', arg)
elif opt == 'user':
# self.user = arg
self.__setattr__('user', arg)
elif opt in ('b', '--banner'):
# self.banner = True
self.__setattr__('banner', True)
elif opt == 'pass':
# self.password = arg
self.__setattr__('password', arg)
elif opt in ('-u', '--upload'):
# self.upload = arg
self.__setattr__('upload', arg)
elif opt in ('-l', '--listen'):
# self.listening = True
self.__setattr__('upload', True)
elif opt in ('-w', '--write'):
# self.write_to = arg
self.__setattr__('write_to', arg)
elif opt in ('-e', '--execute'):
# self.execute = arg
self.__setattr__('execute', arg)
elif opt in ('-s', '--shell'):
# self.shell = True
self.__setattr__('shell', True)
elif opt in ('-v', '--verbose'):
# self.verbose = True
self.__setattr__('verbose', True)
elif not self.target or not self.port:
raise SyntaxError("Must explicitly state target IP and Port!")
elif True not in [not self.connecting or not self.listening]:
input((not self.connecting or not self.listening))
raise SyntaxError("Must explicitly state connecting or listening function!")
else:
raise SyntaxError(f"Unhandled option: {opt}")
except (getopt.GetoptError, SyntaxError) as err:
print(err)
self.usage()
target: str = '127.0.0.1'
"""Target IP"""
port: int = 9999
"""Target port"""
known_hosts = ''
"""Optional key support, using absolute path to .ssh/known_hosts"""
user: str = getpass.getuser()
"""Username to pass to custom server"""
password: str = None
"""password to sign in with"""
# Connecting functions
connecting: bool = False
"""Bool to connect to listening server on [host]:[port]"""
# Listening functions
listening: bool = False
"""Bool to listen on [host]:[port] for incoming connections"""
shell: bool = False
"""Initialize a shell loop, to run one-off commands by connecting clients"""
close_connection: str = 'bhpquit'
"""Specific command to disconnect connected client"""
shutdown_listening: str = 'bhpshutdown'
"""Specific command to shutdown listening script"""
listening_active: bool = False
"""Boolean used to keep server alive"""
timeout: int = 60
"""Listening server's Timeout value"""
verbose = True
""" """
class ShutdownServer(socket.error):
"""Custom error used to shutdown listening server"""
class ShutdownClient(socket.error):
"""Custom error used to safely disconnect connecting client"""
class SSHCustom:
"""
Dedicated SSH client and server, designed specifically for windows implementations
(Note that it's usefullness is arguably lessened by the lastest Win10's built in SSH port)
See --help for more information
"""
def __init__(self):
"""
Custom SSH Client/Server built on Paramiko API. Can be imported or run from command line.
See Readme or --help for more information
"""
self.atts: SshcAttributes = SshcAttributes()
"""Attributes module"""
self.help = Helpers()
"""Helper static functions"""
def verprint(self, *to_print) -> None:
"""
Default check against verbosity attribute, to see if allowed to print
Args:
*to_print: emulation of print *args. pass as normal
"""
if self.atts.verbose:
for item in to_print:
self.help.bin_print(item, end=' ')
print()
def main(self):
"""
Primary logic loop. After init, builds listening post or starts connecting client
"""
if self.atts.listening:
# Time to listen, potentially upload items, execute commands, and drop a shell back
child = SSHServer()
child.server()
else:
# Try connecting to target, send a potential starting command
child = SSHClient()
child.client()
class SSHServer(SSHCustom, paramiko.ServerInterface):
"""Custom SSH client, using Paramiko API wrapper"""
def __init__(self):
super(SSHServer, self).__init__()
# Extension to super init, name spacing an Event
self.event = threading.Event()
def server(self):
"""
Start a TCP server socket, spool threads to handle incoming clients
"""
self.verprint(f"[*] Listening on {self.atts.target}:{self.atts.port}")
try:
# Spool main SSH server
server = socket.socket()
# Bind socket settings
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((self.atts.target, self.atts.port))
server.listen(5)
while self.atts.listening_active:
server_acceptance = server.accept() # Tuple containing client_socket and addr
if self.atts.listening_active:
client_thread = threading.Thread(target=self.handle_connects,
args=(server_acceptance,))
client_thread.start()
except ShutdownServer:
print("")
except Exception as err:
closing = dedent(f"""
--[*] Unexpected error: {err}
----- Closing server""")
self.verprint(closing)
def handle_connects(self, connected_client: Tuple[socket.socket, any]):
"""
Called by server socket for each connection
Args:
connected_client:
Returns:
"""
# Identify target TCP connection
client_socket, addr = connected_client
client_socket.settimeout(self.atts.timeout)
self.verprint(f'--[*] Accepted connection, handler spooled for {addr[0]}:{addr[1]}')
closing = ''
try:
# Create SSH transport object over client_socket
ssh_session = paramiko.Transport(client_socket)
ssh_session.add_server_key(self.rsa_key)
ssh_session.start_server()
ssh_channel = ssh_session.accept(20)
buffer_stream = self.help.receive_data(ssh_channel)
"""Received buffer stream from connecting client"""
response = b''
"""First response to send to connecting client"""
# Determine if server set to init shell or not. Respond either way
if not self.atts.shell:
response = self.help.bin_join(
response, f"\nClosing connection to {self.atts.target}:{self.atts.port}")
self.help.send_data(to_socket=ssh_channel, data_stream=response)
else:
self.shell_loop(ssh_channel, response)
# # # Exception Handling
except ShutdownClient:
closing = dedent(f"""
--[*] Client requested connection close
----- Closing handler {addr[0]}:{addr[1]}
""")
except ShutdownServer:
closing = dedent(f"""
--[*] Client {addr[0]}:{addr[1]} requested shutdown listening post
----- Shutting down
""")
# self.atts.listening_active = False
raise ShutdownServer
except Exception as err:
closing = dedent(f"""
--[*] Unexpected error: {err}
----- Closing handler {addr[0]}:{addr[1]}
""")
finally:
self.verprint(closing)
# Low effort try to send to connected client
try:
self.help.send_data(to_socket=ssh_channel,
data_stream=self.help.bin_join(closing))
# client_socket.shutdown(socket.SHUT_RDWR)
# client_socket.close()
ssh_channel.close()
except Exception as err:
self.verprint(f"Unexpected error while closing handler {addr[0]}:{addr[1]} : ")
self.verprint(err)
def check_for_commands(self, stream: bytes):
"""
Given a datastream, check if a closing command is in it. Raise appropriate handling error
Args:
stream: bytes stream sent from connecting client, to check for bhp commands
"""
# Catch bhp specific commands in stream
if self.atts.close_connection in str(stream):
raise ShutdownClient
if self.atts.shutdown_listening in str(stream):
raise ShutdownServer
def write_file(self, data_buffer) -> bytes:
"""
If allowed, Extension to write a caught data_buffer to local file (self.write_to)
Return feedback to calling functions
Args:
data_buffer: handle_connects's received data stream from it's client_socket.
Returns:
File write feedback, either successful or failure with error
if write_to is None (i.e. not set) return empty bytes string
"""
send_feedback = ''
if self.atts.write_to:
try:
with open(self.atts.write_to, "wb") as file:
file.write(data_buffer)
send_feedback = f"Successfully saved file to {self.atts.write_to}\r\n"
except Exception as err:
send_feedback = f"""Failed to save file to {self.atts.write_to}\r\n{err}\r\n"""
return self.help.bin_join(send_feedback)
def run_command(self, command: Union[str, bytes, None]) -> bytes:
"""
Locally run given command using subprocess, and return results as bytes string
Args:
command: given command to run
"""
if not command:
command_run = ''
elif isinstance(command, bytes):
command_run = command.decode()
else:
command_run = command
try:
output = subprocess.check_output(command_run, stderr=subprocess.STDOUT, shell=True)
except Exception as err:
output = dedent(f"""
Failed to execute command
Command : {command_run}
Error : {err}\r\n""")
return self.help.bin_join(output)
def shell_loop(self, client_socket: socket.socket, initial_response: bytes):
"""
Function to handle one off commands from connecting client. Loops until connection broken.
Args:
client_socket: Answered socket to accept shell commands from
initial_response: Initial response from handle_connects' steps, if any.
Passed here so shell loop can return, with prompt characters
"""
response = initial_response
prompt = f'\n<BHP@{self.atts.target}:{self.atts.port}>#'
while True:
# Loop is broken by explicit errors or commands
self.help.send_data(to_socket=client_socket,
data_stream=self.help.bin_join(response, prompt))
try:
cmd_buffer = self.help.receive_data(from_socket=client_socket)
self.check_for_commands(cmd_buffer)
response = self.run_command(cmd_buffer)
except TimeoutError:
raise TimeoutError("Listening server timeout reached")
except Exception as err:
raise err
class SSHClient(SSHCustom):
"""Custom SSH Client, , using paramiko API wrapper"""
def client(self):
"""
Spool up TCP socket, catch return data, prompt for new to_send. Rinse and repeat
"""
self.verprint(f"Connecting to {self.atts.target}:{self.atts.port}...")
# Bind new SSH client
client = paramiko.SSHClient()
try:
# Optional key support
if self.atts.known_hosts:
client.load_host_keys(self.atts.known_hosts)
# Auto add missing keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect
client.connect(self.atts.target, port=self.atts.port,
username=self.atts.user, password=<PASSWORD>)
# request session channel to server
ssh_session = client.get_transport().open_session()
# Catch banner
if self.atts.banner:
banner = self.help.receive_data(ssh_session)
self.help.bin_print(banner)
# Build initial data to send
if self.atts.upload:
to_send = self.file_stream()
else:
to_send = self.help.bin_join(self.atts.initial_cmd, '\n')
# Primary running loop
while True:
self.help.send_data(ssh_session, to_send)
server_response = self.help.receive_data(ssh_session)
self.help.bin_print('\n', server_response, end=' ')
to_send = input() + '\n'
# # # Exception Handling
except KeyboardInterrupt:
self.verprint("Disconnecting")
pass
except ConnectionRefusedError:
self.verprint('Cannot connect, is listening active?')
except ConnectionAbortedError:
# Socket closed by listener
self.verprint("Closing connection...")
except ConnectionResetError:
self.verprint("Connection prematurely closed. Did server shutdown?")
except Exception as err:
self.verprint("Unknown error!\n", err, "\nDisconnecting")
finally:
try:
# client.shutdown(socket.SHUT_RDWR)
# ssh_session.close()
client.close()
except Exception as err:
self.verprint(
f"Unexpected error when disconnecting from {self.atts.target}:{self.atts.port}")
self.verprint(err)
def file_stream(self):
"""
Targets file at upload and converts to binary stream, to send to listening server
Returns:
Single binary stream of indicated file
"""
file_stream = b''
with open(self.atts.upload, 'rb') as file:
for ndx, line in enumerate(file):
file_stream = self.help.bin_join(file_stream, line)
return file_stream + b'\r\n'
if __name__ == '__main__':
nc = SSHCustom()
nc.main() | 0.52756 | 0.09314 |
import sys, os
import numpy as np
import yaml
def detect_images_type(folder):
images = []
if not os.path.isdir(folder):
raise Exception('{} does not exist'.format(folder))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(folder)):
for fname in sorted(fnames):
tmp_type = fname[fname.find('.')+1:]
if tmp_type in ['jpg', 'jpeg', 'png', 'ppm', 'bmp']:
return tmp_type
break
return ''
def load_allimages_list(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = path
images.append(item)
return images
def load_allimages_list_norec(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = path
images.append(item)
break
return images
def load_allimages_wopath(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
images.append(fname)
break
return images
def load_allmats(dir):
images = []
if not os.path.isdir(dir):
raise Exception('failed to load mats in folder {}'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.mat')):
path = os.path.join(root, fname)
item = path
images.append(item)
return images
def load_allimages(dir):
images = []
if not os.path.isdir(dir):
raise Exception('failed to load images in folder {}'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = (path, 0)
images.append(item)
break
return images
def ensure_dir(file_path):
if not os.path.exists(file_path):
os.makedirs(file_path) | src/utils.py | import sys, os
import numpy as np
import yaml
def detect_images_type(folder):
images = []
if not os.path.isdir(folder):
raise Exception('{} does not exist'.format(folder))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(folder)):
for fname in sorted(fnames):
tmp_type = fname[fname.find('.')+1:]
if tmp_type in ['jpg', 'jpeg', 'png', 'ppm', 'bmp']:
return tmp_type
break
return ''
def load_allimages_list(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = path
images.append(item)
return images
def load_allimages_list_norec(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = path
images.append(item)
break
return images
def load_allimages_wopath(dir):
images = []
if not os.path.isdir(dir):
raise Exception('{} does not exist'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
images.append(fname)
break
return images
def load_allmats(dir):
images = []
if not os.path.isdir(dir):
raise Exception('failed to load mats in folder {}'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.mat')):
path = os.path.join(root, fname)
item = path
images.append(item)
return images
def load_allimages(dir):
images = []
if not os.path.isdir(dir):
raise Exception('failed to load images in folder {}'.format(dir))
sys.exit(-1)
for root, _, fnames in sorted(os.walk(dir)):
for fname in sorted(fnames):
if (fname.endswith('.jpg') or
fname.endswith('.jpeg') or
fname.endswith('.png') or
fname.endswith('.ppm') or
fname.endswith('.bmp')):
path = os.path.join(root, fname)
item = (path, 0)
images.append(item)
break
return images
def ensure_dir(file_path):
if not os.path.exists(file_path):
os.makedirs(file_path) | 0.130368 | 0.109182 |
import os
import cv2
import pickle
import imutils
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as prfs
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential, load_model, save_model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Dropout, Dense, Flatten
def load_data(data_path):
X = []
y = []
labels = os.listdir(data_path)
img_path_per_label = {labels[i]: [os.path.join(data_path, labels[i], img_path) for img_path in os.listdir(data_path + '/' + labels[i])] for i in range(len(labels))}
for key in list(img_path_per_label.keys()):
for img_path in img_path_per_label[key]:
X.append(cv2.resize(cv2.imread(img_path), (30, 30), interpolation=cv2.INTER_BITS2))
y.append(key)
return np.array(X), np.array(y)
def increase_brightness(img, value=20):
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv_img)
limit = 255 - value
v[v <= limit] += value
v[v > limit] = 255
final_hsv = cv2.merge((h, s, v))
return cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
def display_random_set(data, labels):
for i in range(10):
random_val = np.random.randint(low=0, high=len(data))
plt.subplot(2, 5, (i + 1))
plt.imshow(imutils.opencv2matplotlib(data[random_val]))
plt.title(labels[random_val])
plt.axis(False)
plt.show()
def build_model(num_classes, img_dim):
model = Sequential()
model.add(Conv2D(filters=64, kernel_size=(2, 2), padding='same', activation='relu', input_shape=img_dim))
model.add(BatchNormalization())
model.add(Conv2D(filters=64, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=128, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(filters=128, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
sgd = SGD(learning_rate=0.001, nesterov=True, name='SGD_Optimizer')
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['categorical_accuracy', 'mse'])
print(model.summary())
return model
def train_model(x, y, x_val, y_val, model, train=False):
batch_size = 64
num_epochs = 25
if train:
checkpoint = ModelCheckpoint(filepath='traffic_sign_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
history = model.fit(x=x, y=y, validation_data=(x_val, y_val), shuffle=True, batch_size=batch_size, epochs=num_epochs, callbacks=[checkpoint], verbose=1)
save_history_file(file_name='traffic_sign.pickle', history=history)
def save_history_file(file_name, history):
pickle_out = open(file_name, 'wb')
pickle.dump(history.history, pickle_out)
pickle_out.close()
def load_history(file_name):
pickle_in = open(file_name, 'rb')
saved_hist = pickle.load(pickle_in)
return saved_hist
def plot_curves(history):
plt.figure(figsize=(10, 5))
sns.set_style(style='dark')
plt.subplot(1, 2, 1)
plt.plot(history['loss'])
plt.plot(history['val_loss'])
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.title('Training & Validation Loss')
plt.legend(['Train loss', 'Validation loss'])
plt.subplot(1, 2, 2)
plt.plot(history['mse'])
plt.plot(history['val_mse'])
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.title('Training & Validation MSE')
plt.legend(['Train mse', 'Validation mse'])
plt.show()
def accuracy_per_class(labels, precision, recall, f1):
# plt.subplots(figsize=(18, 30))
x = range(len(labels))
plt.subplot(3, 1, 1)
plt.title("Precision per class")
plt.ylim(0, 1.00)
plt.bar(x, precision, color='Red')
plt.xticks(x, rotation=90)
plt.subplot(312)
plt.title('Recall per class')
plt.ylim(0, 1.00)
plt.bar(x, recall, color='Green')
plt.xticks(x, rotation=90)
plt.subplot(313)
plt.title('F1 score per class')
plt.ylim(0, 1.00)
plt.bar(x, f1, color='Blue')
plt.xticks(x, rotation=90)
plt.show()
def load_test_data(test_data_dir, test_data_labels_dir):
# reading csv file
data = np.loadtxt(test_data_labels_dir, delimiter=',', skiprows=1, dtype=str)
x_test = np.array([os.path.join(test_data_dir, img_name) for img_name in data[:, 0]])
x_test = np.array([cv2.resize(cv2.imread(img_path), (30, 30), interpolation=cv2.INTER_BITS2) for img_path in x_test])
y_test = np.array(data[:, 1]).astype(np.int)
return x_test, y_test
def main():
# Reading Data from folders
X, y = load_data(data_path='./crop_dataset/crop_dataset/')
print(f"Data shape: {X.shape}, Labels: {y.shape}\n")
# Displaying random set of images from data
display_random_set(data=X, labels=y)
# Splitting data into training and testing data, training will consist of 70% of the data and 30% of the remaining
# will be testing data.
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42, shuffle=True)
print(f"Training Data: {x_train.shape}, Training labels: {y_train.shape}\nValidation Data: {x_val.shape}, "
f"Validation labels: {y_val.shape}\n")
# Adjusting labels to be represented as categorical data.
y_train = to_categorical(y=y_train, num_classes=len(np.unique(y)))
y_val = to_categorical(y=y_val, num_classes=len(np.unique(y)))
# Creating Neural network model.
model = build_model(num_classes=len(np.unique(y)), img_dim=x_train[0].shape)
# To train the model again change train value to True, change to False to not train.
train_model(x=x_train, y=y_train, x_val=x_val, y_val=y_val, model=model, train=True)
print("[In progress] Loading H5 model and history file...")
classifier = load_model(filepath='traffic_sign_model.h5')
hist_loaded = load_history(file_name='traffic_sign.pickle')
print("[Done] Loading H5 model and history file...")
# Loading data for testing model.
x_test, y_test = load_test_data(test_data_dir='./test_data/test_data', test_data_labels_dir='./test_labels.csv')
predictions = classifier.predict_classes(x_test)
accuracy = np.array([1 if predictions[i] == int(y_test[i]) else 0 for i in range(len(predictions))])
print(f"Accuracy on test data: {np.mean(accuracy) * 100} %.")
# plotting loss and mse curves for training and validation steps
plot_curves(hist_loaded)
# plotting accuracy bar graph per class
labels = np.unique(y)
precision, recall, f1, support = prfs(y_true=y_test, y_pred=predictions, average=None)
accuracy_per_class(labels, precision, recall, f1)
if __name__ == '__main__':
main() | traffic_sign_classifier.py | import os
import cv2
import pickle
import imutils
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import precision_recall_fscore_support as prfs
from tensorflow.keras.optimizers import Adam, SGD
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential, load_model, save_model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Dropout, Dense, Flatten
def load_data(data_path):
X = []
y = []
labels = os.listdir(data_path)
img_path_per_label = {labels[i]: [os.path.join(data_path, labels[i], img_path) for img_path in os.listdir(data_path + '/' + labels[i])] for i in range(len(labels))}
for key in list(img_path_per_label.keys()):
for img_path in img_path_per_label[key]:
X.append(cv2.resize(cv2.imread(img_path), (30, 30), interpolation=cv2.INTER_BITS2))
y.append(key)
return np.array(X), np.array(y)
def increase_brightness(img, value=20):
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv_img)
limit = 255 - value
v[v <= limit] += value
v[v > limit] = 255
final_hsv = cv2.merge((h, s, v))
return cv2.cvtColor(final_hsv, cv2.COLOR_HSV2BGR)
def display_random_set(data, labels):
for i in range(10):
random_val = np.random.randint(low=0, high=len(data))
plt.subplot(2, 5, (i + 1))
plt.imshow(imutils.opencv2matplotlib(data[random_val]))
plt.title(labels[random_val])
plt.axis(False)
plt.show()
def build_model(num_classes, img_dim):
model = Sequential()
model.add(Conv2D(filters=64, kernel_size=(2, 2), padding='same', activation='relu', input_shape=img_dim))
model.add(BatchNormalization())
model.add(Conv2D(filters=64, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(filters=128, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Conv2D(filters=128, kernel_size=(2, 2), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.1))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(256, activation='relu'))
model.add(Dense(64, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
sgd = SGD(learning_rate=0.001, nesterov=True, name='SGD_Optimizer')
model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['categorical_accuracy', 'mse'])
print(model.summary())
return model
def train_model(x, y, x_val, y_val, model, train=False):
batch_size = 64
num_epochs = 25
if train:
checkpoint = ModelCheckpoint(filepath='traffic_sign_model.h5', monitor='val_loss', save_best_only=True, verbose=1)
history = model.fit(x=x, y=y, validation_data=(x_val, y_val), shuffle=True, batch_size=batch_size, epochs=num_epochs, callbacks=[checkpoint], verbose=1)
save_history_file(file_name='traffic_sign.pickle', history=history)
def save_history_file(file_name, history):
pickle_out = open(file_name, 'wb')
pickle.dump(history.history, pickle_out)
pickle_out.close()
def load_history(file_name):
pickle_in = open(file_name, 'rb')
saved_hist = pickle.load(pickle_in)
return saved_hist
def plot_curves(history):
plt.figure(figsize=(10, 5))
sns.set_style(style='dark')
plt.subplot(1, 2, 1)
plt.plot(history['loss'])
plt.plot(history['val_loss'])
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.title('Training & Validation Loss')
plt.legend(['Train loss', 'Validation loss'])
plt.subplot(1, 2, 2)
plt.plot(history['mse'])
plt.plot(history['val_mse'])
plt.xlabel('Iterations')
plt.ylabel('Error')
plt.title('Training & Validation MSE')
plt.legend(['Train mse', 'Validation mse'])
plt.show()
def accuracy_per_class(labels, precision, recall, f1):
# plt.subplots(figsize=(18, 30))
x = range(len(labels))
plt.subplot(3, 1, 1)
plt.title("Precision per class")
plt.ylim(0, 1.00)
plt.bar(x, precision, color='Red')
plt.xticks(x, rotation=90)
plt.subplot(312)
plt.title('Recall per class')
plt.ylim(0, 1.00)
plt.bar(x, recall, color='Green')
plt.xticks(x, rotation=90)
plt.subplot(313)
plt.title('F1 score per class')
plt.ylim(0, 1.00)
plt.bar(x, f1, color='Blue')
plt.xticks(x, rotation=90)
plt.show()
def load_test_data(test_data_dir, test_data_labels_dir):
# reading csv file
data = np.loadtxt(test_data_labels_dir, delimiter=',', skiprows=1, dtype=str)
x_test = np.array([os.path.join(test_data_dir, img_name) for img_name in data[:, 0]])
x_test = np.array([cv2.resize(cv2.imread(img_path), (30, 30), interpolation=cv2.INTER_BITS2) for img_path in x_test])
y_test = np.array(data[:, 1]).astype(np.int)
return x_test, y_test
def main():
# Reading Data from folders
X, y = load_data(data_path='./crop_dataset/crop_dataset/')
print(f"Data shape: {X.shape}, Labels: {y.shape}\n")
# Displaying random set of images from data
display_random_set(data=X, labels=y)
# Splitting data into training and testing data, training will consist of 70% of the data and 30% of the remaining
# will be testing data.
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42, shuffle=True)
print(f"Training Data: {x_train.shape}, Training labels: {y_train.shape}\nValidation Data: {x_val.shape}, "
f"Validation labels: {y_val.shape}\n")
# Adjusting labels to be represented as categorical data.
y_train = to_categorical(y=y_train, num_classes=len(np.unique(y)))
y_val = to_categorical(y=y_val, num_classes=len(np.unique(y)))
# Creating Neural network model.
model = build_model(num_classes=len(np.unique(y)), img_dim=x_train[0].shape)
# To train the model again change train value to True, change to False to not train.
train_model(x=x_train, y=y_train, x_val=x_val, y_val=y_val, model=model, train=True)
print("[In progress] Loading H5 model and history file...")
classifier = load_model(filepath='traffic_sign_model.h5')
hist_loaded = load_history(file_name='traffic_sign.pickle')
print("[Done] Loading H5 model and history file...")
# Loading data for testing model.
x_test, y_test = load_test_data(test_data_dir='./test_data/test_data', test_data_labels_dir='./test_labels.csv')
predictions = classifier.predict_classes(x_test)
accuracy = np.array([1 if predictions[i] == int(y_test[i]) else 0 for i in range(len(predictions))])
print(f"Accuracy on test data: {np.mean(accuracy) * 100} %.")
# plotting loss and mse curves for training and validation steps
plot_curves(hist_loaded)
# plotting accuracy bar graph per class
labels = np.unique(y)
precision, recall, f1, support = prfs(y_true=y_test, y_pred=predictions, average=None)
accuracy_per_class(labels, precision, recall, f1)
if __name__ == '__main__':
main() | 0.641422 | 0.368178 |
from mypkg.db_settings import session
from prompt_toolkit.application import Application
from prompt_toolkit.layout import HSplit, VSplit, Layout, DummyControl, Window
from prompt_toolkit.widgets import Label, TextArea, Frame
from prompt_toolkit.styles import Style
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
from mypkg.prompts.components import generate_main_chunk_components, generate_screen_title_label, generate_chunk_with_diff_screen, generate_move_button, generate_other_chunk_components, ChunkState, generate_diff_screen
from enum import Enum, auto
class ExitState(Enum):
NORMAL = auto()
APPEND = auto()
REMOVE = auto()
def generate_main_screen(chunk_sets, cur_chunk_set_idx, related_chunks):
#main chunks components
chunk_set = chunk_sets[cur_chunk_set_idx]
add_chunks, remove_chunks = chunk_set.add_chunks, chunk_set.remove_chunks
diff_text, diff_area, all_chunks, chunk_state_list, chunk_with_check_boxes, check_boxes = generate_main_chunk_components(add_chunks, remove_chunks)
#related and pending chunks components
all_related_chunks, related_state_list, related_with_check_boxes, related_check_boxes = generate_other_chunk_components(related_chunks, diff_text)
# commit message input field
commit_msg_input = TextArea(
height=3,
prompt="",
text=chunk_set.message,
multiline=True,
wrap_lines=False,
)
# exit button and process
is_not_first = cur_chunk_set_idx > 0
is_not_last = cur_chunk_set_idx < len(chunk_sets) - 1
if is_not_first:
prev_chunk = chunk_sets[cur_chunk_set_idx - 1]
else:
prev_chunk = None
if is_not_last:
next_chunk = chunk_sets[cur_chunk_set_idx + 1]
else:
next_chunk = None
def commit_staged_chunks():
chunk_set.message = commit_msg_input.text
session.commit()
index = 0
cur_chunks = []
cur_chunks.extend(add_chunks)
cur_chunks.extend(remove_chunks)
cur_chunks = sorted(cur_chunks, key = lambda x: (x.context.path, x.start_id))
for cur_chunk in cur_chunks:
chunk_state = chunk_state_list[index]
if chunk_state == ChunkState.PREV and prev_chunk:
cur_chunk.chunk_set_id = prev_chunk.id
elif chunk_state == ChunkState.NEXT and next_chunk:
cur_chunk.chunk_set_id = next_chunk.id
elif chunk_state == ChunkState.PENDING:
cur_chunk.chunk_set_id = None
index += 1
session.commit()
def assign_selected_chunks(chunks, states):
index = 0
chunks_sorted = sorted(chunks, key = lambda x: (x.context.path, x.start_id))
for chunk in chunks_sorted:
state = states[index]
if state == ChunkState.ASSIGN:
chunk.chunk_set_id = chunk_set.id
index += 1
session.commit()
def common_exit_process():
commit_staged_chunks()
assign_selected_chunks(related_chunks, related_state_list)
def remove_exit_process():
cur_chunks = []
cur_chunks.extend(add_chunks)
cur_chunks.extend(remove_chunks)
for cur_chunk in cur_chunks:
cur_chunk.chunk_set_id = None
session.commit()
prev_chunk_kb, next_chunk_kb = KeyBindings(), KeyBindings()
@prev_chunk_kb.add("c-m")
def _(event):
common_exit_process()
event.app.exit(result=(cur_chunk_set_idx - 1, ExitState.NORMAL))
@next_chunk_kb.add("c-m")
def _(event):
common_exit_process()
event.app.exit(result=(cur_chunk_set_idx + 1, ExitState.NORMAL))
if is_not_first:
prev_chunk_button_style = "class:prev-chunk-button"
prev_button_label = "Prev Commit"
else:
prev_chunk_button_style = prev_button_label = ""
if is_not_last:
next_chunk_button_style = "class:next-chunk-button-normal"
next_button_label = "Next Commit"
else:
next_chunk_button_style = "class:next-chunk-button-last"
next_button_label = "Make commits!"
prev_chunk_button = generate_move_button(prev_button_label, is_not_first, prev_chunk_kb, prev_chunk_button_style)
next_chunk_button = generate_move_button(next_button_label, True, next_chunk_kb, next_chunk_button_style)
root_container = HSplit(
[
VSplit(
[
Window(DummyControl()),
Window(DummyControl()),
Label(text="Commit Number: {} / {}".format(cur_chunk_set_idx + 1, len(chunk_sets)), style="class:page-label"),
Window(DummyControl()),
Window(DummyControl())
]
),
VSplit(
[
HSplit(
[
generate_screen_title_label("Current commit({} chunks)".format(len(add_chunks) + len(remove_chunks)), "class:page-num"),
generate_chunk_with_diff_screen(chunk_with_check_boxes),
generate_screen_title_label("Related and Pending Chunks({} chunks)".format(len(related_chunks)), "class:related-label"),
generate_chunk_with_diff_screen(related_with_check_boxes),
]
),
generate_diff_screen(diff_area)
]
),
Label(text="Commit Message"),
Frame(commit_msg_input),
VSplit(
[
prev_chunk_button,
next_chunk_button,
]
),
]
)
# define styles
style = Style(
[
("left-pane", "bg:#454545 #ffffff"),
("right-pane", "bg:#000000 #ffffff"),
("add-chunk", "bg:#006600 #ffffff"),
("remove-chunk", "bg:#880000 #ffffff"),
("chunk-sets", "bg:#454545 #ffffff"),
("check-box", "bg:#151515 #ffffff"),
("prev-chunk-button", "bg:#b22222 #ffffff"),
("next-chunk-button-last", "bg:#ffff00 #000000 bold"),
("next-chunk-button-normal", "bg:#00bfff #ffffff"),
("page-num", "bg:#ffbf7f #000000"),
("related-label", "bg:#6395ed #000000"),
("pending-label", "bg:#2e8b57 #000000"),
("target-add-line", "#4DD45B underline"),
("target-remove-line", "#D44D55 underline"),
("other-add-line", "#4DD45B"),
("other-remove-line", "#D44D55"),
("label-back", "bg:#C4C4C4 #ffffff"),
("patch-label", "bg:#454545 #ffffff"),
("path-label", "bg:#E8C56D #000000"),
("page-label", "bg:#ffffff #000000")
]
)
# define key bindings
gen_kb = KeyBindings()
gen_kb.add("down")(focus_next)
gen_kb.add("up")(focus_previous)
@gen_kb.add("c-q")
def _(event):
event.app.exit()
@gen_kb.add("c-v")
def _(event):
event.app.exit(result=(cur_chunk_set_idx, ExitState.APPEND))
@gen_kb.add("c-s")
def _(event):
remove_exit_process()
event.app.exit(result=(cur_chunk_set_idx, ExitState.REMOVE))
@gen_kb.add("c-t")
def _(event):
event.app.layout.focus(commit_msg_input)
@gen_kb.add("c-f")
def _(event):
if all_chunks:
event.app.layout.focus(all_chunks[0])
@gen_kb.add("c-r")
def _(event):
if all_related_chunks:
event.app.layout.focus(all_related_chunks[0])
@gen_kb.add("c-p")
def _(event):
if is_not_first:
event.app.layout.focus(prev_chunk_button)
@gen_kb.add("c-n")
def _(event):
event.app.layout.focus(next_chunk_button)
@gen_kb.add("c-a")
def _(event):
for check_box in check_boxes:
check_box.text = " [*]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.KEEP
@gen_kb.add("c-d")
def _(event):
for check_box in check_boxes:
check_box.text = " [ ]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.PENDING
@gen_kb.add("s-left")
def _(event):
for check_box in check_boxes:
check_box.text = " [<]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.PREV
@gen_kb.add("s-right")
def _(event):
for check_box in check_boxes:
check_box.text = " [>]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.NEXT
@gen_kb.add("tab")
def _(event):
for check_box in related_check_boxes:
check_box.text = " [*]"
for i in range(len(related_state_list)):
related_state_list[i] = ChunkState.ASSIGN
@gen_kb.add("s-tab")
def _(event):
for check_box in related_check_boxes:
check_box.text = " [ ]"
for i in range(len(related_state_list)):
related_state_list[i] = ChunkState.KEEP
# define layout and application
layout = Layout(container=root_container, focused_element=next_chunk_button)
application = Application(layout=layout, key_bindings=gen_kb, style=style, full_screen=True, mouse_support=True)
return application | mypkg/prompts/main_prompt.py | from mypkg.db_settings import session
from prompt_toolkit.application import Application
from prompt_toolkit.layout import HSplit, VSplit, Layout, DummyControl, Window
from prompt_toolkit.widgets import Label, TextArea, Frame
from prompt_toolkit.styles import Style
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
from mypkg.prompts.components import generate_main_chunk_components, generate_screen_title_label, generate_chunk_with_diff_screen, generate_move_button, generate_other_chunk_components, ChunkState, generate_diff_screen
from enum import Enum, auto
class ExitState(Enum):
NORMAL = auto()
APPEND = auto()
REMOVE = auto()
def generate_main_screen(chunk_sets, cur_chunk_set_idx, related_chunks):
#main chunks components
chunk_set = chunk_sets[cur_chunk_set_idx]
add_chunks, remove_chunks = chunk_set.add_chunks, chunk_set.remove_chunks
diff_text, diff_area, all_chunks, chunk_state_list, chunk_with_check_boxes, check_boxes = generate_main_chunk_components(add_chunks, remove_chunks)
#related and pending chunks components
all_related_chunks, related_state_list, related_with_check_boxes, related_check_boxes = generate_other_chunk_components(related_chunks, diff_text)
# commit message input field
commit_msg_input = TextArea(
height=3,
prompt="",
text=chunk_set.message,
multiline=True,
wrap_lines=False,
)
# exit button and process
is_not_first = cur_chunk_set_idx > 0
is_not_last = cur_chunk_set_idx < len(chunk_sets) - 1
if is_not_first:
prev_chunk = chunk_sets[cur_chunk_set_idx - 1]
else:
prev_chunk = None
if is_not_last:
next_chunk = chunk_sets[cur_chunk_set_idx + 1]
else:
next_chunk = None
def commit_staged_chunks():
chunk_set.message = commit_msg_input.text
session.commit()
index = 0
cur_chunks = []
cur_chunks.extend(add_chunks)
cur_chunks.extend(remove_chunks)
cur_chunks = sorted(cur_chunks, key = lambda x: (x.context.path, x.start_id))
for cur_chunk in cur_chunks:
chunk_state = chunk_state_list[index]
if chunk_state == ChunkState.PREV and prev_chunk:
cur_chunk.chunk_set_id = prev_chunk.id
elif chunk_state == ChunkState.NEXT and next_chunk:
cur_chunk.chunk_set_id = next_chunk.id
elif chunk_state == ChunkState.PENDING:
cur_chunk.chunk_set_id = None
index += 1
session.commit()
def assign_selected_chunks(chunks, states):
index = 0
chunks_sorted = sorted(chunks, key = lambda x: (x.context.path, x.start_id))
for chunk in chunks_sorted:
state = states[index]
if state == ChunkState.ASSIGN:
chunk.chunk_set_id = chunk_set.id
index += 1
session.commit()
def common_exit_process():
commit_staged_chunks()
assign_selected_chunks(related_chunks, related_state_list)
def remove_exit_process():
cur_chunks = []
cur_chunks.extend(add_chunks)
cur_chunks.extend(remove_chunks)
for cur_chunk in cur_chunks:
cur_chunk.chunk_set_id = None
session.commit()
prev_chunk_kb, next_chunk_kb = KeyBindings(), KeyBindings()
@prev_chunk_kb.add("c-m")
def _(event):
common_exit_process()
event.app.exit(result=(cur_chunk_set_idx - 1, ExitState.NORMAL))
@next_chunk_kb.add("c-m")
def _(event):
common_exit_process()
event.app.exit(result=(cur_chunk_set_idx + 1, ExitState.NORMAL))
if is_not_first:
prev_chunk_button_style = "class:prev-chunk-button"
prev_button_label = "Prev Commit"
else:
prev_chunk_button_style = prev_button_label = ""
if is_not_last:
next_chunk_button_style = "class:next-chunk-button-normal"
next_button_label = "Next Commit"
else:
next_chunk_button_style = "class:next-chunk-button-last"
next_button_label = "Make commits!"
prev_chunk_button = generate_move_button(prev_button_label, is_not_first, prev_chunk_kb, prev_chunk_button_style)
next_chunk_button = generate_move_button(next_button_label, True, next_chunk_kb, next_chunk_button_style)
root_container = HSplit(
[
VSplit(
[
Window(DummyControl()),
Window(DummyControl()),
Label(text="Commit Number: {} / {}".format(cur_chunk_set_idx + 1, len(chunk_sets)), style="class:page-label"),
Window(DummyControl()),
Window(DummyControl())
]
),
VSplit(
[
HSplit(
[
generate_screen_title_label("Current commit({} chunks)".format(len(add_chunks) + len(remove_chunks)), "class:page-num"),
generate_chunk_with_diff_screen(chunk_with_check_boxes),
generate_screen_title_label("Related and Pending Chunks({} chunks)".format(len(related_chunks)), "class:related-label"),
generate_chunk_with_diff_screen(related_with_check_boxes),
]
),
generate_diff_screen(diff_area)
]
),
Label(text="Commit Message"),
Frame(commit_msg_input),
VSplit(
[
prev_chunk_button,
next_chunk_button,
]
),
]
)
# define styles
style = Style(
[
("left-pane", "bg:#454545 #ffffff"),
("right-pane", "bg:#000000 #ffffff"),
("add-chunk", "bg:#006600 #ffffff"),
("remove-chunk", "bg:#880000 #ffffff"),
("chunk-sets", "bg:#454545 #ffffff"),
("check-box", "bg:#151515 #ffffff"),
("prev-chunk-button", "bg:#b22222 #ffffff"),
("next-chunk-button-last", "bg:#ffff00 #000000 bold"),
("next-chunk-button-normal", "bg:#00bfff #ffffff"),
("page-num", "bg:#ffbf7f #000000"),
("related-label", "bg:#6395ed #000000"),
("pending-label", "bg:#2e8b57 #000000"),
("target-add-line", "#4DD45B underline"),
("target-remove-line", "#D44D55 underline"),
("other-add-line", "#4DD45B"),
("other-remove-line", "#D44D55"),
("label-back", "bg:#C4C4C4 #ffffff"),
("patch-label", "bg:#454545 #ffffff"),
("path-label", "bg:#E8C56D #000000"),
("page-label", "bg:#ffffff #000000")
]
)
# define key bindings
gen_kb = KeyBindings()
gen_kb.add("down")(focus_next)
gen_kb.add("up")(focus_previous)
@gen_kb.add("c-q")
def _(event):
event.app.exit()
@gen_kb.add("c-v")
def _(event):
event.app.exit(result=(cur_chunk_set_idx, ExitState.APPEND))
@gen_kb.add("c-s")
def _(event):
remove_exit_process()
event.app.exit(result=(cur_chunk_set_idx, ExitState.REMOVE))
@gen_kb.add("c-t")
def _(event):
event.app.layout.focus(commit_msg_input)
@gen_kb.add("c-f")
def _(event):
if all_chunks:
event.app.layout.focus(all_chunks[0])
@gen_kb.add("c-r")
def _(event):
if all_related_chunks:
event.app.layout.focus(all_related_chunks[0])
@gen_kb.add("c-p")
def _(event):
if is_not_first:
event.app.layout.focus(prev_chunk_button)
@gen_kb.add("c-n")
def _(event):
event.app.layout.focus(next_chunk_button)
@gen_kb.add("c-a")
def _(event):
for check_box in check_boxes:
check_box.text = " [*]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.KEEP
@gen_kb.add("c-d")
def _(event):
for check_box in check_boxes:
check_box.text = " [ ]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.PENDING
@gen_kb.add("s-left")
def _(event):
for check_box in check_boxes:
check_box.text = " [<]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.PREV
@gen_kb.add("s-right")
def _(event):
for check_box in check_boxes:
check_box.text = " [>]"
for i in range(len(chunk_state_list)):
chunk_state_list[i] = ChunkState.NEXT
@gen_kb.add("tab")
def _(event):
for check_box in related_check_boxes:
check_box.text = " [*]"
for i in range(len(related_state_list)):
related_state_list[i] = ChunkState.ASSIGN
@gen_kb.add("s-tab")
def _(event):
for check_box in related_check_boxes:
check_box.text = " [ ]"
for i in range(len(related_state_list)):
related_state_list[i] = ChunkState.KEEP
# define layout and application
layout = Layout(container=root_container, focused_element=next_chunk_button)
application = Application(layout=layout, key_bindings=gen_kb, style=style, full_screen=True, mouse_support=True)
return application | 0.225672 | 0.103703 |
import os
from test.data import TEST_DATA_DIR, bob, cheese, hates, likes, michel, pizza, tarek
from rdflib import Dataset, URIRef
timblcardn3 = open(os.path.join(TEST_DATA_DIR, "timbl-card.n3")).read()
def add_stuff(graph):
graph.add((tarek, likes, pizza))
graph.add((tarek, likes, cheese))
graph.add((tarek, likes, bob))
graph.add((tarek, likes, michel))
graph.add((michel, likes, pizza))
graph.add((michel, likes, cheese))
graph.add((michel, likes, tarek))
graph.add((bob, likes, cheese))
graph.add((bob, hates, pizza))
graph.add((bob, hates, michel))
graph.add((bob, likes, tarek))
def test_unique_subjects():
graph = Dataset()
add_stuff(graph)
assert len([sub for sub in graph.subjects()]) == 11
assert len([sub for sub in graph.subjects(unique=True)]) == 3
def test_unique_predicates():
graph = Dataset()
add_stuff(graph)
assert len([pred for pred in graph.predicates()]) == 11
assert len([pred for pred in graph.predicates(unique=True)]) == 2
def test_unique_objects():
graph = Dataset()
add_stuff(graph)
assert len([obj for obj in graph.objects()]) == 11
assert len([obj for obj in graph.objects(unique=True)]) == 5
def test_unique_subject_predicates():
graph = Dataset()
add_stuff(graph)
assert len([sub for sub in graph.subject_predicates()]) == 11
assert len([sub for sub in graph.subject_predicates(unique=True)]) == 4
def test_unique_predicate_objects():
graph = Dataset()
add_stuff(graph)
assert len([pred for pred in graph.predicate_objects()]) == 11
assert len([pred for pred in graph.predicate_objects(unique=True)]) == 7
def test_unique_subject_objects():
graph = Dataset()
add_stuff(graph)
assert len([obj for obj in graph.subject_objects()]) == 11
assert len([obj for obj in graph.subject_objects(unique=True)]) == 11
no_of_statements_in_card = 86
no_of_unique_subjects = 20
no_of_unique_predicates = 58
no_of_unique_objects = 62
def test_parse_berners_lee_card_into_dataset_default():
# Workaround pending completion of identifier-as-context work
# current W-I-P allows parsing direct to Dataset default context
# and doesn't require the dubious creation of a graph with the
# same context identifier as the Dataset default context.
# graph = Dataset()
g = Dataset()
graph = g.graph(URIRef("urn:x-rdflib:default"))
graph.parse(data=timblcardn3, format="n3")
assert len(list(graph.subjects())) == no_of_statements_in_card
assert len(list(graph.subjects(unique=True))) == no_of_unique_subjects
assert len(list(graph.predicates(unique=True))) == no_of_unique_predicates
assert len(list(graph.objects(unique=True))) == no_of_unique_objects
def test_parse_berners_lee_card_into_dataset_context():
g = Dataset()
graph = g.graph()
graph.parse(data=timblcardn3, format="n3")
assert len(list(graph.subjects())) == no_of_statements_in_card
assert len(list(graph.subjects(unique=True))) == no_of_unique_subjects
assert len(list(graph.predicates(unique=True))) == no_of_unique_predicates
assert len(list(graph.objects(unique=True))) == no_of_unique_objects | test/test_dataset/test_dataset_generators.py | import os
from test.data import TEST_DATA_DIR, bob, cheese, hates, likes, michel, pizza, tarek
from rdflib import Dataset, URIRef
timblcardn3 = open(os.path.join(TEST_DATA_DIR, "timbl-card.n3")).read()
def add_stuff(graph):
graph.add((tarek, likes, pizza))
graph.add((tarek, likes, cheese))
graph.add((tarek, likes, bob))
graph.add((tarek, likes, michel))
graph.add((michel, likes, pizza))
graph.add((michel, likes, cheese))
graph.add((michel, likes, tarek))
graph.add((bob, likes, cheese))
graph.add((bob, hates, pizza))
graph.add((bob, hates, michel))
graph.add((bob, likes, tarek))
def test_unique_subjects():
graph = Dataset()
add_stuff(graph)
assert len([sub for sub in graph.subjects()]) == 11
assert len([sub for sub in graph.subjects(unique=True)]) == 3
def test_unique_predicates():
graph = Dataset()
add_stuff(graph)
assert len([pred for pred in graph.predicates()]) == 11
assert len([pred for pred in graph.predicates(unique=True)]) == 2
def test_unique_objects():
graph = Dataset()
add_stuff(graph)
assert len([obj for obj in graph.objects()]) == 11
assert len([obj for obj in graph.objects(unique=True)]) == 5
def test_unique_subject_predicates():
graph = Dataset()
add_stuff(graph)
assert len([sub for sub in graph.subject_predicates()]) == 11
assert len([sub for sub in graph.subject_predicates(unique=True)]) == 4
def test_unique_predicate_objects():
graph = Dataset()
add_stuff(graph)
assert len([pred for pred in graph.predicate_objects()]) == 11
assert len([pred for pred in graph.predicate_objects(unique=True)]) == 7
def test_unique_subject_objects():
graph = Dataset()
add_stuff(graph)
assert len([obj for obj in graph.subject_objects()]) == 11
assert len([obj for obj in graph.subject_objects(unique=True)]) == 11
no_of_statements_in_card = 86
no_of_unique_subjects = 20
no_of_unique_predicates = 58
no_of_unique_objects = 62
def test_parse_berners_lee_card_into_dataset_default():
# Workaround pending completion of identifier-as-context work
# current W-I-P allows parsing direct to Dataset default context
# and doesn't require the dubious creation of a graph with the
# same context identifier as the Dataset default context.
# graph = Dataset()
g = Dataset()
graph = g.graph(URIRef("urn:x-rdflib:default"))
graph.parse(data=timblcardn3, format="n3")
assert len(list(graph.subjects())) == no_of_statements_in_card
assert len(list(graph.subjects(unique=True))) == no_of_unique_subjects
assert len(list(graph.predicates(unique=True))) == no_of_unique_predicates
assert len(list(graph.objects(unique=True))) == no_of_unique_objects
def test_parse_berners_lee_card_into_dataset_context():
g = Dataset()
graph = g.graph()
graph.parse(data=timblcardn3, format="n3")
assert len(list(graph.subjects())) == no_of_statements_in_card
assert len(list(graph.subjects(unique=True))) == no_of_unique_subjects
assert len(list(graph.predicates(unique=True))) == no_of_unique_predicates
assert len(list(graph.objects(unique=True))) == no_of_unique_objects | 0.535098 | 0.448909 |
from toolbox.AirWatchAPI import AirWatchAPI as airwatch
from toolbox.csvReport import csvReport
import argparse
import sys
""" Accepted Arguments """
parser = argparse.ArgumentParser(description='AirWatch Custom Attributes Search')
parser.add_argument('name', help='Get list of devices with matching attribute name')
parser.add_argument("-l", "--list", help='List all available attributes', action="store_true")
parser.add_argument('-find', help='Find attribute with matching name')
parser.add_argument('-csv', help='Get list of devices with matching attribute')
args = parser.parse_args()
api = airwatch()
def searchAttributes(name=None, orgID=None):
caSearch = api.searchCustomAttributes(name, orgID)
if caSearch is None:
return None
else:
return caSearch['CustomAttributes']
def listNames(name=None, attribList=None):
if attribList is None:
caList = searchAttributes(name)
else:
caList = attribList
if caList is None:
print('No Attributes found.')
sys.exit(0)
else:
print('\nAttributes found:')
for attributes in caList:
print('\t' + attributes['Name'])
if args.list:
print('Finding all available attributes')
listNames()
sys.exit(0)
if args.find:
print('Looking for all matching attributes')
listNames(args.find)
sys.exit(0)
if args.name:
attribName = args.name
print('\nLooking for devices with matching attribute')
search = searchAttributes(attribName)
if search is None:
print('No Attributes Found')
elif len(search) > 1:
print('More than one attribute matches requested name')
listNames(attribList=search)
else:
attribName = search[0]['Name']
print('Getting list of all devices with attributes')
deviceList = api.searchDeviceCustomAttributes()
print()
report = []
for device in deviceList['Devices']:
value = None
curAttrib = None
for attribute in device['CustomAttributes']:
if attribute['Name'] == attribName:
device['CustomAttributes'] = [attribute]
report.append(device)
break
if args.csv:
print('Exporting report to CSV')
cReport = csvReport(args.csv)
cReport.jsonToCsv(report)
else:
print(api.prettyJSON(report))
#""" | searchCustomAttributes.py |
from toolbox.AirWatchAPI import AirWatchAPI as airwatch
from toolbox.csvReport import csvReport
import argparse
import sys
""" Accepted Arguments """
parser = argparse.ArgumentParser(description='AirWatch Custom Attributes Search')
parser.add_argument('name', help='Get list of devices with matching attribute name')
parser.add_argument("-l", "--list", help='List all available attributes', action="store_true")
parser.add_argument('-find', help='Find attribute with matching name')
parser.add_argument('-csv', help='Get list of devices with matching attribute')
args = parser.parse_args()
api = airwatch()
def searchAttributes(name=None, orgID=None):
caSearch = api.searchCustomAttributes(name, orgID)
if caSearch is None:
return None
else:
return caSearch['CustomAttributes']
def listNames(name=None, attribList=None):
if attribList is None:
caList = searchAttributes(name)
else:
caList = attribList
if caList is None:
print('No Attributes found.')
sys.exit(0)
else:
print('\nAttributes found:')
for attributes in caList:
print('\t' + attributes['Name'])
if args.list:
print('Finding all available attributes')
listNames()
sys.exit(0)
if args.find:
print('Looking for all matching attributes')
listNames(args.find)
sys.exit(0)
if args.name:
attribName = args.name
print('\nLooking for devices with matching attribute')
search = searchAttributes(attribName)
if search is None:
print('No Attributes Found')
elif len(search) > 1:
print('More than one attribute matches requested name')
listNames(attribList=search)
else:
attribName = search[0]['Name']
print('Getting list of all devices with attributes')
deviceList = api.searchDeviceCustomAttributes()
print()
report = []
for device in deviceList['Devices']:
value = None
curAttrib = None
for attribute in device['CustomAttributes']:
if attribute['Name'] == attribName:
device['CustomAttributes'] = [attribute]
report.append(device)
break
if args.csv:
print('Exporting report to CSV')
cReport = csvReport(args.csv)
cReport.jsonToCsv(report)
else:
print(api.prettyJSON(report))
#""" | 0.212477 | 0.072276 |
import collectd
import sys
import time
import pynsca
from pynsca import NSCANotifier
import json
import hashlib
PLUGIN_NAME = 'collectd_notification'
# notitifcation :
# severity => NOTIF_FAILURE || NOTIF_WARNING || NOTIF_OKAY,
# time => time (),
# message => 'status message',
# host => $hostname_g,
# plugin => 'myplugin',
# type => 'mytype',
# plugin_instance => '',
# type_instance => '',
# meta => [ { name => <name>, value => <value> }, ... ]
# globals
# config from collectd.conf
config = {}
# contains status foreach data
status = []
# status is an array, status_keys has same index as status
# values are uniq keys : host/plugin-instance/type-instance
status_keys = []
def create_key(notification):
"""Create the key for status_keys from notification
in: notification
return: the key
"""
key = notification.host
key += '/'
key += notification.plugin
if notification.plugin_instance:
key += '-'
key += notification.plugin_instance
key += notification.type
if notification.type_instance:
key += '-'
key += notification.type_instance
sha = hashlib.sha1()
sha.update(key)
return sha.hexdigest()
def create_status_entry(notification, time):
""" Create a dict from notification
in: notification and time
return : dict
"""
# collectd severity : nagios satus
# 1 : critical (2)
# 2 : warning (1)
# 4 : ok (0)
severity={ 1:2, 2:1, 4:0 }
return {
'timestamp': time,
'host': notification.host,
'plugin' : notification.plugin,
'plugin_instance': notification.plugin_instance,
'type': notification.type,
'type_instance': notification.type_instance,
'severity': notification.severity,
'nagios_state': severity[notification.severity],
'message': notification.message
}
def notification_callback(notification):
""" callback function
in: notification
"""
if notification.host and notification.plugin and notification.type:
global status
current_time = int(time.time() * 1000)
key = create_key(notification)
index = None
last_severity = None
if key in status_keys:
index = status_keys.index(key)
last_severity = status[index]['severity']
status[index] = create_status_entry(notification, current_time)
else:
status_keys.append(key)
status.append(create_status_entry(notification,current_time))
index = len(status) - 1
if config['nsca']:
send_nsca(status[index])
if last_severity != status[index]['severity']:
if config['status']:
write_status(status)
def write_status(status):
"""Write JSON status file
in: status, the dict of status
"""
with open(config['status_file'], 'w') as outfile:
json.dump(status, outfile)
def send_nsca(status):
"""Send a nsca notification
in: status
"""
nagios_service = status['plugin']
nagios_service += ':'
if status['plugin_instance']:
nagios_service += status['plugin_instance']
nagios_service += ' '
nagios_service += status['type']
if status['type_instance']:
nagios_service += ' '
nagios_service += status['type_instance']
notif = NSCANotifier("localhost")
notif.svc_result(
status['host'],
nagios_service,
status['nagios_state'],
status['message']
)
def configure_callback(data):
"""configure callback function
set global variable config
in: configurationdata
"""
global config
for child in data.children:
config[child.key] = child.values[0]
if 'status_file' not in config:
config['status_file'] = '/var/lib/collectd/status.json'
collectd.register_config(configure_callback)
#collectd.register_init(init_callback)
collectd.register_notification(notification_callback)
#collectd.register_shutdown(shutdown_callback) | collectd_notification.py | import collectd
import sys
import time
import pynsca
from pynsca import NSCANotifier
import json
import hashlib
PLUGIN_NAME = 'collectd_notification'
# notitifcation :
# severity => NOTIF_FAILURE || NOTIF_WARNING || NOTIF_OKAY,
# time => time (),
# message => 'status message',
# host => $hostname_g,
# plugin => 'myplugin',
# type => 'mytype',
# plugin_instance => '',
# type_instance => '',
# meta => [ { name => <name>, value => <value> }, ... ]
# globals
# config from collectd.conf
config = {}
# contains status foreach data
status = []
# status is an array, status_keys has same index as status
# values are uniq keys : host/plugin-instance/type-instance
status_keys = []
def create_key(notification):
"""Create the key for status_keys from notification
in: notification
return: the key
"""
key = notification.host
key += '/'
key += notification.plugin
if notification.plugin_instance:
key += '-'
key += notification.plugin_instance
key += notification.type
if notification.type_instance:
key += '-'
key += notification.type_instance
sha = hashlib.sha1()
sha.update(key)
return sha.hexdigest()
def create_status_entry(notification, time):
""" Create a dict from notification
in: notification and time
return : dict
"""
# collectd severity : nagios satus
# 1 : critical (2)
# 2 : warning (1)
# 4 : ok (0)
severity={ 1:2, 2:1, 4:0 }
return {
'timestamp': time,
'host': notification.host,
'plugin' : notification.plugin,
'plugin_instance': notification.plugin_instance,
'type': notification.type,
'type_instance': notification.type_instance,
'severity': notification.severity,
'nagios_state': severity[notification.severity],
'message': notification.message
}
def notification_callback(notification):
""" callback function
in: notification
"""
if notification.host and notification.plugin and notification.type:
global status
current_time = int(time.time() * 1000)
key = create_key(notification)
index = None
last_severity = None
if key in status_keys:
index = status_keys.index(key)
last_severity = status[index]['severity']
status[index] = create_status_entry(notification, current_time)
else:
status_keys.append(key)
status.append(create_status_entry(notification,current_time))
index = len(status) - 1
if config['nsca']:
send_nsca(status[index])
if last_severity != status[index]['severity']:
if config['status']:
write_status(status)
def write_status(status):
"""Write JSON status file
in: status, the dict of status
"""
with open(config['status_file'], 'w') as outfile:
json.dump(status, outfile)
def send_nsca(status):
"""Send a nsca notification
in: status
"""
nagios_service = status['plugin']
nagios_service += ':'
if status['plugin_instance']:
nagios_service += status['plugin_instance']
nagios_service += ' '
nagios_service += status['type']
if status['type_instance']:
nagios_service += ' '
nagios_service += status['type_instance']
notif = NSCANotifier("localhost")
notif.svc_result(
status['host'],
nagios_service,
status['nagios_state'],
status['message']
)
def configure_callback(data):
"""configure callback function
set global variable config
in: configurationdata
"""
global config
for child in data.children:
config[child.key] = child.values[0]
if 'status_file' not in config:
config['status_file'] = '/var/lib/collectd/status.json'
collectd.register_config(configure_callback)
#collectd.register_init(init_callback)
collectd.register_notification(notification_callback)
#collectd.register_shutdown(shutdown_callback) | 0.159774 | 0.073796 |
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
import json
import lcm
import threading
### SETTINGS
import settings
import forseti2
LCM_URI = settings.LCM_URI
TYPES_ROOT = forseti2
### END SETTINGS
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
"""
Called when a client opens the websocket
"""
self.lc = lcm.LCM(LCM_URI)
self.thread = threading.Thread(target=self.lcm_loop)
self.thread.daemon = True
self.thread.start()
self.subscriptions = {}
def close(self):
"""
Called when the websocket closes
"""
# No thread shutdown and LCM cleanup here, because we assume that the
# program is quitting anyway
pass
### Websocket-related
def on_message(self, message):
"""
Called when a message is received over the websocket
"""
obj = json.loads(message)
msg_type = obj["type"]
data = obj["data"]
if msg_type == "subscribe":
self.add_subscription(data["channel"],
data["msg_type"],
data["subscription_id"])
elif msg_type == "unsubscribe":
self.remove_subscription(data["subscription_id"])
elif msg_type == "publish":
self.lc.publish(data["channel"],
self.dict_to_lcm(data["data"]).encode())
else:
raise Exception, "Invalid websocket message type: " + msg_type
def ws_send(self, type, data):
"""
Convenience method for sending data over the websocket
"""
self.write_message(json.dumps({"type": type, "data": data}))
### LCM-related
def lcm_loop(self):
"""
Runs the LCM handling loop
"""
while True:
try:
self.lc.handle()
except Exception as e:
print "Got exception while handling lcm message", e
def add_subscription(self, channel, msg_type, subscription_id):
"""
Creates an LCM subscription (based on data from a websocket request)
Forwards any LCM messages received to javascript via websockets
"""
def handle(channel, data):
msg = TYPES_ROOT.__getattribute__(msg_type).decode(data)
self.ws_send("packet", {"subscription_id": subscription_id,
"msg": self.lcm_to_dict(msg)})
self.subscriptions[subscription_id] = self.lc.subscribe(channel, handle)
def remove_subscription(self, subscription_id):
if subscription_id not in self.subscriptions:
return
print "UNSUBSCRIBING"
self.lc.unsubscribe(self.subscriptions[subscription_id])
del self.subscriptions[subscription_id]
### Data conversion
def is_lcm_object(self, obj):
"""
Checks if an object is an instance of an LCM type
LCM offers no official way to do this, so test for a uniquely-named method
that is present in all LCM types
"""
return '_get_packed_fingerprint' in dir(obj)
def lcm_to_dict(self, obj):
"""
Converts an instance of an LCM object into a dictionary
"""
res = {}
for slot in obj.__slots__:
value = obj.__getattribute__(slot)
if self.is_lcm_object(value):
res[slot] = self.lcm_to_dict(value)
else:
res[slot] = value
return res
def dict_to_lcm(self, d):
"""
Convert a dictionary holding data for fields into an LCM message object
"""
msg_cls = TYPES_ROOT.__getattribute__(d["__type__"])
msg = msg_cls()
for k, v in d.items():
if k not in msg.__slots__:
continue
if type(v) == dict:
v = self.dict_to_lcm(v)
msg.__setattr__(k, v)
return msg
application = tornado.web.Application([
(r'/', WSHandler)
])
if __name__ == '__main__':
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start() | src/lcm_ws_bridge.py | import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
import json
import lcm
import threading
### SETTINGS
import settings
import forseti2
LCM_URI = settings.LCM_URI
TYPES_ROOT = forseti2
### END SETTINGS
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
"""
Called when a client opens the websocket
"""
self.lc = lcm.LCM(LCM_URI)
self.thread = threading.Thread(target=self.lcm_loop)
self.thread.daemon = True
self.thread.start()
self.subscriptions = {}
def close(self):
"""
Called when the websocket closes
"""
# No thread shutdown and LCM cleanup here, because we assume that the
# program is quitting anyway
pass
### Websocket-related
def on_message(self, message):
"""
Called when a message is received over the websocket
"""
obj = json.loads(message)
msg_type = obj["type"]
data = obj["data"]
if msg_type == "subscribe":
self.add_subscription(data["channel"],
data["msg_type"],
data["subscription_id"])
elif msg_type == "unsubscribe":
self.remove_subscription(data["subscription_id"])
elif msg_type == "publish":
self.lc.publish(data["channel"],
self.dict_to_lcm(data["data"]).encode())
else:
raise Exception, "Invalid websocket message type: " + msg_type
def ws_send(self, type, data):
"""
Convenience method for sending data over the websocket
"""
self.write_message(json.dumps({"type": type, "data": data}))
### LCM-related
def lcm_loop(self):
"""
Runs the LCM handling loop
"""
while True:
try:
self.lc.handle()
except Exception as e:
print "Got exception while handling lcm message", e
def add_subscription(self, channel, msg_type, subscription_id):
"""
Creates an LCM subscription (based on data from a websocket request)
Forwards any LCM messages received to javascript via websockets
"""
def handle(channel, data):
msg = TYPES_ROOT.__getattribute__(msg_type).decode(data)
self.ws_send("packet", {"subscription_id": subscription_id,
"msg": self.lcm_to_dict(msg)})
self.subscriptions[subscription_id] = self.lc.subscribe(channel, handle)
def remove_subscription(self, subscription_id):
if subscription_id not in self.subscriptions:
return
print "UNSUBSCRIBING"
self.lc.unsubscribe(self.subscriptions[subscription_id])
del self.subscriptions[subscription_id]
### Data conversion
def is_lcm_object(self, obj):
"""
Checks if an object is an instance of an LCM type
LCM offers no official way to do this, so test for a uniquely-named method
that is present in all LCM types
"""
return '_get_packed_fingerprint' in dir(obj)
def lcm_to_dict(self, obj):
"""
Converts an instance of an LCM object into a dictionary
"""
res = {}
for slot in obj.__slots__:
value = obj.__getattribute__(slot)
if self.is_lcm_object(value):
res[slot] = self.lcm_to_dict(value)
else:
res[slot] = value
return res
def dict_to_lcm(self, d):
"""
Convert a dictionary holding data for fields into an LCM message object
"""
msg_cls = TYPES_ROOT.__getattribute__(d["__type__"])
msg = msg_cls()
for k, v in d.items():
if k not in msg.__slots__:
continue
if type(v) == dict:
v = self.dict_to_lcm(v)
msg.__setattr__(k, v)
return msg
application = tornado.web.Application([
(r'/', WSHandler)
])
if __name__ == '__main__':
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8000)
tornado.ioloop.IOLoop.instance().start() | 0.389779 | 0.099208 |
import sys
import os
import shutil
import tempfile
import hashlib
import datetime
from time import time
PY3K = sys.version_info >= (3, 0)
if PY3K:
import urllib.request as ulib
import urllib.parse as urlparse
import http.cookiejar as cjar
else:
import urllib2 as ulib
import urlparse
import cookielib as cjar
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
'''
Humansize.py from Dive into Python3
<NAME> - http://www.diveintopython3.net/
Copyright (c) 2009, <NAME>, All rights reserved.
Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
'''
size = float(size)
if size < 0:
raise ValueError('number must be non-negative')
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if size < multiple:
return '{0:.1f}{1}'.format(size, suffix)
raise ValueError('number too large')
def get_console_width():
"""Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager
"""
if os.name == 'nt':
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# get console handle
from ctypes import windll, Structure, byref
try:
from ctypes.wintypes import SHORT, WORD, DWORD
except ImportError:
# workaround for missing types in Python 2.5
from ctypes import (
c_short as SHORT, c_ushort as WORD, c_ulong as DWORD)
console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# CONSOLE_SCREEN_BUFFER_INFO Structure
class COORD(Structure):
_fields_ = [("X", SHORT), ("Y", SHORT)]
class SMALL_RECT(Structure):
_fields_ = [("Left", SHORT), ("Top", SHORT),
("Right", SHORT), ("Bottom", SHORT)]
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", WORD),
("srWindow", SMALL_RECT),
("dwMaximumWindowSize", DWORD)]
sbi = CONSOLE_SCREEN_BUFFER_INFO()
ret = windll.kernel32.GetConsoleScreenBufferInfo(
console_handle, byref(sbi))
if ret == 0:
return 0
return sbi.srWindow.Right + 1
elif os.name == 'posix':
from fcntl import ioctl
from termios import TIOCGWINSZ
from array import array
winsize = array("H", [0] * 4)
try:
ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize)
except IOError:
pass
return (winsize[1], winsize[0])[0]
return 80
CONSOLE_WIDTH = get_console_width()
# Need 2 spaces more to avoid linefeed on Windows
AVAIL_WIDTH = CONSOLE_WIDTH - 59 if os.name == 'nt' else CONSOLE_WIDTH - 57
def filename_from_url(url):
""":return: detected filename or None"""
fname = os.path.basename(urlparse.urlparse(url).path)
if len(fname.strip(" \n\t.")) == 0:
return None
return fname
def filename_from_headers(headers):
"""Detect filename from Content-Disposition headers if present.
http://greenbytes.de/tech/tc2231/
:param: headers as dict, list or string
:return: filename from content-disposition header or None
"""
if type(headers) == str:
headers = headers.splitlines()
if type(headers) == list:
headers = dict([x.split(':', 1) for x in headers])
cdisp = headers.get("Content-Disposition")
if not cdisp:
return None
cdtype = cdisp.split(';')
if len(cdtype) == 1:
return None
if cdtype[0].strip().lower() not in ('inline', 'attachment'):
return None
# several filename params is illegal, but just in case
fnames = [x for x in cdtype[1:] if x.strip().startswith('filename=')]
if len(fnames) > 1:
return None
name = fnames[0].split('=')[1].strip(' \t"')
name = os.path.basename(name)
if not name:
return None
return name
def filename_fix_existing(filename, dirname):
"""Expands name portion of filename with numeric ' (x)' suffix to
return filename that doesn't exist already.
"""
name, ext = filename.rsplit('.', 1)
names = [x for x in os.listdir(dirname) if x.startswith(name)]
names = [x.rsplit('.', 1)[0] for x in names]
suffixes = [x.replace(name, '') for x in names]
# filter suffixes that match ' (x)' pattern
suffixes = [x[2:-1] for x in suffixes
if x.startswith(' (') and x.endswith(')')]
indexes = [int(x) for x in suffixes
if set(x) <= set('0123456789')]
idx = 1
if indexes:
idx += sorted(indexes)[-1]
return '{0}({1}).{2}'.format(name, idx, ext)
def report_bar(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used to print the download bar
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(9)
total = approximate_size(total_size).center(9)
shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
sys.stdout.write(
" {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
'=' * (shaded - 1),
'>',
' ' * (AVAIL_WIDTH - shaded),
current,
total,
(approximate_size(speed) + '/s').center(11),
eta.center(10)))
sys.stdout.write("\r")
sys.stdout.flush()
def report_unknown(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used
when the total size is unknown
'''
sys.stdout.write(
"Downloading: {0} / Unknown - {1}/s ".format(approximate_size(bytes_so_far),
approximate_size(speed)))
sys.stdout.write("\r")
sys.stdout.flush()
def report_onlysize(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(10)
total = approximate_size(total_size).center(10)
sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + "eta {0}".format(eta))
sys.stdout.write("\r")
sys.stdout.flush()
def md5sum(filename, blocksize=8192):
'''
Returns the MD5 checksum of a file
'''
with open(filename, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(blocksize)
if not data:
break
m.update(data)
return m.hexdigest()
def download(link, outdir='.', chunk_size=4096):
'''
This is the Main function, which downloads a given link
and saves on outdir (default = current directory)
'''
url = None
fh = None
eta = 'unknown '
bytes_so_far = 0
filename = filename_from_url(link) or "."
cj = cjar.CookieJar()
# get filename for temp file in current directory
(fd_tmp, tmpfile) = tempfile.mkstemp(
".tmp", prefix=filename + ".", dir=outdir)
os.close(fd_tmp)
os.unlink(tmpfile)
try:
opener = ulib.build_opener(ulib.HTTPCookieProcessor(cj))
url = opener.open(link)
fh = open(tmpfile, mode='wb')
headers = url.info()
try:
total_size = int(headers['Content-Length'])
except (ValueError, KeyError, TypeError):
total_size = 'unknown'
try:
md5_header = headers['Content-MD5']
except (ValueError, KeyError, TypeError):
md5_header = None
# Define which callback we're gonna use
if total_size != 'unknown':
if CONSOLE_WIDTH > 57:
reporthook = report_bar
else:
reporthook = report_onlysize
else:
reporthook = report_unknown
# Below are the registers to calculate network transfer rate
time_register = time()
speed = 0.0
speed_list = []
bytes_register = 0.0
eta = 'unknown '
# Loop that reads in chunks, calculates speed and does the callback to
# print the progress
while True:
chunk = url.read(chunk_size)
# Update Download Speed every 1 second
if time() - time_register > 0.5:
speed = (bytes_so_far - bytes_register) / \
(time() - time_register)
speed_list.append(speed)
# Set register properly for future use
time_register = time()
bytes_register = bytes_so_far
# Estimative of remaining download time
if total_size != 'unknown' and len(speed_list) == 3:
speed_mean = sum(speed_list) / 3
eta_sec = int((total_size - bytes_so_far) / speed_mean)
eta = str(datetime.timedelta(seconds=eta_sec))
speed_list = []
bytes_so_far += len(chunk)
if not chunk:
sys.stdout.write('\n')
break
fh.write(chunk)
reporthook(bytes_so_far, total_size, speed, eta)
except KeyboardInterrupt:
print('\n\nCtrl + C: Download aborted by user')
print('Partial downloaded file:\n{0}'.format(os.path.abspath(tmpfile)))
sys.exit(1)
finally:
if url:
url.close()
if fh:
fh.close()
filenamealt = filename_from_headers(headers)
if filenamealt:
filename = filenamealt
# add numeric '(x)' suffix if filename already exists
if os.path.exists(os.path.join(outdir, filename)):
filename = filename_fix_existing(filename, outdir)
filename = os.path.join(outdir, filename)
shutil.move(tmpfile, filename)
# Check if sizes matches
if total_size != 'unknown' and total_size != bytes_so_far:
print(
'\n\nWARNING!! Downloaded file size mismatches... Probably corrupted...')
# Check md5 if it was in html header
if md5_header:
print('\nValidating MD5 checksum...')
if md5_header == md5sum(filename):
print('MD5 checksum passed!')
else:
print('MD5 checksum do NOT passed!!!')
return filename
if __name__ == '__main__':
if len(sys.argv) == 1 or sys.argv[1] in {'-h', '--help'}:
print('Usage: {0} <URL>'.format(sys.argv[0]))
args = [str(elem) for elem in sys.argv[1:]]
for link in args:
print('Downloading ' + link)
filename = download(link)
print('\nSaved under {0}'.format(filename)) | wgetter.py | import sys
import os
import shutil
import tempfile
import hashlib
import datetime
from time import time
PY3K = sys.version_info >= (3, 0)
if PY3K:
import urllib.request as ulib
import urllib.parse as urlparse
import http.cookiejar as cjar
else:
import urllib2 as ulib
import urlparse
import cookielib as cjar
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
'''
Humansize.py from Dive into Python3
<NAME> - http://www.diveintopython3.net/
Copyright (c) 2009, <NAME>, All rights reserved.
Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
'''
size = float(size)
if size < 0:
raise ValueError('number must be non-negative')
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if size < multiple:
return '{0:.1f}{1}'.format(size, suffix)
raise ValueError('number too large')
def get_console_width():
"""Return width of available window area. Autodetection works for
Windows and POSIX platforms. Returns 80 for others
Code from http://bitbucket.org/techtonik/python-pager
"""
if os.name == 'nt':
STD_INPUT_HANDLE = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
# get console handle
from ctypes import windll, Structure, byref
try:
from ctypes.wintypes import SHORT, WORD, DWORD
except ImportError:
# workaround for missing types in Python 2.5
from ctypes import (
c_short as SHORT, c_ushort as WORD, c_ulong as DWORD)
console_handle = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
# CONSOLE_SCREEN_BUFFER_INFO Structure
class COORD(Structure):
_fields_ = [("X", SHORT), ("Y", SHORT)]
class SMALL_RECT(Structure):
_fields_ = [("Left", SHORT), ("Top", SHORT),
("Right", SHORT), ("Bottom", SHORT)]
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
_fields_ = [("dwSize", COORD),
("dwCursorPosition", COORD),
("wAttributes", WORD),
("srWindow", SMALL_RECT),
("dwMaximumWindowSize", DWORD)]
sbi = CONSOLE_SCREEN_BUFFER_INFO()
ret = windll.kernel32.GetConsoleScreenBufferInfo(
console_handle, byref(sbi))
if ret == 0:
return 0
return sbi.srWindow.Right + 1
elif os.name == 'posix':
from fcntl import ioctl
from termios import TIOCGWINSZ
from array import array
winsize = array("H", [0] * 4)
try:
ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize)
except IOError:
pass
return (winsize[1], winsize[0])[0]
return 80
CONSOLE_WIDTH = get_console_width()
# Need 2 spaces more to avoid linefeed on Windows
AVAIL_WIDTH = CONSOLE_WIDTH - 59 if os.name == 'nt' else CONSOLE_WIDTH - 57
def filename_from_url(url):
""":return: detected filename or None"""
fname = os.path.basename(urlparse.urlparse(url).path)
if len(fname.strip(" \n\t.")) == 0:
return None
return fname
def filename_from_headers(headers):
"""Detect filename from Content-Disposition headers if present.
http://greenbytes.de/tech/tc2231/
:param: headers as dict, list or string
:return: filename from content-disposition header or None
"""
if type(headers) == str:
headers = headers.splitlines()
if type(headers) == list:
headers = dict([x.split(':', 1) for x in headers])
cdisp = headers.get("Content-Disposition")
if not cdisp:
return None
cdtype = cdisp.split(';')
if len(cdtype) == 1:
return None
if cdtype[0].strip().lower() not in ('inline', 'attachment'):
return None
# several filename params is illegal, but just in case
fnames = [x for x in cdtype[1:] if x.strip().startswith('filename=')]
if len(fnames) > 1:
return None
name = fnames[0].split('=')[1].strip(' \t"')
name = os.path.basename(name)
if not name:
return None
return name
def filename_fix_existing(filename, dirname):
"""Expands name portion of filename with numeric ' (x)' suffix to
return filename that doesn't exist already.
"""
name, ext = filename.rsplit('.', 1)
names = [x for x in os.listdir(dirname) if x.startswith(name)]
names = [x.rsplit('.', 1)[0] for x in names]
suffixes = [x.replace(name, '') for x in names]
# filter suffixes that match ' (x)' pattern
suffixes = [x[2:-1] for x in suffixes
if x.startswith(' (') and x.endswith(')')]
indexes = [int(x) for x in suffixes
if set(x) <= set('0123456789')]
idx = 1
if indexes:
idx += sorted(indexes)[-1]
return '{0}({1}).{2}'.format(name, idx, ext)
def report_bar(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used to print the download bar
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(9)
total = approximate_size(total_size).center(9)
shaded = int(float(bytes_so_far) / total_size * AVAIL_WIDTH)
sys.stdout.write(
" {0}% [{1}{2}{3}] {4}/{5} {6} eta{7}".format(str(percent).center(4),
'=' * (shaded - 1),
'>',
' ' * (AVAIL_WIDTH - shaded),
current,
total,
(approximate_size(speed) + '/s').center(11),
eta.center(10)))
sys.stdout.write("\r")
sys.stdout.flush()
def report_unknown(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used
when the total size is unknown
'''
sys.stdout.write(
"Downloading: {0} / Unknown - {1}/s ".format(approximate_size(bytes_so_far),
approximate_size(speed)))
sys.stdout.write("\r")
sys.stdout.flush()
def report_onlysize(bytes_so_far, total_size, speed, eta):
'''
This callback for the download function is used when console width
is not enough to print the bar.
It prints only the sizes
'''
percent = int(bytes_so_far * 100 / total_size)
current = approximate_size(bytes_so_far).center(10)
total = approximate_size(total_size).center(10)
sys.stdout.write('D: {0}% -{1}/{2}'.format(percent, current, total) + "eta {0}".format(eta))
sys.stdout.write("\r")
sys.stdout.flush()
def md5sum(filename, blocksize=8192):
'''
Returns the MD5 checksum of a file
'''
with open(filename, 'rb') as fh:
m = hashlib.md5()
while True:
data = fh.read(blocksize)
if not data:
break
m.update(data)
return m.hexdigest()
def download(link, outdir='.', chunk_size=4096):
'''
This is the Main function, which downloads a given link
and saves on outdir (default = current directory)
'''
url = None
fh = None
eta = 'unknown '
bytes_so_far = 0
filename = filename_from_url(link) or "."
cj = cjar.CookieJar()
# get filename for temp file in current directory
(fd_tmp, tmpfile) = tempfile.mkstemp(
".tmp", prefix=filename + ".", dir=outdir)
os.close(fd_tmp)
os.unlink(tmpfile)
try:
opener = ulib.build_opener(ulib.HTTPCookieProcessor(cj))
url = opener.open(link)
fh = open(tmpfile, mode='wb')
headers = url.info()
try:
total_size = int(headers['Content-Length'])
except (ValueError, KeyError, TypeError):
total_size = 'unknown'
try:
md5_header = headers['Content-MD5']
except (ValueError, KeyError, TypeError):
md5_header = None
# Define which callback we're gonna use
if total_size != 'unknown':
if CONSOLE_WIDTH > 57:
reporthook = report_bar
else:
reporthook = report_onlysize
else:
reporthook = report_unknown
# Below are the registers to calculate network transfer rate
time_register = time()
speed = 0.0
speed_list = []
bytes_register = 0.0
eta = 'unknown '
# Loop that reads in chunks, calculates speed and does the callback to
# print the progress
while True:
chunk = url.read(chunk_size)
# Update Download Speed every 1 second
if time() - time_register > 0.5:
speed = (bytes_so_far - bytes_register) / \
(time() - time_register)
speed_list.append(speed)
# Set register properly for future use
time_register = time()
bytes_register = bytes_so_far
# Estimative of remaining download time
if total_size != 'unknown' and len(speed_list) == 3:
speed_mean = sum(speed_list) / 3
eta_sec = int((total_size - bytes_so_far) / speed_mean)
eta = str(datetime.timedelta(seconds=eta_sec))
speed_list = []
bytes_so_far += len(chunk)
if not chunk:
sys.stdout.write('\n')
break
fh.write(chunk)
reporthook(bytes_so_far, total_size, speed, eta)
except KeyboardInterrupt:
print('\n\nCtrl + C: Download aborted by user')
print('Partial downloaded file:\n{0}'.format(os.path.abspath(tmpfile)))
sys.exit(1)
finally:
if url:
url.close()
if fh:
fh.close()
filenamealt = filename_from_headers(headers)
if filenamealt:
filename = filenamealt
# add numeric '(x)' suffix if filename already exists
if os.path.exists(os.path.join(outdir, filename)):
filename = filename_fix_existing(filename, outdir)
filename = os.path.join(outdir, filename)
shutil.move(tmpfile, filename)
# Check if sizes matches
if total_size != 'unknown' and total_size != bytes_so_far:
print(
'\n\nWARNING!! Downloaded file size mismatches... Probably corrupted...')
# Check md5 if it was in html header
if md5_header:
print('\nValidating MD5 checksum...')
if md5_header == md5sum(filename):
print('MD5 checksum passed!')
else:
print('MD5 checksum do NOT passed!!!')
return filename
if __name__ == '__main__':
if len(sys.argv) == 1 or sys.argv[1] in {'-h', '--help'}:
print('Usage: {0} <URL>'.format(sys.argv[0]))
args = [str(elem) for elem in sys.argv[1:]]
for link in args:
print('Downloading ' + link)
filename = download(link)
print('\nSaved under {0}'.format(filename)) | 0.416203 | 0.247521 |
from math import ceil
from functools import cached_property
class Paginator:
ELLIPSIS = '...'
def __init__(self, object_list, per_page, count):
"""
Pagintator class.
:param object_list: Can be any iterable or tortoise queryset.
If it's a queryset, tortoise's .offset() and .limit()
methods are used, otherwise Python's slicing [:] is used.
:param per_page: No. of objects to list on a page.
:param count: Total number of objects.
"""
self.object_list = object_list
self.per_page = per_page
self.count = count
def validate_page_num(self, page_num):
try:
page_num = int(page_num)
if page_num < 1:
page_num = 1
elif page_num > self.num_pages:
page_num = max(self.num_pages, 1) # use max to avoid 0 page_num
except ValueError:
page_num = 1
return page_num
def get_page(self, page_num):
page_num = self.validate_page_num(page_num)
offset = (page_num - 1) * self.per_page
until = offset + self.per_page
if isinstance(self.object_list, list):
return Page(self.object_list[offset:until], page_num, self)
else:
return self.get_page_from_queryset(page_num)
def get_page_from_queryset(self, page_num):
"""Admin backends must override this to return objects from database."""
raise NotImplementedError('Implement in subclass')
@cached_property
def num_pages(self):
"""Returns total pages"""
if self.count == 0:
return 0
hits = max(1, self.count)
return ceil(hits / self.per_page)
@property
def page_range(self):
"""
Return a 1-based range of pages for iterating through within
a template for loop.
"""
return range(1, self.num_pages + 1)
def get_elided_page_range(self, page_num=1, *, on_each_side=3, on_ends=2):
"""
Return a 1-based range of pages with some values elided.
If the page range is larger than a given size, the whole range is not
provided and a compact form is returned instead, e.g. for a paginator
with 50 pages, if page 43 were the current page, the output, with the
default arguments, would be:
1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50.
"""
if page_num == 1 or page_num == self.num_pages:
on_each_side = 2
else:
on_each_side = 1
page_num = self.validate_page_num(page_num)
if self.num_pages <= (on_each_side + on_ends) * 2:
yield from self.page_range
return
if page_num > (1 + on_each_side + on_ends) + 1:
yield from range(1, on_ends + 1)
yield self.ELLIPSIS
yield from range(page_num - on_each_side, page_num + 1)
else:
yield from range(1, page_num + 1)
if page_num < (self.num_pages - on_each_side - on_ends) - 1:
yield from range(page_num + 1, page_num + on_each_side + 1)
yield self.ELLIPSIS
yield from range(self.num_pages - on_ends + 1, self.num_pages + 1)
else:
yield from range(page_num + 1, self.num_pages + 1)
class Page:
def __init__(self, object_list, number, paginator):
self.objects = object_list
self.number = number
self.paginator = paginator
def __repr__(self):
return '<Page %s of %s>' % (self.number, self.paginator.num_pages)
def has_next(self):
return self.number < self.paginator.num_pages
def has_previous(self):
return self.number > 1
def next_page_number(self):
return self.number + 1
def previous_page_number(self):
return self.number - 1 | tornadmin/utils/paginator.py | from math import ceil
from functools import cached_property
class Paginator:
ELLIPSIS = '...'
def __init__(self, object_list, per_page, count):
"""
Pagintator class.
:param object_list: Can be any iterable or tortoise queryset.
If it's a queryset, tortoise's .offset() and .limit()
methods are used, otherwise Python's slicing [:] is used.
:param per_page: No. of objects to list on a page.
:param count: Total number of objects.
"""
self.object_list = object_list
self.per_page = per_page
self.count = count
def validate_page_num(self, page_num):
try:
page_num = int(page_num)
if page_num < 1:
page_num = 1
elif page_num > self.num_pages:
page_num = max(self.num_pages, 1) # use max to avoid 0 page_num
except ValueError:
page_num = 1
return page_num
def get_page(self, page_num):
page_num = self.validate_page_num(page_num)
offset = (page_num - 1) * self.per_page
until = offset + self.per_page
if isinstance(self.object_list, list):
return Page(self.object_list[offset:until], page_num, self)
else:
return self.get_page_from_queryset(page_num)
def get_page_from_queryset(self, page_num):
"""Admin backends must override this to return objects from database."""
raise NotImplementedError('Implement in subclass')
@cached_property
def num_pages(self):
"""Returns total pages"""
if self.count == 0:
return 0
hits = max(1, self.count)
return ceil(hits / self.per_page)
@property
def page_range(self):
"""
Return a 1-based range of pages for iterating through within
a template for loop.
"""
return range(1, self.num_pages + 1)
def get_elided_page_range(self, page_num=1, *, on_each_side=3, on_ends=2):
"""
Return a 1-based range of pages with some values elided.
If the page range is larger than a given size, the whole range is not
provided and a compact form is returned instead, e.g. for a paginator
with 50 pages, if page 43 were the current page, the output, with the
default arguments, would be:
1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50.
"""
if page_num == 1 or page_num == self.num_pages:
on_each_side = 2
else:
on_each_side = 1
page_num = self.validate_page_num(page_num)
if self.num_pages <= (on_each_side + on_ends) * 2:
yield from self.page_range
return
if page_num > (1 + on_each_side + on_ends) + 1:
yield from range(1, on_ends + 1)
yield self.ELLIPSIS
yield from range(page_num - on_each_side, page_num + 1)
else:
yield from range(1, page_num + 1)
if page_num < (self.num_pages - on_each_side - on_ends) - 1:
yield from range(page_num + 1, page_num + on_each_side + 1)
yield self.ELLIPSIS
yield from range(self.num_pages - on_ends + 1, self.num_pages + 1)
else:
yield from range(page_num + 1, self.num_pages + 1)
class Page:
def __init__(self, object_list, number, paginator):
self.objects = object_list
self.number = number
self.paginator = paginator
def __repr__(self):
return '<Page %s of %s>' % (self.number, self.paginator.num_pages)
def has_next(self):
return self.number < self.paginator.num_pages
def has_previous(self):
return self.number > 1
def next_page_number(self):
return self.number + 1
def previous_page_number(self):
return self.number - 1 | 0.805709 | 0.275127 |
from typing import Dict, Iterable, Union
from operator import attrgetter
import numpy as np
from numpy import ndarray
from netprop.data import Data
class DormModel:
"""
Definition or method model
"""
def __init__(self,
name: str,
covs: Iterable[str],
uprior: Dict[str, Iterable[float]] = None,
gprior: Dict[str, Iterable[float]] = None):
self.name = name
self.covs = list(covs)
self.uprior = uprior
self.gprior = gprior
@property
def size(self) -> int:
return len(self.covs)
def get_prior(self,
prior_info: Union[Dict[str, Iterable[float]], None],
default_prior: Iterable[float]) -> ndarray:
prior = np.repeat(np.asarray(default_prior)[:, None], self.size, axis=1)
if prior_info is not None:
for k, v in prior_info.items():
if k in self.covs:
prior[:, self.covs.index(k)] = v
return prior
uprior = property(attrgetter("_uprior"))
@uprior.setter
def uprior(self, uprior_info: Union[Dict[str, Iterable[float]], None]):
default_uprior = [-np.inf, np.inf]
if uprior_info is not None:
for p in uprior_info.values():
assert p[0] <= p[1], "Uniform prior lower bound <= upper bound."
self._uprior = self.get_prior(uprior_info, default_uprior)
gprior = property(attrgetter("_gprior"))
@gprior.setter
def gprior(self, gprior_info: Union[Dict[str, Iterable[float]], None]):
default_gprior = [0.0, np.inf]
if gprior_info is not None:
for p in gprior_info.values():
assert p[1] > 0, "Gaussian prior sd must be positive."
self._gprior = self.get_prior(gprior_info, default_gprior)
def get_mat(self, data: Data) -> ndarray:
return data[self.covs]
def __repr__(self) -> str:
return f"{type(self).__name__}({self.name}, covs={self.covs})" | src/netprop/dorm_model.py | from typing import Dict, Iterable, Union
from operator import attrgetter
import numpy as np
from numpy import ndarray
from netprop.data import Data
class DormModel:
"""
Definition or method model
"""
def __init__(self,
name: str,
covs: Iterable[str],
uprior: Dict[str, Iterable[float]] = None,
gprior: Dict[str, Iterable[float]] = None):
self.name = name
self.covs = list(covs)
self.uprior = uprior
self.gprior = gprior
@property
def size(self) -> int:
return len(self.covs)
def get_prior(self,
prior_info: Union[Dict[str, Iterable[float]], None],
default_prior: Iterable[float]) -> ndarray:
prior = np.repeat(np.asarray(default_prior)[:, None], self.size, axis=1)
if prior_info is not None:
for k, v in prior_info.items():
if k in self.covs:
prior[:, self.covs.index(k)] = v
return prior
uprior = property(attrgetter("_uprior"))
@uprior.setter
def uprior(self, uprior_info: Union[Dict[str, Iterable[float]], None]):
default_uprior = [-np.inf, np.inf]
if uprior_info is not None:
for p in uprior_info.values():
assert p[0] <= p[1], "Uniform prior lower bound <= upper bound."
self._uprior = self.get_prior(uprior_info, default_uprior)
gprior = property(attrgetter("_gprior"))
@gprior.setter
def gprior(self, gprior_info: Union[Dict[str, Iterable[float]], None]):
default_gprior = [0.0, np.inf]
if gprior_info is not None:
for p in gprior_info.values():
assert p[1] > 0, "Gaussian prior sd must be positive."
self._gprior = self.get_prior(gprior_info, default_gprior)
def get_mat(self, data: Data) -> ndarray:
return data[self.covs]
def __repr__(self) -> str:
return f"{type(self).__name__}({self.name}, covs={self.covs})" | 0.902074 | 0.339417 |
import datetime;
import pickle;
import re;
import sys;
try:
temp = pickle.load(open('dump.dat'))#created in emailGrab
parsed = open("parsed.dat", "w")
except IOError:
print 'Error opening one or more files.'
sys.exit(1);
line = ''
count = 0
hex = re.compile('[0-9A-F]{2}')
#Packet-specific parsers
def parsegps1(c):
p = {};
#p['type'] = 'gps1';
p['valid'] = c[0] >> 7;
p['ns'] = c[0] & 0x01;
p['ew'] = (c[0] >> 1) & 0x01;
p['toofewsats'] = c[1] >> 7;
p['sats'] = c[1] & 0x7f;
p['hdil'] = c[2];
p['lat_d'] = c[3] + (c[4] << 8)
p['lat_m'] = (c[5] + (c[6] << 8) + (c[7] << 16) + (c[8] << 24)) * 1.0 / 10000.0
p['lat_dec'] = p['lat_d'] + (p['lat_m'] / 60.0);
p['lon_d'] = c[9] + (c[10] << 8)
p['lon_m'] = (c[11] + (c[12] << 8) + (c[13] << 16) + (c[14] << 24)) * 1.0 / 10000.0
p['lon_dec'] = p['lon_d'] + (p['lon_m'] / 60.0);
p['alt'] = c[15] + (c[16] << 8);
return p;
def parsertstate(c):
p = {};
#p['type'] = "runtime state";
p['energy_in'] = c[0] + (c[1] << 8) + (c[2] << 16) + (c[3] << 24)
p['energy_out'] = c[4] + (c[5] << 8) + (c[6] << 16) + (c[7] << 24)
p['batt_volts'] =( c[8] + (c[9] << 8) ) * 1.0 / 1000.0;
p['batt_energy_est'] = c[10] + (c[11] << 8) + (c[12] << 16) + (c[13] << 24)
p['current_state'] = c[14];
p['current_grade'] = c[15];
p['temperature'] = c[16] + (c[17] << 8);
return p;
def parsertpath(c):
p={};
#p['type'] = "runtime path"
p['path_id'] = c[0] + (c[1] << 8)
p['count'] = c[2] + (c[3] << 8)
p['energy'] = c[4] + (c[5] << 8) + (c[6] << 16) + (c[7] << 24)
p['probability'] = c[8] * 1.0 / 100.0;
p['source_probability'] = c[9] * 1.0 / 100.0;
return p;
def parseconn(c):
p={}
#p['type'] = 'connection event'
p['address'] = c[0] + (c[1] << 8);
p['duration'] = c[2] + (c[3] << 8);
p['quality'] = c[4];
return p;
#end of packet-specific parsers
packet_types = {1:'gps1',2:'gps2',4:'runtime state',5:'runtime path',6:'connection event'};
def parsepacket(pkt, timeSent):
bytes = pkt
thepkt = {};
thepkt['datasrc'] = bytes[0];
thepkt['sequence'] = bytes[2] + (bytes[3] << 8);
thepkt['pkttype'] = bytes[1] & 0x7f;
thepkt['timeinvalid'] = bytes[1] >> 7
thepkt['type'] = packet_types[thepkt['pkttype']];
thepkt['time_sent'] = timeSent;#email time
thepkt['timestamp']=bytes[4]+(bytes[5]<<8)+(bytes[6]<<16)+(bytes[7]<<24)
tempByte = bytes[8:]
#additional parsing
if thepkt['pkttype'] == 1: #gps first half
thepkt['payload'] = parsegps1(bytes[8:]);
if (thepkt['pkttype'] == 2 and len(tempByte) == 12): #gps second half
thepkt['payload'] = parsegps2(bytes[8:]);
if thepkt['pkttype'] == 4: #rtstate
thepkt['payload'] = parsertstate(bytes[8:]);
if (thepkt['pkttype'] == 5 and len(tempByte) == 10): #rtpath
thepkt['payload'] = parsertpath(bytes[8:]);
if (thepkt['pkttype'] == 6 and len(tempByte) == 5): #connection
thepkt['payload'] = parseconn(bytes[8:]);
return thepkt;
def date_format(time):
#replace month with apropriate value
time = time.split(' ')
if time[3] == 'Jan':
time[3] = '01'
print 'worked Jan'
if time[3] == 'Feb':
time[3] = '02'
print 'worked Feb'
if time[3] == 'Mar':
time[3] = '03'
print 'worked Mar'
if time[3] == 'Apr':
time[3] = '04'
print 'worked Apr'
if time[3] == 'May':
time[3] = '05'
print 'worked May'
if time[3] == 'Jun':
time[3] = '06'
print 'worked Jun'
if time[3] == 'Jul':
time[3] = '07'
print 'worked Jul'
if time[3] == 'Aug':
time[3] = '08'
print 'worked Aug'
if time[3] == 'Sep':
time[3] = '08'
print 'worked Sep'
if time[3] == 'Oct':
time[3] = '10'
print 'worked Oct'
if time[3] == 'Nov':
time[3] = '11'
print 'worked Nov'
if time[3] == 'Dec':
time[3] = '12'
print 'worked Dec'
#put date into apropriate format for MySQL 'DATETIME'
return time[4] + '-' + time[3] + '-' + time[2] + ' ' + time[5]
pDat = []
for num in temp:
for num2 in num['body'].split('\n'):#breaks up individual lines
write = 1
tempChar = ''
for num3 in num2.split(','): #breaks into ind. value
if len(num3)==2 and hex.match(num3): #ensures there is a two digit hex value
try:
tempChar += chr(int(num3,16))#converts from hex to ascii char
write = 0
except TypeError:
print 'Error while attempting to translate.'
elif len(num3)!= 2 or not hex.match(num3):#skip the entire line if part of its no good
break
if write == 0 and len(tempChar)>=6: #only parses a full line
line = tempChar;
write = 1;
print ("Count", count)
count +=1
binline = []
for c in line:
binline.append(ord(c))
pDat.append(parsepacket(binline, date_format(num['timeSent'])));
try:
pickle.dump(pDat, parsed)
parsed.close()
except IOError:
print 'Error writing to file'
sys.exit(1) | eon/eon/src/util/vis/Parsing/older/newParse.py |
import datetime;
import pickle;
import re;
import sys;
try:
temp = pickle.load(open('dump.dat'))#created in emailGrab
parsed = open("parsed.dat", "w")
except IOError:
print 'Error opening one or more files.'
sys.exit(1);
line = ''
count = 0
hex = re.compile('[0-9A-F]{2}')
#Packet-specific parsers
def parsegps1(c):
p = {};
#p['type'] = 'gps1';
p['valid'] = c[0] >> 7;
p['ns'] = c[0] & 0x01;
p['ew'] = (c[0] >> 1) & 0x01;
p['toofewsats'] = c[1] >> 7;
p['sats'] = c[1] & 0x7f;
p['hdil'] = c[2];
p['lat_d'] = c[3] + (c[4] << 8)
p['lat_m'] = (c[5] + (c[6] << 8) + (c[7] << 16) + (c[8] << 24)) * 1.0 / 10000.0
p['lat_dec'] = p['lat_d'] + (p['lat_m'] / 60.0);
p['lon_d'] = c[9] + (c[10] << 8)
p['lon_m'] = (c[11] + (c[12] << 8) + (c[13] << 16) + (c[14] << 24)) * 1.0 / 10000.0
p['lon_dec'] = p['lon_d'] + (p['lon_m'] / 60.0);
p['alt'] = c[15] + (c[16] << 8);
return p;
def parsertstate(c):
p = {};
#p['type'] = "runtime state";
p['energy_in'] = c[0] + (c[1] << 8) + (c[2] << 16) + (c[3] << 24)
p['energy_out'] = c[4] + (c[5] << 8) + (c[6] << 16) + (c[7] << 24)
p['batt_volts'] =( c[8] + (c[9] << 8) ) * 1.0 / 1000.0;
p['batt_energy_est'] = c[10] + (c[11] << 8) + (c[12] << 16) + (c[13] << 24)
p['current_state'] = c[14];
p['current_grade'] = c[15];
p['temperature'] = c[16] + (c[17] << 8);
return p;
def parsertpath(c):
p={};
#p['type'] = "runtime path"
p['path_id'] = c[0] + (c[1] << 8)
p['count'] = c[2] + (c[3] << 8)
p['energy'] = c[4] + (c[5] << 8) + (c[6] << 16) + (c[7] << 24)
p['probability'] = c[8] * 1.0 / 100.0;
p['source_probability'] = c[9] * 1.0 / 100.0;
return p;
def parseconn(c):
p={}
#p['type'] = 'connection event'
p['address'] = c[0] + (c[1] << 8);
p['duration'] = c[2] + (c[3] << 8);
p['quality'] = c[4];
return p;
#end of packet-specific parsers
packet_types = {1:'gps1',2:'gps2',4:'runtime state',5:'runtime path',6:'connection event'};
def parsepacket(pkt, timeSent):
bytes = pkt
thepkt = {};
thepkt['datasrc'] = bytes[0];
thepkt['sequence'] = bytes[2] + (bytes[3] << 8);
thepkt['pkttype'] = bytes[1] & 0x7f;
thepkt['timeinvalid'] = bytes[1] >> 7
thepkt['type'] = packet_types[thepkt['pkttype']];
thepkt['time_sent'] = timeSent;#email time
thepkt['timestamp']=bytes[4]+(bytes[5]<<8)+(bytes[6]<<16)+(bytes[7]<<24)
tempByte = bytes[8:]
#additional parsing
if thepkt['pkttype'] == 1: #gps first half
thepkt['payload'] = parsegps1(bytes[8:]);
if (thepkt['pkttype'] == 2 and len(tempByte) == 12): #gps second half
thepkt['payload'] = parsegps2(bytes[8:]);
if thepkt['pkttype'] == 4: #rtstate
thepkt['payload'] = parsertstate(bytes[8:]);
if (thepkt['pkttype'] == 5 and len(tempByte) == 10): #rtpath
thepkt['payload'] = parsertpath(bytes[8:]);
if (thepkt['pkttype'] == 6 and len(tempByte) == 5): #connection
thepkt['payload'] = parseconn(bytes[8:]);
return thepkt;
def date_format(time):
#replace month with apropriate value
time = time.split(' ')
if time[3] == 'Jan':
time[3] = '01'
print 'worked Jan'
if time[3] == 'Feb':
time[3] = '02'
print 'worked Feb'
if time[3] == 'Mar':
time[3] = '03'
print 'worked Mar'
if time[3] == 'Apr':
time[3] = '04'
print 'worked Apr'
if time[3] == 'May':
time[3] = '05'
print 'worked May'
if time[3] == 'Jun':
time[3] = '06'
print 'worked Jun'
if time[3] == 'Jul':
time[3] = '07'
print 'worked Jul'
if time[3] == 'Aug':
time[3] = '08'
print 'worked Aug'
if time[3] == 'Sep':
time[3] = '08'
print 'worked Sep'
if time[3] == 'Oct':
time[3] = '10'
print 'worked Oct'
if time[3] == 'Nov':
time[3] = '11'
print 'worked Nov'
if time[3] == 'Dec':
time[3] = '12'
print 'worked Dec'
#put date into apropriate format for MySQL 'DATETIME'
return time[4] + '-' + time[3] + '-' + time[2] + ' ' + time[5]
pDat = []
for num in temp:
for num2 in num['body'].split('\n'):#breaks up individual lines
write = 1
tempChar = ''
for num3 in num2.split(','): #breaks into ind. value
if len(num3)==2 and hex.match(num3): #ensures there is a two digit hex value
try:
tempChar += chr(int(num3,16))#converts from hex to ascii char
write = 0
except TypeError:
print 'Error while attempting to translate.'
elif len(num3)!= 2 or not hex.match(num3):#skip the entire line if part of its no good
break
if write == 0 and len(tempChar)>=6: #only parses a full line
line = tempChar;
write = 1;
print ("Count", count)
count +=1
binline = []
for c in line:
binline.append(ord(c))
pDat.append(parsepacket(binline, date_format(num['timeSent'])));
try:
pickle.dump(pDat, parsed)
parsed.close()
except IOError:
print 'Error writing to file'
sys.exit(1) | 0.101974 | 0.119408 |
import collections
import numpy
import os
import six.moves.urllib
import tarfile
import texmex_python
def get_gmm_random_dataset(k, dimension=100, test_size=5000, train_size=500):
def random_gmm(k, n_sample):
result = numpy.zeros((n_sample, dimension))
for _ in range(k):
cov_source = numpy.random.random((dimension, dimension))
cov = cov_source.dot(cov_source.T)
result += numpy.random.multivariate_normal(numpy.random.random(dimension), cov, n_sample)
return result
train_test = random_gmm(k, train_size + test_size)
train = train_test[:train_size, :]
test = train_test[train_size:, :]
return train, test
def get_siftsmall_dataset(cache_directory="."):
return get_texmex_dataset(
url="ftp://ftp.irisa.fr/local/texmex/corpus/siftsmall.tar.gz",
filename="siftsmall.tar.gz",
member_names=["siftsmall/siftsmall_learn.fvecs", "siftsmall/siftsmall_base.fvecs"],
cache_directory=cache_directory,
)
def get_sift1m_dataset(cache_directory="."):
return get_texmex_dataset(
url="ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz",
filename="sift.tar.gz",
member_names=["sift/sift_learn.fvecs", "sift/sift_base.fvecs"],
cache_directory=cache_directory,
)
def get_texmex_dataset(url, filename, member_names, cache_directory="."):
path = os.path.join(cache_directory, filename)
if not os.path.exists(path):
print("downloading {}".format(url))
six.moves.urllib.request.urlretrieve(url, path)
learn_base = []
for member_name in member_names:
tardir = tarfile.open(path, "r:gz")
member = tardir.getmember(member_name)
data = texmex_python.reader.read_fvec(tardir.extractfile(member))
learn_base.append(data)
return learn_base
def calc_error(assignments, raw_features, num_classes):
"""
calculate class internal errors
"""
## calculate mean feature for all classes
mean_vectors = collections.defaultdict(lambda: None)
count = {i: 0 for i in range(num_classes)}
for assignment, raw_feature in zip(assignments, raw_features):
count[assignment] += 1
if mean_vectors[assignment] is None:
mean_vectors[assignment] = raw_feature.copy()
else:
mean_vectors[assignment] += raw_feature
mean_vectors = {
i: sum_vector / count[i]
for i, sum_vector in mean_vectors.items()
}
## calculate sum error
sum_errors = {i: 0 for i in range(num_classes)}
for assignment, raw_feature in zip(assignments, raw_features):
sum_errors[assignment] += numpy.linalg.norm(raw_feature - mean_vectors[assignment])
## output
total_error = sum(sum_errors.values())
micro_average_error = sum(sum_errors.values()) / len(assignments)
macro_average_error = sum([
sum_error / count[class_index] if count[class_index] > 0 else 0
for class_index, sum_error in sum_errors.items()
]) / len(sum_errors)
return total_error, micro_average_error, macro_average_error | pqkmeans/evaluation.py | import collections
import numpy
import os
import six.moves.urllib
import tarfile
import texmex_python
def get_gmm_random_dataset(k, dimension=100, test_size=5000, train_size=500):
def random_gmm(k, n_sample):
result = numpy.zeros((n_sample, dimension))
for _ in range(k):
cov_source = numpy.random.random((dimension, dimension))
cov = cov_source.dot(cov_source.T)
result += numpy.random.multivariate_normal(numpy.random.random(dimension), cov, n_sample)
return result
train_test = random_gmm(k, train_size + test_size)
train = train_test[:train_size, :]
test = train_test[train_size:, :]
return train, test
def get_siftsmall_dataset(cache_directory="."):
return get_texmex_dataset(
url="ftp://ftp.irisa.fr/local/texmex/corpus/siftsmall.tar.gz",
filename="siftsmall.tar.gz",
member_names=["siftsmall/siftsmall_learn.fvecs", "siftsmall/siftsmall_base.fvecs"],
cache_directory=cache_directory,
)
def get_sift1m_dataset(cache_directory="."):
return get_texmex_dataset(
url="ftp://ftp.irisa.fr/local/texmex/corpus/sift.tar.gz",
filename="sift.tar.gz",
member_names=["sift/sift_learn.fvecs", "sift/sift_base.fvecs"],
cache_directory=cache_directory,
)
def get_texmex_dataset(url, filename, member_names, cache_directory="."):
path = os.path.join(cache_directory, filename)
if not os.path.exists(path):
print("downloading {}".format(url))
six.moves.urllib.request.urlretrieve(url, path)
learn_base = []
for member_name in member_names:
tardir = tarfile.open(path, "r:gz")
member = tardir.getmember(member_name)
data = texmex_python.reader.read_fvec(tardir.extractfile(member))
learn_base.append(data)
return learn_base
def calc_error(assignments, raw_features, num_classes):
"""
calculate class internal errors
"""
## calculate mean feature for all classes
mean_vectors = collections.defaultdict(lambda: None)
count = {i: 0 for i in range(num_classes)}
for assignment, raw_feature in zip(assignments, raw_features):
count[assignment] += 1
if mean_vectors[assignment] is None:
mean_vectors[assignment] = raw_feature.copy()
else:
mean_vectors[assignment] += raw_feature
mean_vectors = {
i: sum_vector / count[i]
for i, sum_vector in mean_vectors.items()
}
## calculate sum error
sum_errors = {i: 0 for i in range(num_classes)}
for assignment, raw_feature in zip(assignments, raw_features):
sum_errors[assignment] += numpy.linalg.norm(raw_feature - mean_vectors[assignment])
## output
total_error = sum(sum_errors.values())
micro_average_error = sum(sum_errors.values()) / len(assignments)
macro_average_error = sum([
sum_error / count[class_index] if count[class_index] > 0 else 0
for class_index, sum_error in sum_errors.items()
]) / len(sum_errors)
return total_error, micro_average_error, macro_average_error | 0.343672 | 0.214486 |
import os
import sys
import json
import numpy as np
import dataloader.file_io.get_path as gp
import dataloader.definitions.labels_file as lf
class DatasetParameterset:
"""A class that contains all dataset-specific parameters
- K: Extrinsic camera matrix as a Numpy array. If not available, take None
- stereo_T: Distance between the two cameras (see e.g. http://www.cvlibs.net/datasets/kitti/setup.php, 0.54m)
- labels:
- labels_mode: 'fromid' or 'fromrgb', depending on which format the segmentation images have
- depth_mode: 'uint_16' or 'uint_16_subtract_one' depending on which format the depth images have
- flow_mode: specifies how the flow images are stored, e.g. 'kitti'
- splits: List of splits that are available for this dataset
"""
def __init__(self, dataset):
path_getter = gp.GetPath()
dataset_folder = path_getter.get_data_path()
path = os.path.join(dataset_folder, dataset, 'parameters.json')
if not os.path.isdir(os.path.join(dataset_folder, dataset)):
raise Exception('There is no dataset folder called {}'.format(dataset))
if not os.path.isfile(path):
raise Exception('There is no parameters.json file in the dataset folder. Please create it using the '
'dataset_index.py in the folder dataloader/file_io in order to load this dataset')
with open(path) as file:
param_dict = json.load(file)
self._dataset = dataset
self._K = param_dict['K']
if self._K is not None:
self._K = np.array(self._K, dtype=np.float32)
if param_dict['stereo_T'] is not None:
self._stereo_T = np.eye(4, dtype=np.float32)
self._stereo_T[0, 3] = param_dict['stereo_T']
else:
self._stereo_T = None
self._depth_mode = param_dict['depth_mode']
self._flow_mode = param_dict['flow_mode']
self._splits = param_dict['splits']
labels_name = param_dict['labels']
if labels_name in lf.dataset_labels.keys():
self.labels = lf.dataset_labels[labels_name].getlabels()
self.labels_mode = param_dict['labels_mode']
else:
self.labels = None
self.labels_mode = None
@property
def dataset(self):
return self._dataset
@property
def K(self):
return self._K
@property
def stereo_T(self):
return self._stereo_T
@property
def depth_mode(self):
return self._depth_mode
@property
def flow_mode(self):
return self._flow_mode
@property
def splits(self):
return self._splits | merged_depth/nets/SGDepth/dataloader/pt_data_loader/dataset_parameterset.py |
import os
import sys
import json
import numpy as np
import dataloader.file_io.get_path as gp
import dataloader.definitions.labels_file as lf
class DatasetParameterset:
"""A class that contains all dataset-specific parameters
- K: Extrinsic camera matrix as a Numpy array. If not available, take None
- stereo_T: Distance between the two cameras (see e.g. http://www.cvlibs.net/datasets/kitti/setup.php, 0.54m)
- labels:
- labels_mode: 'fromid' or 'fromrgb', depending on which format the segmentation images have
- depth_mode: 'uint_16' or 'uint_16_subtract_one' depending on which format the depth images have
- flow_mode: specifies how the flow images are stored, e.g. 'kitti'
- splits: List of splits that are available for this dataset
"""
def __init__(self, dataset):
path_getter = gp.GetPath()
dataset_folder = path_getter.get_data_path()
path = os.path.join(dataset_folder, dataset, 'parameters.json')
if not os.path.isdir(os.path.join(dataset_folder, dataset)):
raise Exception('There is no dataset folder called {}'.format(dataset))
if not os.path.isfile(path):
raise Exception('There is no parameters.json file in the dataset folder. Please create it using the '
'dataset_index.py in the folder dataloader/file_io in order to load this dataset')
with open(path) as file:
param_dict = json.load(file)
self._dataset = dataset
self._K = param_dict['K']
if self._K is not None:
self._K = np.array(self._K, dtype=np.float32)
if param_dict['stereo_T'] is not None:
self._stereo_T = np.eye(4, dtype=np.float32)
self._stereo_T[0, 3] = param_dict['stereo_T']
else:
self._stereo_T = None
self._depth_mode = param_dict['depth_mode']
self._flow_mode = param_dict['flow_mode']
self._splits = param_dict['splits']
labels_name = param_dict['labels']
if labels_name in lf.dataset_labels.keys():
self.labels = lf.dataset_labels[labels_name].getlabels()
self.labels_mode = param_dict['labels_mode']
else:
self.labels = None
self.labels_mode = None
@property
def dataset(self):
return self._dataset
@property
def K(self):
return self._K
@property
def stereo_T(self):
return self._stereo_T
@property
def depth_mode(self):
return self._depth_mode
@property
def flow_mode(self):
return self._flow_mode
@property
def splits(self):
return self._splits | 0.554229 | 0.37439 |
import sys
from .bitcoin import Transaction, TransactionInput, TransactionOutput
from .users import UserNetwork
class TransactionNetwork:
""" List of transactions with an unique set of all encountered addresses
(as inputs or outputs of all transactions)
"""
def __init__(self):
self.addresses = UserNetwork()
def build(self, spark_df):
""" From a Spark dataframe following the json format build the transaction network
:param spark_df: PySpark Dataframe object of bitcoin transactions
"""
print("\nGetting already known addresses from Graph Database...")
self.addresses.populate_known_addresses()
# Will iterate over each row of the pyspark dataframe
transactions_total = spark_df.count()
transactions_iterator = spark_df.toLocalIterator()
transactions_total_count = 0
# Transactions are committed every 10000
transactions_batch_limit = 10000
transactions_batch_count = 0
print("Building graph from", transactions_total, "transactions...")
print("Transactions : Addresses : Progression :")
for t in transactions_iterator:
# Each transaction is converted to a Transaction object and processed by the UserNetwork
self.addresses.add_transaction(TransactionNetwork.json_to_transaction(t))
# Display transactions count and heuristics usage
transactions_total_count += 1
sys.stdout.write(
"\r{0: >12} {1: >12} ({2}%)".format(
transactions_total_count,
len(self.addresses.known_addresses),
round(transactions_total_count/transactions_total*100, 2)
))
sys.stdout.flush()
# Commit new transactions every transactions_batch_limit
transactions_batch_count += 1
if transactions_batch_count == transactions_batch_limit:
self.addresses.commit_new_entries()
transactions_batch_count = 0
print("\nDone")
def build_identity_hint_network(self, spark_df):
print("Building Identity hint network...")
self.addresses.populate_known_addresses_with_users()
transactions_iterator = spark_df.toLocalIterator()
transactions_total = spark_df.count()
transactions_total_count = 0
# Transactions are committed every 10000
transactions_batch_limit = 10000
transactions_batch_count = 0
print("Adding edges between users for", transactions_total, "transactions...")
print("Transactions : Progression :")
for t in transactions_iterator:
transactions_total_count += 1
self.addresses.h4_community_detection(TransactionNetwork.json_to_transaction(t))
sys.stdout.write(
"\r{0: >12} ({1}%)".format(
transactions_total_count,
round(transactions_total_count / transactions_total * 100, 2)
))
sys.stdout.flush()
# Commit new transactions every transactions_batch_limit
transactions_batch_count += 1
if transactions_batch_count == transactions_batch_limit:
self.addresses.commit_new_user_relations()
transactions_batch_count = 0
@staticmethod
def json_to_transaction(transaction_json):
""" Create Transaction object from json representation
:param transaction_json: JSON Object of a transaction
"""
transaction_inputs = []
transaction_outputs = []
for t_in in transaction_json.tx_ins:
transaction_in = TransactionInput(t_in.address, t_in.value)
transaction_inputs.append(transaction_in)
for t_out in transaction_json.tx_outs:
transaction_out = TransactionOutput(t_out.address, t_out.value)
transaction_outputs.append(transaction_out)
return Transaction(transaction_inputs, transaction_outputs, transaction_json.timestamp) | app/transactions.py | import sys
from .bitcoin import Transaction, TransactionInput, TransactionOutput
from .users import UserNetwork
class TransactionNetwork:
""" List of transactions with an unique set of all encountered addresses
(as inputs or outputs of all transactions)
"""
def __init__(self):
self.addresses = UserNetwork()
def build(self, spark_df):
""" From a Spark dataframe following the json format build the transaction network
:param spark_df: PySpark Dataframe object of bitcoin transactions
"""
print("\nGetting already known addresses from Graph Database...")
self.addresses.populate_known_addresses()
# Will iterate over each row of the pyspark dataframe
transactions_total = spark_df.count()
transactions_iterator = spark_df.toLocalIterator()
transactions_total_count = 0
# Transactions are committed every 10000
transactions_batch_limit = 10000
transactions_batch_count = 0
print("Building graph from", transactions_total, "transactions...")
print("Transactions : Addresses : Progression :")
for t in transactions_iterator:
# Each transaction is converted to a Transaction object and processed by the UserNetwork
self.addresses.add_transaction(TransactionNetwork.json_to_transaction(t))
# Display transactions count and heuristics usage
transactions_total_count += 1
sys.stdout.write(
"\r{0: >12} {1: >12} ({2}%)".format(
transactions_total_count,
len(self.addresses.known_addresses),
round(transactions_total_count/transactions_total*100, 2)
))
sys.stdout.flush()
# Commit new transactions every transactions_batch_limit
transactions_batch_count += 1
if transactions_batch_count == transactions_batch_limit:
self.addresses.commit_new_entries()
transactions_batch_count = 0
print("\nDone")
def build_identity_hint_network(self, spark_df):
print("Building Identity hint network...")
self.addresses.populate_known_addresses_with_users()
transactions_iterator = spark_df.toLocalIterator()
transactions_total = spark_df.count()
transactions_total_count = 0
# Transactions are committed every 10000
transactions_batch_limit = 10000
transactions_batch_count = 0
print("Adding edges between users for", transactions_total, "transactions...")
print("Transactions : Progression :")
for t in transactions_iterator:
transactions_total_count += 1
self.addresses.h4_community_detection(TransactionNetwork.json_to_transaction(t))
sys.stdout.write(
"\r{0: >12} ({1}%)".format(
transactions_total_count,
round(transactions_total_count / transactions_total * 100, 2)
))
sys.stdout.flush()
# Commit new transactions every transactions_batch_limit
transactions_batch_count += 1
if transactions_batch_count == transactions_batch_limit:
self.addresses.commit_new_user_relations()
transactions_batch_count = 0
@staticmethod
def json_to_transaction(transaction_json):
""" Create Transaction object from json representation
:param transaction_json: JSON Object of a transaction
"""
transaction_inputs = []
transaction_outputs = []
for t_in in transaction_json.tx_ins:
transaction_in = TransactionInput(t_in.address, t_in.value)
transaction_inputs.append(transaction_in)
for t_out in transaction_json.tx_outs:
transaction_out = TransactionOutput(t_out.address, t_out.value)
transaction_outputs.append(transaction_out)
return Transaction(transaction_inputs, transaction_outputs, transaction_json.timestamp) | 0.619586 | 0.415373 |
from .device import Device
from threading import Timer
from .const import (
LOGGER,
STATUS_RESPONSE_INPUTS,
STATUS_RESPONSE_INPUTS_INPUT,
STATUS_RESPONSE_INPUTS_EVENT,
STATUS_RESPONSE_INPUTS_EVENT_CNT
)
class Switch(Device):
"""Class to represent a power meter value"""
def __init__(self, block, channel, position,
event_pos=None, event_cnt_pos=None, simulate_state=False):
super(Switch, self).__init__(block)
self.id = block.id
if channel > 0:
self.id += "-" + str(channel)
self._channel = channel - 1
self.device_nr = channel
else:
self._channel = 0
self._position = position
self._event_pos = event_pos
self._event_cnt_pos = event_cnt_pos
self._simulate_state = simulate_state
self.sensor_values = {}
self.device_type = "SWITCH"
self.last_event = None
self.event_cnt = None
def update_coap(self, payload):
"""Get the power"""
state = self.coap_get(payload, self._position)
if self._event_pos:
self.last_event = payload.get(self._event_pos)
event_cnt = payload.get(self._event_cnt_pos)
if self.event_cnt and self.event_cnt != event_cnt:
self.event_cnt = event_cnt
if self._simulate_state:
state = 1
self.timer = Timer(1,self._turn_off)
self.timer.start()
self._update(state != 0, {'last_event' : self.last_event,
'event_cnt' : self.event_cnt})
def update_status_information(self, status):
"""Update the status information."""
new_state = None
inputs = status.get(STATUS_RESPONSE_INPUTS)
if inputs:
value = inputs[self._channel]
new_state = value.get(STATUS_RESPONSE_INPUTS_INPUT, None)
self.last_event = value.get(STATUS_RESPONSE_INPUTS_EVENT, None)
event_cnt = value.get(STATUS_RESPONSE_INPUTS_EVENT_CNT, None)
if self.event_cnt != event_cnt:
self.event_cnt = event_cnt
if self._simulate_state:
new_state = True
self.timer = Timer(1,self._turn_off)
self.timer.start()
self._update(new_state != 0, {'last_event' : self.last_event,
'event_cnt' : self.event_cnt})
def _turn_off(self):
self._update(False) | pyShelly/switch.py |
from .device import Device
from threading import Timer
from .const import (
LOGGER,
STATUS_RESPONSE_INPUTS,
STATUS_RESPONSE_INPUTS_INPUT,
STATUS_RESPONSE_INPUTS_EVENT,
STATUS_RESPONSE_INPUTS_EVENT_CNT
)
class Switch(Device):
"""Class to represent a power meter value"""
def __init__(self, block, channel, position,
event_pos=None, event_cnt_pos=None, simulate_state=False):
super(Switch, self).__init__(block)
self.id = block.id
if channel > 0:
self.id += "-" + str(channel)
self._channel = channel - 1
self.device_nr = channel
else:
self._channel = 0
self._position = position
self._event_pos = event_pos
self._event_cnt_pos = event_cnt_pos
self._simulate_state = simulate_state
self.sensor_values = {}
self.device_type = "SWITCH"
self.last_event = None
self.event_cnt = None
def update_coap(self, payload):
"""Get the power"""
state = self.coap_get(payload, self._position)
if self._event_pos:
self.last_event = payload.get(self._event_pos)
event_cnt = payload.get(self._event_cnt_pos)
if self.event_cnt and self.event_cnt != event_cnt:
self.event_cnt = event_cnt
if self._simulate_state:
state = 1
self.timer = Timer(1,self._turn_off)
self.timer.start()
self._update(state != 0, {'last_event' : self.last_event,
'event_cnt' : self.event_cnt})
def update_status_information(self, status):
"""Update the status information."""
new_state = None
inputs = status.get(STATUS_RESPONSE_INPUTS)
if inputs:
value = inputs[self._channel]
new_state = value.get(STATUS_RESPONSE_INPUTS_INPUT, None)
self.last_event = value.get(STATUS_RESPONSE_INPUTS_EVENT, None)
event_cnt = value.get(STATUS_RESPONSE_INPUTS_EVENT_CNT, None)
if self.event_cnt != event_cnt:
self.event_cnt = event_cnt
if self._simulate_state:
new_state = True
self.timer = Timer(1,self._turn_off)
self.timer.start()
self._update(new_state != 0, {'last_event' : self.last_event,
'event_cnt' : self.event_cnt})
def _turn_off(self):
self._update(False) | 0.527073 | 0.12363 |
from abc import ABC
from video_streaming import settings
from video_streaming.celery import celery_app
from video_streaming.core.tasks import ChainCallbackMixin
from video_streaming.ffmpeg.utils import FfmpegCallback
from video_streaming.ffmpeg.constants import TASK_DECORATOR_KWARGS
from .base import BaseStreamingTask
from .mixins import CreatePlaylistMixin
class CreatePlaylistTask(
ChainCallbackMixin,
CreatePlaylistMixin,
BaseStreamingTask,
ABC
):
# rewrite BaseOutputMixin.save_failed
def save_failed(self, request_id, output_id):
super().save_failed(request_id, output_id)
# stop reason will only be set if there is no reason before.
# set common reason for the task after many retries or etc.
self.save_job_stop_reason(
self.stop_reason.FAILED_CREATE_PLAYLIST,
request_id
)
@celery_app.task(name="create_playlist",
base=CreatePlaylistTask,
**TASK_DECORATOR_KWARGS)
def create_playlist(
self,
*args,
video_path: str = None,
output_path: str = None,
s3_output_key: str = None,
fragmented: bool = settings.DEFAULT_SEGMENT_TYPE_IS_FMP4,
encode_format: str = settings.DEFAULT_ENCODE_FORMAT,
video_codec: str = None,
audio_codec: str = None,
quality_names: list[str] = None,
custom_qualities: list[dict] = None,
async_run: bool = False,
request_id: str = None,
output_id: str = None,
is_hls: bool = settings.DEFAULT_PLAYLIST_IS_HLS,
**kwargs
) -> dict:
"""create an playlist ( HLS or DASH )
Args:
self:
*args:
s3_output_key:
fragmented:
encode_format:
request_id:
is_hls:
type of playlist, True is HLS, False is MPEG-DASH
video_path:
The local input path
output_path:
The local output path
video_codec:
The video codec format, e.g "libx264", "libx265"
or "libvpx-vp9"
audio_codec:
The audio codec format, e.g "aac"
quality_names:
List of quality names to generate. e.g. ["360p","720p"]
or [Resolutions.R_360P, Resolutions.R_720P]
custom_qualities:
a list of dict includes size and bitrate
e.g. [dict(size=[256, 144], bitrate=[97280, 65536])]
async_run:
default of async_run is False to don't call async method
inside the task, it can raise RuntimeError: asyncio.run()
cannot be called from a running event loop
output_id:
output_id is using in redis key, to save progress of
every output, also it's using to create different path
for outputs
**kwargs:
some unused parameters from previous tasks that set by __call__
Required parameters:
- request_id
- output_id
- input_path
- output_path or s3_output_key
Returns:
a dict includes directory
"""
self.check_create_playlist_requirements(
request_id=request_id,
output_id=output_id,
video_path=video_path,
output_path=output_path,
s3_output_key=s3_output_key)
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
# save primary status using request_id
self.save_primary_status(
self.primary_status.OUTPUTS_PROGRESSING,
request_id)
# save output status using output_id and request_id
self.save_output_status(
self.output_status.PREPARATION_PROCESSING,
output_id,
request_id)
# get output directory and set output_path if is None
output_path, directory = self.ensure_set_output_location(
request_id,
output_id,
output_path=output_path,
s3_output_key=s3_output_key)
playlist = self.initial_protocol(
video_path,
output_id,
request_id,
encode_format,
video_codec=video_codec,
audio_codec=audio_codec,
is_hls=is_hls,
fragmented=fragmented,
custom_qualities=custom_qualities,
quality_names=quality_names)
try:
# self.output_path includes the file name
playlist.output(
output_path,
monitor=FfmpegCallback(
task=self,
task_id=self.request.id.__str__(),
output_id=output_id,
request_id=request_id
).progress,
ffmpeg_bin=settings.FFMPEG_BIN_PATH,
async_run=async_run)
except Exception as e:
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
# TODO handle possible Runtime Errors
# notice : video processing has cost to retry
raise self.retry(
exc=e,
max_retries=settings.TASK_RETRY_FFMPEG_COMMAND_MAX)
# TODO check ffmpeg is really finished successfully,
# Sometimes FfmpegCallback has an error but the Ffmpeg stops
# without error and returns 'ffmpeg executed command successfully'
# it's possible process killed in FfmpegCallback
# so, checking the force stop before continuing
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
self.save_output_status(
self.output_status.PROCESSING_FINISHED,
output_id,
request_id)
return dict(directory=directory) | video-streaming/video_streaming/ffmpeg/tasks/create_playlist.py | from abc import ABC
from video_streaming import settings
from video_streaming.celery import celery_app
from video_streaming.core.tasks import ChainCallbackMixin
from video_streaming.ffmpeg.utils import FfmpegCallback
from video_streaming.ffmpeg.constants import TASK_DECORATOR_KWARGS
from .base import BaseStreamingTask
from .mixins import CreatePlaylistMixin
class CreatePlaylistTask(
ChainCallbackMixin,
CreatePlaylistMixin,
BaseStreamingTask,
ABC
):
# rewrite BaseOutputMixin.save_failed
def save_failed(self, request_id, output_id):
super().save_failed(request_id, output_id)
# stop reason will only be set if there is no reason before.
# set common reason for the task after many retries or etc.
self.save_job_stop_reason(
self.stop_reason.FAILED_CREATE_PLAYLIST,
request_id
)
@celery_app.task(name="create_playlist",
base=CreatePlaylistTask,
**TASK_DECORATOR_KWARGS)
def create_playlist(
self,
*args,
video_path: str = None,
output_path: str = None,
s3_output_key: str = None,
fragmented: bool = settings.DEFAULT_SEGMENT_TYPE_IS_FMP4,
encode_format: str = settings.DEFAULT_ENCODE_FORMAT,
video_codec: str = None,
audio_codec: str = None,
quality_names: list[str] = None,
custom_qualities: list[dict] = None,
async_run: bool = False,
request_id: str = None,
output_id: str = None,
is_hls: bool = settings.DEFAULT_PLAYLIST_IS_HLS,
**kwargs
) -> dict:
"""create an playlist ( HLS or DASH )
Args:
self:
*args:
s3_output_key:
fragmented:
encode_format:
request_id:
is_hls:
type of playlist, True is HLS, False is MPEG-DASH
video_path:
The local input path
output_path:
The local output path
video_codec:
The video codec format, e.g "libx264", "libx265"
or "libvpx-vp9"
audio_codec:
The audio codec format, e.g "aac"
quality_names:
List of quality names to generate. e.g. ["360p","720p"]
or [Resolutions.R_360P, Resolutions.R_720P]
custom_qualities:
a list of dict includes size and bitrate
e.g. [dict(size=[256, 144], bitrate=[97280, 65536])]
async_run:
default of async_run is False to don't call async method
inside the task, it can raise RuntimeError: asyncio.run()
cannot be called from a running event loop
output_id:
output_id is using in redis key, to save progress of
every output, also it's using to create different path
for outputs
**kwargs:
some unused parameters from previous tasks that set by __call__
Required parameters:
- request_id
- output_id
- input_path
- output_path or s3_output_key
Returns:
a dict includes directory
"""
self.check_create_playlist_requirements(
request_id=request_id,
output_id=output_id,
video_path=video_path,
output_path=output_path,
s3_output_key=s3_output_key)
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
# save primary status using request_id
self.save_primary_status(
self.primary_status.OUTPUTS_PROGRESSING,
request_id)
# save output status using output_id and request_id
self.save_output_status(
self.output_status.PREPARATION_PROCESSING,
output_id,
request_id)
# get output directory and set output_path if is None
output_path, directory = self.ensure_set_output_location(
request_id,
output_id,
output_path=output_path,
s3_output_key=s3_output_key)
playlist = self.initial_protocol(
video_path,
output_id,
request_id,
encode_format,
video_codec=video_codec,
audio_codec=audio_codec,
is_hls=is_hls,
fragmented=fragmented,
custom_qualities=custom_qualities,
quality_names=quality_names)
try:
# self.output_path includes the file name
playlist.output(
output_path,
monitor=FfmpegCallback(
task=self,
task_id=self.request.id.__str__(),
output_id=output_id,
request_id=request_id
).progress,
ffmpeg_bin=settings.FFMPEG_BIN_PATH,
async_run=async_run)
except Exception as e:
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
# TODO handle possible Runtime Errors
# notice : video processing has cost to retry
raise self.retry(
exc=e,
max_retries=settings.TASK_RETRY_FFMPEG_COMMAND_MAX)
# TODO check ffmpeg is really finished successfully,
# Sometimes FfmpegCallback has an error but the Ffmpeg stops
# without error and returns 'ffmpeg executed command successfully'
# it's possible process killed in FfmpegCallback
# so, checking the force stop before continuing
if self.is_forced_to_stop(request_id):
raise self.raise_revoke(request_id)
if self.is_output_forced_to_stop(request_id, output_id):
raise self.raise_revoke_output(request_id, output_id)
self.save_output_status(
self.output_status.PROCESSING_FINISHED,
output_id,
request_id)
return dict(directory=directory) | 0.550124 | 0.120853 |
from scipy.optimize import fsolve
def interpolator(value , x_series, y_series):
if not(len(x_series) == len(y_series)):
print('x and y must have the same lenght')
return 'ERR'
for i in range(1, len(x_series)):
if (value <= x_series[i]) and (value >= x_series[i - 1]):
return (y_series[i] - y_series[i - 1]) / (x_series[i] - x_series[i - 1]) * (value - x_series[i - 1]) + y_series[i - 1]
else:
continue
# Se arrivo qui vuol dire che non ho trovato un match
print('ERROR: Value out of range')
return 0
def oldintersection(x1_series, y1_series, x2_series, y2_series, initial_guess = 0):
if not(len(x1_series) == len(y1_series) and len(x2_series) == len(y2_series)):
print('x and y must have the same lenght')
return 'ERR'
else:
def objective(x):
return interpolator(x, x1_series, y1_series) - interpolator(x, x2_series, y2_series)
x = fsolve(objective, initial_guess)
y = interpolator(x, x1_series, y1_series)
return [x, y]
def intersection(x1_series, y1_series, x2_series, y2_series):
if not(len(x1_series) == len(y1_series) and len(x2_series) == len(y2_series)):
print('x and y must have the same lenght')
return 'ERR'
else:
step = x1_series[1] - x1_series[0]
for i in range(1, len(x1_series)):
yP1 = y1_series[i - 1]
yP2 = y1_series[i]
yB1 = interpolator(x1_series[i - 1], x2_series, y2_series)
yB2 = interpolator(x1_series[i], x2_series, y2_series)
if (yP1 - yB1)*(yP2 - yB2) < 0:
A = (yP2 - yP1)/step
B = (yB2 - yB1)/step
x_intersection = (yB1 - yP1)/(A - B) + x1_series[i - 1]
return x_intersection, interpolator(x_intersection, x1_series, y1_series)
else:
continue | Code/Performance/Functions.py | from scipy.optimize import fsolve
def interpolator(value , x_series, y_series):
if not(len(x_series) == len(y_series)):
print('x and y must have the same lenght')
return 'ERR'
for i in range(1, len(x_series)):
if (value <= x_series[i]) and (value >= x_series[i - 1]):
return (y_series[i] - y_series[i - 1]) / (x_series[i] - x_series[i - 1]) * (value - x_series[i - 1]) + y_series[i - 1]
else:
continue
# Se arrivo qui vuol dire che non ho trovato un match
print('ERROR: Value out of range')
return 0
def oldintersection(x1_series, y1_series, x2_series, y2_series, initial_guess = 0):
if not(len(x1_series) == len(y1_series) and len(x2_series) == len(y2_series)):
print('x and y must have the same lenght')
return 'ERR'
else:
def objective(x):
return interpolator(x, x1_series, y1_series) - interpolator(x, x2_series, y2_series)
x = fsolve(objective, initial_guess)
y = interpolator(x, x1_series, y1_series)
return [x, y]
def intersection(x1_series, y1_series, x2_series, y2_series):
if not(len(x1_series) == len(y1_series) and len(x2_series) == len(y2_series)):
print('x and y must have the same lenght')
return 'ERR'
else:
step = x1_series[1] - x1_series[0]
for i in range(1, len(x1_series)):
yP1 = y1_series[i - 1]
yP2 = y1_series[i]
yB1 = interpolator(x1_series[i - 1], x2_series, y2_series)
yB2 = interpolator(x1_series[i], x2_series, y2_series)
if (yP1 - yB1)*(yP2 - yB2) < 0:
A = (yP2 - yP1)/step
B = (yB2 - yB1)/step
x_intersection = (yB1 - yP1)/(A - B) + x1_series[i - 1]
return x_intersection, interpolator(x_intersection, x1_series, y1_series)
else:
continue | 0.316053 | 0.602997 |
import argparse
from typing import List
from pydantic import BaseModel, Field
from MHDDoS.methods.methods import Methods
class Arguments(BaseModel):
targets: List[str] = Field(default=[])
config: str = Field(default=None)
config_fetch_interval: float = Field(default=600)
attack_methods: List[str] = Field(default=[])
requests_per_connection: int = 100
proxies: str = Field(default=None)
proxies_validation_timeout: float = Field(default=3)
proxies_fetch_interval: float = Field(default=600)
no_gui: bool = Field(default=False)
ignore_geolocation_change: bool = Field(default=False)
def parse_command_line_args() -> Arguments:
parser = argparse.ArgumentParser()
parser.add_argument(
"targets",
nargs="*",
type=str,
help="List of targets, separated by spaces",
)
parser.add_argument(
"-c",
"--config",
type=str,
help="URL or local path of a file with attack targets",
)
parser.add_argument(
"--config-fetch-interval",
type=float,
default=600,
help="How often to fetch the targets configuration (in seconds) (default is 600)",
)
# parser.add_argument(
# "-t",
# "--threads",
# type=int,
# default=-1,
# help=f"Total number of threads to run (default is CPU * THREADS_PER_CORE).\n"
# f"NOTE: Unused parameter. Kept for compatibility with mhddos_proxy commands. Palyanytsya manages threads automatically.",
# )
# parser.add_argument(
# "--rpc",
# type=int,
# default=2000,
# help=f"How many requests to send on a single proxy connection (default is 2000)\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya keeps the connections alive until they are changes by the configuration re-fetch.",
# )
# parser.add_argument(
# "--debug",
# action="store_true",
# default=False,
# help=f"Print log as text\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya always logs debug info into STDERR.",
# )
# parser.add_argument(
# "--table",
# action="store_true",
# default=False,
# help="Print log as table\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya provides a command-line GUI with attack status by default.",
# )
parser.add_argument(
"--vpn",
dest="vpn_mode",
action="store_true",
default=False,
help="Disable proxies to use VPN",
)
# parser.add_argument(
# "--http-methods",
# nargs="+",
# type=str.upper,
# default=["GET", "POST", "STRESS"],
# choices=Methods.LAYER7_METHODS,
# help="List of HTTP(s) attack methods to use. Default is GET + POST|STRESS",
# )
parser.add_argument(
"-m",
"--attack-methods",
nargs="+",
type=str.upper,
default=["TCP", "GET", "POST", "STRESS"],
choices=Methods.ALL_METHODS,
help="List of MHDDoS attack methods to use. Default is TCP + GET + POST + STRESS",
)
parser.add_argument(
"-r",
"--requests-per-connection",
type=int,
default=100,
help="Number of requests per single connection when running a Layer 7 attack",
)
parser.add_argument(
"-p",
"--proxies",
help="URL or local path to a file with proxies to use",
)
parser.add_argument(
"--proxies-validation-timeout",
type=float,
default=3,
help="How many seconds to wait for the proxy to make a connection (default is 5)"
)
parser.add_argument(
"--proxies-fetch-interval",
type=float,
default=600,
help="How often to fetch the proxies (in seconds) (default is 600)",
)
parser.add_argument(
"--no-gui",
action="store_true",
default=False,
help="Disable the GUI and display live logs from all processes instead",
)
parser.add_argument(
"-g",
"--ignore-geolocation-change",
action="store_true",
default=False,
help="Do not pause current attacks if the local machine's IP geolocation changes (for example, when VPN disconnects)",
)
# parser.add_argument(
# "--itarmy",
# action="store_true",
# default=False,
# )
args = parser.parse_args()
args = Arguments.parse_obj(args.__dict__)
return args | utils/input_args.py | import argparse
from typing import List
from pydantic import BaseModel, Field
from MHDDoS.methods.methods import Methods
class Arguments(BaseModel):
targets: List[str] = Field(default=[])
config: str = Field(default=None)
config_fetch_interval: float = Field(default=600)
attack_methods: List[str] = Field(default=[])
requests_per_connection: int = 100
proxies: str = Field(default=None)
proxies_validation_timeout: float = Field(default=3)
proxies_fetch_interval: float = Field(default=600)
no_gui: bool = Field(default=False)
ignore_geolocation_change: bool = Field(default=False)
def parse_command_line_args() -> Arguments:
parser = argparse.ArgumentParser()
parser.add_argument(
"targets",
nargs="*",
type=str,
help="List of targets, separated by spaces",
)
parser.add_argument(
"-c",
"--config",
type=str,
help="URL or local path of a file with attack targets",
)
parser.add_argument(
"--config-fetch-interval",
type=float,
default=600,
help="How often to fetch the targets configuration (in seconds) (default is 600)",
)
# parser.add_argument(
# "-t",
# "--threads",
# type=int,
# default=-1,
# help=f"Total number of threads to run (default is CPU * THREADS_PER_CORE).\n"
# f"NOTE: Unused parameter. Kept for compatibility with mhddos_proxy commands. Palyanytsya manages threads automatically.",
# )
# parser.add_argument(
# "--rpc",
# type=int,
# default=2000,
# help=f"How many requests to send on a single proxy connection (default is 2000)\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya keeps the connections alive until they are changes by the configuration re-fetch.",
# )
# parser.add_argument(
# "--debug",
# action="store_true",
# default=False,
# help=f"Print log as text\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya always logs debug info into STDERR.",
# )
# parser.add_argument(
# "--table",
# action="store_true",
# default=False,
# help="Print log as table\n"
# f"NOTE: Unused argument. Kept for compatibility with mhddos_proxy commands. Palyanytsya provides a command-line GUI with attack status by default.",
# )
parser.add_argument(
"--vpn",
dest="vpn_mode",
action="store_true",
default=False,
help="Disable proxies to use VPN",
)
# parser.add_argument(
# "--http-methods",
# nargs="+",
# type=str.upper,
# default=["GET", "POST", "STRESS"],
# choices=Methods.LAYER7_METHODS,
# help="List of HTTP(s) attack methods to use. Default is GET + POST|STRESS",
# )
parser.add_argument(
"-m",
"--attack-methods",
nargs="+",
type=str.upper,
default=["TCP", "GET", "POST", "STRESS"],
choices=Methods.ALL_METHODS,
help="List of MHDDoS attack methods to use. Default is TCP + GET + POST + STRESS",
)
parser.add_argument(
"-r",
"--requests-per-connection",
type=int,
default=100,
help="Number of requests per single connection when running a Layer 7 attack",
)
parser.add_argument(
"-p",
"--proxies",
help="URL or local path to a file with proxies to use",
)
parser.add_argument(
"--proxies-validation-timeout",
type=float,
default=3,
help="How many seconds to wait for the proxy to make a connection (default is 5)"
)
parser.add_argument(
"--proxies-fetch-interval",
type=float,
default=600,
help="How often to fetch the proxies (in seconds) (default is 600)",
)
parser.add_argument(
"--no-gui",
action="store_true",
default=False,
help="Disable the GUI and display live logs from all processes instead",
)
parser.add_argument(
"-g",
"--ignore-geolocation-change",
action="store_true",
default=False,
help="Do not pause current attacks if the local machine's IP geolocation changes (for example, when VPN disconnects)",
)
# parser.add_argument(
# "--itarmy",
# action="store_true",
# default=False,
# )
args = parser.parse_args()
args = Arguments.parse_obj(args.__dict__)
return args | 0.717012 | 0.201401 |
import re
import io
day23 = __import__("day-23")
process = day23.process_gen
def get_intcode():
with open('day-25.txt', 'r') as f:
text = f.read().strip()
idata = [int(x) for x in text.split(',')]
return idata
def parse_output(text):
lines = text.split('\n')
name, doors, items = None, [], []
parse_doors, parse_items = False, False
for line in lines:
line = line.strip()
if match := re.match("== (.*) ==", line):
name = match[1]
elif line == "Doors here lead:":
parse_doors = True
elif line == "Items here:":
parse_items = True
elif parse_doors:
if match := re.match("- (east|west|south|north)", line):
doors.append(match[1])
else:
parse_doors = False
elif parse_items:
if match := re.match("- (.*)", line):
items.append(match[1])
else:
parse_items = False
return name, doors, items
def build_map():
def walk(path):
path = list(path)
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
rv = None
buf = io.StringIO()
while True:
name, v = next(g)
if name == 'output':
buf.write(chr(v))
elif name == 'input':
rv = parse_output(buf.getvalue())
buf = io.StringIO()
if path:
push_cmd(path.pop(0))
else:
return rv
name, doors, items = walk([])
visited = set()
stack = [(name, doors, [])]
while stack:
name, doors, path = stack.pop()
if name in visited:
continue
visited.add(name)
for door in doors:
new_path = path + [door]
new_name, new_doors, _ = walk(new_path)
stack.append((new_name, new_doors, new_path))
print(visited)
def run(items):
# Hull Breach:
# east - Holodeck
# south - Stables (cake)
# east - Observatory (electoromagnet)
# east - Passages (infinite loop)
# north - Science Lab (photons)
# south - Kitchen
# west - Arcade (mutex)
# west - Sick Bay (klein bottle)
# south - Hot Chocolate Fountain
# east - Gift Wrapping Center (monolith)
# south - Crew Quarters (fuel cell)
# west - Corridor (escape pod)
# west - Warp Drive Maintenance (astrolabe)
# west - Hallway (molten lava)
# west - Storage
# north - Engineering (tambourine)
# west - Navigation (dark matter)
# west - Security Checkpoint
# north
# {'astrolabe', 'monolith', 'tambourine', 'dark matter'}
commands = [
'south',
'take cake',
'south',
'west',
'take mutex',
'east',
'north',
'north',
'west',
'take klein bottle',
'south',
'east',
'take monolith',
'south',
'take fuel cell',
'west',
'west',
'take astrolabe',
'east',
'east',
'north',
'west',
'north',
'west',
'north',
'take tambourine',
'south',
'west',
'take dark matter',
'west',
'north', # security check!
]
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
buf = io.StringIO()
try:
while True:
name, v = next(g)
if name == 'output':
buf.write(chr(v))
elif name == 'input':
text = buf.getvalue()
if 'Pressure-Sensitive Floor' in text:
if 'heavier' not in text and 'lighter' not in text:
print(text)
buf = io.StringIO()
if commands:
value = commands.pop(0)
if value.startswith('take'):
if any(value.endswith(x) for x in items):
pass
else:
value = commands.pop(0)
else:
break
push_cmd(value)
except StopIteration:
print(items)
print(buf.getvalue())
def run_vm():
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
while True:
name, v = next(g)
if name == 'output':
print(chr(v), end='')
elif name == 'input':
value = input('IN: ')
push_cmd(value)
import itertools
def run_scissors():
items = set([
"mutex",
"dark matter",
"klein bottle",
"tambourine",
"fuel cell",
"astrolabe",
"monolith",
"cake",
])
for i in range(len(items)):
for it in itertools.combinations(items, i):
new_items = items - set(it)
run(new_items)
if __name__ == '__main__':
build_map() | day-25.py | import re
import io
day23 = __import__("day-23")
process = day23.process_gen
def get_intcode():
with open('day-25.txt', 'r') as f:
text = f.read().strip()
idata = [int(x) for x in text.split(',')]
return idata
def parse_output(text):
lines = text.split('\n')
name, doors, items = None, [], []
parse_doors, parse_items = False, False
for line in lines:
line = line.strip()
if match := re.match("== (.*) ==", line):
name = match[1]
elif line == "Doors here lead:":
parse_doors = True
elif line == "Items here:":
parse_items = True
elif parse_doors:
if match := re.match("- (east|west|south|north)", line):
doors.append(match[1])
else:
parse_doors = False
elif parse_items:
if match := re.match("- (.*)", line):
items.append(match[1])
else:
parse_items = False
return name, doors, items
def build_map():
def walk(path):
path = list(path)
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
rv = None
buf = io.StringIO()
while True:
name, v = next(g)
if name == 'output':
buf.write(chr(v))
elif name == 'input':
rv = parse_output(buf.getvalue())
buf = io.StringIO()
if path:
push_cmd(path.pop(0))
else:
return rv
name, doors, items = walk([])
visited = set()
stack = [(name, doors, [])]
while stack:
name, doors, path = stack.pop()
if name in visited:
continue
visited.add(name)
for door in doors:
new_path = path + [door]
new_name, new_doors, _ = walk(new_path)
stack.append((new_name, new_doors, new_path))
print(visited)
def run(items):
# Hull Breach:
# east - Holodeck
# south - Stables (cake)
# east - Observatory (electoromagnet)
# east - Passages (infinite loop)
# north - Science Lab (photons)
# south - Kitchen
# west - Arcade (mutex)
# west - Sick Bay (klein bottle)
# south - Hot Chocolate Fountain
# east - Gift Wrapping Center (monolith)
# south - Crew Quarters (fuel cell)
# west - Corridor (escape pod)
# west - Warp Drive Maintenance (astrolabe)
# west - Hallway (molten lava)
# west - Storage
# north - Engineering (tambourine)
# west - Navigation (dark matter)
# west - Security Checkpoint
# north
# {'astrolabe', 'monolith', 'tambourine', 'dark matter'}
commands = [
'south',
'take cake',
'south',
'west',
'take mutex',
'east',
'north',
'north',
'west',
'take klein bottle',
'south',
'east',
'take monolith',
'south',
'take fuel cell',
'west',
'west',
'take astrolabe',
'east',
'east',
'north',
'west',
'north',
'west',
'north',
'take tambourine',
'south',
'west',
'take dark matter',
'west',
'north', # security check!
]
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
buf = io.StringIO()
try:
while True:
name, v = next(g)
if name == 'output':
buf.write(chr(v))
elif name == 'input':
text = buf.getvalue()
if 'Pressure-Sensitive Floor' in text:
if 'heavier' not in text and 'lighter' not in text:
print(text)
buf = io.StringIO()
if commands:
value = commands.pop(0)
if value.startswith('take'):
if any(value.endswith(x) for x in items):
pass
else:
value = commands.pop(0)
else:
break
push_cmd(value)
except StopIteration:
print(items)
print(buf.getvalue())
def run_vm():
idata = get_intcode()
inp = []
g = process(idata, inp)
def push_cmd(cmd):
for ch in reversed(cmd + '\n'):
inp.append(ord(ch))
while True:
name, v = next(g)
if name == 'output':
print(chr(v), end='')
elif name == 'input':
value = input('IN: ')
push_cmd(value)
import itertools
def run_scissors():
items = set([
"mutex",
"dark matter",
"klein bottle",
"tambourine",
"fuel cell",
"astrolabe",
"monolith",
"cake",
])
for i in range(len(items)):
for it in itertools.combinations(items, i):
new_items = items - set(it)
run(new_items)
if __name__ == '__main__':
build_map() | 0.099607 | 0.1602 |
import configparser
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
class PysentelConfig(object):
"""
Module for handling configs in an easy and objected manner.
"""
def __init__(self):
"""
Initialization constructor - create config-object and import configs.
"""
# Initialize configparser and the config-file
self.config = configparser.ConfigParser()
self.config.read('/etc/pysentel/pysentel.ini')
try:
self.interval = int(self.config['Pysentel']['interval'])
self.sensors = self._get_sensors()
self.influxdb = dict(self.config.items('InfluxDBIngest'))
except configparser.NoSectionError:
pass
def _get_sensors(self) -> dict:
"""
Internal function for extracting configured sensors
:return: Dict of sensors with sensor_id as key and name as value.
"""
sensors = {}
for k, v in self.config.items('Sensors'):
sensors[k] = v
return sensors
class InfluxDataIngest:
"""
Module for handling ingests to InfluxDB-bucket.
"""
def __init__(self,
url: str,
org: str,
bucket: str,
token: str):
"""
Initialization constructor - start our DB-connection.
:param url: Define url for the InfluxDB connection. Required.
:param org: Define InfluxDB organization. Required.
:param bucket: Define InfluxDB bucket to ingest into. Required.
:param token: Define authentication-token with write-access. Required.
"""
self.org = org
self.bucket = bucket
self.url = url
self.token = token
self.connection = self._establish_connection()
self.client = self._write_definitions()
def __del__(self):
""" Destructor for closing object correctly. """
self._close_connection()
def _establish_connection(self):
""" Create connection to InfluxDB. """
return InfluxDBClient(
url=self.url,
token=self.token,
org=self.org)
def _write_definitions(self):
""" Define write options for write_api. """
return self.connection.write_api(write_options=SYNCHRONOUS)
def _close_connection(self):
""" Closing connection to InfluxDB. """
return self.client.close()
def write_points(self, datapoints: list):
"""
Write the provided datapoints to InfluxDB-bucket.
:param datapoints: List of dictionaries for all points to be written.
Required.
"""
if not datapoints or not isinstance(datapoints, list):
ValueError('Provided "datapoints" is either not provided or is '
'not a list.')
return self.client.write(
bucket=self.bucket,
org=self.org,
record=datapoints) | pysentel/helpers.py | import configparser
from influxdb_client import InfluxDBClient
from influxdb_client.client.write_api import SYNCHRONOUS
class PysentelConfig(object):
"""
Module for handling configs in an easy and objected manner.
"""
def __init__(self):
"""
Initialization constructor - create config-object and import configs.
"""
# Initialize configparser and the config-file
self.config = configparser.ConfigParser()
self.config.read('/etc/pysentel/pysentel.ini')
try:
self.interval = int(self.config['Pysentel']['interval'])
self.sensors = self._get_sensors()
self.influxdb = dict(self.config.items('InfluxDBIngest'))
except configparser.NoSectionError:
pass
def _get_sensors(self) -> dict:
"""
Internal function for extracting configured sensors
:return: Dict of sensors with sensor_id as key and name as value.
"""
sensors = {}
for k, v in self.config.items('Sensors'):
sensors[k] = v
return sensors
class InfluxDataIngest:
"""
Module for handling ingests to InfluxDB-bucket.
"""
def __init__(self,
url: str,
org: str,
bucket: str,
token: str):
"""
Initialization constructor - start our DB-connection.
:param url: Define url for the InfluxDB connection. Required.
:param org: Define InfluxDB organization. Required.
:param bucket: Define InfluxDB bucket to ingest into. Required.
:param token: Define authentication-token with write-access. Required.
"""
self.org = org
self.bucket = bucket
self.url = url
self.token = token
self.connection = self._establish_connection()
self.client = self._write_definitions()
def __del__(self):
""" Destructor for closing object correctly. """
self._close_connection()
def _establish_connection(self):
""" Create connection to InfluxDB. """
return InfluxDBClient(
url=self.url,
token=self.token,
org=self.org)
def _write_definitions(self):
""" Define write options for write_api. """
return self.connection.write_api(write_options=SYNCHRONOUS)
def _close_connection(self):
""" Closing connection to InfluxDB. """
return self.client.close()
def write_points(self, datapoints: list):
"""
Write the provided datapoints to InfluxDB-bucket.
:param datapoints: List of dictionaries for all points to be written.
Required.
"""
if not datapoints or not isinstance(datapoints, list):
ValueError('Provided "datapoints" is either not provided or is '
'not a list.')
return self.client.write(
bucket=self.bucket,
org=self.org,
record=datapoints) | 0.662141 | 0.129623 |
class HiveConnectParams(object):
"""Implementation of the 'HiveConnectParams' model.
Specifies an Object containing information about a registered Hive
source.
Attributes:
hdfs_entity_id (int|long): Specifies the entity id of the HDFS source
for this Hive
kerberos_principal (string): Specifies the kerberos principal.
metastore (string): Specifies the Hive metastore host.
thrift_port (int): Specifies the Hive metastore thrift Port
"""
# Create a mapping from Model property names to API property names
_names = {
"hdfs_entity_id":'hdfsEntityId',
"kerberos_principal":'kerberosPrincipal',
"metastore": 'metastore',
"thrift_port": 'thriftPort'
}
def __init__(self,
hdfs_entity_id=None,
kerberos_principal=None,
metastore=None,
thrift_port=None):
"""Constructor for the HiveConnectParams class"""
# Initialize members of the class
self.hdfs_entity_id = hdfs_entity_id
self.kerberos_principal = kerberos_principal
self.metastore = metastore
self.thrift_port = thrift_port
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
hdfs_entity_id = dictionary.get('hdfsEntityId')
kerberos_principal = dictionary.get('kerberosPrincipal')
metastore = dictionary.get('metastore', None)
thrift_port = dictionary.get('thriftPort', None)
# Return an object of this model
return cls(hdfs_entity_id,
kerberos_principal,
metastore,
thrift_port) | cohesity_management_sdk/models/hive_connect_params.py |
class HiveConnectParams(object):
"""Implementation of the 'HiveConnectParams' model.
Specifies an Object containing information about a registered Hive
source.
Attributes:
hdfs_entity_id (int|long): Specifies the entity id of the HDFS source
for this Hive
kerberos_principal (string): Specifies the kerberos principal.
metastore (string): Specifies the Hive metastore host.
thrift_port (int): Specifies the Hive metastore thrift Port
"""
# Create a mapping from Model property names to API property names
_names = {
"hdfs_entity_id":'hdfsEntityId',
"kerberos_principal":'kerberosPrincipal',
"metastore": 'metastore',
"thrift_port": 'thriftPort'
}
def __init__(self,
hdfs_entity_id=None,
kerberos_principal=None,
metastore=None,
thrift_port=None):
"""Constructor for the HiveConnectParams class"""
# Initialize members of the class
self.hdfs_entity_id = hdfs_entity_id
self.kerberos_principal = kerberos_principal
self.metastore = metastore
self.thrift_port = thrift_port
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
hdfs_entity_id = dictionary.get('hdfsEntityId')
kerberos_principal = dictionary.get('kerberosPrincipal')
metastore = dictionary.get('metastore', None)
thrift_port = dictionary.get('thriftPort', None)
# Return an object of this model
return cls(hdfs_entity_id,
kerberos_principal,
metastore,
thrift_port) | 0.863363 | 0.405802 |
import argparse
import sys
import tempfile
from time import time
import random
from os import listdir
from os.path import isfile, join
import pandas
import numpy as np
import tensorflow as tf
from sklearn import metrics
# model settings
# Static seed to allow for reproducability between training runs
tf.set_random_seed(12345)
trainingCycles = 500000 # Number of training steps before ending
batchSize = 1000 # Number of examples per training batch
summarySteps = 1000 # Number of training steps between each summary
dropout = 0.5 # Node dropout for training
nodeLayout = [40, 30, 20, 10] # Layout of nodes in each layer
mainDirectory = str("./model_1/")
trainFiles = [f for f in listdir("./train/") if isfile(join("./train/", f))]
evalFiles = [f for f in listdir("./eval/") if isfile(join("./eval/", f))]
# Initialises data arrays
trainDataX = np.empty([0, 4])
trainDataY = np.empty([0, 2])
evalDataX = np.empty([0, 4])
evalDataY = np.empty([0, 2])
# Reads training data into memory
readPos = 0
for fileName in trainFiles:
importedData = pandas.read_csv("./train/" + fileName, sep=',')
xValuesDF = importedData[["RSI14", "RSI50", "STOCH14K", "STOCH14D"]]
yValuesDF = importedData[["longOutput", "shortOutput"]]
xValues = np.array(xValuesDF.values.tolist())
yValues = np.array(yValuesDF.values.tolist())
trainDataX = np.concatenate([trainDataX, xValues], axis=0)
trainDataY = np.concatenate([trainDataY, yValues], axis=0)
if readPos % 50 == 0 and readPos > 0:
print("Loaded " + str(readPos) + " training files")
readPos += 1
print("\n\n")
# Reads evalutation data into memory
readPos = 0
for fileName in evalFiles:
importedData = pandas.read_csv("./eval/" + fileName, sep=',')
xValuesDF = importedData[["RSI14", "RSI50", "STOCH14K", "STOCH14D"]]
yValuesDF = importedData[["longOutput", "shortOutput"]]
xValues = np.array(xValuesDF.values.tolist())
yValues = np.array(yValuesDF.values.tolist())
evalDataX = np.concatenate([evalDataX, xValues], axis=0)
evalDataY = np.concatenate([evalDataY, yValues], axis=0)
if readPos % 50 == 0 and readPos > 0:
print("Loaded " + str(readPos) + " training files")
readPos += 1
print("\n\n")
# used to sample batches from your data for training
def createTrainingBatch(amount):
randomBatchPos = np.random.randint(0, trainDataX.shape[0], amount)
xOut = trainDataX[randomBatchPos]
yOut = trainDataY[randomBatchPos]
return xOut, yOut
tf.logging.set_verbosity(tf.logging.INFO)
# ML training and evaluation functions
def train():
globalStepTensor = tf.Variable(0, trainable=False, name='global_step')
sess = tf.InteractiveSession()
# placeholder for the input features
x = tf.placeholder(tf.float32, [None, 4])
# placeholder for the one-hot labels
y = tf.placeholder(tf.float32, [None, 2])
# placeholder for node dropout rate
internalDropout = tf.placeholder(tf.float32, None)
net = x # input layer is the trading indicators
# Creates the neural network model
with tf.name_scope('network'):
# Initialises each layer in the network
layerPos = 0
for units in nodeLayout:
net = tf.layers.dense(
net,
units=units,
activation=tf.nn.tanh,
name=str(
"dense" +
str(units) +
"_" +
str(layerPos))) # adds each layer to the networm as specified by nodeLayout
# dropout layer after each layer
net = tf.layers.dropout(net, rate=internalDropout)
layerPos += 1
logits = tf.layers.dense(
net, 2, activation=tf.nn.softmax) # network output
with tf.name_scope('lossFunction'):
cross_entropy_loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(
labels=y,
logits=logits)) # on NO account put this within a name scope - tensorboard shits itself
with tf.name_scope('trainingStep'):
tf.summary.scalar('crossEntropyLoss', cross_entropy_loss)
trainStep = tf.train.AdamOptimizer(0.0001).minimize(
cross_entropy_loss, global_step=globalStepTensor)
with tf.name_scope('accuracy'):
correctPrediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correctPrediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
trainWriter = tf.summary.FileWriter(
mainDirectory + '/train', sess.graph, flush_secs=1, max_queue=2)
evalWriter = tf.summary.FileWriter(
mainDirectory + '/eval', sess.graph, flush_secs=1, max_queue=2)
tf.global_variables_initializer().run()
# Saves the model at defined checkpoints and loads any available model at
# start-up
saver = tf.train.Saver(max_to_keep=2, name="checkpoint")
path = tf.train.get_checkpoint_state(mainDirectory)
if path is not None:
saver.restore(sess, tf.train.latest_checkpoint(mainDirectory))
lastTime = time()
while tf.train.global_step(sess, globalStepTensor) <= trainingCycles:
globalStep = tf.train.global_step(sess, globalStepTensor)
# generates batch for each training cycle
xFeed, yFeed = createTrainingBatch(batchSize)
# Record summaries and accuracy on both train and eval data
if globalStep % summarySteps == 0:
currentTime = time()
totalTime = (currentTime - lastTime)
print(str(totalTime) + " seconds, " +
str(summarySteps / totalTime) + " steps/sec")
lastTime = currentTime
summary, accuracyOut, _ = sess.run([
merged,
accuracy,
trainStep
],
feed_dict={
x: xFeed,
y: yFeed,
internalDropout: dropout
})
trainWriter.add_summary(summary, globalStep)
trainWriter.flush()
print('Train accuracy at step %s: %s' % (globalStep, accuracyOut))
summary, accuracyOut = sess.run([
merged,
accuracy,
],
feed_dict={
x: evalDataX,
y: evalDataY,
internalDropout: 0
})
evalWriter.add_summary(summary, globalStep)
evalWriter.flush()
print('Eval accuracy at step %s: %s' % (globalStep, accuracyOut))
print("\n\n")
saver.save(sess, save_path=str(mainDirectory + "model"),
global_step=globalStep) # saves a snapshot of the model
else: # Training cycle
_ = sess.run(
[trainStep], feed_dict={
x: xFeed,
y: yFeed,
internalDropout: dropout
})
trainWriter.close()
evalWriter.close()
train() | Chatbot_KG/stock/MLP.py | import argparse
import sys
import tempfile
from time import time
import random
from os import listdir
from os.path import isfile, join
import pandas
import numpy as np
import tensorflow as tf
from sklearn import metrics
# model settings
# Static seed to allow for reproducability between training runs
tf.set_random_seed(12345)
trainingCycles = 500000 # Number of training steps before ending
batchSize = 1000 # Number of examples per training batch
summarySteps = 1000 # Number of training steps between each summary
dropout = 0.5 # Node dropout for training
nodeLayout = [40, 30, 20, 10] # Layout of nodes in each layer
mainDirectory = str("./model_1/")
trainFiles = [f for f in listdir("./train/") if isfile(join("./train/", f))]
evalFiles = [f for f in listdir("./eval/") if isfile(join("./eval/", f))]
# Initialises data arrays
trainDataX = np.empty([0, 4])
trainDataY = np.empty([0, 2])
evalDataX = np.empty([0, 4])
evalDataY = np.empty([0, 2])
# Reads training data into memory
readPos = 0
for fileName in trainFiles:
importedData = pandas.read_csv("./train/" + fileName, sep=',')
xValuesDF = importedData[["RSI14", "RSI50", "STOCH14K", "STOCH14D"]]
yValuesDF = importedData[["longOutput", "shortOutput"]]
xValues = np.array(xValuesDF.values.tolist())
yValues = np.array(yValuesDF.values.tolist())
trainDataX = np.concatenate([trainDataX, xValues], axis=0)
trainDataY = np.concatenate([trainDataY, yValues], axis=0)
if readPos % 50 == 0 and readPos > 0:
print("Loaded " + str(readPos) + " training files")
readPos += 1
print("\n\n")
# Reads evalutation data into memory
readPos = 0
for fileName in evalFiles:
importedData = pandas.read_csv("./eval/" + fileName, sep=',')
xValuesDF = importedData[["RSI14", "RSI50", "STOCH14K", "STOCH14D"]]
yValuesDF = importedData[["longOutput", "shortOutput"]]
xValues = np.array(xValuesDF.values.tolist())
yValues = np.array(yValuesDF.values.tolist())
evalDataX = np.concatenate([evalDataX, xValues], axis=0)
evalDataY = np.concatenate([evalDataY, yValues], axis=0)
if readPos % 50 == 0 and readPos > 0:
print("Loaded " + str(readPos) + " training files")
readPos += 1
print("\n\n")
# used to sample batches from your data for training
def createTrainingBatch(amount):
randomBatchPos = np.random.randint(0, trainDataX.shape[0], amount)
xOut = trainDataX[randomBatchPos]
yOut = trainDataY[randomBatchPos]
return xOut, yOut
tf.logging.set_verbosity(tf.logging.INFO)
# ML training and evaluation functions
def train():
globalStepTensor = tf.Variable(0, trainable=False, name='global_step')
sess = tf.InteractiveSession()
# placeholder for the input features
x = tf.placeholder(tf.float32, [None, 4])
# placeholder for the one-hot labels
y = tf.placeholder(tf.float32, [None, 2])
# placeholder for node dropout rate
internalDropout = tf.placeholder(tf.float32, None)
net = x # input layer is the trading indicators
# Creates the neural network model
with tf.name_scope('network'):
# Initialises each layer in the network
layerPos = 0
for units in nodeLayout:
net = tf.layers.dense(
net,
units=units,
activation=tf.nn.tanh,
name=str(
"dense" +
str(units) +
"_" +
str(layerPos))) # adds each layer to the networm as specified by nodeLayout
# dropout layer after each layer
net = tf.layers.dropout(net, rate=internalDropout)
layerPos += 1
logits = tf.layers.dense(
net, 2, activation=tf.nn.softmax) # network output
with tf.name_scope('lossFunction'):
cross_entropy_loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits_v2(
labels=y,
logits=logits)) # on NO account put this within a name scope - tensorboard shits itself
with tf.name_scope('trainingStep'):
tf.summary.scalar('crossEntropyLoss', cross_entropy_loss)
trainStep = tf.train.AdamOptimizer(0.0001).minimize(
cross_entropy_loss, global_step=globalStepTensor)
with tf.name_scope('accuracy'):
correctPrediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correctPrediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
trainWriter = tf.summary.FileWriter(
mainDirectory + '/train', sess.graph, flush_secs=1, max_queue=2)
evalWriter = tf.summary.FileWriter(
mainDirectory + '/eval', sess.graph, flush_secs=1, max_queue=2)
tf.global_variables_initializer().run()
# Saves the model at defined checkpoints and loads any available model at
# start-up
saver = tf.train.Saver(max_to_keep=2, name="checkpoint")
path = tf.train.get_checkpoint_state(mainDirectory)
if path is not None:
saver.restore(sess, tf.train.latest_checkpoint(mainDirectory))
lastTime = time()
while tf.train.global_step(sess, globalStepTensor) <= trainingCycles:
globalStep = tf.train.global_step(sess, globalStepTensor)
# generates batch for each training cycle
xFeed, yFeed = createTrainingBatch(batchSize)
# Record summaries and accuracy on both train and eval data
if globalStep % summarySteps == 0:
currentTime = time()
totalTime = (currentTime - lastTime)
print(str(totalTime) + " seconds, " +
str(summarySteps / totalTime) + " steps/sec")
lastTime = currentTime
summary, accuracyOut, _ = sess.run([
merged,
accuracy,
trainStep
],
feed_dict={
x: xFeed,
y: yFeed,
internalDropout: dropout
})
trainWriter.add_summary(summary, globalStep)
trainWriter.flush()
print('Train accuracy at step %s: %s' % (globalStep, accuracyOut))
summary, accuracyOut = sess.run([
merged,
accuracy,
],
feed_dict={
x: evalDataX,
y: evalDataY,
internalDropout: 0
})
evalWriter.add_summary(summary, globalStep)
evalWriter.flush()
print('Eval accuracy at step %s: %s' % (globalStep, accuracyOut))
print("\n\n")
saver.save(sess, save_path=str(mainDirectory + "model"),
global_step=globalStep) # saves a snapshot of the model
else: # Training cycle
_ = sess.run(
[trainStep], feed_dict={
x: xFeed,
y: yFeed,
internalDropout: dropout
})
trainWriter.close()
evalWriter.close()
train() | 0.54819 | 0.419232 |
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import random
class PlotWindow(QDialog):
def __init__(self, parent=None):
super(PlotWindow, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
# self.button = QPushButton('Plot')
# self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
def plot(self, data=None, xLabel: str="X", yLabel: str="Y", x=None, y=None):
''' plot some random stuff '''
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# rotate and align the tick labels so they look better
self.figure.autofmt_xdate()
# discards the old graph
# ax.hold(False) # deprecated, see above
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# plot data
if x is not None and y is not None:
ax.plot(x, y, '*-')
ax.set_xlabel(xLabel)
ax.set_ylabel(yLabel)
else:
ax.plot(xLabel, yLabel, 'ro-',data=data)
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
PlotWindow = Window()
PlotWindow.show()
sys.exit(app.exec_()) | Interfaz/PlotWindow.py | import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import random
class PlotWindow(QDialog):
def __init__(self, parent=None):
super(PlotWindow, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
# self.button = QPushButton('Plot')
# self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
# layout.addWidget(self.button)
self.setLayout(layout)
def plot(self, data=None, xLabel: str="X", yLabel: str="Y", x=None, y=None):
''' plot some random stuff '''
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# rotate and align the tick labels so they look better
self.figure.autofmt_xdate()
# discards the old graph
# ax.hold(False) # deprecated, see above
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# plot data
if x is not None and y is not None:
ax.plot(x, y, '*-')
ax.set_xlabel(xLabel)
ax.set_ylabel(yLabel)
else:
ax.plot(xLabel, yLabel, 'ro-',data=data)
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
PlotWindow = Window()
PlotWindow.show()
sys.exit(app.exec_()) | 0.542621 | 0.314702 |
import argparse
import os
import sys
from enerpi.base import BASE_PATH, DATA_PATH, CONFIG, log, check_resource_files, NGINX_CONFIG_FILE, UWSGI_CONFIG_FILE
from enerpi.prettyprinting import print_secc, print_cyan, print_red, print_magenta
FLASK_WEBSERVER_PORT = CONFIG.getint('ENERPI_WEBSERVER', 'FLASK_WEBSERVER_PORT', fallback=7777)
PERIOD_MINUTES_RSC_GEN = CONFIG.getint('ENERPI_WEBSERVER', 'RSC_GEN_EVERY_MINUTES', fallback=15)
USER_SERVER = CONFIG.get('ENERPI_WEBSERVER', 'USER_SERVER', fallback='www-data')
basedir = os.path.abspath(os.path.dirname(__file__))
def make_cron_command_task_periodic_rscgen():
"""
CRON task for generate web resources with enerpiplot.mule_rscgen.py
Example command:
*/15 * * * * sudo -u www-data /home/pi/PYTHON/py35/bin/python
/home/pi/PYTHON/py35/lib/python3.5/site-packages/enerpiweb/mule_rscgen.py -o
:return: :str: cron_command
"""
# cmd_server = '*/{period} * * * * ...'
cmd_server = 'sudo -u {user_server} {python_pathbin}/python3 {path_enerpiplot}/mule_rscgen.py -o'
local_params = dict(path_enerpiplot=os.path.abspath(os.path.join(BASE_PATH, '..', 'enerpiplot')),
period=PERIOD_MINUTES_RSC_GEN, user_server=USER_SERVER,
python_pathbin=os.path.dirname(sys.executable))
return cmd_server.format(**local_params)
def _make_webserver_config(overwrite=False):
"""
Genera y escribe en DATA_PATH la configuración de la aplicación web para NGINX y UWSGI-EMPEROR.
Muestra los comandos para realizar los enlaces correspondientes en /etc/nginx y /etc/uwsgi-emperor.
"""
path_config_uwsgi = os.path.join(DATA_PATH, UWSGI_CONFIG_FILE)
path_config_nginx = os.path.join(DATA_PATH, NGINX_CONFIG_FILE)
if overwrite or not (os.path.exists(path_config_nginx) and os.path.exists(path_config_uwsgi)):
nginx_template = os.path.join(basedir, 'templates', 'nginx_conf_mask.txt')
uwsgi_template = os.path.join(basedir, 'templates', 'uwsgi_ini_mask.txt')
with open(nginx_template, 'r') as f:
nginx_raw = f.read()
with open(uwsgi_template, 'r') as f:
uwsgi_raw = f.read()
local_params = dict(file_location=DATA_PATH,
filename=UWSGI_CONFIG_FILE,
path_enerpiplot=os.path.abspath(os.path.join(basedir, '..', 'enerpiplot')),
path_enerpiweb=basedir,
path_venv=os.path.abspath(os.path.join(os.path.dirname(sys.executable), '..')))
uwsgi_conf = uwsgi_raw.format(**local_params)
nginx_conf = nginx_raw.replace(
'{file_location}', local_params['file_location']
).replace(
'{path_enerpiweb}', local_params['path_enerpiweb']
).replace('{filename}', NGINX_CONFIG_FILE)
# Copy config files to DATA_PATH
check_resource_files(DATA_PATH, verbose=True)
with open(os.path.join(DATA_PATH, UWSGI_CONFIG_FILE), 'w') as f:
f.write(uwsgi_conf)
with open(os.path.join(DATA_PATH, NGINX_CONFIG_FILE), 'w') as f:
f.write(nginx_conf)
# Show Info
print_secc('NGINX Config generated:')
print_cyan(nginx_conf)
print_secc('UWSGI INI Config generated:')
print_cyan(uwsgi_conf)
else:
# Show Info
print_secc('NGINX Config at "{}":'.format(path_config_nginx))
print_cyan(open(path_config_nginx, 'r').read())
print_secc('UWSGI INI Config at "{}":'.format(path_config_uwsgi))
print_cyan(open(path_config_uwsgi, 'r').read())
print_red('\n* Append the NGINX config to your actual server, or make the next symlink:\n **"{}"**'
.format('sudo ln -s {}/{} /etc/nginx/sites-enabled/'.format(DATA_PATH, NGINX_CONFIG_FILE)))
print_red('* Make a symlink to deposit the UWSGI-Emperor configuration:\n **"{}"**\n'
.format('sudo ln -s {}/{} /etc/uwsgi-emperor/vassals/'.format(DATA_PATH, UWSGI_CONFIG_FILE)))
print_magenta('* To start the webserver, restart NGINX & UWSGI-EMPEROR:\n **"{}"**\n **"{}"**\n'
.format('sudo service nginx restart', 'sudo service uwsgi-emperor restart'))
def main():
"""
CLI para ejecutar el webserver a mano vía flask en puerto 7777, o para mostrar/instalar la configuración
de UWSGI y NGINX para servir la aplicación
"""
p = argparse.ArgumentParser(description="\033[1m\033[5m\033[32m{}\033[0m\n\n".format('ENERPI Web Server'),
epilog='\033[34m\n*** By default, ENERPIWEB starts with flask server ***\n' +
'\033[0m', formatter_class=argparse.RawTextHelpFormatter)
p.add_argument('-p', '--port', action='store', type=int, metavar='P', default=FLASK_WEBSERVER_PORT,
help='✏ Flask PORT. Default: {}'.format(FLASK_WEBSERVER_PORT))
p.add_argument('-d', '--debug', action='store_true', help='☕ DEBUG Mode')
p.add_argument('-i', '--info', action='store_true', help='︎ℹ️ Show config params for NGINX + UWSGI')
p.add_argument('--install', action='store_true',
help='⚒ Install CRON task for WEB RSC generator every {} minutes'.format(PERIOD_MINUTES_RSC_GEN))
p.add_argument('--uninstall', action='store_true', help='⚒ Uninstall CRON task for WEB RSC generator')
args = p.parse_args()
if args.info:
_make_webserver_config(overwrite=False)
elif args.install or args.uninstall:
from enerpi.config.crontasks import set_command_periodic, clear_cron_commands
# INSTALL / UNINSTALL CRON TASKS & KEY
cmd_server = make_cron_command_task_periodic_rscgen()
if args.install:
log('** (Re-)Create webserver config files:', 'ok', True, False)
_make_webserver_config(overwrite=True)
log('** Installing CRON task for web resources generation every {} minutes:\n"{}"'
.format(PERIOD_MINUTES_RSC_GEN, cmd_server), 'ok', True, False)
set_command_periodic(cmd_server, comment='Generador de recursos para ENERPIWEB',
minute=PERIOD_MINUTES_RSC_GEN, verbose=True)
else:
log('** Deleting CRON task for web resources generation every X minutes:\n"{}"'
.format(cmd_server), 'warn', True, False)
clear_cron_commands([cmd_server], verbose=True)
print_red('\n* To stop the webserver, remove config files from {}:\n **"{}"**\n **"{}"**\n'
.format('NGINX & UWSGI-EMPEROR',
'sudo rm /etc/uwsgi-emperor/vassals/{}'.format(UWSGI_CONFIG_FILE),
'sudo rm /etc/nginx/sites-enabled/{}'.format(NGINX_CONFIG_FILE)))
else:
from enerpiweb import app as application
log('EJECUTANDO FLASK WSGI A MANO en P:{}!'.format(args.port), 'ok', True, False)
application.run(host="0.0.0.0", port=args.port, processes=1, threaded=True, debug=args.debug)
if __name__ == '__main__':
main() | enerpiweb/command_enerpiweb.py | import argparse
import os
import sys
from enerpi.base import BASE_PATH, DATA_PATH, CONFIG, log, check_resource_files, NGINX_CONFIG_FILE, UWSGI_CONFIG_FILE
from enerpi.prettyprinting import print_secc, print_cyan, print_red, print_magenta
FLASK_WEBSERVER_PORT = CONFIG.getint('ENERPI_WEBSERVER', 'FLASK_WEBSERVER_PORT', fallback=7777)
PERIOD_MINUTES_RSC_GEN = CONFIG.getint('ENERPI_WEBSERVER', 'RSC_GEN_EVERY_MINUTES', fallback=15)
USER_SERVER = CONFIG.get('ENERPI_WEBSERVER', 'USER_SERVER', fallback='www-data')
basedir = os.path.abspath(os.path.dirname(__file__))
def make_cron_command_task_periodic_rscgen():
"""
CRON task for generate web resources with enerpiplot.mule_rscgen.py
Example command:
*/15 * * * * sudo -u www-data /home/pi/PYTHON/py35/bin/python
/home/pi/PYTHON/py35/lib/python3.5/site-packages/enerpiweb/mule_rscgen.py -o
:return: :str: cron_command
"""
# cmd_server = '*/{period} * * * * ...'
cmd_server = 'sudo -u {user_server} {python_pathbin}/python3 {path_enerpiplot}/mule_rscgen.py -o'
local_params = dict(path_enerpiplot=os.path.abspath(os.path.join(BASE_PATH, '..', 'enerpiplot')),
period=PERIOD_MINUTES_RSC_GEN, user_server=USER_SERVER,
python_pathbin=os.path.dirname(sys.executable))
return cmd_server.format(**local_params)
def _make_webserver_config(overwrite=False):
"""
Genera y escribe en DATA_PATH la configuración de la aplicación web para NGINX y UWSGI-EMPEROR.
Muestra los comandos para realizar los enlaces correspondientes en /etc/nginx y /etc/uwsgi-emperor.
"""
path_config_uwsgi = os.path.join(DATA_PATH, UWSGI_CONFIG_FILE)
path_config_nginx = os.path.join(DATA_PATH, NGINX_CONFIG_FILE)
if overwrite or not (os.path.exists(path_config_nginx) and os.path.exists(path_config_uwsgi)):
nginx_template = os.path.join(basedir, 'templates', 'nginx_conf_mask.txt')
uwsgi_template = os.path.join(basedir, 'templates', 'uwsgi_ini_mask.txt')
with open(nginx_template, 'r') as f:
nginx_raw = f.read()
with open(uwsgi_template, 'r') as f:
uwsgi_raw = f.read()
local_params = dict(file_location=DATA_PATH,
filename=UWSGI_CONFIG_FILE,
path_enerpiplot=os.path.abspath(os.path.join(basedir, '..', 'enerpiplot')),
path_enerpiweb=basedir,
path_venv=os.path.abspath(os.path.join(os.path.dirname(sys.executable), '..')))
uwsgi_conf = uwsgi_raw.format(**local_params)
nginx_conf = nginx_raw.replace(
'{file_location}', local_params['file_location']
).replace(
'{path_enerpiweb}', local_params['path_enerpiweb']
).replace('{filename}', NGINX_CONFIG_FILE)
# Copy config files to DATA_PATH
check_resource_files(DATA_PATH, verbose=True)
with open(os.path.join(DATA_PATH, UWSGI_CONFIG_FILE), 'w') as f:
f.write(uwsgi_conf)
with open(os.path.join(DATA_PATH, NGINX_CONFIG_FILE), 'w') as f:
f.write(nginx_conf)
# Show Info
print_secc('NGINX Config generated:')
print_cyan(nginx_conf)
print_secc('UWSGI INI Config generated:')
print_cyan(uwsgi_conf)
else:
# Show Info
print_secc('NGINX Config at "{}":'.format(path_config_nginx))
print_cyan(open(path_config_nginx, 'r').read())
print_secc('UWSGI INI Config at "{}":'.format(path_config_uwsgi))
print_cyan(open(path_config_uwsgi, 'r').read())
print_red('\n* Append the NGINX config to your actual server, or make the next symlink:\n **"{}"**'
.format('sudo ln -s {}/{} /etc/nginx/sites-enabled/'.format(DATA_PATH, NGINX_CONFIG_FILE)))
print_red('* Make a symlink to deposit the UWSGI-Emperor configuration:\n **"{}"**\n'
.format('sudo ln -s {}/{} /etc/uwsgi-emperor/vassals/'.format(DATA_PATH, UWSGI_CONFIG_FILE)))
print_magenta('* To start the webserver, restart NGINX & UWSGI-EMPEROR:\n **"{}"**\n **"{}"**\n'
.format('sudo service nginx restart', 'sudo service uwsgi-emperor restart'))
def main():
"""
CLI para ejecutar el webserver a mano vía flask en puerto 7777, o para mostrar/instalar la configuración
de UWSGI y NGINX para servir la aplicación
"""
p = argparse.ArgumentParser(description="\033[1m\033[5m\033[32m{}\033[0m\n\n".format('ENERPI Web Server'),
epilog='\033[34m\n*** By default, ENERPIWEB starts with flask server ***\n' +
'\033[0m', formatter_class=argparse.RawTextHelpFormatter)
p.add_argument('-p', '--port', action='store', type=int, metavar='P', default=FLASK_WEBSERVER_PORT,
help='✏ Flask PORT. Default: {}'.format(FLASK_WEBSERVER_PORT))
p.add_argument('-d', '--debug', action='store_true', help='☕ DEBUG Mode')
p.add_argument('-i', '--info', action='store_true', help='︎ℹ️ Show config params for NGINX + UWSGI')
p.add_argument('--install', action='store_true',
help='⚒ Install CRON task for WEB RSC generator every {} minutes'.format(PERIOD_MINUTES_RSC_GEN))
p.add_argument('--uninstall', action='store_true', help='⚒ Uninstall CRON task for WEB RSC generator')
args = p.parse_args()
if args.info:
_make_webserver_config(overwrite=False)
elif args.install or args.uninstall:
from enerpi.config.crontasks import set_command_periodic, clear_cron_commands
# INSTALL / UNINSTALL CRON TASKS & KEY
cmd_server = make_cron_command_task_periodic_rscgen()
if args.install:
log('** (Re-)Create webserver config files:', 'ok', True, False)
_make_webserver_config(overwrite=True)
log('** Installing CRON task for web resources generation every {} minutes:\n"{}"'
.format(PERIOD_MINUTES_RSC_GEN, cmd_server), 'ok', True, False)
set_command_periodic(cmd_server, comment='Generador de recursos para ENERPIWEB',
minute=PERIOD_MINUTES_RSC_GEN, verbose=True)
else:
log('** Deleting CRON task for web resources generation every X minutes:\n"{}"'
.format(cmd_server), 'warn', True, False)
clear_cron_commands([cmd_server], verbose=True)
print_red('\n* To stop the webserver, remove config files from {}:\n **"{}"**\n **"{}"**\n'
.format('NGINX & UWSGI-EMPEROR',
'sudo rm /etc/uwsgi-emperor/vassals/{}'.format(UWSGI_CONFIG_FILE),
'sudo rm /etc/nginx/sites-enabled/{}'.format(NGINX_CONFIG_FILE)))
else:
from enerpiweb import app as application
log('EJECUTANDO FLASK WSGI A MANO en P:{}!'.format(args.port), 'ok', True, False)
application.run(host="0.0.0.0", port=args.port, processes=1, threaded=True, debug=args.debug)
if __name__ == '__main__':
main() | 0.212069 | 0.046812 |
from .base_options import BaseOptions
class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser)
# visualization parameters
parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console')
parser.add_argument('--eval_freq', type=int, default=2, help='frequency of epochs to perform evaluation on validation set')
# network saving and loading parameters
parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results')
parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')
parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')
# training parameters
parser.add_argument('--n_epochs', type=int, default=2000, help='number of epochs with the initial learning rate')
parser.add_argument('--n_epochs_decay', type=int, default=500, help='number of epochs to linearly decay learning rate to zero')
parser.add_argument('--beta1', default=0.9, type=float, help='beta1 fro adam optimizer')
parser.add_argument('--beta2', default=0.999, type=float, help='beta2 fro adam optimizer')
parser.add_argument('--lr', type=float, default=0.005, help='initial learning rate for adam')
parser.add_argument('--lr_policy', type=str, default='step', help='learning rate policy. [linear | step | plateau | cosine]')
parser.add_argument('--lr_decay_iters', type=int, default=5e10, help='multiply by a gamma every lr_decay_iters iterations')
self.isTrain = True
return parser | options/train_options.py | from .base_options import BaseOptions
class TrainOptions(BaseOptions):
"""This class includes training options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser)
# visualization parameters
parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console')
parser.add_argument('--eval_freq', type=int, default=2, help='frequency of epochs to perform evaluation on validation set')
# network saving and loading parameters
parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results')
parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')
parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')
# training parameters
parser.add_argument('--n_epochs', type=int, default=2000, help='number of epochs with the initial learning rate')
parser.add_argument('--n_epochs_decay', type=int, default=500, help='number of epochs to linearly decay learning rate to zero')
parser.add_argument('--beta1', default=0.9, type=float, help='beta1 fro adam optimizer')
parser.add_argument('--beta2', default=0.999, type=float, help='beta2 fro adam optimizer')
parser.add_argument('--lr', type=float, default=0.005, help='initial learning rate for adam')
parser.add_argument('--lr_policy', type=str, default='step', help='learning rate policy. [linear | step | plateau | cosine]')
parser.add_argument('--lr_decay_iters', type=int, default=5e10, help='multiply by a gamma every lr_decay_iters iterations')
self.isTrain = True
return parser | 0.690455 | 0.216923 |
from typing import Tuple, List, Dict, Optional
import torch
from torch import Tensor
from transformers import AutoTokenizer, RobertaTokenizer
from torch.utils.data.dataset import Dataset, T_co, TensorDataset
class BaseDictCollator:
def __init__(self, add_mlm_labels: bool = False, mlm_probability: float = 0.15, tokenizer: str = 'bert-base-uncased'):
self.add_mlm_labels = add_mlm_labels
self.mlm_probability = mlm_probability
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)
def __call__(self, batch: List[Tuple[Tensor, ...]]) -> Dict[str, Tensor]:
if len(batch[0]) == 4:
input_ids, attention_mask, token_type_ids, labels = list(zip(*batch))
mlm_input_ids = None
mlm_attention_mask = None
elif len(batch[0]) == 3:
input_ids, attention_mask, labels = list(zip(*batch))
token_type_ids = None
mlm_input_ids = None
mlm_attention_mask = None
elif len(batch[0]) == 6:
input_ids, attention_mask, token_type_ids, labels, mlm_input_ids, mlm_attention_mask = list(zip(*batch))
elif len(batch[0]) == 5:
input_ids, attention_mask, labels, mlm_input_ids, mlm_attention_mask = list(zip(*batch))
token_type_ids = None
else:
raise RuntimeError()
input_ids = torch.stack(input_ids, dim=0)
attention_mask = torch.stack(attention_mask, dim=0)
labels = torch.stack(labels, dim=0)
outputs = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"labels": labels,
}
if token_type_ids is not None:
outputs["token_type_ids"] = torch.stack(token_type_ids, dim=0)
if self.add_mlm_labels:
if mlm_input_ids is None:
mlm_input_ids = input_ids[:, 0].clone()
mlm_input_ids, mlm_labels = self.mask_tokens(mlm_input_ids)
outputs["mlm_input_ids"] = mlm_input_ids
outputs["mlm_labels"] = mlm_labels
else:
mlm_input_ids = torch.stack(mlm_input_ids, dim=0)
mlm_attention_mask = torch.stack(mlm_attention_mask, dim=0)
mlm_input_ids, mlm_labels = self.mask_tokens(mlm_input_ids)
outputs["mlm_input_ids"] = mlm_input_ids
outputs["mlm_attention_mask"] = mlm_attention_mask
outputs["mlm_labels"] = mlm_labels
return outputs
def mask_tokens(
self, inputs: torch.Tensor, special_tokens_mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
"""
labels = inputs.clone()
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
probability_matrix = torch.full(labels.shape, self.mlm_probability)
if special_tokens_mask is None:
special_tokens_mask = [
self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
]
special_tokens_mask = torch.tensor(special_tokens_mask, dtype=torch.bool)
# Remove padding.
special_tokens_mask = special_tokens_mask | (labels == self.tokenizer.pad_token_id)
else:
special_tokens_mask = special_tokens_mask.bool()
probability_matrix.masked_fill_(special_tokens_mask, value=0.0)
masked_indices = torch.bernoulli(probability_matrix).bool()
labels[~masked_indices] = -1 # We only compute loss on masked tokens
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
# 10% of the time, we replace masked input tokens with random word
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long)
inputs[indices_random] = random_words[indices_random]
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
return inputs, labels
class UnalignedTensorDataset(Dataset):
def __init__(self, tensor_groups: Tuple[Tuple[Tensor, ...], ...], id_for_len: int):
self.length = tensor_groups[id_for_len][0].size(0)
self.tensors = []
for _tensors in tensor_groups:
assert all(_tensors[0].size(0) == _tensor.size(0) for _tensor in _tensors), "Size mismatch between tensors"
self.tensors.extend(_tensors)
def __getitem__(self, index) -> T_co:
res = []
for _tensor in self.tensors:
res.append(_tensor[index % _tensor.size(0)])
return res
def __len__(self):
return self.length | dataset/collators/base_collator.py | from typing import Tuple, List, Dict, Optional
import torch
from torch import Tensor
from transformers import AutoTokenizer, RobertaTokenizer
from torch.utils.data.dataset import Dataset, T_co, TensorDataset
class BaseDictCollator:
def __init__(self, add_mlm_labels: bool = False, mlm_probability: float = 0.15, tokenizer: str = 'bert-base-uncased'):
self.add_mlm_labels = add_mlm_labels
self.mlm_probability = mlm_probability
self.tokenizer = AutoTokenizer.from_pretrained(tokenizer)
def __call__(self, batch: List[Tuple[Tensor, ...]]) -> Dict[str, Tensor]:
if len(batch[0]) == 4:
input_ids, attention_mask, token_type_ids, labels = list(zip(*batch))
mlm_input_ids = None
mlm_attention_mask = None
elif len(batch[0]) == 3:
input_ids, attention_mask, labels = list(zip(*batch))
token_type_ids = None
mlm_input_ids = None
mlm_attention_mask = None
elif len(batch[0]) == 6:
input_ids, attention_mask, token_type_ids, labels, mlm_input_ids, mlm_attention_mask = list(zip(*batch))
elif len(batch[0]) == 5:
input_ids, attention_mask, labels, mlm_input_ids, mlm_attention_mask = list(zip(*batch))
token_type_ids = None
else:
raise RuntimeError()
input_ids = torch.stack(input_ids, dim=0)
attention_mask = torch.stack(attention_mask, dim=0)
labels = torch.stack(labels, dim=0)
outputs = {
"input_ids": input_ids,
"attention_mask": attention_mask,
"labels": labels,
}
if token_type_ids is not None:
outputs["token_type_ids"] = torch.stack(token_type_ids, dim=0)
if self.add_mlm_labels:
if mlm_input_ids is None:
mlm_input_ids = input_ids[:, 0].clone()
mlm_input_ids, mlm_labels = self.mask_tokens(mlm_input_ids)
outputs["mlm_input_ids"] = mlm_input_ids
outputs["mlm_labels"] = mlm_labels
else:
mlm_input_ids = torch.stack(mlm_input_ids, dim=0)
mlm_attention_mask = torch.stack(mlm_attention_mask, dim=0)
mlm_input_ids, mlm_labels = self.mask_tokens(mlm_input_ids)
outputs["mlm_input_ids"] = mlm_input_ids
outputs["mlm_attention_mask"] = mlm_attention_mask
outputs["mlm_labels"] = mlm_labels
return outputs
def mask_tokens(
self, inputs: torch.Tensor, special_tokens_mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
"""
labels = inputs.clone()
# We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
probability_matrix = torch.full(labels.shape, self.mlm_probability)
if special_tokens_mask is None:
special_tokens_mask = [
self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
]
special_tokens_mask = torch.tensor(special_tokens_mask, dtype=torch.bool)
# Remove padding.
special_tokens_mask = special_tokens_mask | (labels == self.tokenizer.pad_token_id)
else:
special_tokens_mask = special_tokens_mask.bool()
probability_matrix.masked_fill_(special_tokens_mask, value=0.0)
masked_indices = torch.bernoulli(probability_matrix).bool()
labels[~masked_indices] = -1 # We only compute loss on masked tokens
# 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
# 10% of the time, we replace masked input tokens with random word
indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long)
inputs[indices_random] = random_words[indices_random]
# The rest of the time (10% of the time) we keep the masked input tokens unchanged
return inputs, labels
class UnalignedTensorDataset(Dataset):
def __init__(self, tensor_groups: Tuple[Tuple[Tensor, ...], ...], id_for_len: int):
self.length = tensor_groups[id_for_len][0].size(0)
self.tensors = []
for _tensors in tensor_groups:
assert all(_tensors[0].size(0) == _tensor.size(0) for _tensor in _tensors), "Size mismatch between tensors"
self.tensors.extend(_tensors)
def __getitem__(self, index) -> T_co:
res = []
for _tensor in self.tensors:
res.append(_tensor[index % _tensor.size(0)])
return res
def __len__(self):
return self.length | 0.940469 | 0.599895 |
import base64
import json
from copy import deepcopy
from typing import Any, Dict, Mapping
from flask import Blueprint, current_app, request
from mock import patch
from eduid_userdb import User
from eduid_userdb.fixtures.fido_credentials import u2f_credential, webauthn_credential
from eduid_userdb.fixtures.users import new_user_example
from eduid_common.api.app import EduIDBaseApp
from eduid_common.api.testing import EduidAPITestCase
from eduid_common.authn.fido_tokens import VerificationProblem, start_token_verification, verify_webauthn
from eduid_common.config.base import EduIDBaseAppConfig, WebauthnConfigMixin2
from eduid_common.config.parsers import load_config
class MockFidoConfig(EduIDBaseAppConfig, WebauthnConfigMixin2):
mfa_testing: bool = True
generate_u2f_challenges: bool = True
views = Blueprint('testing', 'testing', url_prefix='')
@views.route('/start', methods=["GET"])
def start_verification():
current_app.logger.info('Endpoint start_verification called')
user = current_app.central_userdb.get_user_by_eppn('hubba-bubba')
data = json.loads(request.query_string[17:])
try:
result = verify_webauthn(user, data, 'testing', current_app.conf.fido2_rp_id)
except VerificationProblem:
result = {'success': False, 'message': 'mfa.verification-problem'}
current_app.logger.info(f'Endpoint start_verification result: {result}')
return json.dumps(result)
class MockFidoApp(EduIDBaseApp):
def __init__(self, config: MockFidoConfig):
super().__init__(config)
self.conf = config
SAMPLE_WEBAUTHN_REQUEST = {
'authenticatorData': '<KEY>',
'clientDataJSON': '<KEY>',
'credentialId': '<KEY>0Cad3fbtUA_Q',
# This is a fake signature, we mock its verification below
'signature': 'MEYCIQC5gM8inamJGUFKu3bNo4fT0jmJQuw33OSSXc242NCuiwIhAIWnVw2Spow72j6J92KaY2rLR6qSXEbLam09ZXbSkBnQ',
}
class FidoTokensTestCase(EduidAPITestCase):
app: MockFidoApp
def setUp(self):
super().setUp()
self.webauthn_credential = webauthn_credential
self.u2f_credential = u2f_credential
self.test_user = User.from_dict(data=new_user_example.to_dict())
def load_app(self, test_config: Mapping[str, Any]) -> MockFidoApp:
"""
Called from the parent class, so we can provide the appropriate flask
app for this test case.
"""
config = load_config(typ=MockFidoConfig, app_name='testing', ns='webapp', test_config=test_config)
app = MockFidoApp(config)
app.register_blueprint(views)
return app
def update_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
config.update(
{
'app_name': 'testing',
'available_languages': {'en': 'English', 'sv': 'Svenska'},
'celery_config': {
'result_backend': 'amqp',
'task_serializer': 'json',
'mongo_uri': config['mongo_uri'],
},
'u2f_app_id': 'https://eduid.se/u2f-app-id.json',
'fido2_rp_id': 'idp.dev.eduid.se',
'u2f_valid_facets': ['https://dashboard.dev.eduid.se', 'https://idp.dev.eduid.se'],
}
)
return config
def test_u2f_start_verification(self):
# Add a working U2F credential for this test
self.test_user.credentials.add(self.u2f_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction():
with self.app.test_request_context():
config = start_token_verification(self.test_user, 'testing', self.app.conf.fido2_rp_id)
assert 'u2fdata' not in config
assert 'webauthn_options' in config
s = config['webauthn_options']
_decoded = base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
# _decoded is still CBOR encoded, so we just check for some known strings
assert b'publicKey' in _decoded
assert b'idp.dev.eduid.se' in _decoded
assert b'challenge' in _decoded
def test_webauthn_start_verification(self):
# Add a working Webauthn credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction():
with self.app.test_request_context():
config = start_token_verification(self.test_user, 'testing', self.app.conf.fido2_rp_id)
assert 'u2fdata' not in config
assert 'webauthn_options' in config
s = config['webauthn_options']
_decoded = base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
# _decoded is still CBOR encoded, so we just check for some known strings
assert b'publicKey' in _decoded
assert b'idp.dev.eduid.se' in _decoded
assert b'challenge' in _decoded
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify(self, mock_verify):
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], True)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_origin(self, mock_verify):
self.app.conf.fido2_rp_id = 'wrong.rp.id'
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_challenge(self, mock_verify):
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': 'WRONG_CHALLENGE_COx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_credential(self, mock_verify):
req = deepcopy(SAMPLE_WEBAUTHN_REQUEST)
req['credentialId'] = req['credentialId'].replace('0', '9')
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(req))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False) | src/eduid_common/authn/tests/test_fido_tokens.py | import base64
import json
from copy import deepcopy
from typing import Any, Dict, Mapping
from flask import Blueprint, current_app, request
from mock import patch
from eduid_userdb import User
from eduid_userdb.fixtures.fido_credentials import u2f_credential, webauthn_credential
from eduid_userdb.fixtures.users import new_user_example
from eduid_common.api.app import EduIDBaseApp
from eduid_common.api.testing import EduidAPITestCase
from eduid_common.authn.fido_tokens import VerificationProblem, start_token_verification, verify_webauthn
from eduid_common.config.base import EduIDBaseAppConfig, WebauthnConfigMixin2
from eduid_common.config.parsers import load_config
class MockFidoConfig(EduIDBaseAppConfig, WebauthnConfigMixin2):
mfa_testing: bool = True
generate_u2f_challenges: bool = True
views = Blueprint('testing', 'testing', url_prefix='')
@views.route('/start', methods=["GET"])
def start_verification():
current_app.logger.info('Endpoint start_verification called')
user = current_app.central_userdb.get_user_by_eppn('hubba-bubba')
data = json.loads(request.query_string[17:])
try:
result = verify_webauthn(user, data, 'testing', current_app.conf.fido2_rp_id)
except VerificationProblem:
result = {'success': False, 'message': 'mfa.verification-problem'}
current_app.logger.info(f'Endpoint start_verification result: {result}')
return json.dumps(result)
class MockFidoApp(EduIDBaseApp):
def __init__(self, config: MockFidoConfig):
super().__init__(config)
self.conf = config
SAMPLE_WEBAUTHN_REQUEST = {
'authenticatorData': '<KEY>',
'clientDataJSON': '<KEY>',
'credentialId': '<KEY>0Cad3fbtUA_Q',
# This is a fake signature, we mock its verification below
'signature': 'MEYCIQC5gM8inamJGUFKu3bNo4fT0jmJQuw33OSSXc242NCuiwIhAIWnVw2Spow72j6J92KaY2rLR6qSXEbLam09ZXbSkBnQ',
}
class FidoTokensTestCase(EduidAPITestCase):
app: MockFidoApp
def setUp(self):
super().setUp()
self.webauthn_credential = webauthn_credential
self.u2f_credential = u2f_credential
self.test_user = User.from_dict(data=new_user_example.to_dict())
def load_app(self, test_config: Mapping[str, Any]) -> MockFidoApp:
"""
Called from the parent class, so we can provide the appropriate flask
app for this test case.
"""
config = load_config(typ=MockFidoConfig, app_name='testing', ns='webapp', test_config=test_config)
app = MockFidoApp(config)
app.register_blueprint(views)
return app
def update_config(self, config: Dict[str, Any]) -> Dict[str, Any]:
config.update(
{
'app_name': 'testing',
'available_languages': {'en': 'English', 'sv': 'Svenska'},
'celery_config': {
'result_backend': 'amqp',
'task_serializer': 'json',
'mongo_uri': config['mongo_uri'],
},
'u2f_app_id': 'https://eduid.se/u2f-app-id.json',
'fido2_rp_id': 'idp.dev.eduid.se',
'u2f_valid_facets': ['https://dashboard.dev.eduid.se', 'https://idp.dev.eduid.se'],
}
)
return config
def test_u2f_start_verification(self):
# Add a working U2F credential for this test
self.test_user.credentials.add(self.u2f_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction():
with self.app.test_request_context():
config = start_token_verification(self.test_user, 'testing', self.app.conf.fido2_rp_id)
assert 'u2fdata' not in config
assert 'webauthn_options' in config
s = config['webauthn_options']
_decoded = base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
# _decoded is still CBOR encoded, so we just check for some known strings
assert b'publicKey' in _decoded
assert b'idp.dev.eduid.se' in _decoded
assert b'challenge' in _decoded
def test_webauthn_start_verification(self):
# Add a working Webauthn credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction():
with self.app.test_request_context():
config = start_token_verification(self.test_user, 'testing', self.app.conf.fido2_rp_id)
assert 'u2fdata' not in config
assert 'webauthn_options' in config
s = config['webauthn_options']
_decoded = base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
# _decoded is still CBOR encoded, so we just check for some known strings
assert b'publicKey' in _decoded
assert b'idp.dev.eduid.se' in _decoded
assert b'challenge' in _decoded
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify(self, mock_verify):
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], True)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_origin(self, mock_verify):
self.app.conf.fido2_rp_id = 'wrong.rp.id'
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_challenge(self, mock_verify):
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': 'WRONG_CHALLENGE_COx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(SAMPLE_WEBAUTHN_REQUEST))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False)
@patch('fido2.cose.ES256.verify')
def test_webauthn_verify_wrong_credential(self, mock_verify):
req = deepcopy(SAMPLE_WEBAUTHN_REQUEST)
req['credentialId'] = req['credentialId'].replace('0', '9')
mock_verify.return_value = True
# Add a working U2F credential for this test
self.test_user.credentials.add(self.webauthn_credential)
self.amdb.save(self.test_user, check_sync=False)
eppn = self.test_user.eppn
with self.app.test_request_context():
with self.session_cookie(self.browser, eppn) as client:
with client.session_transaction() as sess:
fido2state = {
'challenge': '3h_EAZpY25xDdSJCOMx1ABZEA5Odz3yejUI3AUNTQWc',
'user_verification': 'preferred',
}
sess['testing.webauthn.state'] = json.dumps(fido2state)
sess.persist()
resp = client.get('/start?webauthn_request=' + json.dumps(req))
resp_data = json.loads(resp.data)
self.assertEqual(resp_data['success'], False) | 0.605449 | 0.118334 |
from enum import Enum, auto
from ..geometry import Position, Vector, Size
from ..events import handlers
from .core import Align, ZOrder
from . import toolkit
from . import basic
from . import containers
from . import decorations
from . import renderers
class UIWidget:
def __init__(self, default_colors, *args, **kwargs):
super().__init__(*args, **kwargs)
self.renderer = renderers.ClearPanel(
colors=default_colors,
)
self.widget = None
self.manager = None
@property
def colors(self):
return self.renderer.colors
@colors.setter
def colors(self, colors):
self.renderer.colors = colors
def layout(self, manager, widget, panel, z_order):
self.manager = manager
self.widget = widget
manager.insert(
widget,
ui_widget=self,
)
return super().layout(manager, widget, panel, z_order)
def redraw(self):
self.manager.redraw(self.widget)
class WidgetState(Enum):
HOVERED = auto()
PRESSED = auto()
FOCUSED = auto()
SELECTED = auto()
class Stateful:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.states = set()
@property
def is_hovered(self):
return WidgetState.HOVERED in self.states
@property
def is_pressed(self):
return WidgetState.PRESSD in self.states
@property
def is_focused(self):
return WidgetState.FOCUSED in self.states
@property
def is_selected(self):
return WidgetState.SELECTED in self.states
def enter(self):
self.states.add(WidgetState.HOVERED)
def leave(self):
self.states.discard(WidgetState.HOVERED)
self.states.discard(WidgetState.PRESSED)
def press(self, position):
self.states.add(WidgetState.PRESSED)
def focus(self):
self.states.add(WidgetState.FOCUSED)
def unfocus(self):
self.states.discard(WidgetState.FOCUSED)
def select(self):
self.states.add(WidgetState.SELECTED)
def unselect(self):
self.states.discard(WidgetState.SELECTED)
def toggle(self):
is_selected = WidgetState.SELECTED in self.states
if is_selected:
self.unselect()
else:
self.select()
class MouseOperated(Stateful):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.handlers.on_mouse_click.update({
handlers.MouseLeftButton(): self.on_click,
})
self.handlers.on_mouse_press.update({
handlers.MouseLeftButton(): self.on_press,
})
self.handlers.on_mouse_up.update({
handlers.MouseLeftButton(): self.on_enter,
})
self.handlers.on_mouse_in.update({
handlers.MouseIn(): self.on_enter,
})
self.handlers.on_mouse_over.update({
handlers.MouseOver(): self.on_over,
})
self.handlers.on_mouse_out.update({
handlers.MouseOut(): self.on_leave,
})
def on_enter(self, widget, *args, **kwargs):
self.enter()
def on_over(self, widget, position, *args, **kwargs):
self.hover(position)
def on_leave(self, widget, *args, **kwargs):
self.leave()
def on_press(self, widget, position, *args, **kwargs):
self.press(position)
def on_click(self, widget, position, *args, **kwargs):
self.toggle()
def hover(self, position):
if not self.is_hovered:
self.enter()
class WithHotkey(Stateful):
def __init__(self, ecs, key_binding, *args, **kwargs):
super().__init__(*args, **kwargs)
self.handlers.on_key_press.update({
handlers.OnKeyPress(ecs, key_binding): self.on_hotkey,
})
def on_hotkey(self, widget, key, *args, **kwargs):
self.toggle()
class Activable:
def __init__(self, callback, value, *args, **kwargs):
super().__init__(*args, **kwargs)
self.callback = callback
self.value = value
def activate(self):
return self.callback(self.widget, self.value)
def select(self):
super().select()
self.activate()
class TextInput(MouseOperated, UIWidget, containers.Stack, toolkit.Widget):
def __init__(self, ecs, width, *,
default_colors,
default_text=None,
align=Align.TOP_LEFT,
):
super().__init__(
width=width,
height=1,
align=Align.TOP_LEFT,
default_colors=default_colors,
)
self.text = basic.Text(
default_text or '',
width=width,
)
self.cursor = basic.Cursor(
# colors=default_colors.invert(),
blinking=1200,
)
self.cursor.position = Position(len(self.txt), 0)
self.children.extend([
self.text,
# TODO: Show Cursor only if has focus and ready for input?
self.cursor,
])
self.handlers.on_text_input.update({
handlers.TextInput(): self.on_input,
})
self.handlers.on_key_press.update({
handlers.TextEdit(ecs): self.on_edit,
})
@property
def txt(self):
return self.text.txt
@txt.setter
def txt(self, txt):
self.text.txt = txt
def on_input(self, widget, char):
if len(self.txt) < self.width-1:
before_cursor = self.txt[:self.cursor.position.x]
after_cursor = self.txt[self.cursor.position.x:]
self.txt = before_cursor + char + after_cursor
self.cursor.move(Vector(1, 0))
def on_edit(self, widget, cmd):
if not cmd:
return
elif cmd == 'CLEAR':
self.txt = ''
self.cursor.position = Position.ZERO
elif cmd == 'BACKSPACE':
before_cursor = self.txt[:self.cursor.position.x]
if before_cursor:
after_cursor = self.txt[self.cursor.position.x:]
self.txt = before_cursor[:-1] + after_cursor
self.cursor.move(Vector(-1, 0))
elif cmd == 'DELETE':
after_cursor = self.txt[self.cursor.position.x:]
if after_cursor:
before_cursor = self.txt[:self.cursor.position.x]
self.txt = before_cursor + after_cursor[1:]
elif cmd == 'HOME':
self.cursor.position = Position.ZERO
elif cmd == 'END':
self.cursor.position = Position(len(self.txt), 0)
elif cmd == 'FORWARD':
if self.cursor.position.x < len(self.txt):
self.cursor.move(Vector(1, 0))
elif cmd == 'BACKWARD':
if self.cursor.position.x > 0:
self.cursor.move(Vector(-1, 0))
elif cmd == 'PASTE':
pass
class Button(Activable, MouseOperated, UIWidget, toolkit.PostProcessed, decorations.Framed):
def __init__(self, value, callback, text, frame, *,
default_colors,
selected_colors=None, press_colors=None,
selected_renderers=None,
align=Align.TOP_LEFT,
):
super().__init__(
callback=callback, value=value,
content=text,
frame=frame,
align=align,
default_colors=default_colors,
)
self.default_colors = default_colors
self.selected_colors = selected_colors or self.default_colors
self.press_colors = press_colors or self.selected_colors
self.selected_renderers = list(selected_renderers or [])
@property
def txt(self):
return self.content.txt
@txt.setter
def txt(self, txt):
self.content.txt = text
def enter(self):
super().enter()
self.colors = self.selected_colors
self.post_renderers = self.selected_renderers
self.redraw();
def leave(self):
super().leave()
self.colors = self.default_colors
self.post_renderers = []
self.redraw()
def press(self, position):
super().press(position)
self.colors = self.press_colors
self.post_renderers = self.selected_renderers
self.redraw()
class ListItem(Activable, MouseOperated, WithHotkey, UIWidget, toolkit.PostProcessed, containers.Row):
def __init__(self, ecs, key_binding, callback, value, index, item, *,
default_colors,
selected_renderers=None,
align=Align.TOP_LEFT,
):
super().__init__(
ecs=ecs, key_binding=key_binding,
callback=callback, value=value,
content=[
index,
item,
],
align=align,
default_colors=default_colors,
)
self.selected_renderers = list(selected_renderers or [])
def enter(self):
super().enter()
self.post_renderers = self.selected_renderers
self.redraw();
def leave(self):
super().leave()
self.post_renderers = []
self.redraw()
def press(self, position):
super().press(position)
self.post_renderers = self.selected_renderers
self.redraw()
def focus(self):
super().focus()
self.post_renderers = self.selected_renderers
self.redraw()
def unfocus(self):
super().unfocus()
self.post_renderers = []
self.redraw()
class ListBox(containers.List):
def __init__(self, ecs, align=Align.TOP_LEFT):
super().__init__(align=align)
self.items = []
self.handlers.on_key_press.update({
handlers.NextPrevKeyPress(ecs, 'list.NEXT', 'list.PREV'): self.on_focus_change,
handlers.OnKeyPress(ecs, 'list.SELECT'): self.on_select,
})
self.handlers.on_mouse_over.update({
handlers.MouseOver(): self.on_mouse_over,
})
def append_item(self, item):
self.append(item)
self.items.append(item)
def append_separator(self, separator):
self.append(separator)
def on_mouse_over(self, widget, position):
for item in self.items:
if item.is_focused and not item.is_hovered:
return item.unfocus()
def on_focus_change(self, widget, direction):
index = None
for i, item in enumerate(self.items):
if item.is_focused or item.is_hovered:
index = i
break
if index is not None:
self.items[index].unfocus()
self.items[index].leave()
index += direction
index %= len(self.items)
self.items[index].focus()
else:
index = max(direction-1, -1)
self.items[index].focus()
def on_select(self, widget, value):
for item in self.items:
if item.is_focused or item.is_hovered:
return item.toggle()
def on_index(self, widget, index):
if index < len(self.items):
self.items[index].toggle()
# TODO: Consider renaming to FramedPanel?
class Window(UIWidget, containers.Stack):
DEFAULT_Z_ORDER = ZOrder.BASE
def __init__(self, frame, default_colors, *,
title=None,
on_key_press=None,
**kwargs
):
super().__init__(default_colors=default_colors, **kwargs)
self.frame = containers.Stack()
# TODO: Instead of frame use header, footer?
self.content = containers.Stack()
self.handlers.on_key_press.update(on_key_press or {})
self.children.extend([
decorations.Framed(
content=self.content,
frame=frame,
align=Align.TOP_LEFT,
),
self.frame,
])
if title:
self.frame.append(title)
def append(self, widget):
self.content.append(widget)
def extend(self, widgets):
self.content.extend(widgets)
class ModalWindow(Window, toolkit.Widget):
DEFAULT_Z_ORDER = ZOrder.MODAL
def __init__(self, size, align, frame, default_colors, *,
title=None,
on_key_press=None,
**kwargs
):
super().__init__(
width=size.width,
height=size.height,
align=align,
frame=frame,
default_colors=default_colors,
title=title,
on_key_press=on_key_press,
**kwargs,
) | rogal/console/widgets.py | from enum import Enum, auto
from ..geometry import Position, Vector, Size
from ..events import handlers
from .core import Align, ZOrder
from . import toolkit
from . import basic
from . import containers
from . import decorations
from . import renderers
class UIWidget:
def __init__(self, default_colors, *args, **kwargs):
super().__init__(*args, **kwargs)
self.renderer = renderers.ClearPanel(
colors=default_colors,
)
self.widget = None
self.manager = None
@property
def colors(self):
return self.renderer.colors
@colors.setter
def colors(self, colors):
self.renderer.colors = colors
def layout(self, manager, widget, panel, z_order):
self.manager = manager
self.widget = widget
manager.insert(
widget,
ui_widget=self,
)
return super().layout(manager, widget, panel, z_order)
def redraw(self):
self.manager.redraw(self.widget)
class WidgetState(Enum):
HOVERED = auto()
PRESSED = auto()
FOCUSED = auto()
SELECTED = auto()
class Stateful:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.states = set()
@property
def is_hovered(self):
return WidgetState.HOVERED in self.states
@property
def is_pressed(self):
return WidgetState.PRESSD in self.states
@property
def is_focused(self):
return WidgetState.FOCUSED in self.states
@property
def is_selected(self):
return WidgetState.SELECTED in self.states
def enter(self):
self.states.add(WidgetState.HOVERED)
def leave(self):
self.states.discard(WidgetState.HOVERED)
self.states.discard(WidgetState.PRESSED)
def press(self, position):
self.states.add(WidgetState.PRESSED)
def focus(self):
self.states.add(WidgetState.FOCUSED)
def unfocus(self):
self.states.discard(WidgetState.FOCUSED)
def select(self):
self.states.add(WidgetState.SELECTED)
def unselect(self):
self.states.discard(WidgetState.SELECTED)
def toggle(self):
is_selected = WidgetState.SELECTED in self.states
if is_selected:
self.unselect()
else:
self.select()
class MouseOperated(Stateful):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.handlers.on_mouse_click.update({
handlers.MouseLeftButton(): self.on_click,
})
self.handlers.on_mouse_press.update({
handlers.MouseLeftButton(): self.on_press,
})
self.handlers.on_mouse_up.update({
handlers.MouseLeftButton(): self.on_enter,
})
self.handlers.on_mouse_in.update({
handlers.MouseIn(): self.on_enter,
})
self.handlers.on_mouse_over.update({
handlers.MouseOver(): self.on_over,
})
self.handlers.on_mouse_out.update({
handlers.MouseOut(): self.on_leave,
})
def on_enter(self, widget, *args, **kwargs):
self.enter()
def on_over(self, widget, position, *args, **kwargs):
self.hover(position)
def on_leave(self, widget, *args, **kwargs):
self.leave()
def on_press(self, widget, position, *args, **kwargs):
self.press(position)
def on_click(self, widget, position, *args, **kwargs):
self.toggle()
def hover(self, position):
if not self.is_hovered:
self.enter()
class WithHotkey(Stateful):
def __init__(self, ecs, key_binding, *args, **kwargs):
super().__init__(*args, **kwargs)
self.handlers.on_key_press.update({
handlers.OnKeyPress(ecs, key_binding): self.on_hotkey,
})
def on_hotkey(self, widget, key, *args, **kwargs):
self.toggle()
class Activable:
def __init__(self, callback, value, *args, **kwargs):
super().__init__(*args, **kwargs)
self.callback = callback
self.value = value
def activate(self):
return self.callback(self.widget, self.value)
def select(self):
super().select()
self.activate()
class TextInput(MouseOperated, UIWidget, containers.Stack, toolkit.Widget):
def __init__(self, ecs, width, *,
default_colors,
default_text=None,
align=Align.TOP_LEFT,
):
super().__init__(
width=width,
height=1,
align=Align.TOP_LEFT,
default_colors=default_colors,
)
self.text = basic.Text(
default_text or '',
width=width,
)
self.cursor = basic.Cursor(
# colors=default_colors.invert(),
blinking=1200,
)
self.cursor.position = Position(len(self.txt), 0)
self.children.extend([
self.text,
# TODO: Show Cursor only if has focus and ready for input?
self.cursor,
])
self.handlers.on_text_input.update({
handlers.TextInput(): self.on_input,
})
self.handlers.on_key_press.update({
handlers.TextEdit(ecs): self.on_edit,
})
@property
def txt(self):
return self.text.txt
@txt.setter
def txt(self, txt):
self.text.txt = txt
def on_input(self, widget, char):
if len(self.txt) < self.width-1:
before_cursor = self.txt[:self.cursor.position.x]
after_cursor = self.txt[self.cursor.position.x:]
self.txt = before_cursor + char + after_cursor
self.cursor.move(Vector(1, 0))
def on_edit(self, widget, cmd):
if not cmd:
return
elif cmd == 'CLEAR':
self.txt = ''
self.cursor.position = Position.ZERO
elif cmd == 'BACKSPACE':
before_cursor = self.txt[:self.cursor.position.x]
if before_cursor:
after_cursor = self.txt[self.cursor.position.x:]
self.txt = before_cursor[:-1] + after_cursor
self.cursor.move(Vector(-1, 0))
elif cmd == 'DELETE':
after_cursor = self.txt[self.cursor.position.x:]
if after_cursor:
before_cursor = self.txt[:self.cursor.position.x]
self.txt = before_cursor + after_cursor[1:]
elif cmd == 'HOME':
self.cursor.position = Position.ZERO
elif cmd == 'END':
self.cursor.position = Position(len(self.txt), 0)
elif cmd == 'FORWARD':
if self.cursor.position.x < len(self.txt):
self.cursor.move(Vector(1, 0))
elif cmd == 'BACKWARD':
if self.cursor.position.x > 0:
self.cursor.move(Vector(-1, 0))
elif cmd == 'PASTE':
pass
class Button(Activable, MouseOperated, UIWidget, toolkit.PostProcessed, decorations.Framed):
def __init__(self, value, callback, text, frame, *,
default_colors,
selected_colors=None, press_colors=None,
selected_renderers=None,
align=Align.TOP_LEFT,
):
super().__init__(
callback=callback, value=value,
content=text,
frame=frame,
align=align,
default_colors=default_colors,
)
self.default_colors = default_colors
self.selected_colors = selected_colors or self.default_colors
self.press_colors = press_colors or self.selected_colors
self.selected_renderers = list(selected_renderers or [])
@property
def txt(self):
return self.content.txt
@txt.setter
def txt(self, txt):
self.content.txt = text
def enter(self):
super().enter()
self.colors = self.selected_colors
self.post_renderers = self.selected_renderers
self.redraw();
def leave(self):
super().leave()
self.colors = self.default_colors
self.post_renderers = []
self.redraw()
def press(self, position):
super().press(position)
self.colors = self.press_colors
self.post_renderers = self.selected_renderers
self.redraw()
class ListItem(Activable, MouseOperated, WithHotkey, UIWidget, toolkit.PostProcessed, containers.Row):
def __init__(self, ecs, key_binding, callback, value, index, item, *,
default_colors,
selected_renderers=None,
align=Align.TOP_LEFT,
):
super().__init__(
ecs=ecs, key_binding=key_binding,
callback=callback, value=value,
content=[
index,
item,
],
align=align,
default_colors=default_colors,
)
self.selected_renderers = list(selected_renderers or [])
def enter(self):
super().enter()
self.post_renderers = self.selected_renderers
self.redraw();
def leave(self):
super().leave()
self.post_renderers = []
self.redraw()
def press(self, position):
super().press(position)
self.post_renderers = self.selected_renderers
self.redraw()
def focus(self):
super().focus()
self.post_renderers = self.selected_renderers
self.redraw()
def unfocus(self):
super().unfocus()
self.post_renderers = []
self.redraw()
class ListBox(containers.List):
def __init__(self, ecs, align=Align.TOP_LEFT):
super().__init__(align=align)
self.items = []
self.handlers.on_key_press.update({
handlers.NextPrevKeyPress(ecs, 'list.NEXT', 'list.PREV'): self.on_focus_change,
handlers.OnKeyPress(ecs, 'list.SELECT'): self.on_select,
})
self.handlers.on_mouse_over.update({
handlers.MouseOver(): self.on_mouse_over,
})
def append_item(self, item):
self.append(item)
self.items.append(item)
def append_separator(self, separator):
self.append(separator)
def on_mouse_over(self, widget, position):
for item in self.items:
if item.is_focused and not item.is_hovered:
return item.unfocus()
def on_focus_change(self, widget, direction):
index = None
for i, item in enumerate(self.items):
if item.is_focused or item.is_hovered:
index = i
break
if index is not None:
self.items[index].unfocus()
self.items[index].leave()
index += direction
index %= len(self.items)
self.items[index].focus()
else:
index = max(direction-1, -1)
self.items[index].focus()
def on_select(self, widget, value):
for item in self.items:
if item.is_focused or item.is_hovered:
return item.toggle()
def on_index(self, widget, index):
if index < len(self.items):
self.items[index].toggle()
# TODO: Consider renaming to FramedPanel?
class Window(UIWidget, containers.Stack):
DEFAULT_Z_ORDER = ZOrder.BASE
def __init__(self, frame, default_colors, *,
title=None,
on_key_press=None,
**kwargs
):
super().__init__(default_colors=default_colors, **kwargs)
self.frame = containers.Stack()
# TODO: Instead of frame use header, footer?
self.content = containers.Stack()
self.handlers.on_key_press.update(on_key_press or {})
self.children.extend([
decorations.Framed(
content=self.content,
frame=frame,
align=Align.TOP_LEFT,
),
self.frame,
])
if title:
self.frame.append(title)
def append(self, widget):
self.content.append(widget)
def extend(self, widgets):
self.content.extend(widgets)
class ModalWindow(Window, toolkit.Widget):
DEFAULT_Z_ORDER = ZOrder.MODAL
def __init__(self, size, align, frame, default_colors, *,
title=None,
on_key_press=None,
**kwargs
):
super().__init__(
width=size.width,
height=size.height,
align=align,
frame=frame,
default_colors=default_colors,
title=title,
on_key_press=on_key_press,
**kwargs,
) | 0.733261 | 0.139895 |
import copy
from .. import base
__all__ = ['SplitRegressor']
class SplitRegressor(base.Regressor):
"""Runs a different regressor based on the value of a specified attribute.
Parameters:
on (str): The feature on which to perform the split.
models (dict): A mapping between feature values and regressor.
default_model (base.Regressor): The regressor used for feature values that are not
specified in ``models``.
Example:
::
>>> from creme import compose
>>> from creme import dummy
>>> from creme import stats
>>> X = [
... {'key': 'a', 'y': 2},
... {'key': 'a', 'y': 3},
... {'key': 'a', 'y': 4},
... {'key': 'b', 'y': 1},
... {'key': 'b', 'y': 42},
... {'key': 'b', 'y': 1337},
... {'key': 'c', 'y': 6},
... {'key': 'c', 'y': 1},
... {'key': 'c', 'y': 6}
... ]
>>> model = compose.SplitRegressor(
... on='key',
... models={
... 'a': dummy.StatisticRegressor(stats.Mean()),
... 'b': dummy.StatisticRegressor(stats.Quantile(0.5))
... },
... default_model=dummy.StatisticRegressor(stats.Min())
... )
>>> for x in X:
... y = x.pop('y')
... model = model.fit_one(x, y)
>>> model.models['a'].statistic.get()
3.0
>>> model.predict_one({'key': 'a'})
3.0
>>> model.models['b'].statistic.get()
42
>>> model.default_model.statistic.get()
1
"""
def __init__(self, on, models, default_model):
self.on = on
self.models = copy.deepcopy(models)
self.default_model = copy.deepcopy(default_model)
def fit_one(self, x, y):
x = copy.copy(x)
key = x[self.on]
x.pop(self.on)
self.models.get(key, self.default_model).fit_one(x, y)
return self
def predict_one(self, x):
x = copy.copy(x)
key = x[self.on]
x.pop(self.on)
return self.models.get(key, self.default_model).predict_one(x) | creme/compose/split.py | import copy
from .. import base
__all__ = ['SplitRegressor']
class SplitRegressor(base.Regressor):
"""Runs a different regressor based on the value of a specified attribute.
Parameters:
on (str): The feature on which to perform the split.
models (dict): A mapping between feature values and regressor.
default_model (base.Regressor): The regressor used for feature values that are not
specified in ``models``.
Example:
::
>>> from creme import compose
>>> from creme import dummy
>>> from creme import stats
>>> X = [
... {'key': 'a', 'y': 2},
... {'key': 'a', 'y': 3},
... {'key': 'a', 'y': 4},
... {'key': 'b', 'y': 1},
... {'key': 'b', 'y': 42},
... {'key': 'b', 'y': 1337},
... {'key': 'c', 'y': 6},
... {'key': 'c', 'y': 1},
... {'key': 'c', 'y': 6}
... ]
>>> model = compose.SplitRegressor(
... on='key',
... models={
... 'a': dummy.StatisticRegressor(stats.Mean()),
... 'b': dummy.StatisticRegressor(stats.Quantile(0.5))
... },
... default_model=dummy.StatisticRegressor(stats.Min())
... )
>>> for x in X:
... y = x.pop('y')
... model = model.fit_one(x, y)
>>> model.models['a'].statistic.get()
3.0
>>> model.predict_one({'key': 'a'})
3.0
>>> model.models['b'].statistic.get()
42
>>> model.default_model.statistic.get()
1
"""
def __init__(self, on, models, default_model):
self.on = on
self.models = copy.deepcopy(models)
self.default_model = copy.deepcopy(default_model)
def fit_one(self, x, y):
x = copy.copy(x)
key = x[self.on]
x.pop(self.on)
self.models.get(key, self.default_model).fit_one(x, y)
return self
def predict_one(self, x):
x = copy.copy(x)
key = x[self.on]
x.pop(self.on)
return self.models.get(key, self.default_model).predict_one(x) | 0.878965 | 0.448426 |
"""Hyper-parameters support classes for TensorFlow Lattice estimators."""
from distutils.util import strtobool
import six
from tensorflow_lattice.python.lib import regularizers
class PerFeatureHParams(object):
"""Parameters object with per feature parametrization.
Each parameter can be overwritten for specific features by setting
`feature__<feature_name>__<parameter_name>`, otherwise it falls back to the
global parameter name value `<parameter_name>`.
Parameter types are set from their first value set -- but they can also be
reset by `set_param_type`.
Example: let's say we have a parameter `lattice_size` that should be 2 if not
specified (global value), but can be overridden per feature; let's assume
there are 3 features: `a`, `b`, and `c` (added after construction). Then:
```python
hparams = PerFeatureHParams(["a", "b"], lattice_size=2,
feature__b__lattice_size=3)
hparams.add_feature(["c"])
hparams.get_param("lattice_size") == 2
hparams.get_feature_param("a", "lattice_size") == 2
hparams.get_feature_param("b", "lattice_size") == 3
hparams.get_feature_param("c", "lattice_size") == 2
hparams.get_feature_param("d", "lattice_size") raises a ValueError
```
Use the `get_feature_param` method to automatically get the specialized value,
or fall-back to the global one.
"""
# Used to separate feature prefix, name and parameter name.
FEATURE_SEPARATOR = '__'
# Feature prefix for feature specific parameter values.
FEATURE_PREFIX = 'feature'
def __init__(self, feature_names=None, **kwargs):
"""Construct with arbitrary list of parameters.
Args:
feature_names: list of feature names. Only features names listed here
(or added later with add_feature) can have feature specific parameter
values.
**kwargs: parameters names.
Returns:
PerFeatureHParams object.
Raises:
ValueError: if a feature-specific parameter value is set for an
unknown feature.
"""
super(PerFeatureHParams, self).__init__()
self._data = {}
self._params_type = {}
self._feature_names = set(
feature_names) if feature_names is not None else set()
for feature_name in self._feature_names:
PerFeatureHParams._check_feature_name(feature_name)
# First set the global parameters, so they become known and then feature
# specific parameters.
for param_name, value in six.iteritems(kwargs):
if not PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
for param_name, value in six.iteritems(kwargs):
if PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
@staticmethod
def _check_feature_name(feature_name):
"""Raises ValueError if feature_name is not valid."""
if (PerFeatureHParams.FEATURE_SEPARATOR in feature_name or
'=' in feature_name):
raise ValueError(
'Invalid feature name "{}": "{}" and "=" are not supported in '
'feature names'.format(feature_name,
PerFeatureHParams.FEATURE_SEPARATOR))
@staticmethod
def _is_feature_specific(param_name):
return param_name.startswith(PerFeatureHParams.FEATURE_PREFIX +
PerFeatureHParams.FEATURE_SEPARATOR)
def get_feature_names(self):
"""Returns copy of list of known feature names."""
feature_names_list = list(self._feature_names)
feature_names_list.sort()
return feature_names_list
def add_feature(self, feature_name):
"""Add feature_name (one name or list of names) to list of known names."""
if isinstance(feature_name, list):
# Add all elements in the list, if a list.
for f in feature_name:
if not isinstance(f, six.string_types):
raise ValueError(
'feature_name should either be a list of strings, or a string, '
'got "%s"' % feature_name)
PerFeatureHParams._check_feature_name(f)
self._feature_names.add(f)
elif isinstance(feature_name, six.string_types):
PerFeatureHParams._check_feature_name(feature_name)
self._feature_names.add(feature_name)
else:
raise ValueError(
'feature_name should either be a list of strings, or a string, '
'got "%s"' % feature_name)
return self
def param_name_for_feature(self, feature_name, param_name):
"""Returns parameter name for specific feature parameter."""
if feature_name not in self._feature_names:
raise ValueError('Unknown feature name "%s" for parameter "%s"' %
(feature_name, param_name))
return PerFeatureHParams.FEATURE_SEPARATOR.join(
[PerFeatureHParams.FEATURE_PREFIX, feature_name, param_name])
def is_feature_set_param(self, feature_name, param_name):
"""Returns whether param_name parameter is set for feature_name."""
key = self.param_name_for_feature(feature_name, param_name)
return hasattr(self, key)
def get_feature_param(self, feature_name, param_name, default=None):
"""Returns parameter for feature or falls back to global parameter."""
key = self.param_name_for_feature(feature_name, param_name)
if hasattr(self, key):
return getattr(self, key, None)
return getattr(self, param_name, default)
def set_feature_param(self, feature_name, param_name, value):
"""Sets parameter value specific for feature. Returns self."""
if feature_name not in self.get_feature_names():
raise ValueError(
'Unknown feature name "%s" when trying to set parameter "%s", known '
'values are %s' % (feature_name, param_name,
self.get_feature_names()))
if param_name not in self._params_type:
raise ValueError(
'Unknown parameter name "%s" when trying to set parameter for '
'feature "%s"' % (param_name, feature_name))
key = self.param_name_for_feature(feature_name, param_name)
self._data[key] = value
return self
def get_param(self, param_name, default=None):
"""Returns the global parameter or falls back to default."""
return self._data[param_name] if param_name in self._data else default
def __getattr__(self, param_name):
if param_name.startswith('_') or param_name not in self._data:
raise AttributeError('No value set for "{}"'.format(param_name))
return self._data[param_name]
@staticmethod
def _parse_value(value_str, value_type):
"""Parses string a the given value_type."""
if value_type is str:
return value_str
elif value_type is int:
return int(value_str)
elif value_type is float:
return float(value_str)
elif value_type is bool:
return strtobool(value_str)
raise ValueError(
'Do not know how to parse types {} -- value was {!r}'.format(
value_type, value_str))
def _set_param(self, param_name, value, parse):
"""Sets parameter, optionally parse it."""
# Make sure that feature specific parameters are properly named.
if PerFeatureHParams._is_feature_specific(param_name):
parts = param_name.split(PerFeatureHParams.FEATURE_SEPARATOR, 3)
if len(parts) != 3:
raise ValueError(
'Bad formatted feature specific parameter "{}", please use '
'"{}{}<feature_name>{}<parameter_name>"'.format(
param_name, PerFeatureHParams.FEATURE_PREFIX,
PerFeatureHParams.FEATURE_SEPARATOR,
PerFeatureHParams.FEATURE_SEPARATOR))
if parts[1] not in self._feature_names:
raise ValueError(
'Unknown feature "{}" for feature specific parameter "{}"'.format(
parts[1], param_name))
if parts[2] not in self._params_type:
raise ValueError(
'Unknown parameter name "{}", can not set for feature "{}"'.format(
parts[2], parts[1]))
if parse:
value = PerFeatureHParams._parse_value(value,
self._params_type[parts[2]])
else:
# Non-feature specific parameter: set _param_type if not yet set.
if param_name not in self._params_type:
if parse:
raise ValueError(
'Parsing value for unknown parameter "{}"'.format(param_name))
self._params_type[param_name] = type(value)
elif parse:
value = PerFeatureHParams._parse_value(value,
self._params_type[param_name])
self._data[param_name] = value
def set_param(self, param_name, value):
"""Sets parameter value. Returns self."""
self._set_param(param_name, value, parse=False)
return self
def set_param_type(self, param_name, param_type):
"""Sets the parameter type, it must already exist. Returns self."""
if param_name not in self._params_type:
raise ValueError(
'Can not set parameter type if parameter has not been set for "{}"'.
format(param_name))
self._params_type[param_name] = param_type
def parse_param(self, param_name, value_str):
"""Parses parameter values from string. Returns self."""
self._set_param(param_name, value_str, parse=True)
return self
def get_global_and_feature_params(self, param_names, feature_names):
"""Returns values for multiple params, global and for each feature.
Args:
param_names: list of parameters to get values for.
feature_names: list of features to get specific values for.
Returns:
* List of global values for parameters requested in `param_names`.
* List of list of per feature values for parameters requested in
`param_names` for features requested in `feature_names`.
"""
global_values = [self.get_param(param_name) for param_name in param_names]
feature_values = []
for feature in feature_names:
feature_values.append([
self.get_feature_param(feature, param_name)
for param_name in param_names
])
return (global_values, feature_values)
def values(self):
"""Returns shallow copy of the hyperparameter dict."""
return {k: v for k, v in six.iteritems(self._data)}
def __str__(self):
return str(sorted(self.values().items()))
def parse_hparams(self, hparams):
"""Incorporates hyper-parameters from another HParams object.
Copies over values of hyper-parameters from the given object. New parameters
may be set, but not new features. Also works with
`tf.contrib.training.HParams` objects.
Args:
hparams: `PerFeatureHParams` object, but also works with the standard
`tf.contrib.training.HParams` object.
Returns:
Changes affect self, but returns self for convenience.
Raises:
ValueError: if trying to set unknown features, or if setting a feature
specific parameter for an unknown parameter.
"""
# First set the global parameters, so they become known and then feature
# specific parameters.
if hparams is not None:
for param_name, value in six.iteritems(hparams.values()):
if not PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
for param_name, value in six.iteritems(hparams.values()):
if PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
return self
def parse(self, hparams_str):
"""Parses strings into hparams.
Args:
hparams_str: must be a comma separated list of "<key>=<value>",
where "<key>" is a hyper-parameter name, and "<value>" its value.
Returns:
Changes affect self, but returns self for convenience.
Raises:
ValueError: if there is a problem with the input:
* if trying to set an unknown parameter.
* if trying to set unknown feature(s)
* if can't convert value to parameter type.
"""
if hparams_str:
for pair in hparams_str.split(','):
(key, value) = pair.split('=')
self.parse_param(key, value)
return self
class CalibratedHParams(PerFeatureHParams):
"""PerFeatureHParams specialization with input calibration parameters.
The following hyper-parameters can be set as global, or per-feature (see
base `PerFeatureHParams` for details):
* `feature_names`: list of feature names. Only features names listed here
(or added later with add_feature) can have feature specific parameter
values.
* `num_keypoints`: Number of keypoints to use for calibration, Set to 0 or
`None` for no calibration.
* `calibration_output_min`, `calibration_output_max`: initial and final
values for calibrations. -1.0 to 1.0 works well for calibrated linear
models. For lattices one will want to set these to (0, `lattice_size`-1).
Only used during initialization of the calibration, if `quantiles_dir`
is given to the calibrated model (as opposed to defining one's own value
with `keypoints_initializers_fn`). It must be defined for calibration to
work, no default is set.
* `calibration_bound`: If output of calibration max/min are bound to the
limits given in `calibration_output_min/max`.
* `monotonicity`: Monotonicity for the feature. 0 for no monotonicity,
1 and -1 for increasing and decreasing monotonicity respectively.
* `missing_input_value`: If set, and if the input has this value it is
assumed
to be missing and the output will either be calibrated to some value
between `[calibration_output_min, calibration_output_max]` or set to a
fixed value set by missing_output_value.
* `missing_output_value`: Requires missing_input_value also to be set. If
set
if will convert missing input to this value. Leave it undefined and the
output will be learned.
* `calibration_<regularizer_name>` for all regularizer_name's in
regularizers.CALIBRATOR_REGULARIZERS. e.g. `calibration_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'num_keypoints': 10,
'calibration_output_min': None,
'calibration_output_max': None,
'calibration_bound': False,
'monotonicity': 0,
'missing_input_value': None,
'missing_output_value': None,
}
regularizer_hparam_names = [
'calibration_{}'.format(regularizer_name)
for regularizer_name in regularizers.CALIBRATOR_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedHParams, self).__init__(feature_names, **args)
self.set_param_type('monotonicity', int)
self.set_param_type('calibration_output_min', float)
self.set_param_type('calibration_output_max', float)
self.set_param_type('missing_input_value', float)
self.set_param_type('missing_output_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedLinearHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedLinear models.
Same as `CalibratedHParams` (hyper-parameters for input calibration) plus
the global learning_rate.
The parameters `calibration_output_min` and `calibration_output_max` shouldn't
be changed (they are fixed at -1. and +1), since they are eventually re-scaled
by the linear layer on top.
It supports regularization, monotonicity and missing values (input and
optionally output).
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'calibration_output_min': -1.,
'calibration_output_max': 1.,
}
args.update(kwargs)
super(CalibratedLinearHParams, self).__init__(feature_names, **args)
class CalibratedLatticeHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedLattice models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global or per feature parameter that controls number
of cells for a feature. Should be greater than equal to 2, and the
recommended default value is 2. Also calibrator output min and max should be
[0, lattice_size - 1], and the output should be bounded, since a lattice
expects an input in the range [0, lattice_size - 1].
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `missing_input_value`: Value for which a feature is considered missing. Such
values are either automatically learned to some calibrated value, or,
if missing_vertex is set, they get their own value in the lattice.
* `missing_vertex`: if missing_input_value is set, this boolean value indicate
whether to create an extra vertex for missing values.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'lattice_size': 2,
'interpolation_type': 'hypercube',
'calibration_bound': True,
'missing_input_value': None,
'missing_vertex': False,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedLatticeHParams, self).__init__(feature_names, **args)
self.set_param_type('missing_input_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedRtlHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedRtl (RandomTinyLattices) models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global or per feature parameter that controls number
of cells for a feature. Should be greater than equal to 2, and the
recommended default value is 2. Also calibrator output min and max should be
[0, lattice_size - 1], and the output should be bounded, since a lattice
expects an input in the range [0, lattice_size - 1]. (Note if missing_vertex
is True, then we add an extra vertex, so input range is [0, lattice_size])
* `num_lattices`: (int) a number of lattices to be created.
* `lattice_rank`: (int) a lattice rank in each lattice.
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `ensemble_bias`: (float) an initial value of bias term to be added to the
output of ensemble.
* `rtl_seed`: (int) a random seed for rtl construction.
* `missing_input_value`: Value for which a feature is considered missing. Such
values are either automatically learned to some calibrated value, or,
if missing_vertex is set, they get their own value in the lattice.
* `missing_vertex`: if missing_input_value is set, this boolean value indicate
whether to create an extra vertex for missing values.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'lattice_size': 2,
'num_lattices': None,
'lattice_rank': None,
'interpolation_type': 'hypercube',
'rtl_seed': 12345,
'calibration_bound': True,
'missing_input_value': None,
'missing_vertex': False,
'ensemble_bias': 0.0,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedRtlHParams, self).__init__(feature_names, **args)
self.set_param_type('num_lattices', int)
self.set_param_type('lattice_rank', int)
self.set_param_type('missing_input_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedEtlHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedEtl (Embedded tiny lattices) models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Note that this architecture does not support any of per-feature based lattice
hyper-parameters such as missing_vertex, per-feature missing_input_value,
per-feature lattice_size, per-feature lattice regularization, because after
the linear embedding, all of features are mixed together, so it is not clear
how to merge per-feature parameters after the linear embedding layer.
If there is no non-monotonic feature, but `non_monotonic_lattice_rank` or
`non_monotonic_num_lattices` are not `None`, then this will raise the error.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global parameter that controls number of
cells for a feature. Should be greater than equal to 2, and the recommended
default value is 2. Also calibrator output min and max should be
[0, `lattice_size` - 1], and the output should be bounded.
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `monotonic_lattice_rank`: (int) a lattice rank in each monotonic lattice.
* `monotonic_num_lattices`: (int) a number of monotonic lattices to be
created.
* `monotonic_lattice_size`: (int) lattice cell size for each monotonic lattice
in the ensemble lattices layer.
* `non_monotonic_lattice_rank`: (int) a lattice rank in each non monotonic
lattice. If all features are monotonic, this parameter should be None.
* `non_monotonic_num_lattices`: (int) a number of non-monotonic lattices to be
created. If all features are monotonic, this parameter should be None.
* `monotonic_lattice_size`: (int) lattice cell size for each non-monotonic
lattice in the ensemble lattices layer.
* `linear_embedding_calibration_min`: (float) a global parameter that controls
a minimum value of intermediate calibration layers. Default is -100.
* `linear_embedding_calibration_max`: (float) a global parameter that controls
a maximum value of intermediate calibration layers. Default is 100.
* `linear_embedding_calibration_num_keypoints`: (float) a global parameter
that controls a `num_keypoints` in intermediate calibration layers. Default
is 100.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'monotonic_lattice_rank': None,
'monotonic_num_lattices': None,
'monotonic_lattice_size': None,
'non_monotonic_lattice_rank': None,
'non_monotonic_num_lattices': None,
'non_monotonic_lattice_size': None,
'interpolation_type': 'hypercube',
'calibration_bound': True,
'linear_embedding_calibration_min': -100.0,
'linear_embedding_calibration_max': 100.0,
'linear_embedding_calibration_num_keypoints': 100,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedEtlHParams, self).__init__(feature_names, **args)
self.set_param_type('monotonic_lattice_rank', int)
self.set_param_type('monotonic_num_lattices', int)
self.set_param_type('monotonic_lattice_size', int)
self.set_param_type('non_monotonic_lattice_rank', int)
self.set_param_type('non_monotonic_num_lattices', int)
self.set_param_type('non_monotonic_lattice_size', int)
self.set_param_type('linear_embedding_calibration_min', float)
self.set_param_type('linear_embedding_calibration_max', float)
self.set_param_type('linear_embedding_calibration_num_keypoints', int)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float) | tensorflow_lattice/python/estimators/hparams.py | """Hyper-parameters support classes for TensorFlow Lattice estimators."""
from distutils.util import strtobool
import six
from tensorflow_lattice.python.lib import regularizers
class PerFeatureHParams(object):
"""Parameters object with per feature parametrization.
Each parameter can be overwritten for specific features by setting
`feature__<feature_name>__<parameter_name>`, otherwise it falls back to the
global parameter name value `<parameter_name>`.
Parameter types are set from their first value set -- but they can also be
reset by `set_param_type`.
Example: let's say we have a parameter `lattice_size` that should be 2 if not
specified (global value), but can be overridden per feature; let's assume
there are 3 features: `a`, `b`, and `c` (added after construction). Then:
```python
hparams = PerFeatureHParams(["a", "b"], lattice_size=2,
feature__b__lattice_size=3)
hparams.add_feature(["c"])
hparams.get_param("lattice_size") == 2
hparams.get_feature_param("a", "lattice_size") == 2
hparams.get_feature_param("b", "lattice_size") == 3
hparams.get_feature_param("c", "lattice_size") == 2
hparams.get_feature_param("d", "lattice_size") raises a ValueError
```
Use the `get_feature_param` method to automatically get the specialized value,
or fall-back to the global one.
"""
# Used to separate feature prefix, name and parameter name.
FEATURE_SEPARATOR = '__'
# Feature prefix for feature specific parameter values.
FEATURE_PREFIX = 'feature'
def __init__(self, feature_names=None, **kwargs):
"""Construct with arbitrary list of parameters.
Args:
feature_names: list of feature names. Only features names listed here
(or added later with add_feature) can have feature specific parameter
values.
**kwargs: parameters names.
Returns:
PerFeatureHParams object.
Raises:
ValueError: if a feature-specific parameter value is set for an
unknown feature.
"""
super(PerFeatureHParams, self).__init__()
self._data = {}
self._params_type = {}
self._feature_names = set(
feature_names) if feature_names is not None else set()
for feature_name in self._feature_names:
PerFeatureHParams._check_feature_name(feature_name)
# First set the global parameters, so they become known and then feature
# specific parameters.
for param_name, value in six.iteritems(kwargs):
if not PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
for param_name, value in six.iteritems(kwargs):
if PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
@staticmethod
def _check_feature_name(feature_name):
"""Raises ValueError if feature_name is not valid."""
if (PerFeatureHParams.FEATURE_SEPARATOR in feature_name or
'=' in feature_name):
raise ValueError(
'Invalid feature name "{}": "{}" and "=" are not supported in '
'feature names'.format(feature_name,
PerFeatureHParams.FEATURE_SEPARATOR))
@staticmethod
def _is_feature_specific(param_name):
return param_name.startswith(PerFeatureHParams.FEATURE_PREFIX +
PerFeatureHParams.FEATURE_SEPARATOR)
def get_feature_names(self):
"""Returns copy of list of known feature names."""
feature_names_list = list(self._feature_names)
feature_names_list.sort()
return feature_names_list
def add_feature(self, feature_name):
"""Add feature_name (one name or list of names) to list of known names."""
if isinstance(feature_name, list):
# Add all elements in the list, if a list.
for f in feature_name:
if not isinstance(f, six.string_types):
raise ValueError(
'feature_name should either be a list of strings, or a string, '
'got "%s"' % feature_name)
PerFeatureHParams._check_feature_name(f)
self._feature_names.add(f)
elif isinstance(feature_name, six.string_types):
PerFeatureHParams._check_feature_name(feature_name)
self._feature_names.add(feature_name)
else:
raise ValueError(
'feature_name should either be a list of strings, or a string, '
'got "%s"' % feature_name)
return self
def param_name_for_feature(self, feature_name, param_name):
"""Returns parameter name for specific feature parameter."""
if feature_name not in self._feature_names:
raise ValueError('Unknown feature name "%s" for parameter "%s"' %
(feature_name, param_name))
return PerFeatureHParams.FEATURE_SEPARATOR.join(
[PerFeatureHParams.FEATURE_PREFIX, feature_name, param_name])
def is_feature_set_param(self, feature_name, param_name):
"""Returns whether param_name parameter is set for feature_name."""
key = self.param_name_for_feature(feature_name, param_name)
return hasattr(self, key)
def get_feature_param(self, feature_name, param_name, default=None):
"""Returns parameter for feature or falls back to global parameter."""
key = self.param_name_for_feature(feature_name, param_name)
if hasattr(self, key):
return getattr(self, key, None)
return getattr(self, param_name, default)
def set_feature_param(self, feature_name, param_name, value):
"""Sets parameter value specific for feature. Returns self."""
if feature_name not in self.get_feature_names():
raise ValueError(
'Unknown feature name "%s" when trying to set parameter "%s", known '
'values are %s' % (feature_name, param_name,
self.get_feature_names()))
if param_name not in self._params_type:
raise ValueError(
'Unknown parameter name "%s" when trying to set parameter for '
'feature "%s"' % (param_name, feature_name))
key = self.param_name_for_feature(feature_name, param_name)
self._data[key] = value
return self
def get_param(self, param_name, default=None):
"""Returns the global parameter or falls back to default."""
return self._data[param_name] if param_name in self._data else default
def __getattr__(self, param_name):
if param_name.startswith('_') or param_name not in self._data:
raise AttributeError('No value set for "{}"'.format(param_name))
return self._data[param_name]
@staticmethod
def _parse_value(value_str, value_type):
"""Parses string a the given value_type."""
if value_type is str:
return value_str
elif value_type is int:
return int(value_str)
elif value_type is float:
return float(value_str)
elif value_type is bool:
return strtobool(value_str)
raise ValueError(
'Do not know how to parse types {} -- value was {!r}'.format(
value_type, value_str))
def _set_param(self, param_name, value, parse):
"""Sets parameter, optionally parse it."""
# Make sure that feature specific parameters are properly named.
if PerFeatureHParams._is_feature_specific(param_name):
parts = param_name.split(PerFeatureHParams.FEATURE_SEPARATOR, 3)
if len(parts) != 3:
raise ValueError(
'Bad formatted feature specific parameter "{}", please use '
'"{}{}<feature_name>{}<parameter_name>"'.format(
param_name, PerFeatureHParams.FEATURE_PREFIX,
PerFeatureHParams.FEATURE_SEPARATOR,
PerFeatureHParams.FEATURE_SEPARATOR))
if parts[1] not in self._feature_names:
raise ValueError(
'Unknown feature "{}" for feature specific parameter "{}"'.format(
parts[1], param_name))
if parts[2] not in self._params_type:
raise ValueError(
'Unknown parameter name "{}", can not set for feature "{}"'.format(
parts[2], parts[1]))
if parse:
value = PerFeatureHParams._parse_value(value,
self._params_type[parts[2]])
else:
# Non-feature specific parameter: set _param_type if not yet set.
if param_name not in self._params_type:
if parse:
raise ValueError(
'Parsing value for unknown parameter "{}"'.format(param_name))
self._params_type[param_name] = type(value)
elif parse:
value = PerFeatureHParams._parse_value(value,
self._params_type[param_name])
self._data[param_name] = value
def set_param(self, param_name, value):
"""Sets parameter value. Returns self."""
self._set_param(param_name, value, parse=False)
return self
def set_param_type(self, param_name, param_type):
"""Sets the parameter type, it must already exist. Returns self."""
if param_name not in self._params_type:
raise ValueError(
'Can not set parameter type if parameter has not been set for "{}"'.
format(param_name))
self._params_type[param_name] = param_type
def parse_param(self, param_name, value_str):
"""Parses parameter values from string. Returns self."""
self._set_param(param_name, value_str, parse=True)
return self
def get_global_and_feature_params(self, param_names, feature_names):
"""Returns values for multiple params, global and for each feature.
Args:
param_names: list of parameters to get values for.
feature_names: list of features to get specific values for.
Returns:
* List of global values for parameters requested in `param_names`.
* List of list of per feature values for parameters requested in
`param_names` for features requested in `feature_names`.
"""
global_values = [self.get_param(param_name) for param_name in param_names]
feature_values = []
for feature in feature_names:
feature_values.append([
self.get_feature_param(feature, param_name)
for param_name in param_names
])
return (global_values, feature_values)
def values(self):
"""Returns shallow copy of the hyperparameter dict."""
return {k: v for k, v in six.iteritems(self._data)}
def __str__(self):
return str(sorted(self.values().items()))
def parse_hparams(self, hparams):
"""Incorporates hyper-parameters from another HParams object.
Copies over values of hyper-parameters from the given object. New parameters
may be set, but not new features. Also works with
`tf.contrib.training.HParams` objects.
Args:
hparams: `PerFeatureHParams` object, but also works with the standard
`tf.contrib.training.HParams` object.
Returns:
Changes affect self, but returns self for convenience.
Raises:
ValueError: if trying to set unknown features, or if setting a feature
specific parameter for an unknown parameter.
"""
# First set the global parameters, so they become known and then feature
# specific parameters.
if hparams is not None:
for param_name, value in six.iteritems(hparams.values()):
if not PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
for param_name, value in six.iteritems(hparams.values()):
if PerFeatureHParams._is_feature_specific(param_name):
self.set_param(param_name, value)
return self
def parse(self, hparams_str):
"""Parses strings into hparams.
Args:
hparams_str: must be a comma separated list of "<key>=<value>",
where "<key>" is a hyper-parameter name, and "<value>" its value.
Returns:
Changes affect self, but returns self for convenience.
Raises:
ValueError: if there is a problem with the input:
* if trying to set an unknown parameter.
* if trying to set unknown feature(s)
* if can't convert value to parameter type.
"""
if hparams_str:
for pair in hparams_str.split(','):
(key, value) = pair.split('=')
self.parse_param(key, value)
return self
class CalibratedHParams(PerFeatureHParams):
"""PerFeatureHParams specialization with input calibration parameters.
The following hyper-parameters can be set as global, or per-feature (see
base `PerFeatureHParams` for details):
* `feature_names`: list of feature names. Only features names listed here
(or added later with add_feature) can have feature specific parameter
values.
* `num_keypoints`: Number of keypoints to use for calibration, Set to 0 or
`None` for no calibration.
* `calibration_output_min`, `calibration_output_max`: initial and final
values for calibrations. -1.0 to 1.0 works well for calibrated linear
models. For lattices one will want to set these to (0, `lattice_size`-1).
Only used during initialization of the calibration, if `quantiles_dir`
is given to the calibrated model (as opposed to defining one's own value
with `keypoints_initializers_fn`). It must be defined for calibration to
work, no default is set.
* `calibration_bound`: If output of calibration max/min are bound to the
limits given in `calibration_output_min/max`.
* `monotonicity`: Monotonicity for the feature. 0 for no monotonicity,
1 and -1 for increasing and decreasing monotonicity respectively.
* `missing_input_value`: If set, and if the input has this value it is
assumed
to be missing and the output will either be calibrated to some value
between `[calibration_output_min, calibration_output_max]` or set to a
fixed value set by missing_output_value.
* `missing_output_value`: Requires missing_input_value also to be set. If
set
if will convert missing input to this value. Leave it undefined and the
output will be learned.
* `calibration_<regularizer_name>` for all regularizer_name's in
regularizers.CALIBRATOR_REGULARIZERS. e.g. `calibration_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'num_keypoints': 10,
'calibration_output_min': None,
'calibration_output_max': None,
'calibration_bound': False,
'monotonicity': 0,
'missing_input_value': None,
'missing_output_value': None,
}
regularizer_hparam_names = [
'calibration_{}'.format(regularizer_name)
for regularizer_name in regularizers.CALIBRATOR_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedHParams, self).__init__(feature_names, **args)
self.set_param_type('monotonicity', int)
self.set_param_type('calibration_output_min', float)
self.set_param_type('calibration_output_max', float)
self.set_param_type('missing_input_value', float)
self.set_param_type('missing_output_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedLinearHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedLinear models.
Same as `CalibratedHParams` (hyper-parameters for input calibration) plus
the global learning_rate.
The parameters `calibration_output_min` and `calibration_output_max` shouldn't
be changed (they are fixed at -1. and +1), since they are eventually re-scaled
by the linear layer on top.
It supports regularization, monotonicity and missing values (input and
optionally output).
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'calibration_output_min': -1.,
'calibration_output_max': 1.,
}
args.update(kwargs)
super(CalibratedLinearHParams, self).__init__(feature_names, **args)
class CalibratedLatticeHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedLattice models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global or per feature parameter that controls number
of cells for a feature. Should be greater than equal to 2, and the
recommended default value is 2. Also calibrator output min and max should be
[0, lattice_size - 1], and the output should be bounded, since a lattice
expects an input in the range [0, lattice_size - 1].
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `missing_input_value`: Value for which a feature is considered missing. Such
values are either automatically learned to some calibrated value, or,
if missing_vertex is set, they get their own value in the lattice.
* `missing_vertex`: if missing_input_value is set, this boolean value indicate
whether to create an extra vertex for missing values.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'lattice_size': 2,
'interpolation_type': 'hypercube',
'calibration_bound': True,
'missing_input_value': None,
'missing_vertex': False,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedLatticeHParams, self).__init__(feature_names, **args)
self.set_param_type('missing_input_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedRtlHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedRtl (RandomTinyLattices) models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global or per feature parameter that controls number
of cells for a feature. Should be greater than equal to 2, and the
recommended default value is 2. Also calibrator output min and max should be
[0, lattice_size - 1], and the output should be bounded, since a lattice
expects an input in the range [0, lattice_size - 1]. (Note if missing_vertex
is True, then we add an extra vertex, so input range is [0, lattice_size])
* `num_lattices`: (int) a number of lattices to be created.
* `lattice_rank`: (int) a lattice rank in each lattice.
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `ensemble_bias`: (float) an initial value of bias term to be added to the
output of ensemble.
* `rtl_seed`: (int) a random seed for rtl construction.
* `missing_input_value`: Value for which a feature is considered missing. Such
values are either automatically learned to some calibrated value, or,
if missing_vertex is set, they get their own value in the lattice.
* `missing_vertex`: if missing_input_value is set, this boolean value indicate
whether to create an extra vertex for missing values.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'lattice_size': 2,
'num_lattices': None,
'lattice_rank': None,
'interpolation_type': 'hypercube',
'rtl_seed': 12345,
'calibration_bound': True,
'missing_input_value': None,
'missing_vertex': False,
'ensemble_bias': 0.0,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedRtlHParams, self).__init__(feature_names, **args)
self.set_param_type('num_lattices', int)
self.set_param_type('lattice_rank', int)
self.set_param_type('missing_input_value', float)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float)
class CalibratedEtlHParams(CalibratedHParams):
"""Hyper-parameters for CalibratedEtl (Embedded tiny lattices) models.
Supports regularization and monotonicity like described in `CalibratedHParam`.
Values for `calibration_output_min`, `calibration_output_max` and
`missing_output_value` get set automatically.
Note that this architecture does not support any of per-feature based lattice
hyper-parameters such as missing_vertex, per-feature missing_input_value,
per-feature lattice_size, per-feature lattice regularization, because after
the linear embedding, all of features are mixed together, so it is not clear
how to merge per-feature parameters after the linear embedding layer.
If there is no non-monotonic feature, but `non_monotonic_lattice_rank` or
`non_monotonic_num_lattices` are not `None`, then this will raise the error.
Added parameters:
* `learning_rate`: (float) a global parameter that assigns a step size of an
optimizer.
* `lattice_size`: (int) a global parameter that controls number of
cells for a feature. Should be greater than equal to 2, and the recommended
default value is 2. Also calibrator output min and max should be
[0, `lattice_size` - 1], and the output should be bounded.
* `interpolation_type`: a global parameter that defines if the lattice will
interpolate using the full hypercube or only the simplex ("hyper-triangle",
much faster for larger lattices) around the point being evaluated.
Valid values: 'hypercube' or 'simplex'
* `monotonic_lattice_rank`: (int) a lattice rank in each monotonic lattice.
* `monotonic_num_lattices`: (int) a number of monotonic lattices to be
created.
* `monotonic_lattice_size`: (int) lattice cell size for each monotonic lattice
in the ensemble lattices layer.
* `non_monotonic_lattice_rank`: (int) a lattice rank in each non monotonic
lattice. If all features are monotonic, this parameter should be None.
* `non_monotonic_num_lattices`: (int) a number of non-monotonic lattices to be
created. If all features are monotonic, this parameter should be None.
* `monotonic_lattice_size`: (int) lattice cell size for each non-monotonic
lattice in the ensemble lattices layer.
* `linear_embedding_calibration_min`: (float) a global parameter that controls
a minimum value of intermediate calibration layers. Default is -100.
* `linear_embedding_calibration_max`: (float) a global parameter that controls
a maximum value of intermediate calibration layers. Default is 100.
* `linear_embedding_calibration_num_keypoints`: (float) a global parameter
that controls a `num_keypoints` in intermediate calibration layers. Default
is 100.
* `lattice_<regularizer_name>` for all regularizer_name's in
regularizers.LATTICE_REGULARIZERS. e.g. `lattice_l2_reg`.
"""
def __init__(self, feature_names=None, **kwargs):
# Set default args, and override with given ones.
args = {
'learning_rate': 0.1,
'monotonic_lattice_rank': None,
'monotonic_num_lattices': None,
'monotonic_lattice_size': None,
'non_monotonic_lattice_rank': None,
'non_monotonic_num_lattices': None,
'non_monotonic_lattice_size': None,
'interpolation_type': 'hypercube',
'calibration_bound': True,
'linear_embedding_calibration_min': -100.0,
'linear_embedding_calibration_max': 100.0,
'linear_embedding_calibration_num_keypoints': 100,
}
regularizer_hparam_names = [
'lattice_{}'.format(regularizer_name)
for regularizer_name in regularizers.LATTICE_REGULARIZERS
]
args.update({
regularizer_name: None for regularizer_name in regularizer_hparam_names
})
args.update(kwargs)
super(CalibratedEtlHParams, self).__init__(feature_names, **args)
self.set_param_type('monotonic_lattice_rank', int)
self.set_param_type('monotonic_num_lattices', int)
self.set_param_type('monotonic_lattice_size', int)
self.set_param_type('non_monotonic_lattice_rank', int)
self.set_param_type('non_monotonic_num_lattices', int)
self.set_param_type('non_monotonic_lattice_size', int)
self.set_param_type('linear_embedding_calibration_min', float)
self.set_param_type('linear_embedding_calibration_max', float)
self.set_param_type('linear_embedding_calibration_num_keypoints', int)
for regularizer_name in regularizer_hparam_names:
self.set_param_type(regularizer_name, float) | 0.958499 | 0.716305 |
import numpy as np
import dolfin as df
import ufl
import matplotlib.pyplot as plt
if __name__ == '__main__':
# Number of elements
nel = 200
# Local approximation order
p = 2
# Strength of nonlinearity
a = 10
# Construct mesh on [0,1]
mesh = df.IntervalMesh(nel,0,1)
# Define function space
V = df.FunctionSpace(mesh,"Lagrange",1)
u = df.Function(V)
v = df.TestFunction(V)
du = df.TrialFunction(V)
# Identify boundaries
tol = 1E-14
def left_boundary(x, on_boundary):
return on_boundary and abs(x[0]) < tol
def right_boundary(x, on_boundary):
return on_boundary and abs(x[0]-1) < tol
# Define nonlinear term with continuation parameter
def q(u,a,g):
g1 = df.Constant(g)
g2 = df.Constant(1-g)
return g1*ufl.operators.exp(df.Constant(a)*u)+g2
# Define boundary conditions for the solution
Gamma_0 = df.DirichletBC(V, df.Constant(0.0), left_boundary)
Gamma_1 = df.DirichletBC(V, df.Constant(1.0), right_boundary)
bc = [Gamma_0, Gamma_1]
# Make homogeneous equivalent of boundary conditions for update
bch = df.homogenize(bc)
# Define function for storing the Newton updates
u_inc = df.Function(V)
# Initial guess of a function that satisfies the boundary conditions
ui = df.Expression('x[0]')
# Evaluate u using the initial data
u.interpolate(ui)
# Extract the mesh nodes
xg = mesh.coordinates()
# Set number of continuuation steps
Nc = 20
steps = [(float(k)/(Nc-1))**3 for k in range(Nc)]
for s in steps:
# Construct form and its Jacobian
F = u.dx(0)*v.dx(0)*q(u,a,s)*df.dx
dF = df.derivative(F,u,du)
# Assemble the system for the Newton update with boundary conditions
A,b = df.assemble_system(dF,-F,bch)
# Solve for update
df.solve(A,u_inc.vector(),b)
# update solution
u.vector()[:] += u_inc.vector()
# Extract values
ug = u.compute_vertex_values()
# Display iterate
plt.plot(xg,ug)
str_bvp = r'$\frac{d}{dx}\left[e^{10u}\frac{du}{dx}\right]=0$'
str_bc = r'$u(0)=0,\; u(1)=1$'
plt.title('Iterated Solution',fontsize=20)
plt.text(0.6,0.4,str_bvp,fontsize=26)
plt.text(0.6,0.2,str_bc,fontsize=18)
plt.xlabel('x',fontsize=18)
plt.ylabel('u(x)',fontsize=18)
plt.show() | newton.py | import numpy as np
import dolfin as df
import ufl
import matplotlib.pyplot as plt
if __name__ == '__main__':
# Number of elements
nel = 200
# Local approximation order
p = 2
# Strength of nonlinearity
a = 10
# Construct mesh on [0,1]
mesh = df.IntervalMesh(nel,0,1)
# Define function space
V = df.FunctionSpace(mesh,"Lagrange",1)
u = df.Function(V)
v = df.TestFunction(V)
du = df.TrialFunction(V)
# Identify boundaries
tol = 1E-14
def left_boundary(x, on_boundary):
return on_boundary and abs(x[0]) < tol
def right_boundary(x, on_boundary):
return on_boundary and abs(x[0]-1) < tol
# Define nonlinear term with continuation parameter
def q(u,a,g):
g1 = df.Constant(g)
g2 = df.Constant(1-g)
return g1*ufl.operators.exp(df.Constant(a)*u)+g2
# Define boundary conditions for the solution
Gamma_0 = df.DirichletBC(V, df.Constant(0.0), left_boundary)
Gamma_1 = df.DirichletBC(V, df.Constant(1.0), right_boundary)
bc = [Gamma_0, Gamma_1]
# Make homogeneous equivalent of boundary conditions for update
bch = df.homogenize(bc)
# Define function for storing the Newton updates
u_inc = df.Function(V)
# Initial guess of a function that satisfies the boundary conditions
ui = df.Expression('x[0]')
# Evaluate u using the initial data
u.interpolate(ui)
# Extract the mesh nodes
xg = mesh.coordinates()
# Set number of continuuation steps
Nc = 20
steps = [(float(k)/(Nc-1))**3 for k in range(Nc)]
for s in steps:
# Construct form and its Jacobian
F = u.dx(0)*v.dx(0)*q(u,a,s)*df.dx
dF = df.derivative(F,u,du)
# Assemble the system for the Newton update with boundary conditions
A,b = df.assemble_system(dF,-F,bch)
# Solve for update
df.solve(A,u_inc.vector(),b)
# update solution
u.vector()[:] += u_inc.vector()
# Extract values
ug = u.compute_vertex_values()
# Display iterate
plt.plot(xg,ug)
str_bvp = r'$\frac{d}{dx}\left[e^{10u}\frac{du}{dx}\right]=0$'
str_bc = r'$u(0)=0,\; u(1)=1$'
plt.title('Iterated Solution',fontsize=20)
plt.text(0.6,0.4,str_bvp,fontsize=26)
plt.text(0.6,0.2,str_bc,fontsize=18)
plt.xlabel('x',fontsize=18)
plt.ylabel('u(x)',fontsize=18)
plt.show() | 0.743541 | 0.614365 |
import pytest
from unittest import mock
from molly.constants import TOP_20_PORTS, ALL_PORTS, FIRST_1000_PORTS
def test_basic_molly(_molly):
assert _molly.max_workers == 4
assert _molly.hostname == 'scanme.nmap.org'
assert _molly.mode == 'common'
_molly.max_workers = 20
_molly.target = 'localhost'
_molly.mode = 'custom'
assert _molly.max_workers == 20
assert _molly.target == 'localhost'
assert _molly.mode == 'custom'
def test_add_ports_to_queue_ints(_molly):
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(FIRST_1000_PORTS)
assert _molly.queue.qsize() == 1023
def test_add_ports_to_queue_list(_molly):
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(TOP_20_PORTS)
assert _molly.queue.qsize() == 20
def test_add_ports_to_queue_tuple(_molly):
port_range = (23, 99)
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(port_range)
assert _molly.queue.qsize() == (port_range[1] - port_range[0])
def test_get_ports_to_scan_basic(_molly):
_molly.mode = 'basic'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(FIRST_1000_PORTS)
def test_get_ports_to_scan_common(_molly):
_molly.mode = 'common'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(TOP_20_PORTS)
def test_get_ports_to_scan_error(_molly):
_molly.mode = 'wjlwqoehwewe'
with pytest.raises(ValueError) as exc_info:
_molly.get_ports_to_scan()
err_msg = f"Unexpected value for --mode option: {_molly.mode}"
assert str(exc_info.value) == err_msg
def test_get_ports_to_scan_full(_molly):
_molly.mode = 'full'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(ALL_PORTS)
def test_get_ports_to_scan_custom(_molly):
_molly.mode = 'custom'
custom_port_range = (23, 34)
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
with mock.patch.object(
_molly, '_get_custom_port_range',
return_value=custom_port_range) as mock_port_range:
_molly.get_ports_to_scan()
mock_port_range.assert_called_once()
add_ports_mock.assert_called_once_with(custom_port_range)
def test_get_custom_port_range_one_port_error(_molly):
invalid_port_range = '23, '
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Port range should be TWO numbers, separated by a comma. You provided (23,)"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_get_custom_port_range_number_string_error(_molly):
invalid_port_range = '23, somestring'
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Illegal value for port range, you provided ('23', 'somestring')"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_get_custom_port_range_number_wrong_order_error(_molly):
invalid_port_range = '233, 98'
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Start port cannot be bigger than the last port. You provided (233, 98)"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_molly_connect(_molly):
port = 90
with mock.patch('molly.molly.socket') as sock:
_molly._connect(port)
sock.socket.assert_called_once_with(sock.AF_INET, sock.SOCK_STREAM)
def test_molly_parse_target_ip_v4(_molly):
ip = '172.16.58.3'
target = _molly._parse_target(ip)
assert target == ip
def test_molly_parse_target_ip_domain_name(_molly):
ip = '172.16.58.3'
domain = 'scanme.nmap.org'
target = _molly._parse_target(domain)
assert target == ip
with mock.patch('socket.gethostbyname', return_value=None) as sock:
_molly._parse_target(domain)
sock.assert_called_once_with(domain)
def test_molly_parse_target_ip_error_domain(_molly):
domain = 'pkepowe.eqpwewqe.l'
with pytest.raises(SystemExit) as exc_info:
_molly._parse_target(domain)
assert domain in str(exc_info.value) | molly/tests/test_molly.py | import pytest
from unittest import mock
from molly.constants import TOP_20_PORTS, ALL_PORTS, FIRST_1000_PORTS
def test_basic_molly(_molly):
assert _molly.max_workers == 4
assert _molly.hostname == 'scanme.nmap.org'
assert _molly.mode == 'common'
_molly.max_workers = 20
_molly.target = 'localhost'
_molly.mode = 'custom'
assert _molly.max_workers == 20
assert _molly.target == 'localhost'
assert _molly.mode == 'custom'
def test_add_ports_to_queue_ints(_molly):
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(FIRST_1000_PORTS)
assert _molly.queue.qsize() == 1023
def test_add_ports_to_queue_list(_molly):
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(TOP_20_PORTS)
assert _molly.queue.qsize() == 20
def test_add_ports_to_queue_tuple(_molly):
port_range = (23, 99)
assert _molly.queue.qsize() == 0
_molly._add_ports_to_queue(port_range)
assert _molly.queue.qsize() == (port_range[1] - port_range[0])
def test_get_ports_to_scan_basic(_molly):
_molly.mode = 'basic'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(FIRST_1000_PORTS)
def test_get_ports_to_scan_common(_molly):
_molly.mode = 'common'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(TOP_20_PORTS)
def test_get_ports_to_scan_error(_molly):
_molly.mode = 'wjlwqoehwewe'
with pytest.raises(ValueError) as exc_info:
_molly.get_ports_to_scan()
err_msg = f"Unexpected value for --mode option: {_molly.mode}"
assert str(exc_info.value) == err_msg
def test_get_ports_to_scan_full(_molly):
_molly.mode = 'full'
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
_molly.get_ports_to_scan()
add_ports_mock.assert_called_once_with(ALL_PORTS)
def test_get_ports_to_scan_custom(_molly):
_molly.mode = 'custom'
custom_port_range = (23, 34)
with mock.patch.object(_molly, '_add_ports_to_queue') as add_ports_mock:
with mock.patch.object(
_molly, '_get_custom_port_range',
return_value=custom_port_range) as mock_port_range:
_molly.get_ports_to_scan()
mock_port_range.assert_called_once()
add_ports_mock.assert_called_once_with(custom_port_range)
def test_get_custom_port_range_one_port_error(_molly):
invalid_port_range = '23, '
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Port range should be TWO numbers, separated by a comma. You provided (23,)"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_get_custom_port_range_number_string_error(_molly):
invalid_port_range = '23, somestring'
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Illegal value for port range, you provided ('23', 'somestring')"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_get_custom_port_range_number_wrong_order_error(_molly):
invalid_port_range = '233, 98'
with mock.patch('click.prompt', return_value=invalid_port_range) as clk:
with pytest.raises(SystemExit) as exc_info:
_molly._get_custom_port_range()
err_msg = "[Error]: Start port cannot be bigger than the last port. You provided (233, 98)"
assert err_msg == str(exc_info.value)
clk.assert_called_once()
def test_molly_connect(_molly):
port = 90
with mock.patch('molly.molly.socket') as sock:
_molly._connect(port)
sock.socket.assert_called_once_with(sock.AF_INET, sock.SOCK_STREAM)
def test_molly_parse_target_ip_v4(_molly):
ip = '172.16.58.3'
target = _molly._parse_target(ip)
assert target == ip
def test_molly_parse_target_ip_domain_name(_molly):
ip = '172.16.58.3'
domain = 'scanme.nmap.org'
target = _molly._parse_target(domain)
assert target == ip
with mock.patch('socket.gethostbyname', return_value=None) as sock:
_molly._parse_target(domain)
sock.assert_called_once_with(domain)
def test_molly_parse_target_ip_error_domain(_molly):
domain = 'pkepowe.eqpwewqe.l'
with pytest.raises(SystemExit) as exc_info:
_molly._parse_target(domain)
assert domain in str(exc_info.value) | 0.590425 | 0.482002 |
import os
import subprocess
program = lambda num_runs, threshold: f'''
#include <vector>
#include "llvm/Analysis/InlineCost.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/Cloning.h"
using namespace llvm;
namespace {{
const int INLINE_THRESHOLD = {threshold};
const int NUM_RUNS = {num_runs};
struct FunctionInliningPass : public FunctionPass {{
static char ID;
FunctionInliningPass() : FunctionPass(ID) {{}}
virtual bool runOnFunction(Function &F) {{
bool modified = false;
for (int i = 0; i < NUM_RUNS; ++i) {{
std::vector<Instruction *> worklist;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {{
worklist.push_back(&*I);
}}
for (Instruction *I : worklist) {{
CallInst *call = dyn_cast<CallInst>(I);
if (call != nullptr) {{
Function *fun = call->getCalledFunction();
if (fun != nullptr && isInlineViable(*fun) &&
fun->getInstructionCount() <= INLINE_THRESHOLD) {{
InlineFunctionInfo info;
InlineFunction(call, info);
modified = true;
}}
}}
}}
}}
return modified;
}}
}};
}} // namespace
char FunctionInliningPass::ID = 0;
// Register the pass so `opt -function-inlining` runs it.
static RegisterPass<FunctionInliningPass> X("function-inlining",
"a useful pass");
'''
if __name__ == '__main__':
for threshold in (10, 100, 1000):
for num_runs in (1, 2, 3):
prog = program(num_runs, threshold)
with open('function-inlining/FunctionInlining.cpp', 'w') as f:
f.write(prog)
result = subprocess.run(['./build.sh'])
assert result.returncode == 0, "benis"
result = subprocess.run(['python3', 'benchmark.py', f'out-{num_runs}-{threshold}.csv'])
assert result.returncode == 0, "big ol begnis" | run.py | import os
import subprocess
program = lambda num_runs, threshold: f'''
#include <vector>
#include "llvm/Analysis/InlineCost.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Transforms/Utils/Cloning.h"
using namespace llvm;
namespace {{
const int INLINE_THRESHOLD = {threshold};
const int NUM_RUNS = {num_runs};
struct FunctionInliningPass : public FunctionPass {{
static char ID;
FunctionInliningPass() : FunctionPass(ID) {{}}
virtual bool runOnFunction(Function &F) {{
bool modified = false;
for (int i = 0; i < NUM_RUNS; ++i) {{
std::vector<Instruction *> worklist;
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {{
worklist.push_back(&*I);
}}
for (Instruction *I : worklist) {{
CallInst *call = dyn_cast<CallInst>(I);
if (call != nullptr) {{
Function *fun = call->getCalledFunction();
if (fun != nullptr && isInlineViable(*fun) &&
fun->getInstructionCount() <= INLINE_THRESHOLD) {{
InlineFunctionInfo info;
InlineFunction(call, info);
modified = true;
}}
}}
}}
}}
return modified;
}}
}};
}} // namespace
char FunctionInliningPass::ID = 0;
// Register the pass so `opt -function-inlining` runs it.
static RegisterPass<FunctionInliningPass> X("function-inlining",
"a useful pass");
'''
if __name__ == '__main__':
for threshold in (10, 100, 1000):
for num_runs in (1, 2, 3):
prog = program(num_runs, threshold)
with open('function-inlining/FunctionInlining.cpp', 'w') as f:
f.write(prog)
result = subprocess.run(['./build.sh'])
assert result.returncode == 0, "benis"
result = subprocess.run(['python3', 'benchmark.py', f'out-{num_runs}-{threshold}.csv'])
assert result.returncode == 0, "big ol begnis" | 0.264833 | 0.052014 |
from tqdm import tqdm
import numpy as np
from typing import Any, Callable, List, Optional, Union
from alibi_detect.cd.base_online import BaseUniDriftOnline
from alibi_detect.utils.misc import quantile
from scipy.stats import hypergeom
import numba as nb
import warnings
class FETDriftOnline(BaseUniDriftOnline):
def __init__(
self,
x_ref: Union[np.ndarray, list],
ert: float,
window_sizes: List[int],
preprocess_fn: Optional[Callable] = None,
n_bootstraps: int = 10000,
t_max: Optional[int] = None,
alternative: str = 'greater',
lam: float = 0.99,
n_features: Optional[int] = None,
verbose: bool = True,
input_shape: Optional[tuple] = None,
data_type: Optional[str] = None
) -> None:
"""
Online Fisher exact test (FET) data drift detector using preconfigured thresholds, which tests for a
change in the mean of binary univariate data. This detector is an adaption of that proposed by
:cite:t:`Ross2012b`.
For multivariate data, the detector makes a correction similar to the Bonferroni correction used for
the offline detector. Given :math:`d` features, the detector configures thresholds by
targeting the :math:`1-\\beta` quantile of test statistics over the simulated streams, where
:math:`\\beta = 1 - (1-(1/ERT))^{(1/d)}`. For the univariate case, this simplifies to
:math:`\\beta = 1/ERT`. At prediction time, drift is flagged if the test statistic of any feature stream
exceed the thresholds.
Note
----
In the multivariate case, for the ERT to be accurately targeted the feature streams must be independent.
Parameters
----------
x_ref
Data used as reference distribution.
ert
The expected run-time (ERT) in the absence of drift. For the univariate detectors, the ERT is defined
as the expected run-time after the smallest window is full i.e. the run-time from t=min(windows_sizes).
window_sizes
window sizes for the sliding test-windows used to compute the test-statistic.
Smaller windows focus on responding quickly to severe drift, larger windows focus on
ability to detect slight drift.
preprocess_fn
Function to preprocess the data before computing the data drift metrics.
n_bootstraps
The number of bootstrap simulations used to configure the thresholds. The larger this is the
more accurately the desired ERT will be targeted. Should ideally be at least an order of magnitude
larger than the ERT.
t_max
Length of the streams to simulate when configuring thresholds. If `None`, this is set to
2 * max(`window_sizes`) - 1.
alternative
Defines the alternative hypothesis. Options are 'greater' or 'less', which correspond to
an increase or decrease in the mean of the Bernoulli stream.
lam
Smoothing coefficient used for exponential moving average.
n_features
Number of features used in the statistical test. No need to pass it if no preprocessing takes place.
In case of a preprocessing step, this can also be inferred automatically but could be more
expensive to compute.
verbose
Whether or not to print progress during configuration.
input_shape
Shape of input data.
data_type
Optionally specify the data type (tabular, image or time-series). Added to metadata.
"""
super().__init__(
x_ref=x_ref,
ert=ert,
window_sizes=window_sizes,
preprocess_fn=preprocess_fn,
n_bootstraps=n_bootstraps,
n_features=n_features,
verbose=verbose,
input_shape=input_shape,
data_type=data_type
)
self.lam = lam
if alternative.lower() not in ['greater', 'less']:
raise ValueError("`alternative` must be either 'greater' or 'less'.")
self.alternative = alternative.lower()
# Stream length
if t_max is not None:
if t_max < 2 * self.max_ws - 1:
raise ValueError("`t_max` must be >= 2 * max(`window_sizes`) for the FETDriftOnline detector.")
else:
t_max = 2 * self.max_ws - 1
self.t_max = t_max
# Check data is only [False, True] or [0, 1]
values = set(np.unique(self.x_ref))
if not set(values).issubset(['0', '1', True, False]):
raise ValueError("The `x_ref` data must consist of only (0,1)'s or (False,True)'s for the "
"FETDriftOnline detector.")
if len(np.unique(self.x_ref.astype('int'))) == 1:
raise ValueError("The `x_ref` data consists of all 0's or all 1's. Thresholds cannot be configured.")
# Configure thresholds and initialise detector
self._initialise()
self._configure_thresholds()
def _configure_ref(self) -> None:
self.sum_ref = np.sum(self.x_ref, axis=0)
def _configure_thresholds(self) -> None:
"""
A function that simulates trajectories of the (smoothed) Fisher exact test statistic for the desired
reference set and window sizes under the null distribution, where both the reference set and deployment
stream follow the same distribution. It then uses these simulated trajectories to estimate thresholds.
The test statistics are smoothed using an exponential moving average to remove their discreteness and
therefore allow more precise quantiles to be targeted.
In the unsmoothed case the thresholds should stop changing after t=(2*max-window-size - 1) and therefore
we need only simulate trajectories and estimate thresholds up to this point. If heavy smoothing is applied
(i.e. if `lam`<<1), a larger `t_max` may be necessary in order to ensure the thresholds have converged.
"""
if self.verbose:
print("Using %d bootstrap simulations to configure thresholds..." % self.n_bootstraps)
# Assuming independent features, calibrate to beta = 1 - (1-FPR)^(1/n_features)
beta = 1 - (1-self.fpr)**(1/self.n_features)
# Init progress bar
if self.verbose:
if self.n_features > 1:
msg = "Simulating streams for %d window(s) and %d features(s)" \
% (len(self.window_sizes), self.n_features)
else:
msg = "Simulating streams for %d window(s)" % len(self.window_sizes)
pbar = tqdm(total=int(self.n_features*len(self.window_sizes)), desc=msg)
else:
pbar = None
# Compute test statistic at each t_max number of t's, for each stream and each feature
self.permit_probs = np.full((self.t_max, self.n_features), np.nan)
thresholds = np.full((self.t_max, self.n_features), np.nan, dtype=np.float32)
for f in range(self.n_features):
# Compute stats for given feature (for each stream)
stats = self._simulate_streams(self.x_ref[:, f], pbar)
# At each t for each stream, find max stats. over window sizes
with warnings.catch_warnings():
warnings.filterwarnings(action='ignore', message='All-NaN slice encountered')
max_stats = np.nanmax(stats, -1)
# Find threshold (at each t) that satisfies eqn. (2) in Ross et al.
for t in range(np.min(self.window_sizes)-1, self.t_max):
# Compute (1-beta) quantile of max_stats at a given t, over all streams
threshold = np.float32(quantile(max_stats[:, t], 1 - beta, interpolate=False, type=6))
stats_below = max_stats[max_stats[:, t] < threshold]
# Check for stats equal to threshold
prob_of_equal = (max_stats[:, t] <= threshold).mean() - (max_stats[:, t] < threshold).mean()
if prob_of_equal == 0.0:
permit_prob = np.inf
max_stats = stats_below # Remove streams where change point detected
else:
undershoot = 1 - beta - (max_stats[:, t] < threshold).mean()
permit_prob = undershoot / prob_of_equal
stats_equal = max_stats[max_stats[:, t] == threshold]
n_keep_equal = np.random.binomial(len(stats_equal), permit_prob)
# Remove streams where change point detected, but allow permit_prob streams where stats=thresh
max_stats = np.concatenate([stats_below, stats_equal[:n_keep_equal]])
thresholds[t, f] = threshold
self.permit_probs[t, f] = permit_prob
self.thresholds = thresholds
def _simulate_streams(self, x_ref: np.ndarray, pbar: Optional[tqdm]) -> np.ndarray:
"""
Computes test statistic for each stream.
Almost all of the work done here is done in a call to scipy's hypergeom for each window size.
"""
n_windows = len(self.window_sizes)
stats = np.full((self.n_bootstraps, self.t_max, n_windows), np.nan, dtype=np.float32)
p = np.mean(x_ref)
sum_ref = np.sum(x_ref)
x_stream = np.random.choice([False, True], (self.n_bootstraps, self.t_max), p=[1 - p, p])
cumsums_stream = np.cumsum(x_stream, axis=-1)
cumsums_stream = np.concatenate([np.zeros_like(cumsums_stream[..., 0:1]), cumsums_stream], axis=-1)
for k in range(n_windows):
if pbar is not None:
pbar.update(1)
ws = self.window_sizes[k]
cumsums_last_ws = cumsums_stream[:, ws:] - cumsums_stream[:, :-ws]
# Perform FET with hypergeom.cdf (this is vectorised over streams)
if self.alternative == 'greater':
p_val = hypergeom.cdf(sum_ref, self.n+ws, sum_ref + cumsums_last_ws, self.n)
else:
p_val = hypergeom.cdf(cumsums_last_ws, self.n+ws, sum_ref + cumsums_last_ws, ws)
stats[:, (ws - 1):, k] = self._exp_moving_avg(1 - p_val, self.lam)
return stats
@staticmethod
@nb.njit(cache=True)
def _exp_moving_avg(arr: np.ndarray, lam: float) -> np.ndarray:
""" Apply exponential moving average over the final axis."""
output = np.zeros_like(arr)
output[..., 0] = arr[..., 0]
for i in range(1, arr.shape[-1]):
output[..., i] = (1 - lam) * output[..., i - 1] + lam * arr[..., i]
return output
def _update_state(self, x_t: np.ndarray):
self.t += 1
if self.t == 1:
# Initialise stream
self.xs = x_t
else:
# Update stream
self.xs = np.concatenate([self.xs, x_t])
def _check_drift(self, test_stats: np.ndarray, thresholds: np.ndarray) -> int:
"""
Private method to compare test stats to thresholds. The max stats over all windows are compute for each
feature. Drift is flagged if `max_stats` for any feature exceeds the thresholds for that feature.
Parameters
----------
test_stats
Array of test statistics with shape (n_windows, n_features)
thresholds
Array of thresholds with shape (t_max, n_features).
Returns
-------
An int equal to 1 if drift, 0 otherwise.
"""
with warnings.catch_warnings():
warnings.filterwarnings(action='ignore', message='All-NaN slice encountered')
max_stats = np.nanmax(test_stats, axis=0)
# If any stats greater than thresholds, flag drift and return
if (max_stats > thresholds).any():
return 1
# If still no drift, check if any stats equal to threshold. If so, flag drift with proba self.probs_when_equal
equal_inds = np.where(max_stats == thresholds)[0]
for equal_ind in equal_inds:
if np.random.uniform() > self.permit_probs[min(self.t-1, len(self.thresholds)-1), equal_ind]:
return 1
return 0
def score(self, x_t: Union[np.ndarray, Any]) -> np.ndarray:
"""
Compute the test-statistic (FET) between the reference window(s) and test window.
If a given test-window is not yet full then a test-statistic of np.nan is returned for that window.
Parameters
----------
x_t
A single instance.
Returns
-------
Estimated FET test statistics (1-p_val) between reference window and test windows.
"""
values = set(np.unique(x_t))
if not set(values).issubset(['0', '1', True, False]):
raise ValueError("The `x_t` data must consist of only (0,1)'s or (False,True)'s for the "
"FETDriftOnline detector.")
x_t = super()._preprocess_xt(x_t)
self._update_state(x_t)
stats = np.zeros((len(self.window_sizes), self.n_features), dtype=np.float32)
for k, ws in enumerate(self.window_sizes):
if self.t >= ws:
sum_last_ws = np.sum(self.xs[-ws:, :], axis=0)
# Perform FET with hypergeom.cdf (this is vectorised over features)
if self.alternative == 'greater':
p_vals = hypergeom.cdf(self.sum_ref, self.n+ws, self.sum_ref + sum_last_ws, self.n)
else:
p_vals = hypergeom.cdf(sum_last_ws, self.n+ws, self.sum_ref + sum_last_ws, ws)
# Compute test stat and apply smoothing
stats_k = 1 - p_vals
for f in range(self.n_features):
if len(self.test_stats) != 0 and not np.isnan(self.test_stats[-1, k, f]):
stats_k[f] = (1 - self.lam) * self.test_stats[-1, k, f] + self.lam * stats_k[f]
stats[k, :] = stats_k
else:
stats[k, :] = np.nan
return stats | alibi_detect/cd/fet_online.py | from tqdm import tqdm
import numpy as np
from typing import Any, Callable, List, Optional, Union
from alibi_detect.cd.base_online import BaseUniDriftOnline
from alibi_detect.utils.misc import quantile
from scipy.stats import hypergeom
import numba as nb
import warnings
class FETDriftOnline(BaseUniDriftOnline):
def __init__(
self,
x_ref: Union[np.ndarray, list],
ert: float,
window_sizes: List[int],
preprocess_fn: Optional[Callable] = None,
n_bootstraps: int = 10000,
t_max: Optional[int] = None,
alternative: str = 'greater',
lam: float = 0.99,
n_features: Optional[int] = None,
verbose: bool = True,
input_shape: Optional[tuple] = None,
data_type: Optional[str] = None
) -> None:
"""
Online Fisher exact test (FET) data drift detector using preconfigured thresholds, which tests for a
change in the mean of binary univariate data. This detector is an adaption of that proposed by
:cite:t:`Ross2012b`.
For multivariate data, the detector makes a correction similar to the Bonferroni correction used for
the offline detector. Given :math:`d` features, the detector configures thresholds by
targeting the :math:`1-\\beta` quantile of test statistics over the simulated streams, where
:math:`\\beta = 1 - (1-(1/ERT))^{(1/d)}`. For the univariate case, this simplifies to
:math:`\\beta = 1/ERT`. At prediction time, drift is flagged if the test statistic of any feature stream
exceed the thresholds.
Note
----
In the multivariate case, for the ERT to be accurately targeted the feature streams must be independent.
Parameters
----------
x_ref
Data used as reference distribution.
ert
The expected run-time (ERT) in the absence of drift. For the univariate detectors, the ERT is defined
as the expected run-time after the smallest window is full i.e. the run-time from t=min(windows_sizes).
window_sizes
window sizes for the sliding test-windows used to compute the test-statistic.
Smaller windows focus on responding quickly to severe drift, larger windows focus on
ability to detect slight drift.
preprocess_fn
Function to preprocess the data before computing the data drift metrics.
n_bootstraps
The number of bootstrap simulations used to configure the thresholds. The larger this is the
more accurately the desired ERT will be targeted. Should ideally be at least an order of magnitude
larger than the ERT.
t_max
Length of the streams to simulate when configuring thresholds. If `None`, this is set to
2 * max(`window_sizes`) - 1.
alternative
Defines the alternative hypothesis. Options are 'greater' or 'less', which correspond to
an increase or decrease in the mean of the Bernoulli stream.
lam
Smoothing coefficient used for exponential moving average.
n_features
Number of features used in the statistical test. No need to pass it if no preprocessing takes place.
In case of a preprocessing step, this can also be inferred automatically but could be more
expensive to compute.
verbose
Whether or not to print progress during configuration.
input_shape
Shape of input data.
data_type
Optionally specify the data type (tabular, image or time-series). Added to metadata.
"""
super().__init__(
x_ref=x_ref,
ert=ert,
window_sizes=window_sizes,
preprocess_fn=preprocess_fn,
n_bootstraps=n_bootstraps,
n_features=n_features,
verbose=verbose,
input_shape=input_shape,
data_type=data_type
)
self.lam = lam
if alternative.lower() not in ['greater', 'less']:
raise ValueError("`alternative` must be either 'greater' or 'less'.")
self.alternative = alternative.lower()
# Stream length
if t_max is not None:
if t_max < 2 * self.max_ws - 1:
raise ValueError("`t_max` must be >= 2 * max(`window_sizes`) for the FETDriftOnline detector.")
else:
t_max = 2 * self.max_ws - 1
self.t_max = t_max
# Check data is only [False, True] or [0, 1]
values = set(np.unique(self.x_ref))
if not set(values).issubset(['0', '1', True, False]):
raise ValueError("The `x_ref` data must consist of only (0,1)'s or (False,True)'s for the "
"FETDriftOnline detector.")
if len(np.unique(self.x_ref.astype('int'))) == 1:
raise ValueError("The `x_ref` data consists of all 0's or all 1's. Thresholds cannot be configured.")
# Configure thresholds and initialise detector
self._initialise()
self._configure_thresholds()
def _configure_ref(self) -> None:
self.sum_ref = np.sum(self.x_ref, axis=0)
def _configure_thresholds(self) -> None:
"""
A function that simulates trajectories of the (smoothed) Fisher exact test statistic for the desired
reference set and window sizes under the null distribution, where both the reference set and deployment
stream follow the same distribution. It then uses these simulated trajectories to estimate thresholds.
The test statistics are smoothed using an exponential moving average to remove their discreteness and
therefore allow more precise quantiles to be targeted.
In the unsmoothed case the thresholds should stop changing after t=(2*max-window-size - 1) and therefore
we need only simulate trajectories and estimate thresholds up to this point. If heavy smoothing is applied
(i.e. if `lam`<<1), a larger `t_max` may be necessary in order to ensure the thresholds have converged.
"""
if self.verbose:
print("Using %d bootstrap simulations to configure thresholds..." % self.n_bootstraps)
# Assuming independent features, calibrate to beta = 1 - (1-FPR)^(1/n_features)
beta = 1 - (1-self.fpr)**(1/self.n_features)
# Init progress bar
if self.verbose:
if self.n_features > 1:
msg = "Simulating streams for %d window(s) and %d features(s)" \
% (len(self.window_sizes), self.n_features)
else:
msg = "Simulating streams for %d window(s)" % len(self.window_sizes)
pbar = tqdm(total=int(self.n_features*len(self.window_sizes)), desc=msg)
else:
pbar = None
# Compute test statistic at each t_max number of t's, for each stream and each feature
self.permit_probs = np.full((self.t_max, self.n_features), np.nan)
thresholds = np.full((self.t_max, self.n_features), np.nan, dtype=np.float32)
for f in range(self.n_features):
# Compute stats for given feature (for each stream)
stats = self._simulate_streams(self.x_ref[:, f], pbar)
# At each t for each stream, find max stats. over window sizes
with warnings.catch_warnings():
warnings.filterwarnings(action='ignore', message='All-NaN slice encountered')
max_stats = np.nanmax(stats, -1)
# Find threshold (at each t) that satisfies eqn. (2) in Ross et al.
for t in range(np.min(self.window_sizes)-1, self.t_max):
# Compute (1-beta) quantile of max_stats at a given t, over all streams
threshold = np.float32(quantile(max_stats[:, t], 1 - beta, interpolate=False, type=6))
stats_below = max_stats[max_stats[:, t] < threshold]
# Check for stats equal to threshold
prob_of_equal = (max_stats[:, t] <= threshold).mean() - (max_stats[:, t] < threshold).mean()
if prob_of_equal == 0.0:
permit_prob = np.inf
max_stats = stats_below # Remove streams where change point detected
else:
undershoot = 1 - beta - (max_stats[:, t] < threshold).mean()
permit_prob = undershoot / prob_of_equal
stats_equal = max_stats[max_stats[:, t] == threshold]
n_keep_equal = np.random.binomial(len(stats_equal), permit_prob)
# Remove streams where change point detected, but allow permit_prob streams where stats=thresh
max_stats = np.concatenate([stats_below, stats_equal[:n_keep_equal]])
thresholds[t, f] = threshold
self.permit_probs[t, f] = permit_prob
self.thresholds = thresholds
def _simulate_streams(self, x_ref: np.ndarray, pbar: Optional[tqdm]) -> np.ndarray:
"""
Computes test statistic for each stream.
Almost all of the work done here is done in a call to scipy's hypergeom for each window size.
"""
n_windows = len(self.window_sizes)
stats = np.full((self.n_bootstraps, self.t_max, n_windows), np.nan, dtype=np.float32)
p = np.mean(x_ref)
sum_ref = np.sum(x_ref)
x_stream = np.random.choice([False, True], (self.n_bootstraps, self.t_max), p=[1 - p, p])
cumsums_stream = np.cumsum(x_stream, axis=-1)
cumsums_stream = np.concatenate([np.zeros_like(cumsums_stream[..., 0:1]), cumsums_stream], axis=-1)
for k in range(n_windows):
if pbar is not None:
pbar.update(1)
ws = self.window_sizes[k]
cumsums_last_ws = cumsums_stream[:, ws:] - cumsums_stream[:, :-ws]
# Perform FET with hypergeom.cdf (this is vectorised over streams)
if self.alternative == 'greater':
p_val = hypergeom.cdf(sum_ref, self.n+ws, sum_ref + cumsums_last_ws, self.n)
else:
p_val = hypergeom.cdf(cumsums_last_ws, self.n+ws, sum_ref + cumsums_last_ws, ws)
stats[:, (ws - 1):, k] = self._exp_moving_avg(1 - p_val, self.lam)
return stats
@staticmethod
@nb.njit(cache=True)
def _exp_moving_avg(arr: np.ndarray, lam: float) -> np.ndarray:
""" Apply exponential moving average over the final axis."""
output = np.zeros_like(arr)
output[..., 0] = arr[..., 0]
for i in range(1, arr.shape[-1]):
output[..., i] = (1 - lam) * output[..., i - 1] + lam * arr[..., i]
return output
def _update_state(self, x_t: np.ndarray):
self.t += 1
if self.t == 1:
# Initialise stream
self.xs = x_t
else:
# Update stream
self.xs = np.concatenate([self.xs, x_t])
def _check_drift(self, test_stats: np.ndarray, thresholds: np.ndarray) -> int:
"""
Private method to compare test stats to thresholds. The max stats over all windows are compute for each
feature. Drift is flagged if `max_stats` for any feature exceeds the thresholds for that feature.
Parameters
----------
test_stats
Array of test statistics with shape (n_windows, n_features)
thresholds
Array of thresholds with shape (t_max, n_features).
Returns
-------
An int equal to 1 if drift, 0 otherwise.
"""
with warnings.catch_warnings():
warnings.filterwarnings(action='ignore', message='All-NaN slice encountered')
max_stats = np.nanmax(test_stats, axis=0)
# If any stats greater than thresholds, flag drift and return
if (max_stats > thresholds).any():
return 1
# If still no drift, check if any stats equal to threshold. If so, flag drift with proba self.probs_when_equal
equal_inds = np.where(max_stats == thresholds)[0]
for equal_ind in equal_inds:
if np.random.uniform() > self.permit_probs[min(self.t-1, len(self.thresholds)-1), equal_ind]:
return 1
return 0
def score(self, x_t: Union[np.ndarray, Any]) -> np.ndarray:
"""
Compute the test-statistic (FET) between the reference window(s) and test window.
If a given test-window is not yet full then a test-statistic of np.nan is returned for that window.
Parameters
----------
x_t
A single instance.
Returns
-------
Estimated FET test statistics (1-p_val) between reference window and test windows.
"""
values = set(np.unique(x_t))
if not set(values).issubset(['0', '1', True, False]):
raise ValueError("The `x_t` data must consist of only (0,1)'s or (False,True)'s for the "
"FETDriftOnline detector.")
x_t = super()._preprocess_xt(x_t)
self._update_state(x_t)
stats = np.zeros((len(self.window_sizes), self.n_features), dtype=np.float32)
for k, ws in enumerate(self.window_sizes):
if self.t >= ws:
sum_last_ws = np.sum(self.xs[-ws:, :], axis=0)
# Perform FET with hypergeom.cdf (this is vectorised over features)
if self.alternative == 'greater':
p_vals = hypergeom.cdf(self.sum_ref, self.n+ws, self.sum_ref + sum_last_ws, self.n)
else:
p_vals = hypergeom.cdf(sum_last_ws, self.n+ws, self.sum_ref + sum_last_ws, ws)
# Compute test stat and apply smoothing
stats_k = 1 - p_vals
for f in range(self.n_features):
if len(self.test_stats) != 0 and not np.isnan(self.test_stats[-1, k, f]):
stats_k[f] = (1 - self.lam) * self.test_stats[-1, k, f] + self.lam * stats_k[f]
stats[k, :] = stats_k
else:
stats[k, :] = np.nan
return stats | 0.952849 | 0.554531 |
from base64 import b64encode, b64decode
from bs4 import BeautifulSoup as soup
from bz2 import BZ2File
from collections import Counter, OrderedDict
from copy import deepcopy
from datetime import datetime as dt, timedelta
try:
from etk.extractors.date_extractor import DateExtractor
except OSError:
from spacy.cli import download
download('en_core_web_sm')
from etk.extractors.date_extractor import DateExtractor
from etk.extractors.spacy_ner_extractor import SpacyNerExtractor
from hashlib import sha256
from json import load, dump, loads, dumps
from math import sqrt, ceil, floor
from nltk import word_tokenize, pos_tag, ne_chunk, download as nltk_download
from nltk.corpus import stopwords
from numpy import array
from os import makedirs, listdir, rename, remove, chmod
from os.path import dirname, abspath, exists, join
from pandas import DataFrame
from pickle import load as pload, dump as pdump
from pprint import pprint
from random import choices, shuffle, seed
from regex import findall, sub, search, compile, match, DOTALL, MULTILINE, VERBOSE
from requests import get, post, head
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import WebDriverException
from shutil import rmtree
from sklearn.cluster import KMeans
from sys import stdout, exc_info
from tarfile import open as tar_open
from threading import Thread
from time import strftime, sleep, time
from traceback import print_exc, format_exc
from urllib.parse import urljoin, quote
from hashlib import md5
from xml.etree.cElementTree import iterparse
from wikipediaapi import Wikipedia
# --- constants ---------------------------------------------------------------
PATH_RESOURCES = join(dirname(__file__), 'resources')
PATH_LOG = join(PATH_RESOURCES, 'log_%s.txt')
PATH_ALL_TABLES = join(PATH_RESOURCES, 'all_tables.jsonl')
PATTERN_LOG = '[%s] %s\n'
SCRIPT_ADD_RENDER = """
function pathTo(element) {
if (element === document) return ""
var ix = 0
var siblings = element.parentNode.childNodes
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] === element) return pathTo(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']'
if (siblings[i].nodeType === 1 && siblings[i].tagName === element.tagName) ix++
}
}
var removeElements = []
function addRender(subtree) {
var style = getComputedStyle(subtree)
if (subtree.tagName == "TR" && subtree.children.length == 0 || subtree.offsetWidth == undefined || style["display"] == "none" || subtree.tagName == "SUP" && subtree.className == "reference") {
removeElements.push(subtree)
return
}
var serialStyle = ""
for (let prop of style) {
if (prop[0] != "-") {
serialStyle += prop + ":" + style[prop].replace(/:/g, "") + "|"
}
}
serialStyle += "width:" + subtree.offsetWidth / document.body.offsetWidth + "|height:" + subtree.offsetHeight / document.body.offsetHeight
if (subtree.tagName == "TD" || subtree.tagName == "TH") {
serialStyle += "|colspan:" + subtree.colSpan + "|rowspan:" + subtree.rowSpan
}
subtree.setAttribute("data-computed-style", serialStyle)
subtree.setAttribute("data-xpath", pathTo(subtree).toLowerCase())
for (let child of subtree.children) addRender(child)
}
function preprocess() {
var elements = document.querySelectorAll(injected_script_selector)
for (let subtree of elements) addRender(subtree)
for (let elem of removeElements) elem.remove()
}
const injected_script_selector = arguments[0]
if (document.readyState == 'complete') {
preprocess()
} else {
window.onload = function(){preprocess()}
}
"""
# --- import directives -------------------------------------------------------
makedirs(PATH_RESOURCES, exist_ok=True)
try:
stopwords.words("english")
except:
nltk_download('stopwords')
# --- format ------------------------------------------------------------------
def date_stamp():
''' Return the current timestamp. '''
return strftime('%Y-%m-%d, %H:%M:%S')
def bytes_to_human(size, decimal_places=2):
''' Returns a human readable file size from a number of bytes. '''
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
if size < 1024: break
size /= 1024
return f'{size:.{decimal_places}f}{unit}B'
def seconds_to_human(seconds):
''' Returns a human readable string from a number of seconds. '''
return str(timedelta(seconds=int(seconds))).zfill(8)
def hashed(text):
''' Returns the md5 hash of a text. Not recommended for security concerns. '''
return md5(text.encode()).hexdigest()
def fname_escape(text):
return sub(r'([^\w\s\.])', lambda x: f'_{ord(x.group())}_', text.replace('_', '_95_'))
def fname_unescape(text):
return sub(r'(_\d+_)', lambda x: chr(int(x.group()[1:-1])), text)
# --- log ---------------------------------------------------------------------
def log(log_name, text):
''' Logs the given text to the log specified, and prints it. '''
text = PATTERN_LOG % (date_stamp(), text)
print('[%s] %s' % (log_name, text), end='')
with open(PATH_LOG % log_name, 'a', encoding='utf-8') as fp:
fp.write(text)
def log_error():
''' Used inside an except sentence, logs the error to the error log. '''
log('error', format_exc())
def cache(target, args, identifier=None, cache_life=3 * 24 * 3600):
''' Run the target function with the given args, and store it to a pickled
cache folder using the given identifier or the name of the function. The
next time it is executed, the cached output is returned unless cache_life
time expires. '''
if identifier == None: identifier = target.__name__
identifier = sub(r'[/\\\*;\[\]\'\":=,<>]', '_', identifier)
path = join(PATH_RESOURCES, f'.pickled/{identifier}.pk')
makedirs(dirname(path), exist_ok=True)
now = time()
if exists(path):
with open(path, 'rb') as fp:
save_time, value = pload(fp)
if now - save_time <= cache_life:
return value
res = target(*args)
with open(path, 'wb') as fp:
pdump((now, res), fp, protocol=3)
return res
# --- network -----------------------------------------------------------------
def download_file(url, path=None, chunk_size=10**5):
''' Downloads a file keeping track of the progress. '''
if path == None: path = url.split('/')[-1]
r = get(url, stream=True)
total_bytes = int(r.headers.get('content-length'))
bytes_downloaded = 0
start = time()
print('Downloading %s (%s)' % (url, bytes_to_human(total_bytes)))
with open(path, 'wb') as fp:
for chunk in r.iter_content(chunk_size=chunk_size):
if not chunk: continue
fp.write(chunk)
bytes_downloaded += len(chunk)
percent = bytes_downloaded / total_bytes
bar = ('█' * int(percent * 32)).ljust(32)
time_delta = time() - start
eta = seconds_to_human((total_bytes - bytes_downloaded) * time_delta / bytes_downloaded)
avg_speed = bytes_to_human(bytes_downloaded / time_delta).rjust(9)
stdout.flush()
stdout.write('\r %6.02f%% |%s| %s/s eta %s' % (100 * percent, bar, avg_speed, eta))
print()
_driver = None
def get_driver(headless=True, disable_images=True, open_links_same_tab=False):
''' Returns a Firefox webdriver, and run one if there is no any active. '''
global _driver
if _driver == None:
opts = Options()
opts.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
if open_links_same_tab:
opts.set_preference('browser.link.open_newwindow.restriction', 0)
opts.set_preference('browser.link.open_newwindow', 1)
if headless: opts.set_headless()
if disable_images: opts.set_preference('permissions.default.image', 2)
_driver = Firefox(options=opts)
_driver.set_page_load_timeout(15)
return _driver
def close_driver():
''' Close the current Firefox webdriver, if any. '''
global _driver
if _driver != None:
print('Closing Firefox driver')
_driver.close()
def get_with_render(url, render_selector='table', headless=True, disable_images=True, open_links_same_tab=False):
''' Downloads a page and renders it to return the page source, the width,
and the height in pixels. Elements on the subtree selected using
render_selector contain a data-computed-style attribute and a data-xpath. '''
driver = get_driver(headless, disable_images, open_links_same_tab)
driver.get(url)
driver.execute_script(SCRIPT_ADD_RENDER, render_selector)
sleep(.5)
return driver.page_source
# --- vector ------------------------------------------------------------------
def vectors_average(vectors):
''' Given a list of mixed feature vectors, returns the average of all them.
For numerical features, aritmetic average is used. For categorical ones,
the most common is used. '''
vectors = [v for v in vectors if len(v)]
res = {}
if len(vectors):
for feat in vectors[0]:
if type(vectors[0][feat]) == str:
val = Counter(v[feat] for v in vectors).most_common(1)[0][0]
else:
val = sum(v[feat] for v in vectors) / len(vectors)
res[feat] = val
return res
def vectors_weighted_average(vectors):
''' Given a list of tuples of type <weight, mixed feature vector>, returns
the weighted average of all them. For numerical features, aritmetic average
is used. For categorical ones, weighted frequencies are used to return the
most common. '''
if len(vectors) == 1: return vectors[0][1]
res = {}
total_weight = sum(v[0] for v in vectors)
if total_weight == 0:
total_weight = len(vectors)
for n in range(total_weight):
vectors[n][0] = 1
vectors = [(w / total_weight, fs) for w, fs in vectors]
for f in vectors[0][1]:
if type(vectors[0][1][f]) == str:
sum_feat = {}
for weight, features in vectors:
if features[f] in sum_feat:
sum_feat[features[f]] += weight
else:
sum_feat[features[f]] = weight
res[f] = max(sum_feat.items(), key=lambda v: v[1])[0]
else:
val = 0
for weight, features in vectors:
val += weight * features[f]
res[f] = val
return res
def vectors_difference(v1, v2, prefix=''):
''' Given two mixed feature vectors, return another vector with the
differences amongst them. For numerical features, absolute value difference
is computed. For categorical features, Gower distance is used. '''
res = {}
for feat in v1:
if type(v1[feat]) == str:
res[prefix + feat] = 0 if v1[feat] == v2[feat] else 1
else:
res[prefix + feat] = abs(v1[feat] - v2[feat])
return res
def vector_module(vector):
''' Given a mixed feature vector, return the norm of their numerical
attributes. '''
nums = [v**2 for v in vector.values() if type(v) != str]
return sqrt(sum(nums))
def binarize_categorical(vectors):
''' Given a 2-D list of mixed feature vectors, transform every categorical
feature into a binary one, using the seen values of all the vectors. '''
vectors = deepcopy(vectors)
cat_vector = next([k for k, v in cell.items() if type(v) == str] for row in vectors for cell in row if len(cell))
for f in cat_vector:
values = list(set(cell[f] for row in vectors for cell in row if len(cell)))
for r, row in enumerate(vectors):
for c, cell in enumerate(row):
if len(cell) == 0: continue
for v in values:
vectors[r][c][f'{f}-{v}'] = 1 if v == cell[f] else 0
del vectors[r][c][f]
return vectors
# --- parsing -----------------------------------------------------------------
_find_dates_extractor = DateExtractor()
def find_dates(text):
try:
res = _find_dates_extractor.extract(text, prefer_language_date_order=False)
if len(res): return res[0].value
except:
log('info', f'ETK DateExtractor raised an error on value {text}. Using RegEx fallback instead.')
_find_entities_extractor = SpacyNerExtractor('dummy_parameter')
def find_entities(text):
try:
return {ext.value: ext.tag for ext in _find_entities_extractor.extract(text)}
except:
log('info', f'ETK SpacyNerExtractor raised an error on value {text}.')
return {}
# --- math --------------------------------------------------------------------
def distinct(lst, uniqueness_function):
''' Returns a list in the same order with just the elements with a distinct
value on the uniqueness_function.
I.e.: `distinct([1, 5, 7, 9], lambda x: x % 3)` would return [1, 5, 9].'''
values = []
keys = []
for v in lst:
k = uniqueness_function(v)
if k not in keys:
keys.append(k)
values.append(v)
return values | datamart/materializers/wikitables_downloader/utils.py | from base64 import b64encode, b64decode
from bs4 import BeautifulSoup as soup
from bz2 import BZ2File
from collections import Counter, OrderedDict
from copy import deepcopy
from datetime import datetime as dt, timedelta
try:
from etk.extractors.date_extractor import DateExtractor
except OSError:
from spacy.cli import download
download('en_core_web_sm')
from etk.extractors.date_extractor import DateExtractor
from etk.extractors.spacy_ner_extractor import SpacyNerExtractor
from hashlib import sha256
from json import load, dump, loads, dumps
from math import sqrt, ceil, floor
from nltk import word_tokenize, pos_tag, ne_chunk, download as nltk_download
from nltk.corpus import stopwords
from numpy import array
from os import makedirs, listdir, rename, remove, chmod
from os.path import dirname, abspath, exists, join
from pandas import DataFrame
from pickle import load as pload, dump as pdump
from pprint import pprint
from random import choices, shuffle, seed
from regex import findall, sub, search, compile, match, DOTALL, MULTILINE, VERBOSE
from requests import get, post, head
from selenium.common.exceptions import TimeoutException
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import WebDriverException
from shutil import rmtree
from sklearn.cluster import KMeans
from sys import stdout, exc_info
from tarfile import open as tar_open
from threading import Thread
from time import strftime, sleep, time
from traceback import print_exc, format_exc
from urllib.parse import urljoin, quote
from hashlib import md5
from xml.etree.cElementTree import iterparse
from wikipediaapi import Wikipedia
# --- constants ---------------------------------------------------------------
PATH_RESOURCES = join(dirname(__file__), 'resources')
PATH_LOG = join(PATH_RESOURCES, 'log_%s.txt')
PATH_ALL_TABLES = join(PATH_RESOURCES, 'all_tables.jsonl')
PATTERN_LOG = '[%s] %s\n'
SCRIPT_ADD_RENDER = """
function pathTo(element) {
if (element === document) return ""
var ix = 0
var siblings = element.parentNode.childNodes
for (var i = 0; i < siblings.length; i++) {
if (siblings[i] === element) return pathTo(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']'
if (siblings[i].nodeType === 1 && siblings[i].tagName === element.tagName) ix++
}
}
var removeElements = []
function addRender(subtree) {
var style = getComputedStyle(subtree)
if (subtree.tagName == "TR" && subtree.children.length == 0 || subtree.offsetWidth == undefined || style["display"] == "none" || subtree.tagName == "SUP" && subtree.className == "reference") {
removeElements.push(subtree)
return
}
var serialStyle = ""
for (let prop of style) {
if (prop[0] != "-") {
serialStyle += prop + ":" + style[prop].replace(/:/g, "") + "|"
}
}
serialStyle += "width:" + subtree.offsetWidth / document.body.offsetWidth + "|height:" + subtree.offsetHeight / document.body.offsetHeight
if (subtree.tagName == "TD" || subtree.tagName == "TH") {
serialStyle += "|colspan:" + subtree.colSpan + "|rowspan:" + subtree.rowSpan
}
subtree.setAttribute("data-computed-style", serialStyle)
subtree.setAttribute("data-xpath", pathTo(subtree).toLowerCase())
for (let child of subtree.children) addRender(child)
}
function preprocess() {
var elements = document.querySelectorAll(injected_script_selector)
for (let subtree of elements) addRender(subtree)
for (let elem of removeElements) elem.remove()
}
const injected_script_selector = arguments[0]
if (document.readyState == 'complete') {
preprocess()
} else {
window.onload = function(){preprocess()}
}
"""
# --- import directives -------------------------------------------------------
makedirs(PATH_RESOURCES, exist_ok=True)
try:
stopwords.words("english")
except:
nltk_download('stopwords')
# --- format ------------------------------------------------------------------
def date_stamp():
''' Return the current timestamp. '''
return strftime('%Y-%m-%d, %H:%M:%S')
def bytes_to_human(size, decimal_places=2):
''' Returns a human readable file size from a number of bytes. '''
for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
if size < 1024: break
size /= 1024
return f'{size:.{decimal_places}f}{unit}B'
def seconds_to_human(seconds):
''' Returns a human readable string from a number of seconds. '''
return str(timedelta(seconds=int(seconds))).zfill(8)
def hashed(text):
''' Returns the md5 hash of a text. Not recommended for security concerns. '''
return md5(text.encode()).hexdigest()
def fname_escape(text):
return sub(r'([^\w\s\.])', lambda x: f'_{ord(x.group())}_', text.replace('_', '_95_'))
def fname_unescape(text):
return sub(r'(_\d+_)', lambda x: chr(int(x.group()[1:-1])), text)
# --- log ---------------------------------------------------------------------
def log(log_name, text):
''' Logs the given text to the log specified, and prints it. '''
text = PATTERN_LOG % (date_stamp(), text)
print('[%s] %s' % (log_name, text), end='')
with open(PATH_LOG % log_name, 'a', encoding='utf-8') as fp:
fp.write(text)
def log_error():
''' Used inside an except sentence, logs the error to the error log. '''
log('error', format_exc())
def cache(target, args, identifier=None, cache_life=3 * 24 * 3600):
''' Run the target function with the given args, and store it to a pickled
cache folder using the given identifier or the name of the function. The
next time it is executed, the cached output is returned unless cache_life
time expires. '''
if identifier == None: identifier = target.__name__
identifier = sub(r'[/\\\*;\[\]\'\":=,<>]', '_', identifier)
path = join(PATH_RESOURCES, f'.pickled/{identifier}.pk')
makedirs(dirname(path), exist_ok=True)
now = time()
if exists(path):
with open(path, 'rb') as fp:
save_time, value = pload(fp)
if now - save_time <= cache_life:
return value
res = target(*args)
with open(path, 'wb') as fp:
pdump((now, res), fp, protocol=3)
return res
# --- network -----------------------------------------------------------------
def download_file(url, path=None, chunk_size=10**5):
''' Downloads a file keeping track of the progress. '''
if path == None: path = url.split('/')[-1]
r = get(url, stream=True)
total_bytes = int(r.headers.get('content-length'))
bytes_downloaded = 0
start = time()
print('Downloading %s (%s)' % (url, bytes_to_human(total_bytes)))
with open(path, 'wb') as fp:
for chunk in r.iter_content(chunk_size=chunk_size):
if not chunk: continue
fp.write(chunk)
bytes_downloaded += len(chunk)
percent = bytes_downloaded / total_bytes
bar = ('█' * int(percent * 32)).ljust(32)
time_delta = time() - start
eta = seconds_to_human((total_bytes - bytes_downloaded) * time_delta / bytes_downloaded)
avg_speed = bytes_to_human(bytes_downloaded / time_delta).rjust(9)
stdout.flush()
stdout.write('\r %6.02f%% |%s| %s/s eta %s' % (100 * percent, bar, avg_speed, eta))
print()
_driver = None
def get_driver(headless=True, disable_images=True, open_links_same_tab=False):
''' Returns a Firefox webdriver, and run one if there is no any active. '''
global _driver
if _driver == None:
opts = Options()
opts.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
if open_links_same_tab:
opts.set_preference('browser.link.open_newwindow.restriction', 0)
opts.set_preference('browser.link.open_newwindow', 1)
if headless: opts.set_headless()
if disable_images: opts.set_preference('permissions.default.image', 2)
_driver = Firefox(options=opts)
_driver.set_page_load_timeout(15)
return _driver
def close_driver():
''' Close the current Firefox webdriver, if any. '''
global _driver
if _driver != None:
print('Closing Firefox driver')
_driver.close()
def get_with_render(url, render_selector='table', headless=True, disable_images=True, open_links_same_tab=False):
''' Downloads a page and renders it to return the page source, the width,
and the height in pixels. Elements on the subtree selected using
render_selector contain a data-computed-style attribute and a data-xpath. '''
driver = get_driver(headless, disable_images, open_links_same_tab)
driver.get(url)
driver.execute_script(SCRIPT_ADD_RENDER, render_selector)
sleep(.5)
return driver.page_source
# --- vector ------------------------------------------------------------------
def vectors_average(vectors):
''' Given a list of mixed feature vectors, returns the average of all them.
For numerical features, aritmetic average is used. For categorical ones,
the most common is used. '''
vectors = [v for v in vectors if len(v)]
res = {}
if len(vectors):
for feat in vectors[0]:
if type(vectors[0][feat]) == str:
val = Counter(v[feat] for v in vectors).most_common(1)[0][0]
else:
val = sum(v[feat] for v in vectors) / len(vectors)
res[feat] = val
return res
def vectors_weighted_average(vectors):
''' Given a list of tuples of type <weight, mixed feature vector>, returns
the weighted average of all them. For numerical features, aritmetic average
is used. For categorical ones, weighted frequencies are used to return the
most common. '''
if len(vectors) == 1: return vectors[0][1]
res = {}
total_weight = sum(v[0] for v in vectors)
if total_weight == 0:
total_weight = len(vectors)
for n in range(total_weight):
vectors[n][0] = 1
vectors = [(w / total_weight, fs) for w, fs in vectors]
for f in vectors[0][1]:
if type(vectors[0][1][f]) == str:
sum_feat = {}
for weight, features in vectors:
if features[f] in sum_feat:
sum_feat[features[f]] += weight
else:
sum_feat[features[f]] = weight
res[f] = max(sum_feat.items(), key=lambda v: v[1])[0]
else:
val = 0
for weight, features in vectors:
val += weight * features[f]
res[f] = val
return res
def vectors_difference(v1, v2, prefix=''):
''' Given two mixed feature vectors, return another vector with the
differences amongst them. For numerical features, absolute value difference
is computed. For categorical features, Gower distance is used. '''
res = {}
for feat in v1:
if type(v1[feat]) == str:
res[prefix + feat] = 0 if v1[feat] == v2[feat] else 1
else:
res[prefix + feat] = abs(v1[feat] - v2[feat])
return res
def vector_module(vector):
''' Given a mixed feature vector, return the norm of their numerical
attributes. '''
nums = [v**2 for v in vector.values() if type(v) != str]
return sqrt(sum(nums))
def binarize_categorical(vectors):
''' Given a 2-D list of mixed feature vectors, transform every categorical
feature into a binary one, using the seen values of all the vectors. '''
vectors = deepcopy(vectors)
cat_vector = next([k for k, v in cell.items() if type(v) == str] for row in vectors for cell in row if len(cell))
for f in cat_vector:
values = list(set(cell[f] for row in vectors for cell in row if len(cell)))
for r, row in enumerate(vectors):
for c, cell in enumerate(row):
if len(cell) == 0: continue
for v in values:
vectors[r][c][f'{f}-{v}'] = 1 if v == cell[f] else 0
del vectors[r][c][f]
return vectors
# --- parsing -----------------------------------------------------------------
_find_dates_extractor = DateExtractor()
def find_dates(text):
try:
res = _find_dates_extractor.extract(text, prefer_language_date_order=False)
if len(res): return res[0].value
except:
log('info', f'ETK DateExtractor raised an error on value {text}. Using RegEx fallback instead.')
_find_entities_extractor = SpacyNerExtractor('dummy_parameter')
def find_entities(text):
try:
return {ext.value: ext.tag for ext in _find_entities_extractor.extract(text)}
except:
log('info', f'ETK SpacyNerExtractor raised an error on value {text}.')
return {}
# --- math --------------------------------------------------------------------
def distinct(lst, uniqueness_function):
''' Returns a list in the same order with just the elements with a distinct
value on the uniqueness_function.
I.e.: `distinct([1, 5, 7, 9], lambda x: x % 3)` would return [1, 5, 9].'''
values = []
keys = []
for v in lst:
k = uniqueness_function(v)
if k not in keys:
keys.append(k)
values.append(v)
return values | 0.328422 | 0.095097 |
import os
import sys
import getopt
from pptx import Presentation
from pptx.util import Inches
def main():
argv = sys.argv[1:]
pathtofiles = '.'
outputfile = 'test.pptx'
templatefile = './template.pptx'
sort = 'm'
try:
opts, args = getopt.getopt(argv,"hfi:o:t:",["imagelocationdirectory=",
"outputfile=",
"templatefile=",
"sortbyfilename="])
except getopt.GetoptError:
print ('try photoslides -h ')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('photoslides [options]\n'
'The following options can be specified:\n'
'-i, --imagelocationdirectory=<dirOfImages> Must be absolute reference to the directory where the images are located. Do not unclude "/" at end. Default is the current directory.\n'
'-o, --outputfile=<output.pptx> Name of powerpoint file to generate. Defaults to test.pptx\n'
'-t, --templatefile=<template.pptx> Source presentation to use. Defaults to ./template.pptx This tool adds the blank slide style which is assumed to'
' be 7th in sequence of the master layouts.\n'
'-f, --sortbyfilename Sort image files by filename. Default sort is by date modified.\n')
sys.exit()
elif opt in ("-i", "--imagelocationdirectory"):
pathtofiles = arg
elif opt in ("-o", "--outputfile"):
outputfile = arg
elif opt in ("-t", "--templatefile"):
templatefile = arg
elif opt in ("-f", "--sortbyfilename"):
sort = 'f'
prs = Presentation(templatefile)
blank_slide_layout = prs.slide_layouts[6]
left = top = Inches(0)
height = prs.slide_height
folder = os.fsencode(pathtofiles)
filenames = []
for file in os.listdir(folder):
filename = os.fsdecode(file)
if filename.endswith( ('.jpeg', '.png', '.gif', '.tiff') ): # image files supported by powerpint...
filenames.append(pathtofiles + "/" + filename)
if sort == "f":
filenames.sort()
else:
filenames.sort(key=os.path.getmtime)
for file in filenames:
slide = prs.slides.add_slide(blank_slide_layout)
pic = slide.shapes.add_picture(file, left, top, height=height)
prs.save(outputfile)
if __name__ == "__main__":
main() | photoslides/__main__.py | import os
import sys
import getopt
from pptx import Presentation
from pptx.util import Inches
def main():
argv = sys.argv[1:]
pathtofiles = '.'
outputfile = 'test.pptx'
templatefile = './template.pptx'
sort = 'm'
try:
opts, args = getopt.getopt(argv,"hfi:o:t:",["imagelocationdirectory=",
"outputfile=",
"templatefile=",
"sortbyfilename="])
except getopt.GetoptError:
print ('try photoslides -h ')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('photoslides [options]\n'
'The following options can be specified:\n'
'-i, --imagelocationdirectory=<dirOfImages> Must be absolute reference to the directory where the images are located. Do not unclude "/" at end. Default is the current directory.\n'
'-o, --outputfile=<output.pptx> Name of powerpoint file to generate. Defaults to test.pptx\n'
'-t, --templatefile=<template.pptx> Source presentation to use. Defaults to ./template.pptx This tool adds the blank slide style which is assumed to'
' be 7th in sequence of the master layouts.\n'
'-f, --sortbyfilename Sort image files by filename. Default sort is by date modified.\n')
sys.exit()
elif opt in ("-i", "--imagelocationdirectory"):
pathtofiles = arg
elif opt in ("-o", "--outputfile"):
outputfile = arg
elif opt in ("-t", "--templatefile"):
templatefile = arg
elif opt in ("-f", "--sortbyfilename"):
sort = 'f'
prs = Presentation(templatefile)
blank_slide_layout = prs.slide_layouts[6]
left = top = Inches(0)
height = prs.slide_height
folder = os.fsencode(pathtofiles)
filenames = []
for file in os.listdir(folder):
filename = os.fsdecode(file)
if filename.endswith( ('.jpeg', '.png', '.gif', '.tiff') ): # image files supported by powerpint...
filenames.append(pathtofiles + "/" + filename)
if sort == "f":
filenames.sort()
else:
filenames.sort(key=os.path.getmtime)
for file in filenames:
slide = prs.slides.add_slide(blank_slide_layout)
pic = slide.shapes.add_picture(file, left, top, height=height)
prs.save(outputfile)
if __name__ == "__main__":
main() | 0.098957 | 0.086054 |
import itertools as itt
import os
import tempfile
from ..biotools import blast_sequence
class PostProcessingMixin:
def compute_full_assembly_plan(self, id_prefix="S", id_digits=5):
""" """
counter = itt.count()
def rec(quote):
if not quote.accepted:
return quote
if any(
[
hasattr(quote.source, attr)
for attr in ["supplier", "primers_supplier"]
]
):
if quote.assembly_plan is None:
quote = quote.source.get_quote(
quote.sequence,
max_lead_time=quote.lead_time,
with_assembly_plan=True,
)
segments = {
segment: rec(subquote)
for segment, subquote in sorted(
quote.assembly_plan.items(), key=lambda item: item[0]
)
}
quote.assembly_plan = segments
if id_prefix:
index = next(counter)
quote.id = "{id_prefix}_{index:0{id_digits}}".format(
id_prefix=id_prefix, index=index, id_digits=id_digits
)
return quote
rec(self)
if id_prefix:
index = next(counter)
self.id = "{id_prefix}_{index:0{id_digits}}".format(
id_prefix=id_prefix, index=index, id_digits=id_digits
)
self.full_assembly_plan_computed = True
def compute_fragments_final_locations(self):
"""Compute the exact final location of the fragments in the final
sequence.
"""
if not self.full_assembly_plan_computed:
self.compute_full_assembly_plan()
quotes = self.tree_as_list()
quotes_dict = {quote.id: quote for quote in quotes}
_, temp_fasta = tempfile.mkstemp(suffix=".fa")
with open(temp_fasta, "w+") as f:
for quote in quotes:
f.write(">%s\n%s\n" % (quote.id, quote.sequence))
results = blast_sequence(
self.sequence, subject=temp_fasta, word_size=10, perc_identity=100
)
if isinstance(results, list):
alignments = sum([rec.alignments for rec in results], [])
else:
alignments = results.alignments
for al in alignments:
hit = max(al.hsps, key=lambda hit: hit.align_length)
final_location = sorted((hit.query_start, hit.query_end))
matching_segment = sorted((hit.sbjct_start, hit.sbjct_end))
quotes_dict[al.hit_def].final_location = final_location
quotes_dict[al.hit_def].matching_segment = matching_segment
os.remove(temp_fasta)
def propagate_deadline(self, deadline):
"""Add a `deadline` attribute to the quote and propagate it to
the quote's children by taking into account the duration of operations.
For instance if "self" has a duration of 5 and receives a deadline
of 8, the quotes that "self" depends on will receive a deadline of
8-5=3.
"""
self.deadline = deadline
children_deadline = deadline - self.step_duration
if self.assembly_plan is not None:
for segment, child in self.assembly_plan.items():
child.propagate_deadline(children_deadline) | dnaweaver/DnaQuote/PostProcessingMixin.py | import itertools as itt
import os
import tempfile
from ..biotools import blast_sequence
class PostProcessingMixin:
def compute_full_assembly_plan(self, id_prefix="S", id_digits=5):
""" """
counter = itt.count()
def rec(quote):
if not quote.accepted:
return quote
if any(
[
hasattr(quote.source, attr)
for attr in ["supplier", "primers_supplier"]
]
):
if quote.assembly_plan is None:
quote = quote.source.get_quote(
quote.sequence,
max_lead_time=quote.lead_time,
with_assembly_plan=True,
)
segments = {
segment: rec(subquote)
for segment, subquote in sorted(
quote.assembly_plan.items(), key=lambda item: item[0]
)
}
quote.assembly_plan = segments
if id_prefix:
index = next(counter)
quote.id = "{id_prefix}_{index:0{id_digits}}".format(
id_prefix=id_prefix, index=index, id_digits=id_digits
)
return quote
rec(self)
if id_prefix:
index = next(counter)
self.id = "{id_prefix}_{index:0{id_digits}}".format(
id_prefix=id_prefix, index=index, id_digits=id_digits
)
self.full_assembly_plan_computed = True
def compute_fragments_final_locations(self):
"""Compute the exact final location of the fragments in the final
sequence.
"""
if not self.full_assembly_plan_computed:
self.compute_full_assembly_plan()
quotes = self.tree_as_list()
quotes_dict = {quote.id: quote for quote in quotes}
_, temp_fasta = tempfile.mkstemp(suffix=".fa")
with open(temp_fasta, "w+") as f:
for quote in quotes:
f.write(">%s\n%s\n" % (quote.id, quote.sequence))
results = blast_sequence(
self.sequence, subject=temp_fasta, word_size=10, perc_identity=100
)
if isinstance(results, list):
alignments = sum([rec.alignments for rec in results], [])
else:
alignments = results.alignments
for al in alignments:
hit = max(al.hsps, key=lambda hit: hit.align_length)
final_location = sorted((hit.query_start, hit.query_end))
matching_segment = sorted((hit.sbjct_start, hit.sbjct_end))
quotes_dict[al.hit_def].final_location = final_location
quotes_dict[al.hit_def].matching_segment = matching_segment
os.remove(temp_fasta)
def propagate_deadline(self, deadline):
"""Add a `deadline` attribute to the quote and propagate it to
the quote's children by taking into account the duration of operations.
For instance if "self" has a duration of 5 and receives a deadline
of 8, the quotes that "self" depends on will receive a deadline of
8-5=3.
"""
self.deadline = deadline
children_deadline = deadline - self.step_duration
if self.assembly_plan is not None:
for segment, child in self.assembly_plan.items():
child.propagate_deadline(children_deadline) | 0.529263 | 0.138666 |
import logging
from typing import Dict, Sequence, Type, Optional, Callable, Union, Any
from concord.context import Context
from concord.exceptions import ExtensionManagerError
from concord.middleware import (
Middleware,
MiddlewareChain,
chain_of,
sequence_of,
MiddlewareResult,
)
log = logging.getLogger(__name__)
class Extension:
"""Abstract extension class.
TODO: What about dependencies of extension?
It would be cool, and seems like not hard to implement.
"""
NAME = "Extension name is empty."
DESCRIPTION = "Extension description is empty."
VERSION = "1.0.0"
@property
def client_middleware(self) -> Sequence[Middleware]:
"""Middleware list, associated with this extension, and that should be
registered and applied on every event processing.
It is especially useful for sharing states between different extensions.
.. note::
Keep in mind, that this list can be requested multiple times as well
as cached and optimized. You should return the same list on every
request and avoid any changes in the list after first request due to
this changes may be unexpected for other code.
.. warning::
Keep in mind, that client middleware will be executed by middleware
chain.
"""
return []
@property
def extension_middleware(self) -> Sequence[Middleware]:
"""Middleware list, associated with this extension, and that should be
registered for event handling.
.. note::
Keep in mind, that this list can be requested multiple times as well
as cached and optimized. You should return the same list on every
request and avoid any changes in the list after first request due to
this changes may be unexpected for other code.
.. warning::
Keep in mind, that all extension middleware will be executed on
every event. Properly filter events before processing them.
"""
return []
def on_register(self, manager: "Manager"):
"""Listener invoked on registering extension in a manager.
If there is global states and middleware, associated with this
extension, all of this will be registered after invoking this listener.
Args:
manager: Manager instance where extension has been registered.
"""
pass # pragma: no cover
def on_unregister(self, manager: "Manager"):
"""Listener invoked on unregistering extension in a manager.
If there is global states and middleware, associated with this
extension, all of this is already unregistered before invoking this
listener.
Args:
manager: Manager instance where extension has been unregistered.
"""
pass # pragma: no cover
class Manager(Middleware):
"""Extension manager. It is a middleware itself.
Attributes:
_extensions: List of registered extensions. Key is an extension class
(subclass of :class:`Extension`), value is extension instance.
_client_middleware_cache: Cached list of client middleware.
_extension_middleware_cache: Cached list of extension middleware.
_root_middleware_cache: Cached root middleware.
"""
_extensions: Dict[Type[Extension], Extension]
_client_middleware_cache: Optional[Sequence[Middleware]]
_extension_middleware_cache: Optional[Sequence[Middleware]]
_root_middleware_cache: Optional[Middleware]
def __init__(self):
super().__init__()
self._extensions = {}
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
@property
def client_middleware(self) -> Sequence[Middleware]:
"""States list, provided by extensions, and that should be applied on
every event processing."""
if self._client_middleware_cache is None:
self._client_middleware_cache = [
mw
for extension in self._extensions.values()
for mw in extension.client_middleware
]
return self._client_middleware_cache
@property
def extension_middleware(self) -> Sequence[Middleware]:
"""Middleware list, provided by extensions for event handling."""
if self._extension_middleware_cache is None:
self._extension_middleware_cache = [
mw
for extension in self._extensions.values()
for mw in extension.extension_middleware
]
return self._extension_middleware_cache
@property
def root_middleware(self) -> MiddlewareChain:
"""Root middleware, a built chain of client and extension middleware."""
if self._root_middleware_cache is None:
chain = chain_of([sequence_of(self.extension_middleware)])
for mw in self.client_middleware:
chain.add_middleware(mw)
self._root_middleware_cache = chain
return self._root_middleware_cache
def is_extension_registered(self, extension: Type[Extension]) -> bool:
"""Checks is extension registered in the manager.
Args:
extension: Extension to check.
Returns:
``True``, if extensions is registered, otherwise ``False``.
"""
return extension in self._extensions
def register_extension(self, extension: Type[Extension]):
"""Registers extension in the manager.
Args:
extension: Extension to register.
Raises:
ValueError: If not a type provided or if provided type is not a
subclass of :class:`Extension` provided.
concord.exceptions.ExtensionManagerError: If this extension is
already registered in this manager.
"""
if not isinstance(extension, type):
raise ValueError("Not a type")
if not issubclass(extension, Extension):
raise ValueError("Not an extension")
if self.is_extension_registered(extension):
raise ExtensionManagerError("Already registered")
instance = extension()
instance.on_register(self)
self._extensions[extension] = instance
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
log.info(
f'Extension "{extension.NAME} "'
f"(version {extension.VERSION}) has been registered"
)
def unregister_extension(self, extension: Type[Extension]):
"""Unregisters extension in the manager.
Args:
extension: Extension to unregister.
Raises:
ValueError: If not a type provided or if provided type is not a
subclass of :class:`Extension` provided.
concord.exceptions.ExtensionManagerError: If this extension is not
registered in this manager.
"""
if not isinstance(extension, type):
raise ValueError("Not a type")
if not issubclass(extension, Extension):
raise ValueError("Not an extension")
if not self.is_extension_registered(extension):
raise ExtensionManagerError("Not registered")
instance = self._extensions.pop(extension)
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
instance.on_unregister(self)
log.info(
f'Extension "{extension.NAME} "'
f"(version {extension.VERSION}) has been unregistered"
)
async def run(
self, *args, ctx: Context, next: Callable, **kwargs
) -> Union[MiddlewareResult, Any]:
return await self.root_middleware.run(
*args, ctx=ctx, next=next, **kwargs
) | concord/extension.py | import logging
from typing import Dict, Sequence, Type, Optional, Callable, Union, Any
from concord.context import Context
from concord.exceptions import ExtensionManagerError
from concord.middleware import (
Middleware,
MiddlewareChain,
chain_of,
sequence_of,
MiddlewareResult,
)
log = logging.getLogger(__name__)
class Extension:
"""Abstract extension class.
TODO: What about dependencies of extension?
It would be cool, and seems like not hard to implement.
"""
NAME = "Extension name is empty."
DESCRIPTION = "Extension description is empty."
VERSION = "1.0.0"
@property
def client_middleware(self) -> Sequence[Middleware]:
"""Middleware list, associated with this extension, and that should be
registered and applied on every event processing.
It is especially useful for sharing states between different extensions.
.. note::
Keep in mind, that this list can be requested multiple times as well
as cached and optimized. You should return the same list on every
request and avoid any changes in the list after first request due to
this changes may be unexpected for other code.
.. warning::
Keep in mind, that client middleware will be executed by middleware
chain.
"""
return []
@property
def extension_middleware(self) -> Sequence[Middleware]:
"""Middleware list, associated with this extension, and that should be
registered for event handling.
.. note::
Keep in mind, that this list can be requested multiple times as well
as cached and optimized. You should return the same list on every
request and avoid any changes in the list after first request due to
this changes may be unexpected for other code.
.. warning::
Keep in mind, that all extension middleware will be executed on
every event. Properly filter events before processing them.
"""
return []
def on_register(self, manager: "Manager"):
"""Listener invoked on registering extension in a manager.
If there is global states and middleware, associated with this
extension, all of this will be registered after invoking this listener.
Args:
manager: Manager instance where extension has been registered.
"""
pass # pragma: no cover
def on_unregister(self, manager: "Manager"):
"""Listener invoked on unregistering extension in a manager.
If there is global states and middleware, associated with this
extension, all of this is already unregistered before invoking this
listener.
Args:
manager: Manager instance where extension has been unregistered.
"""
pass # pragma: no cover
class Manager(Middleware):
"""Extension manager. It is a middleware itself.
Attributes:
_extensions: List of registered extensions. Key is an extension class
(subclass of :class:`Extension`), value is extension instance.
_client_middleware_cache: Cached list of client middleware.
_extension_middleware_cache: Cached list of extension middleware.
_root_middleware_cache: Cached root middleware.
"""
_extensions: Dict[Type[Extension], Extension]
_client_middleware_cache: Optional[Sequence[Middleware]]
_extension_middleware_cache: Optional[Sequence[Middleware]]
_root_middleware_cache: Optional[Middleware]
def __init__(self):
super().__init__()
self._extensions = {}
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
@property
def client_middleware(self) -> Sequence[Middleware]:
"""States list, provided by extensions, and that should be applied on
every event processing."""
if self._client_middleware_cache is None:
self._client_middleware_cache = [
mw
for extension in self._extensions.values()
for mw in extension.client_middleware
]
return self._client_middleware_cache
@property
def extension_middleware(self) -> Sequence[Middleware]:
"""Middleware list, provided by extensions for event handling."""
if self._extension_middleware_cache is None:
self._extension_middleware_cache = [
mw
for extension in self._extensions.values()
for mw in extension.extension_middleware
]
return self._extension_middleware_cache
@property
def root_middleware(self) -> MiddlewareChain:
"""Root middleware, a built chain of client and extension middleware."""
if self._root_middleware_cache is None:
chain = chain_of([sequence_of(self.extension_middleware)])
for mw in self.client_middleware:
chain.add_middleware(mw)
self._root_middleware_cache = chain
return self._root_middleware_cache
def is_extension_registered(self, extension: Type[Extension]) -> bool:
"""Checks is extension registered in the manager.
Args:
extension: Extension to check.
Returns:
``True``, if extensions is registered, otherwise ``False``.
"""
return extension in self._extensions
def register_extension(self, extension: Type[Extension]):
"""Registers extension in the manager.
Args:
extension: Extension to register.
Raises:
ValueError: If not a type provided or if provided type is not a
subclass of :class:`Extension` provided.
concord.exceptions.ExtensionManagerError: If this extension is
already registered in this manager.
"""
if not isinstance(extension, type):
raise ValueError("Not a type")
if not issubclass(extension, Extension):
raise ValueError("Not an extension")
if self.is_extension_registered(extension):
raise ExtensionManagerError("Already registered")
instance = extension()
instance.on_register(self)
self._extensions[extension] = instance
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
log.info(
f'Extension "{extension.NAME} "'
f"(version {extension.VERSION}) has been registered"
)
def unregister_extension(self, extension: Type[Extension]):
"""Unregisters extension in the manager.
Args:
extension: Extension to unregister.
Raises:
ValueError: If not a type provided or if provided type is not a
subclass of :class:`Extension` provided.
concord.exceptions.ExtensionManagerError: If this extension is not
registered in this manager.
"""
if not isinstance(extension, type):
raise ValueError("Not a type")
if not issubclass(extension, Extension):
raise ValueError("Not an extension")
if not self.is_extension_registered(extension):
raise ExtensionManagerError("Not registered")
instance = self._extensions.pop(extension)
self._client_middleware_cache = None
self._extension_middleware_cache = None
self._root_middleware_cache = None
instance.on_unregister(self)
log.info(
f'Extension "{extension.NAME} "'
f"(version {extension.VERSION}) has been unregistered"
)
async def run(
self, *args, ctx: Context, next: Callable, **kwargs
) -> Union[MiddlewareResult, Any]:
return await self.root_middleware.run(
*args, ctx=ctx, next=next, **kwargs
) | 0.897223 | 0.220741 |
import unittest
import numpy as np
from weis.multifidelity.models.testbed_components import simple_2D_high_model, simple_2D_low_model
from weis.multifidelity.methods.base_method import BaseMethod
class Test(unittest.TestCase):
def test_set_initial_point(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
method_instance.add_objective('y')
method_instance.set_initial_point([0.5, 0.5])
np.testing.assert_allclose(method_instance.design_vectors[-1, :], [0.5, 0.5], )
def test_bounds_and_initial_points(self):
np.random.seed(13)
bounds = {'x' : np.array([[-10., 11.0], [-20.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
init_points = np.array([[ 6.33175062, -15.01163438],
[ 7.30984919, 0.28073316],
[ 10.42462339, -10.4775658 ],
[ 2.78989172, -3.71394319],
[ 3.47388024, -4.83761718]])
np.testing.assert_allclose(method_instance.design_vectors, init_points)
np.random.seed(13)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False, num_initial_points=3)
np.testing.assert_allclose(method_instance.design_vectors, init_points[:3, :])
def test_approximation(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
method_instance.add_objective('y')
method_instance.construct_approximations()
func = method_instance.approximation_functions['y']
flattened_desvars = model_low.flatten_desvars(desvars)
np.testing.assert_allclose(func(flattened_desvars), -5.33064616)
def test_set_initial_point(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
trust_region = BaseMethod(model_low, model_high, bounds, disp=False)
trust_region.add_objective('y')
trust_region.set_initial_point([0.5, 0.5])
np.testing.assert_allclose(trust_region.design_vectors[-1, :], [0.5, 0.5])
if __name__ == '__main__':
unittest.main() | weis/multifidelity/test/test_base_method.py | import unittest
import numpy as np
from weis.multifidelity.models.testbed_components import simple_2D_high_model, simple_2D_low_model
from weis.multifidelity.methods.base_method import BaseMethod
class Test(unittest.TestCase):
def test_set_initial_point(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
method_instance.add_objective('y')
method_instance.set_initial_point([0.5, 0.5])
np.testing.assert_allclose(method_instance.design_vectors[-1, :], [0.5, 0.5], )
def test_bounds_and_initial_points(self):
np.random.seed(13)
bounds = {'x' : np.array([[-10., 11.0], [-20.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
init_points = np.array([[ 6.33175062, -15.01163438],
[ 7.30984919, 0.28073316],
[ 10.42462339, -10.4775658 ],
[ 2.78989172, -3.71394319],
[ 3.47388024, -4.83761718]])
np.testing.assert_allclose(method_instance.design_vectors, init_points)
np.random.seed(13)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False, num_initial_points=3)
np.testing.assert_allclose(method_instance.design_vectors, init_points[:3, :])
def test_approximation(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
method_instance = BaseMethod(model_low, model_high, bounds, disp=False)
method_instance.add_objective('y')
method_instance.construct_approximations()
func = method_instance.approximation_functions['y']
flattened_desvars = model_low.flatten_desvars(desvars)
np.testing.assert_allclose(func(flattened_desvars), -5.33064616)
def test_set_initial_point(self):
np.random.seed(13)
bounds = {'x' : np.array([[0.0, 1.0], [0.0, 1.0]])}
desvars = {'x' : np.array([0., 0.25])}
model_low = simple_2D_low_model(desvars)
model_high = simple_2D_high_model(desvars)
trust_region = BaseMethod(model_low, model_high, bounds, disp=False)
trust_region.add_objective('y')
trust_region.set_initial_point([0.5, 0.5])
np.testing.assert_allclose(trust_region.design_vectors[-1, :], [0.5, 0.5])
if __name__ == '__main__':
unittest.main() | 0.424889 | 0.595669 |
from typing import Optional
from spectrumdevice import MockSpectrumCard, SpectrumCard
from spectrumdevice.devices.measurement import Measurement
from spectrumdevice.settings import (
AcquisitionMode,
CardType,
TriggerSource,
ExternalTriggerMode,
TriggerSettings,
AcquisitionSettings,
)
def standard_single_mode_example(
mock_mode: bool, trigger_source: TriggerSource, device_number: int, ip_address: Optional[str] = None
) -> Measurement:
if not mock_mode:
# Connect to a networked device. To connect to a local (PCIe) device, do not provide an ip_address.
card = SpectrumCard(device_number=device_number, ip_address=ip_address)
else:
# Set up a mock device
card = MockSpectrumCard(
device_number=device_number,
card_type=CardType.TYP_M2P5966_X4,
mock_source_frame_rate_hz=10.0,
num_modules=2,
num_channels_per_module=4,
)
# Trigger settings
trigger_settings = TriggerSettings(
trigger_sources=[trigger_source],
external_trigger_mode=ExternalTriggerMode.SPC_TM_POS,
external_trigger_level_in_mv=1000,
)
# Acquisition settings
acquisition_settings = AcquisitionSettings(
acquisition_mode=AcquisitionMode.SPC_REC_STD_SINGLE,
sample_rate_in_hz=40000000,
acquisition_length_in_samples=400,
pre_trigger_length_in_samples=0,
timeout_in_ms=1000,
enabled_channels=[0],
vertical_ranges_in_mv=[200],
vertical_offsets_in_percent=[0],
timestamping_enabled=True,
)
# Apply settings
card.configure_trigger(trigger_settings)
card.configure_acquisition(acquisition_settings)
# Execute acquisition
meas = card.execute_standard_single_acquisition()
card.reset()
card.disconnect()
return meas
if __name__ == "__main__":
from matplotlib.pyplot import plot, show, xlabel, tight_layout, ylabel
meas = standard_single_mode_example(
mock_mode=True,
trigger_source=TriggerSource.SPC_TMASK_EXT0,
device_number=0,
)
# Plot waveforms
for waveform in meas.waveforms:
plot(waveform)
xlabel("Time (samples)")
ylabel("Amplitude (Volts)")
tight_layout()
ts_format = "%Y-%m-%d %H:%M:%S.%f"
print(f"Acquired {len(meas.waveforms)} waveforms with the following shapes:")
print([wfm.shape for wfm in meas.waveforms])
print("and the following timestamp:")
print(meas.timestamp.strftime(ts_format) if meas.timestamp else "Timestamping disabled")
show() | example_scripts/standard_single_mode.py | from typing import Optional
from spectrumdevice import MockSpectrumCard, SpectrumCard
from spectrumdevice.devices.measurement import Measurement
from spectrumdevice.settings import (
AcquisitionMode,
CardType,
TriggerSource,
ExternalTriggerMode,
TriggerSettings,
AcquisitionSettings,
)
def standard_single_mode_example(
mock_mode: bool, trigger_source: TriggerSource, device_number: int, ip_address: Optional[str] = None
) -> Measurement:
if not mock_mode:
# Connect to a networked device. To connect to a local (PCIe) device, do not provide an ip_address.
card = SpectrumCard(device_number=device_number, ip_address=ip_address)
else:
# Set up a mock device
card = MockSpectrumCard(
device_number=device_number,
card_type=CardType.TYP_M2P5966_X4,
mock_source_frame_rate_hz=10.0,
num_modules=2,
num_channels_per_module=4,
)
# Trigger settings
trigger_settings = TriggerSettings(
trigger_sources=[trigger_source],
external_trigger_mode=ExternalTriggerMode.SPC_TM_POS,
external_trigger_level_in_mv=1000,
)
# Acquisition settings
acquisition_settings = AcquisitionSettings(
acquisition_mode=AcquisitionMode.SPC_REC_STD_SINGLE,
sample_rate_in_hz=40000000,
acquisition_length_in_samples=400,
pre_trigger_length_in_samples=0,
timeout_in_ms=1000,
enabled_channels=[0],
vertical_ranges_in_mv=[200],
vertical_offsets_in_percent=[0],
timestamping_enabled=True,
)
# Apply settings
card.configure_trigger(trigger_settings)
card.configure_acquisition(acquisition_settings)
# Execute acquisition
meas = card.execute_standard_single_acquisition()
card.reset()
card.disconnect()
return meas
if __name__ == "__main__":
from matplotlib.pyplot import plot, show, xlabel, tight_layout, ylabel
meas = standard_single_mode_example(
mock_mode=True,
trigger_source=TriggerSource.SPC_TMASK_EXT0,
device_number=0,
)
# Plot waveforms
for waveform in meas.waveforms:
plot(waveform)
xlabel("Time (samples)")
ylabel("Amplitude (Volts)")
tight_layout()
ts_format = "%Y-%m-%d %H:%M:%S.%f"
print(f"Acquired {len(meas.waveforms)} waveforms with the following shapes:")
print([wfm.shape for wfm in meas.waveforms])
print("and the following timestamp:")
print(meas.timestamp.strftime(ts_format) if meas.timestamp else "Timestamping disabled")
show() | 0.909574 | 0.166438 |
import os
import unittest
from datetime import datetime, timedelta, date
from flask import json
import sys
sys.path.append(".") # Adds higher directory to python modules path.
from extensions import db
from app import create_app
from config import TestConfig
from controllers.database.pandemic_whistle import PandemicWhistle
class ReportTests(unittest.TestCase):
def setUp(self):
app = create_app(TestConfig)
app.app_context().push()
self.client = app.test_client()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def create_records(self):
date1 = datetime(2020, 1, 1).timestamp()
date2 = datetime(2020, 2, 1).timestamp()
date3 = datetime(2020, 3, 1).timestamp()
date4 = datetime(2020, 4, 1).timestamp()
date5 = datetime(2020, 5, 1).timestamp()
p1 = PandemicWhistle(hash='abc1', district_state='OH', district=1, reported_date=date1)
p2 = PandemicWhistle(hash='abc2', district_state='OH', district=1, reported_date=date2)
p3 = PandemicWhistle(hash='abc3', district_state='OH', district=1, reported_date=date3)
p4 = PandemicWhistle(hash='abc4', district_state='OH', district=1, reported_date=date4)
p5 = PandemicWhistle(hash='abc5', district_state='OH', district=1, reported_date=date5)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.add(p4)
db.session.add(p5)
db.session.commit()
def test_no_data(self):
response = self.client.get('/v1/reports', follow_redirects=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.json), 0)
def test_with_data(self):
self.create_records()
response = self.client.get('/v1/reports', follow_redirects=True)
self.assertEqual(len(response.json), 5)
def test_with_start_no_results(self):
self.create_records()
start_date = datetime(2020, 6, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_start_results(self):
self.create_records()
start_date = datetime(2020, 2, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date), follow_redirects=True)
self.assertEqual(len(response.json), 4)
def test_with_end_no_results(self):
self.create_records()
end_date = datetime(2020, 1, 1).timestamp()
response = self.client.get('/v1/reports?end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_end_results(self):
self.create_records()
end_date = datetime(2020, 4, 1).timestamp()
response = self.client.get('/v1/reports?end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 3)
def test_with_both_no_results(self):
self.create_records()
start_date = datetime(2020, 6, 1).timestamp()
end_date = datetime(2020, 7, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date) + '&end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_both_results(self):
self.create_records()
start_date = datetime(2020, 2, 1).timestamp()
end_date = datetime(2020, 5, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date) + '&end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 3)
def test_with_bad_start(self):
self.create_records()
response = self.client.get('/v1/reports?start_date=i_like_cheese', follow_redirects=True)
self.assertEqual(response.json.get('message'), 'Invalid start_date')
self.assertEqual(response.status_code, 400)
def test_with_bad_end(self):
self.create_records()
response = self.client.get('/v1/reports?end_date=i_like_cheese', follow_redirects=True)
self.assertEqual(response.json.get('message'), 'Invalid end_date')
self.assertEqual(response.status_code, 400)
if __name__ == "__main__":
unittest.main() | tests/test_reports.py | import os
import unittest
from datetime import datetime, timedelta, date
from flask import json
import sys
sys.path.append(".") # Adds higher directory to python modules path.
from extensions import db
from app import create_app
from config import TestConfig
from controllers.database.pandemic_whistle import PandemicWhistle
class ReportTests(unittest.TestCase):
def setUp(self):
app = create_app(TestConfig)
app.app_context().push()
self.client = app.test_client()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def create_records(self):
date1 = datetime(2020, 1, 1).timestamp()
date2 = datetime(2020, 2, 1).timestamp()
date3 = datetime(2020, 3, 1).timestamp()
date4 = datetime(2020, 4, 1).timestamp()
date5 = datetime(2020, 5, 1).timestamp()
p1 = PandemicWhistle(hash='abc1', district_state='OH', district=1, reported_date=date1)
p2 = PandemicWhistle(hash='abc2', district_state='OH', district=1, reported_date=date2)
p3 = PandemicWhistle(hash='abc3', district_state='OH', district=1, reported_date=date3)
p4 = PandemicWhistle(hash='abc4', district_state='OH', district=1, reported_date=date4)
p5 = PandemicWhistle(hash='abc5', district_state='OH', district=1, reported_date=date5)
db.session.add(p1)
db.session.add(p2)
db.session.add(p3)
db.session.add(p4)
db.session.add(p5)
db.session.commit()
def test_no_data(self):
response = self.client.get('/v1/reports', follow_redirects=True)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.json), 0)
def test_with_data(self):
self.create_records()
response = self.client.get('/v1/reports', follow_redirects=True)
self.assertEqual(len(response.json), 5)
def test_with_start_no_results(self):
self.create_records()
start_date = datetime(2020, 6, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_start_results(self):
self.create_records()
start_date = datetime(2020, 2, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date), follow_redirects=True)
self.assertEqual(len(response.json), 4)
def test_with_end_no_results(self):
self.create_records()
end_date = datetime(2020, 1, 1).timestamp()
response = self.client.get('/v1/reports?end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_end_results(self):
self.create_records()
end_date = datetime(2020, 4, 1).timestamp()
response = self.client.get('/v1/reports?end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 3)
def test_with_both_no_results(self):
self.create_records()
start_date = datetime(2020, 6, 1).timestamp()
end_date = datetime(2020, 7, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date) + '&end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 0)
def test_with_both_results(self):
self.create_records()
start_date = datetime(2020, 2, 1).timestamp()
end_date = datetime(2020, 5, 1).timestamp()
response = self.client.get('/v1/reports?start_date=' + str(start_date) + '&end_date=' + str(end_date), follow_redirects=True)
self.assertEqual(len(response.json), 3)
def test_with_bad_start(self):
self.create_records()
response = self.client.get('/v1/reports?start_date=i_like_cheese', follow_redirects=True)
self.assertEqual(response.json.get('message'), 'Invalid start_date')
self.assertEqual(response.status_code, 400)
def test_with_bad_end(self):
self.create_records()
response = self.client.get('/v1/reports?end_date=i_like_cheese', follow_redirects=True)
self.assertEqual(response.json.get('message'), 'Invalid end_date')
self.assertEqual(response.status_code, 400)
if __name__ == "__main__":
unittest.main() | 0.296858 | 0.233335 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('billing', '0001_initial'),
('vendors', '0001_initial'),
('carts', '0002_auto_20200601_2225'),
('orders', '0001_initial'),
('products', '0001_initial'),
('customers', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='productpurchase',
name='product',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Product', verbose_name='Product'),
),
migrations.AddField(
model_name='ordershippingmovement',
name='shipping_information',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orders.OrderShippingInformation', verbose_name='Shipping Information'),
),
migrations.AddField(
model_name='ordershippinginformation',
name='customer',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='customers.Customer', verbose_name='Customer'),
),
migrations.AddField(
model_name='ordershippinginformation',
name='vendor_customer',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='vendors.VendorCustomer', verbose_name='Vendor Customer'),
),
migrations.AddField(
model_name='order',
name='billing_profile',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='billing.BillingProfile', verbose_name='Billing Profile'),
),
migrations.AddField(
model_name='order',
name='cart',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='carts.Cart', verbose_name='Cart'),
),
migrations.AddField(
model_name='order',
name='shipping_information',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='orders.OrderShippingInformation', verbose_name='Shipping Information'),
),
] | baby_backend/apps/orders/migrations/0002_auto_20200601_2225.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('billing', '0001_initial'),
('vendors', '0001_initial'),
('carts', '0002_auto_20200601_2225'),
('orders', '0001_initial'),
('products', '0001_initial'),
('customers', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='productpurchase',
name='product',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.Product', verbose_name='Product'),
),
migrations.AddField(
model_name='ordershippingmovement',
name='shipping_information',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orders.OrderShippingInformation', verbose_name='Shipping Information'),
),
migrations.AddField(
model_name='ordershippinginformation',
name='customer',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='customers.Customer', verbose_name='Customer'),
),
migrations.AddField(
model_name='ordershippinginformation',
name='vendor_customer',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='vendors.VendorCustomer', verbose_name='Vendor Customer'),
),
migrations.AddField(
model_name='order',
name='billing_profile',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='billing.BillingProfile', verbose_name='Billing Profile'),
),
migrations.AddField(
model_name='order',
name='cart',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='carts.Cart', verbose_name='Cart'),
),
migrations.AddField(
model_name='order',
name='shipping_information',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='orders.OrderShippingInformation', verbose_name='Shipping Information'),
),
] | 0.589362 | 0.095645 |
import numpy as np
from RecSysFramework.Recommender.MatrixFactorization.MatrixFactorization_Cython import BPR_NNMF, BPRMF, FUNK_NNMF, FunkSVD
from RecSysFramework.Recommender.MatrixFactorization.PureSVD import PureSVD
from RecSysFramework.Recommender.KNN.ItemKNNCFRecommender import ItemKNNCF
from RecSysFramework.Recommender.KNN.UserKNNCFRecommender import UserKNNCF
from RecSysFramework.DataManager.Splitter import Holdout
from RecSysFramework.Evaluation.Evaluator import EvaluatorHoldout
from RecSysFramework.DataManager.DatasetPostprocessing.ImplicitURM import ImplicitURM
from RecSysFramework.DataManager.DatasetPostprocessing.KCore import KCore
from tqdm import tqdm
import RecSysFramework.Utils.compute_popularity as cp
from RecSysFramework.Utils.get_holdout import retrieve_train_validation_test_holdhout_dataset
import pandas as pd
import matplotlib.pyplot as plt
from RecSysFramework.Utils.get_model_from_best_models import get_model
from RecSysFramework.Utils import menu
from collections import OrderedDict
from RecSysFramework.Experiments.utils_experiments import round_all_digits
def recommend_batch(recommender_object, users, remove_seen_flag=True, cutoff=5, remove_top_pop_flag=False):
recs = []
size = 1000
n_users = len(users)
n_batch = n_users // size
for idx in range(n_batch):
recs += recommender_object.recommend(
users[size * idx: size *
(idx + 1)], remove_seen_flag=remove_seen_flag, cutoff=cutoff,
remove_top_pop_flag=remove_top_pop_flag, return_scores=True)[0]
recs += recommender_object.recommend(
users[(size * n_batch) %
n_users: n_users], remove_seen_flag=remove_seen_flag, cutoff=cutoff,
remove_top_pop_flag=remove_top_pop_flag, return_scores=True)[0]
return np.array(recs)
def rec_items_pop_analysis(urm_train, cut_list, recs):
"""
plot the percentage of items recommended in every popularity section
"""
# initialize an empty vector of equal length of the items in the dataset
# we will accumulate on this the number of times that the recommender recommend an
# item
items_predictions_num = np.zeros(urm_train.shape[1])
for user_recs in tqdm(recs):
items_predictions_num[user_recs] += 1
item_pop_tuple_list = cp.compute_popularity_item(urm_train)
items_idxs, interactions = zip(*item_pop_tuple_list)
interactions_cumsum = np.cumsum(interactions)
interactions_cumsum_norm = interactions_cumsum/max(interactions_cumsum)
cut_idxs = []
for cut_perc in cut_list:
cut_idx = (np.abs(interactions_cumsum_norm - cut_perc)).argmin()
cut_idxs.append(cut_idx)
items_partition = np.split(items_idxs, cut_idxs)
items_prediction_cuts = []
for partition in items_partition:
items_prediction_cuts.append(np.sum(items_predictions_num[partition]))
items_prediction_cuts_norm = items_prediction_cuts / \
np.sum(items_prediction_cuts)
print(items_prediction_cuts_norm)
return items_prediction_cuts_norm
def rec_and_hit_items_pop_analysis(urm_train, urm_validation, cut_list, recs):
"""
plot the percentage of items recommended and hit in every popularity section
"""
# initialize an empty vector of equal length of the items in the dataset
# we will accumulate on this the number of times that the recommender recommend an
# item and hit it
items_predictions_num = np.zeros(urm_train.shape[1])
for idx, user_recs in enumerate(recs):
items_to_be_hit_user = urm_validation.indices[urm_validation.indptr[idx]
:urm_validation.indptr[idx+1]]
user_recs_hit = list(set(items_to_be_hit_user) & set(user_recs))
if len(user_recs_hit) > 0:
items_predictions_num[np.array(user_recs_hit, dtype=np.int)] += 1
item_pop_tuple_list = cp.compute_popularity_item(urm_train)
items_idxs, interactions = zip(*item_pop_tuple_list)
interactions_cumsum = np.cumsum(interactions)
interactions_cumsum_norm = interactions_cumsum/max(interactions_cumsum)
cut_idxs = []
for cut_perc in cut_list:
cut_idx = (np.abs(interactions_cumsum_norm - cut_perc)).argmin()
cut_idxs.append(cut_idx)
items_partition = np.split(items_idxs, cut_idxs)
items_prediction_cuts = []
for partition in items_partition:
items_prediction_cuts.append(np.sum(items_predictions_num[partition]))
items_prediction_cuts_norm = items_prediction_cuts / \
np.sum(items_prediction_cuts)
print(items_prediction_cuts_norm)
return items_prediction_cuts_norm, np.array(items_prediction_cuts)
def models_comparison_items_pop_analysis(recs, names, thrs, urm_validation, dataset_name):
s = ''
pop_recs = []
pop_recs_hit_perc = []
pop_recs_hit = []
for rec, name in zip(recs, names):
recommendations = recommend_batch(
rec, np.arange(rec.URM_train.shape[0]))
pop_recs.append(rec_items_pop_analysis(
rec.URM_train, thrs, recommendations, ))
rec_and_hit_perc, rec_and_hit = rec_and_hit_items_pop_analysis(
rec.URM_train, urm_validation, thrs, recommendations, )
pop_recs_hit_perc.append(rec_and_hit_perc)
pop_recs_hit.append(rec_and_hit)
file_name = 'predicted_items_pop_{}'.format(
dataset_name).replace(' ', '_')
analysis_df = pd.DataFrame({name: pop*100 for name, pop in zip(names, pop_recs)},
index=['Long tail', 'Short head'])
ax = analysis_df.T.plot.barh(stacked=True, rot=0)
ax.set_xlabel('Percentage')
ax.get_yticklabels()[0].set_fontweight('bold')
ax.get_yticklabels()[2].set_fontweight('bold')
ax.get_yticklabels()[4].set_fontweight('bold')
ax.margins(x=0)
for idx, p in enumerate(ax.patches):
x, y = p.get_xy()
if x == 0:
if idx in [0, 2, 4]:
width = p.get_width()
ax.text(7+p.get_width(), p.get_y()+0.5*p.get_height(),
'{:1.1f}%'.format(width),
ha='center', va='center', fontweight='bold',)
else:
width = p.get_width()
ax.text(7+p.get_width(), p.get_y()+0.5*p.get_height(),
'{:1.1f}%'.format(width),
ha='center', va='center', )
file_name = 'distr_recs_hits_{}'.format(
dataset_name).replace(' ', '_')
s += gen_latex_code('Distribution of popular and not popular items recommended by the algorithms. Bold highlights NNMFs. The dataset is: ' +
dataset_name + '.', file_name) + '.\n'
plt.savefig(file_name, bbox_inches='tight')
return s
def gen_latex_code(caption, file_name):
return '\\begin{figure}[H] \n \
\\includegraphics[width=1\\textwidth]{pictures/' + file_name + '.png} \n \
\\centering \n \
\\caption{' + caption + '} \n \
\\label{fig:' + file_name + '} \n \
\end{figure}'
def _recommended_items_popularity_analysis(thrs, train, test, validation, dataset_name, ):
"""runs the analysis on popularity bins GIVEN A DATASET
moreover, saves the images and generate latex code that allows to
import the image directly in latex
"""
m1, m1_name = get_model(train, dataset_name, model_name='BPRMF')
m2, m2_name = get_model(train, dataset_name, model_name='BPR_NNMF')
m3, m3_name = get_model(train, dataset_name, model_name='FunkSVD')
m4, m4_name = get_model(train, dataset_name, model_name='FUNK_NNMF')
m5, m5_name = get_model(train, dataset_name, model_name='probmf')
m6, m6_name = get_model(train, dataset_name, model_name='nnprobmf')
m7, m7_name = get_model(train, dataset_name, model_name='ItemKNNCF')
m8, m8_name = get_model(train, dataset_name, model_name='UserKNNCF')
m9, m9_name = get_model(train, dataset_name, model_name='PureSVD')
if dataset_name != 'Movielens20M':
m10, m10_name = get_model(
train, dataset_name, model_name='SLIM_BPR_Cython')
s = models_comparison_items_pop_analysis(
[m6, m5, m4, m3, m2, m1, m9, m10, m8, m7], [m6_name, m5_name, m4_name, m3_name, m2_name, m1_name, m9_name, m10_name, m8_name, m7_name], thrs, validation.get_URM(), dataset_name)
else:
s = models_comparison_items_pop_analysis(
[m6, m5, m4, m3, m2, m1, m9, m8, m7], [m6_name, m5_name, m4_name, m3_name, m2_name, m1_name, m9_name, m8_name, m7_name], thrs, validation.get_URM(), dataset_name)
print(s)
def recommended_items_popularity_analysis():
thrs = [0.66, ]
train, test, validation, dataset_name = retrieve_train_validation_test_holdhout_dataset()
_recommended_items_popularity_analysis(
thrs, train, test, validation, dataset_name, )
if __name__ == '__main__':
recommended_items_popularity_analysis() | RecSysFramework/Experiments/recommended_items_popularity_analysis.py | import numpy as np
from RecSysFramework.Recommender.MatrixFactorization.MatrixFactorization_Cython import BPR_NNMF, BPRMF, FUNK_NNMF, FunkSVD
from RecSysFramework.Recommender.MatrixFactorization.PureSVD import PureSVD
from RecSysFramework.Recommender.KNN.ItemKNNCFRecommender import ItemKNNCF
from RecSysFramework.Recommender.KNN.UserKNNCFRecommender import UserKNNCF
from RecSysFramework.DataManager.Splitter import Holdout
from RecSysFramework.Evaluation.Evaluator import EvaluatorHoldout
from RecSysFramework.DataManager.DatasetPostprocessing.ImplicitURM import ImplicitURM
from RecSysFramework.DataManager.DatasetPostprocessing.KCore import KCore
from tqdm import tqdm
import RecSysFramework.Utils.compute_popularity as cp
from RecSysFramework.Utils.get_holdout import retrieve_train_validation_test_holdhout_dataset
import pandas as pd
import matplotlib.pyplot as plt
from RecSysFramework.Utils.get_model_from_best_models import get_model
from RecSysFramework.Utils import menu
from collections import OrderedDict
from RecSysFramework.Experiments.utils_experiments import round_all_digits
def recommend_batch(recommender_object, users, remove_seen_flag=True, cutoff=5, remove_top_pop_flag=False):
recs = []
size = 1000
n_users = len(users)
n_batch = n_users // size
for idx in range(n_batch):
recs += recommender_object.recommend(
users[size * idx: size *
(idx + 1)], remove_seen_flag=remove_seen_flag, cutoff=cutoff,
remove_top_pop_flag=remove_top_pop_flag, return_scores=True)[0]
recs += recommender_object.recommend(
users[(size * n_batch) %
n_users: n_users], remove_seen_flag=remove_seen_flag, cutoff=cutoff,
remove_top_pop_flag=remove_top_pop_flag, return_scores=True)[0]
return np.array(recs)
def rec_items_pop_analysis(urm_train, cut_list, recs):
"""
plot the percentage of items recommended in every popularity section
"""
# initialize an empty vector of equal length of the items in the dataset
# we will accumulate on this the number of times that the recommender recommend an
# item
items_predictions_num = np.zeros(urm_train.shape[1])
for user_recs in tqdm(recs):
items_predictions_num[user_recs] += 1
item_pop_tuple_list = cp.compute_popularity_item(urm_train)
items_idxs, interactions = zip(*item_pop_tuple_list)
interactions_cumsum = np.cumsum(interactions)
interactions_cumsum_norm = interactions_cumsum/max(interactions_cumsum)
cut_idxs = []
for cut_perc in cut_list:
cut_idx = (np.abs(interactions_cumsum_norm - cut_perc)).argmin()
cut_idxs.append(cut_idx)
items_partition = np.split(items_idxs, cut_idxs)
items_prediction_cuts = []
for partition in items_partition:
items_prediction_cuts.append(np.sum(items_predictions_num[partition]))
items_prediction_cuts_norm = items_prediction_cuts / \
np.sum(items_prediction_cuts)
print(items_prediction_cuts_norm)
return items_prediction_cuts_norm
def rec_and_hit_items_pop_analysis(urm_train, urm_validation, cut_list, recs):
"""
plot the percentage of items recommended and hit in every popularity section
"""
# initialize an empty vector of equal length of the items in the dataset
# we will accumulate on this the number of times that the recommender recommend an
# item and hit it
items_predictions_num = np.zeros(urm_train.shape[1])
for idx, user_recs in enumerate(recs):
items_to_be_hit_user = urm_validation.indices[urm_validation.indptr[idx]
:urm_validation.indptr[idx+1]]
user_recs_hit = list(set(items_to_be_hit_user) & set(user_recs))
if len(user_recs_hit) > 0:
items_predictions_num[np.array(user_recs_hit, dtype=np.int)] += 1
item_pop_tuple_list = cp.compute_popularity_item(urm_train)
items_idxs, interactions = zip(*item_pop_tuple_list)
interactions_cumsum = np.cumsum(interactions)
interactions_cumsum_norm = interactions_cumsum/max(interactions_cumsum)
cut_idxs = []
for cut_perc in cut_list:
cut_idx = (np.abs(interactions_cumsum_norm - cut_perc)).argmin()
cut_idxs.append(cut_idx)
items_partition = np.split(items_idxs, cut_idxs)
items_prediction_cuts = []
for partition in items_partition:
items_prediction_cuts.append(np.sum(items_predictions_num[partition]))
items_prediction_cuts_norm = items_prediction_cuts / \
np.sum(items_prediction_cuts)
print(items_prediction_cuts_norm)
return items_prediction_cuts_norm, np.array(items_prediction_cuts)
def models_comparison_items_pop_analysis(recs, names, thrs, urm_validation, dataset_name):
s = ''
pop_recs = []
pop_recs_hit_perc = []
pop_recs_hit = []
for rec, name in zip(recs, names):
recommendations = recommend_batch(
rec, np.arange(rec.URM_train.shape[0]))
pop_recs.append(rec_items_pop_analysis(
rec.URM_train, thrs, recommendations, ))
rec_and_hit_perc, rec_and_hit = rec_and_hit_items_pop_analysis(
rec.URM_train, urm_validation, thrs, recommendations, )
pop_recs_hit_perc.append(rec_and_hit_perc)
pop_recs_hit.append(rec_and_hit)
file_name = 'predicted_items_pop_{}'.format(
dataset_name).replace(' ', '_')
analysis_df = pd.DataFrame({name: pop*100 for name, pop in zip(names, pop_recs)},
index=['Long tail', 'Short head'])
ax = analysis_df.T.plot.barh(stacked=True, rot=0)
ax.set_xlabel('Percentage')
ax.get_yticklabels()[0].set_fontweight('bold')
ax.get_yticklabels()[2].set_fontweight('bold')
ax.get_yticklabels()[4].set_fontweight('bold')
ax.margins(x=0)
for idx, p in enumerate(ax.patches):
x, y = p.get_xy()
if x == 0:
if idx in [0, 2, 4]:
width = p.get_width()
ax.text(7+p.get_width(), p.get_y()+0.5*p.get_height(),
'{:1.1f}%'.format(width),
ha='center', va='center', fontweight='bold',)
else:
width = p.get_width()
ax.text(7+p.get_width(), p.get_y()+0.5*p.get_height(),
'{:1.1f}%'.format(width),
ha='center', va='center', )
file_name = 'distr_recs_hits_{}'.format(
dataset_name).replace(' ', '_')
s += gen_latex_code('Distribution of popular and not popular items recommended by the algorithms. Bold highlights NNMFs. The dataset is: ' +
dataset_name + '.', file_name) + '.\n'
plt.savefig(file_name, bbox_inches='tight')
return s
def gen_latex_code(caption, file_name):
return '\\begin{figure}[H] \n \
\\includegraphics[width=1\\textwidth]{pictures/' + file_name + '.png} \n \
\\centering \n \
\\caption{' + caption + '} \n \
\\label{fig:' + file_name + '} \n \
\end{figure}'
def _recommended_items_popularity_analysis(thrs, train, test, validation, dataset_name, ):
"""runs the analysis on popularity bins GIVEN A DATASET
moreover, saves the images and generate latex code that allows to
import the image directly in latex
"""
m1, m1_name = get_model(train, dataset_name, model_name='BPRMF')
m2, m2_name = get_model(train, dataset_name, model_name='BPR_NNMF')
m3, m3_name = get_model(train, dataset_name, model_name='FunkSVD')
m4, m4_name = get_model(train, dataset_name, model_name='FUNK_NNMF')
m5, m5_name = get_model(train, dataset_name, model_name='probmf')
m6, m6_name = get_model(train, dataset_name, model_name='nnprobmf')
m7, m7_name = get_model(train, dataset_name, model_name='ItemKNNCF')
m8, m8_name = get_model(train, dataset_name, model_name='UserKNNCF')
m9, m9_name = get_model(train, dataset_name, model_name='PureSVD')
if dataset_name != 'Movielens20M':
m10, m10_name = get_model(
train, dataset_name, model_name='SLIM_BPR_Cython')
s = models_comparison_items_pop_analysis(
[m6, m5, m4, m3, m2, m1, m9, m10, m8, m7], [m6_name, m5_name, m4_name, m3_name, m2_name, m1_name, m9_name, m10_name, m8_name, m7_name], thrs, validation.get_URM(), dataset_name)
else:
s = models_comparison_items_pop_analysis(
[m6, m5, m4, m3, m2, m1, m9, m8, m7], [m6_name, m5_name, m4_name, m3_name, m2_name, m1_name, m9_name, m8_name, m7_name], thrs, validation.get_URM(), dataset_name)
print(s)
def recommended_items_popularity_analysis():
thrs = [0.66, ]
train, test, validation, dataset_name = retrieve_train_validation_test_holdhout_dataset()
_recommended_items_popularity_analysis(
thrs, train, test, validation, dataset_name, )
if __name__ == '__main__':
recommended_items_popularity_analysis() | 0.539469 | 0.236494 |
from json import dumps
from unittest import TestCase, mock
from unittest.mock import Mock
import data_gathering_subsystem.data_modules.air_pollution.air_pollution as air_pollution
class TestAirPollution(TestCase):
@classmethod
def setUp(cls):
air_pollution.instance(log_to_stdout=False, log_to_telegram=False).remove_files()
def tearDown(self):
if hasattr(self, 'data_collector'):
self.data_collector.remove_files()
def test_instance(self):
self.assertIs(air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False),
air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False))
i1 = air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False)
i1._transition_state = i1._FINISHED
self.assertIsNot(i1, air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False))
@mock.patch('requests.get')
def test_correct_data_collection(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(1, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_correct_data_collection_with_more_items_than_allowed_requests(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], 1)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(1, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNotNone(self.data_collector.state['start_index'])
self.assertEqual(1, self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MIN_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
def test_data_collection_with_no_locations(self):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MIN_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_invalid_data_from_server(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({'data': ['invalid', 'data', 'structure']}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_rejected_request_from_server(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "error", "message": "Over quota"}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_not_all_items_saved(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1},
{'location_id': 2, 'name': 'Brampton, Ontario', 'waqi_station_id': 2}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(2, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_no_items_saved(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1},
{'location_id': 2, 'name': 'Brampton, Ontario', 'waqi_station_id': 2}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(2, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency']) | data_gathering_subsystem/test/data_modules/test_air_pollution.py | from json import dumps
from unittest import TestCase, mock
from unittest.mock import Mock
import data_gathering_subsystem.data_modules.air_pollution.air_pollution as air_pollution
class TestAirPollution(TestCase):
@classmethod
def setUp(cls):
air_pollution.instance(log_to_stdout=False, log_to_telegram=False).remove_files()
def tearDown(self):
if hasattr(self, 'data_collector'):
self.data_collector.remove_files()
def test_instance(self):
self.assertIs(air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False),
air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False))
i1 = air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False)
i1._transition_state = i1._FINISHED
self.assertIsNot(i1, air_pollution.instance(log_to_file=False, log_to_stdout=False, log_to_telegram=False))
@mock.patch('requests.get')
def test_correct_data_collection(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(1, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_correct_data_collection_with_more_items_than_allowed_requests(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], 1)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(1, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNotNone(self.data_collector.state['start_index'])
self.assertEqual(1, self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MIN_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
def test_data_collection_with_no_locations(self):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(self.data_collector.finished_execution())
self.assertTrue(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MIN_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_invalid_data_from_server(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({'data': ['invalid', 'data', 'structure']}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_rejected_request_from_server(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "error", "message": "Over quota"}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(0, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_not_all_items_saved(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1},
{'location_id': 2, 'name': 'Brampton, Ontario', 'waqi_station_id': 2}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 1, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(2, self.data_collector.state['data_elements'])
self.assertEqual(1, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency'])
@mock.patch('requests.get')
def test_data_collection_with_no_items_saved(self, mock_requests):
# Mocking MongoDBCollection: initialization and operations
mock_collection = Mock()
mock_collection.close.return_value = None
mock_collection.find.return_value = ([{'location_id': 1, 'name': 'Belleville', 'waqi_station_id': 1},
{'location_id': 2, 'name': 'Brampton, Ontario', 'waqi_station_id': 2}], None)
mock_collection.bulk_write.return_value = insert_result = Mock()
insert_result.bulk_api_result = {'nInserted': 0, 'nMatched': 0, 'nUpserted': 0}
# Mocking requests (get and response content)
mock_requests.return_value = response = Mock()
response.content = dumps({"status": "ok", "data": {"aqi": 25, "idx": 1, "attributions": [
{"url": "http://www.airqualityontario.com/",
"name": "Air Quality Ontario - the Ontario Ministry of the Environment and Climate Change"}],
"city": {"geo": [44.150528, -77.3955], "name": "Belleville, Ontario",
"url": "http://aqicn.org/city/canada/ontario/belleville/"}, "dominentpol": "o3",
"iaqi": {"h": {"v": 63}, "no2": {"v": 3.8}, "o3": {"v": 24.8}, "p": {"v": 1026}, "pm25": {"v": 13},
"t": {"v": -20.85}}, "time": {"s": "2017-12-31 05:00:00", "tz": "-05:00", "v": 1514696400}}}).encode()
# Actual execution
self.data_collector = air_pollution.instance(log_to_stdout=False, log_to_telegram=False)
self.data_collector.collection = mock_collection
self.data_collector.run()
self.assertTrue(mock_collection.method_calls)
self.assertTrue(mock_requests.called)
self.assertTrue(self.data_collector.finished_execution())
self.assertFalse(self.data_collector.successful_execution())
self.assertIsNotNone(self.data_collector.state['data_elements'])
self.assertIsNotNone(self.data_collector.state['inserted_elements'])
self.assertEqual(2, self.data_collector.state['data_elements'])
self.assertEqual(0, self.data_collector.state['inserted_elements'])
self.assertIsNone(self.data_collector.state['start_index'])
self.assertEqual(self.data_collector.config['MAX_UPDATE_FREQUENCY'],
self.data_collector.state['update_frequency']) | 0.616128 | 0.525551 |
import settings
from utils import get_most_recent
from periscope_client import PeriscopeClient
logger = settings.get_logger('unis_client')
class UNISInstance:
def __init__(self, service):
self.service = service
self.config = service["properties"]["configurations"]
unis_url=self.config["unis_url"]
if unis_url and unis_url[-1]=="/":
unis_url = unis_url[:-1]
self.pc = PeriscopeClient(service, unis_url)
self.meas_to_mds = {}
def post(self, url, data={}):
return self.pc.do_req('post', url, data)
def get(self, url, data=None):
return self.pc.do_req('get', url, data)
def delete(self, url, data=None):
return self.pc.do_req('delete', url, data)
def put(self, url, data=None):
if "ts" in data:
del data["ts"]
return self.pc.do_req('put', url, data)
def find_or_create_metadata(self, subject, metric, measurement):
if not measurement["id"] in self.meas_to_mds:
mds = self.get("/metadata?parameters.measurement.href=" + measurement["selfRef"])
if mds:
self.meas_to_mds[measurement["id"]] = mds
mds = self.meas_to_mds.get(measurement["id"], [])
for md in mds:
if md["subject"]["href"] == subject and md["eventType"] == metric:
return md
post_dict = {
"$schema": settings.SCHEMAS["metadata"],
"subject": {
"href": subject,
"rel": "full"
},
"eventType": metric,
"parameters": {
"datumSchema": settings.SCHEMAS["datum"],
"measurement": {
"href": measurement["selfRef"],
"rel": "full"
}
}
}
return self.pc.do_req("post", "/metadata", data=post_dict)
def post_port(self, post_dict, headers=None):
if "$schema" not in post_dict:
post_dict.update({"$schema":settings.SCHEMAS['ports']})
if "urn" not in post_dict:
post_dict.update({"urn":settings.HOST_URN + "port=" + \
post_dict.get("name", "")})
if "location" not in post_dict and "location" in self.service:
post_dict.update({"location": self.service["location"]})
port_post = self.pc.do_req("post", "/ports", data=post_dict)
# Update the node to have these ports as well
if port_post:
node_rep = self.get(self.service["runningOn"]["href"])
if isinstance(node_rep, list):
node_rep = get_most_recent(node_rep)
if len(node_rep) == 1:
node_rep = node_rep[0]
node_rep.setdefault("ports", []).append({"href":port_post["selfRef"],
"rel": "full"})
self.put(node_rep["selfRef"], data=node_rep)
return port_post | blipp/unis_client.py | import settings
from utils import get_most_recent
from periscope_client import PeriscopeClient
logger = settings.get_logger('unis_client')
class UNISInstance:
def __init__(self, service):
self.service = service
self.config = service["properties"]["configurations"]
unis_url=self.config["unis_url"]
if unis_url and unis_url[-1]=="/":
unis_url = unis_url[:-1]
self.pc = PeriscopeClient(service, unis_url)
self.meas_to_mds = {}
def post(self, url, data={}):
return self.pc.do_req('post', url, data)
def get(self, url, data=None):
return self.pc.do_req('get', url, data)
def delete(self, url, data=None):
return self.pc.do_req('delete', url, data)
def put(self, url, data=None):
if "ts" in data:
del data["ts"]
return self.pc.do_req('put', url, data)
def find_or_create_metadata(self, subject, metric, measurement):
if not measurement["id"] in self.meas_to_mds:
mds = self.get("/metadata?parameters.measurement.href=" + measurement["selfRef"])
if mds:
self.meas_to_mds[measurement["id"]] = mds
mds = self.meas_to_mds.get(measurement["id"], [])
for md in mds:
if md["subject"]["href"] == subject and md["eventType"] == metric:
return md
post_dict = {
"$schema": settings.SCHEMAS["metadata"],
"subject": {
"href": subject,
"rel": "full"
},
"eventType": metric,
"parameters": {
"datumSchema": settings.SCHEMAS["datum"],
"measurement": {
"href": measurement["selfRef"],
"rel": "full"
}
}
}
return self.pc.do_req("post", "/metadata", data=post_dict)
def post_port(self, post_dict, headers=None):
if "$schema" not in post_dict:
post_dict.update({"$schema":settings.SCHEMAS['ports']})
if "urn" not in post_dict:
post_dict.update({"urn":settings.HOST_URN + "port=" + \
post_dict.get("name", "")})
if "location" not in post_dict and "location" in self.service:
post_dict.update({"location": self.service["location"]})
port_post = self.pc.do_req("post", "/ports", data=post_dict)
# Update the node to have these ports as well
if port_post:
node_rep = self.get(self.service["runningOn"]["href"])
if isinstance(node_rep, list):
node_rep = get_most_recent(node_rep)
if len(node_rep) == 1:
node_rep = node_rep[0]
node_rep.setdefault("ports", []).append({"href":port_post["selfRef"],
"rel": "full"})
self.put(node_rep["selfRef"], data=node_rep)
return port_post | 0.381911 | 0.223992 |
from abc import ABC
from nerdchess.config import MOVE_REGEX, letterlist, numbers
class Move(ABC):
"""
Represents a move in a game of chess.
Parameters:
move(String): A string that's tested with the regex
'[a-h][1-8][a-h][1-8]'
Attributes:
text(String): String representation of the move r'[a-h][1-8][a-h][1-8]'
origin(String): String representation of the origin square
destination(String): String representation of the destination square
horizontal(int): Amount of horizontal steps in the move
vertical(int): Amount of vertical steps in the move
indices(dict): Origin/destination letter(x)/number(y) mapped to their
list position
"""
def __init__(self, move, *args, **kwargs):
"""Init."""
valid_move = MOVE_REGEX.match(move)
if not valid_move:
raise ValueError('Invalid move')
self.text = move
self.origin = move[:2]
self.destination = move[2:]
self.indices = {
'or': {
'x': letterlist.index(self.origin[0]),
'y': numbers.index(int(self.origin[1]))
},
'dest': {
'x': letterlist.index(self.destination[0]),
'y': numbers.index(int(self.destination[1]))
}
}
(self.horizontal,
self.vertical) = self.get_steps()
@classmethod
def from_position(cls, position, steps):
"""Create a move based on the current position and steps (hori/verti).
Parameters:
position(String): The current position (eg. a1)
steps(tuple(int, int)): The steps taken in the move
Returns:
Move: A new move instance
"""
(letter_steps, number_steps) = steps
current_letter_index = letterlist.index(position[0])
current_number_index = numbers.index(int(position[1]))
new_letter_index = current_letter_index + letter_steps
new_number_index = current_number_index + number_steps
if new_letter_index >= 0 and new_number_index >= 0:
new_letter = letterlist[new_letter_index]
new_number = numbers[new_number_index]
else:
return None
move = "{}{}{}".format(position, new_letter, new_number)
return cls(move)
def square_selectors_between(self):
"""Return selectors of squares between the origin and destination.
Returns:
list(String): A list of selectors of squares.
"""
squares = []
steps = 0
step_range = 0
if self.horizontal == 1 or self.vertical == 1:
return squares
if self.horizontal == -1 or self.vertical == -1:
return squares
h_steps = 1 if self.horizontal > 0 else -1
v_steps = 1 if self.vertical > 0 else -1
if self.is_diagonal():
steps = h_steps
step_range = self.horizontal
elif self.is_horizontal():
v_steps = 0
steps = h_steps
step_range = self.horizontal
elif self.is_vertical():
h_steps = 0
steps = v_steps
step_range = self.vertical
h_counter = h_steps
v_counter = v_steps
for i in range(steps, step_range, steps):
step_index_h = self.indices['or']['x'] + h_counter
step_index_v = self.indices['or']['y'] + v_counter
if step_index_v < 0 or step_index_h < 0:
h_counter = h_counter + h_steps
v_counter = v_counter + v_steps
continue
letter = letterlist[step_index_h]
number = numbers[step_index_v]
square = f"{letter}{number}"
squares.append(square)
h_counter = h_counter + h_steps
v_counter = v_counter + v_steps
return squares
def is_diagonal(self):
"""Is the move diagonal."""
if self.horizontal == 0 or self.vertical == 0:
return False
if not abs(self.horizontal) == abs(self.vertical):
return False
return True
def is_horizontal(self):
"""Is the move horizontal (only)."""
if self.horizontal == 0:
return False
if self.vertical != 0:
return False
return True
def is_vertical(self):
"""Is the move vertical (only)."""
if self.vertical == 0:
return False
if self.horizontal != 0:
return False
return True
def get_steps(self):
"""Return the horizontal/vertical steps of the move."""
horizontal_steps = self.indices['dest']['x'] - \
self.indices['or']['x']
vertical_steps = self.indices['dest']['y'] - \
self.indices['or']['y']
return (horizontal_steps, vertical_steps)
def __eq__(self, item):
"""Describe how to compare a Move."""
if isinstance(item, Move):
return self.text == item.text
try:
return self.text == str(item)
except TypeError:
return NotImplemented
def __str__(self):
"""Text representation of a Move."""
return self.text | nerdchess/move.py | from abc import ABC
from nerdchess.config import MOVE_REGEX, letterlist, numbers
class Move(ABC):
"""
Represents a move in a game of chess.
Parameters:
move(String): A string that's tested with the regex
'[a-h][1-8][a-h][1-8]'
Attributes:
text(String): String representation of the move r'[a-h][1-8][a-h][1-8]'
origin(String): String representation of the origin square
destination(String): String representation of the destination square
horizontal(int): Amount of horizontal steps in the move
vertical(int): Amount of vertical steps in the move
indices(dict): Origin/destination letter(x)/number(y) mapped to their
list position
"""
def __init__(self, move, *args, **kwargs):
"""Init."""
valid_move = MOVE_REGEX.match(move)
if not valid_move:
raise ValueError('Invalid move')
self.text = move
self.origin = move[:2]
self.destination = move[2:]
self.indices = {
'or': {
'x': letterlist.index(self.origin[0]),
'y': numbers.index(int(self.origin[1]))
},
'dest': {
'x': letterlist.index(self.destination[0]),
'y': numbers.index(int(self.destination[1]))
}
}
(self.horizontal,
self.vertical) = self.get_steps()
@classmethod
def from_position(cls, position, steps):
"""Create a move based on the current position and steps (hori/verti).
Parameters:
position(String): The current position (eg. a1)
steps(tuple(int, int)): The steps taken in the move
Returns:
Move: A new move instance
"""
(letter_steps, number_steps) = steps
current_letter_index = letterlist.index(position[0])
current_number_index = numbers.index(int(position[1]))
new_letter_index = current_letter_index + letter_steps
new_number_index = current_number_index + number_steps
if new_letter_index >= 0 and new_number_index >= 0:
new_letter = letterlist[new_letter_index]
new_number = numbers[new_number_index]
else:
return None
move = "{}{}{}".format(position, new_letter, new_number)
return cls(move)
def square_selectors_between(self):
"""Return selectors of squares between the origin and destination.
Returns:
list(String): A list of selectors of squares.
"""
squares = []
steps = 0
step_range = 0
if self.horizontal == 1 or self.vertical == 1:
return squares
if self.horizontal == -1 or self.vertical == -1:
return squares
h_steps = 1 if self.horizontal > 0 else -1
v_steps = 1 if self.vertical > 0 else -1
if self.is_diagonal():
steps = h_steps
step_range = self.horizontal
elif self.is_horizontal():
v_steps = 0
steps = h_steps
step_range = self.horizontal
elif self.is_vertical():
h_steps = 0
steps = v_steps
step_range = self.vertical
h_counter = h_steps
v_counter = v_steps
for i in range(steps, step_range, steps):
step_index_h = self.indices['or']['x'] + h_counter
step_index_v = self.indices['or']['y'] + v_counter
if step_index_v < 0 or step_index_h < 0:
h_counter = h_counter + h_steps
v_counter = v_counter + v_steps
continue
letter = letterlist[step_index_h]
number = numbers[step_index_v]
square = f"{letter}{number}"
squares.append(square)
h_counter = h_counter + h_steps
v_counter = v_counter + v_steps
return squares
def is_diagonal(self):
"""Is the move diagonal."""
if self.horizontal == 0 or self.vertical == 0:
return False
if not abs(self.horizontal) == abs(self.vertical):
return False
return True
def is_horizontal(self):
"""Is the move horizontal (only)."""
if self.horizontal == 0:
return False
if self.vertical != 0:
return False
return True
def is_vertical(self):
"""Is the move vertical (only)."""
if self.vertical == 0:
return False
if self.horizontal != 0:
return False
return True
def get_steps(self):
"""Return the horizontal/vertical steps of the move."""
horizontal_steps = self.indices['dest']['x'] - \
self.indices['or']['x']
vertical_steps = self.indices['dest']['y'] - \
self.indices['or']['y']
return (horizontal_steps, vertical_steps)
def __eq__(self, item):
"""Describe how to compare a Move."""
if isinstance(item, Move):
return self.text == item.text
try:
return self.text == str(item)
except TypeError:
return NotImplemented
def __str__(self):
"""Text representation of a Move."""
return self.text | 0.93627 | 0.541894 |
import base64
import endpoints
import json
import os
from google.appengine.api import mail
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from models import PrivateKeys
from models import Unsubscribed
from protorpc import remote
from subscribe_api_messages import RequestMessage
from subscribe_api_messages import ResponseMessage
PRIVATE_KEYS = ['your_application_specific_private_key']
def send(message):
"""Send email for given message object."""
message.send()
def send_emails(request):
"""Send emails to given emails addresses with provided body."""
message = mail.EmailMessage(sender=request.sender,
subject=request.subject)
private_obj = PrivateKeys.get_or_add(
private_key=request.private_key)
for email_obj in request.email_addresses:
email_address = email_obj.email_address
if Unsubscribed.is_exist(email_address):
continue
body_path = os.path.join(
os.path.dirname(__file__), 'templates/body.html')
encrypt_email = base64.b64encode(
json.dumps({'email_address': email_address,
'pid': private_obj.key().id_or_name()}))
unsubscribe_url = 'https://%s/unsubscribe?id=%s' % (
os.environ['HTTP_HOST'], encrypt_email)
message.html = template.render(
body_path, {'unsubscribe_url': unsubscribe_url,
'body': request.body,
'email_address': email_address})
if request.reply_to:
message.reply_to = request.reply_to
message.to = email_address
if request.async:
deferred.defer(send, message, _queue='email')
else:
send(message)
return True
@endpoints.api(name='subscribe', version='v1',
description='Subscribe API',
title='Subscribe Service')
class SubscribeApi(remote.Service):
"""Class which defines subscibe API v1."""
@endpoints.method(RequestMessage, ResponseMessage,
path='send', http_method='POST',
name='send.emails')
def subscribe_send(self, request):
"""Exposes an API endpoint to send emails for the given email addresses.
Args:
request: An instance of RequestMessage parsed from the API
request.
Returns:
An instance of ResponseMessage containing the status of request.
"""
if request.private_key not in PRIVATE_KEYS:
raise endpoints.UnauthorizedException('Unauthorize Application.')
send_emails(request)
return ResponseMessage(success=True)
APPLICATION = endpoints.api_server([SubscribeApi],
restricted=False) | subscribe_api.py | import base64
import endpoints
import json
import os
from google.appengine.api import mail
from google.appengine.ext import deferred
from google.appengine.ext.webapp import template
from models import PrivateKeys
from models import Unsubscribed
from protorpc import remote
from subscribe_api_messages import RequestMessage
from subscribe_api_messages import ResponseMessage
PRIVATE_KEYS = ['your_application_specific_private_key']
def send(message):
"""Send email for given message object."""
message.send()
def send_emails(request):
"""Send emails to given emails addresses with provided body."""
message = mail.EmailMessage(sender=request.sender,
subject=request.subject)
private_obj = PrivateKeys.get_or_add(
private_key=request.private_key)
for email_obj in request.email_addresses:
email_address = email_obj.email_address
if Unsubscribed.is_exist(email_address):
continue
body_path = os.path.join(
os.path.dirname(__file__), 'templates/body.html')
encrypt_email = base64.b64encode(
json.dumps({'email_address': email_address,
'pid': private_obj.key().id_or_name()}))
unsubscribe_url = 'https://%s/unsubscribe?id=%s' % (
os.environ['HTTP_HOST'], encrypt_email)
message.html = template.render(
body_path, {'unsubscribe_url': unsubscribe_url,
'body': request.body,
'email_address': email_address})
if request.reply_to:
message.reply_to = request.reply_to
message.to = email_address
if request.async:
deferred.defer(send, message, _queue='email')
else:
send(message)
return True
@endpoints.api(name='subscribe', version='v1',
description='Subscribe API',
title='Subscribe Service')
class SubscribeApi(remote.Service):
"""Class which defines subscibe API v1."""
@endpoints.method(RequestMessage, ResponseMessage,
path='send', http_method='POST',
name='send.emails')
def subscribe_send(self, request):
"""Exposes an API endpoint to send emails for the given email addresses.
Args:
request: An instance of RequestMessage parsed from the API
request.
Returns:
An instance of ResponseMessage containing the status of request.
"""
if request.private_key not in PRIVATE_KEYS:
raise endpoints.UnauthorizedException('Unauthorize Application.')
send_emails(request)
return ResponseMessage(success=True)
APPLICATION = endpoints.api_server([SubscribeApi],
restricted=False) | 0.569853 | 0.052863 |
import os
import posixpath
from typing import Callable
from fastapi import APIRouter, File, UploadFile, Depends, Query, Form, Body
from fastapi.responses import JSONResponse
from utils import http
from utils.security import safe_join
from ..config import get_upload
from ..schemas.upload_schema import UploadSchema
router = APIRouter(prefix="/upload")
@router.get("/{upload_key}", tags=["file-upload"])
def check_upload(
upload: Callable[[str], str] = Depends(get_upload),
check_number: int = Query(..., alias="chunkNumber", description="当前块编号,默认从1开始"),
chunk_size: int = Query(..., alias="chunkSize", description="期望块大小"),
current_chunk_size: int = Query(..., alias="currentChunkSize", description="当前块实际大小"),
total_size: int = Query(..., alias="totalSize", description="文件总大小"),
identifier: str = Query(..., alias="identifier", description="文件唯一标识"),
filename: str = Query(..., alias="filename", description="文件原始名称"),
relative_path: str = Query(..., alias="relativePath", description="文件相对路径"),
total_chunks: int = Query(..., alias="totalChunks", description="总块数"),
):
"""
检测上传块是否存在::
- 404: 校验块不存在
- [200, 201, 202]: 校验块存在
- [400, 415, 500, 501]: 接口请求错误
使用simple-upload.js::
https://github.com/simple-uploader/Uploader/blob/develop/README_zh-CN.md
new Uploader({
target: 'http://1192.168.127.12:5000/upload/default',
singleFile: true,
simultaneousUploads: 5,
chunkSize: 1024 * 1024 * 10,
successStatuses: [200, 201, 202],
permanentErrors: [400, 415, 500, 501],
testChunks: false,
allowDuplicateUploads: false
})
:param total_chunks:
:param relative_path:
:param filename:
:param identifier:
:param total_size:
:param current_chunk_size:
:param chunk_size:
:param check_number:
:param upload: 上传文件位置
:return:
"""
return JSONResponse(content=http.fail(), status_code=404)
@router.post("/{upload_key}", tags=["file-upload"])
def post_upload(
upload: Callable[[str], str] = Depends(get_upload),
check_number: int = Form(..., alias="chunkNumber", description="当前块编号,默认从1开始"),
chunk_size: int = Form(..., alias="chunkSize", description="期望块大小"),
current_chunk_size: int = Form(..., alias="currentChunkSize", description="当前块实际大小"),
total_size: int = Form(..., alias="totalSize", description="文件总大小"),
identifier: str = Form(..., alias="identifier", description="文件唯一标识"),
filename: str = Form(..., alias="filename", description="文件原始名称"),
relative_path: str = Form(..., alias="relativePath", description="文件相对路径"),
total_chunks: int = Form(..., alias="totalChunks", description="总块数"),
file: UploadFile = File(...)
):
"""
文件块上传
:param upload: 上传路径获取函数
:param total_chunks:
:param relative_path:
:param filename:
:param identifier:
:param total_size:
:param current_chunk_size:
:param chunk_size:
:param check_number:
:param file: 文件实体
:return:
"""
folder = upload(identifier)
with open(safe_join(folder, str(check_number)), "wb") as fp:
for data in file.file:
fp.write(data)
file.file.close()
return http.ok()
@router.put("/{upload_key}", tags=["file-upload"])
def merge_upload(
upload: Callable[[str], str] = Depends(get_upload),
upload_schema: UploadSchema = Body(..., description="上传文件实体信息")
):
"""
合并文件块完成文件上传
:param upload: 上传路径获取函数
:param upload_schema: 上传文件实体信息
:return:
"""
folder = upload(upload_schema.identifier)
with open(posixpath.join(folder, upload_schema.filename), "wb") as target_fp:
for i in range(1, upload_schema.chunk_size + 1):
chunk_path = posixpath.join(folder, str(i))
with open(chunk_path, "rb") as chunk_fp:
target_fp.write(chunk_fp.read())
target_fp.flush()
os.remove(chunk_path)
return http.ok() | app/file/routes/upload.py | import os
import posixpath
from typing import Callable
from fastapi import APIRouter, File, UploadFile, Depends, Query, Form, Body
from fastapi.responses import JSONResponse
from utils import http
from utils.security import safe_join
from ..config import get_upload
from ..schemas.upload_schema import UploadSchema
router = APIRouter(prefix="/upload")
@router.get("/{upload_key}", tags=["file-upload"])
def check_upload(
upload: Callable[[str], str] = Depends(get_upload),
check_number: int = Query(..., alias="chunkNumber", description="当前块编号,默认从1开始"),
chunk_size: int = Query(..., alias="chunkSize", description="期望块大小"),
current_chunk_size: int = Query(..., alias="currentChunkSize", description="当前块实际大小"),
total_size: int = Query(..., alias="totalSize", description="文件总大小"),
identifier: str = Query(..., alias="identifier", description="文件唯一标识"),
filename: str = Query(..., alias="filename", description="文件原始名称"),
relative_path: str = Query(..., alias="relativePath", description="文件相对路径"),
total_chunks: int = Query(..., alias="totalChunks", description="总块数"),
):
"""
检测上传块是否存在::
- 404: 校验块不存在
- [200, 201, 202]: 校验块存在
- [400, 415, 500, 501]: 接口请求错误
使用simple-upload.js::
https://github.com/simple-uploader/Uploader/blob/develop/README_zh-CN.md
new Uploader({
target: 'http://1192.168.127.12:5000/upload/default',
singleFile: true,
simultaneousUploads: 5,
chunkSize: 1024 * 1024 * 10,
successStatuses: [200, 201, 202],
permanentErrors: [400, 415, 500, 501],
testChunks: false,
allowDuplicateUploads: false
})
:param total_chunks:
:param relative_path:
:param filename:
:param identifier:
:param total_size:
:param current_chunk_size:
:param chunk_size:
:param check_number:
:param upload: 上传文件位置
:return:
"""
return JSONResponse(content=http.fail(), status_code=404)
@router.post("/{upload_key}", tags=["file-upload"])
def post_upload(
upload: Callable[[str], str] = Depends(get_upload),
check_number: int = Form(..., alias="chunkNumber", description="当前块编号,默认从1开始"),
chunk_size: int = Form(..., alias="chunkSize", description="期望块大小"),
current_chunk_size: int = Form(..., alias="currentChunkSize", description="当前块实际大小"),
total_size: int = Form(..., alias="totalSize", description="文件总大小"),
identifier: str = Form(..., alias="identifier", description="文件唯一标识"),
filename: str = Form(..., alias="filename", description="文件原始名称"),
relative_path: str = Form(..., alias="relativePath", description="文件相对路径"),
total_chunks: int = Form(..., alias="totalChunks", description="总块数"),
file: UploadFile = File(...)
):
"""
文件块上传
:param upload: 上传路径获取函数
:param total_chunks:
:param relative_path:
:param filename:
:param identifier:
:param total_size:
:param current_chunk_size:
:param chunk_size:
:param check_number:
:param file: 文件实体
:return:
"""
folder = upload(identifier)
with open(safe_join(folder, str(check_number)), "wb") as fp:
for data in file.file:
fp.write(data)
file.file.close()
return http.ok()
@router.put("/{upload_key}", tags=["file-upload"])
def merge_upload(
upload: Callable[[str], str] = Depends(get_upload),
upload_schema: UploadSchema = Body(..., description="上传文件实体信息")
):
"""
合并文件块完成文件上传
:param upload: 上传路径获取函数
:param upload_schema: 上传文件实体信息
:return:
"""
folder = upload(upload_schema.identifier)
with open(posixpath.join(folder, upload_schema.filename), "wb") as target_fp:
for i in range(1, upload_schema.chunk_size + 1):
chunk_path = posixpath.join(folder, str(i))
with open(chunk_path, "rb") as chunk_fp:
target_fp.write(chunk_fp.read())
target_fp.flush()
os.remove(chunk_path)
return http.ok() | 0.503174 | 0.188735 |
def logic(*args, **kwargs): # More complicated example of custom method. Allows for adding logic gates.
"""
Simple logic gate construct that can take any number of inputs
:param args: first arg is name of gate, all following args are input values
:param kwargs: true=true_condition(default=1) false=false_condition(default=0)
:return: boolean
"""
true = 1
if 'true' in kwargs:
true = kwargs['true']
false = 0
if 'false' in kwargs:
false = kwargs['false']
gate_types = ['AND', 'OR', 'NOT', 'NAND', 'NOR', 'XOR', 'XNOR']
# args[0] is evaluated to find the name of the gate
gate_type = str(args[0])
gate_type = gate_type.upper()
if gate_type not in gate_types:
return "gate not recognized"
if gate_type == 'AND':
for arg in args[1:]: # tests all args excluding the first, as it is the gate name
if arg != true:
return False
return True
if gate_type == 'OR':
for arg in args[1:]:
if arg == true:
return True
return False
if gate_type == 'NOT': # since a NOT gate only takes one argument, any extra will be ignored
for arg in args[1:]:
if arg == true:
return False
else:
return True
if gate_type == 'NAND':
for arg in args[1:]:
if arg == false:
return True
return False
if gate_type == 'NOR':
for arg in args[1:]:
if arg == true:
return False
return True
if gate_type == 'XOR':
x = None
for arg in args[1:]:
if x is None:
if arg == true:
x = True
if arg == false:
x = False
if arg == true:
if x is False:
return True
if arg == false:
if x is True:
return True
return False
if gate_type == 'XNOR':
x = None
for arg in args[1:]:
if x is None:
if arg == true:
x = True
if arg == false:
x = False
if arg == true:
if x is False:
return False
if arg == false:
if x is True:
return False
return True
def filter_logic(test, true_result, false_result): # Very basic function to compliment logic
"""
Function to take in a bool and return a custom value for true or false
:param test: bool
:param true_result:
:param false_result:
:return:
"""
if test:
return true_result
else:
return false_result | sketchymaths/sketchymathmethods/logic.py | def logic(*args, **kwargs): # More complicated example of custom method. Allows for adding logic gates.
"""
Simple logic gate construct that can take any number of inputs
:param args: first arg is name of gate, all following args are input values
:param kwargs: true=true_condition(default=1) false=false_condition(default=0)
:return: boolean
"""
true = 1
if 'true' in kwargs:
true = kwargs['true']
false = 0
if 'false' in kwargs:
false = kwargs['false']
gate_types = ['AND', 'OR', 'NOT', 'NAND', 'NOR', 'XOR', 'XNOR']
# args[0] is evaluated to find the name of the gate
gate_type = str(args[0])
gate_type = gate_type.upper()
if gate_type not in gate_types:
return "gate not recognized"
if gate_type == 'AND':
for arg in args[1:]: # tests all args excluding the first, as it is the gate name
if arg != true:
return False
return True
if gate_type == 'OR':
for arg in args[1:]:
if arg == true:
return True
return False
if gate_type == 'NOT': # since a NOT gate only takes one argument, any extra will be ignored
for arg in args[1:]:
if arg == true:
return False
else:
return True
if gate_type == 'NAND':
for arg in args[1:]:
if arg == false:
return True
return False
if gate_type == 'NOR':
for arg in args[1:]:
if arg == true:
return False
return True
if gate_type == 'XOR':
x = None
for arg in args[1:]:
if x is None:
if arg == true:
x = True
if arg == false:
x = False
if arg == true:
if x is False:
return True
if arg == false:
if x is True:
return True
return False
if gate_type == 'XNOR':
x = None
for arg in args[1:]:
if x is None:
if arg == true:
x = True
if arg == false:
x = False
if arg == true:
if x is False:
return False
if arg == false:
if x is True:
return False
return True
def filter_logic(test, true_result, false_result): # Very basic function to compliment logic
"""
Function to take in a bool and return a custom value for true or false
:param test: bool
:param true_result:
:param false_result:
:return:
"""
if test:
return true_result
else:
return false_result | 0.689096 | 0.397354 |
import torch
import torch.nn as nn
from network.head import *
from network.resnet import *
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
import numpy as np
class ClInfoNCE(nn.Module):
def __init__(self, dim_hidden=2048, dim=128, model='resnet50'):
super(ClInfoNCE, self).__init__()
if model == 'resnet50':
self.net = resnet50()
dim_in = 2048
elif model == 'resnet18':
self.net = resnet18()
dim_in = 512
else:
raise NotImplementedError
self.head1 = ProjectionHead(dim_in=dim_in, dim_out=dim, dim_hidden=dim_hidden)
self.head2 = ProjectionHead(dim_in=dim_in, dim_out=dim, dim_hidden=dim_hidden)
@torch.no_grad()
def build_connected_component(self, dist):
b = dist.size(0)
dist = dist - torch.eye(b, b, device='cuda') * 2
x = torch.arange(b, device='cuda').unsqueeze(1).repeat(1,1).flatten()
y = torch.topk(dist, 1, dim=1, sorted=False)[1].flatten()
rx = torch.cat([x, y]).cpu().numpy()
ry = torch.cat([y, x]).cpu().numpy()
v = np.ones(rx.shape[0])
graph = csr_matrix((v, (rx, ry)), shape=(b,b))
_, labels = connected_components(csgraph=graph, directed=False, return_labels=True)
labels = torch.tensor(labels, device='cuda')
mask = torch.eq(labels.unsqueeze(1), labels.unsqueeze(1).T)
return mask
def build_mask_from_labels(self, labels, rank):
"""build mask from labels,
labels: [all_bz,]
return mask [all_bz, all_bz]
"""
mask = torch.eq(labels.unsqueeze(1), labels.unsqueeze(1).T).float()
mask[range(mask.shape[0]), range(mask.shape[0])] = torch.FloatTensor([1.]).cuda(rank)
return mask
def sup_contra(self, logits, mask, diagnal_mask=None):
if diagnal_mask is not None:
diagnal_mask = 1 - diagnal_mask
mask = mask * diagnal_mask
exp_logits = torch.exp(logits) * diagnal_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
else:
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
mean_log_prob_pos = (mask * log_prob).sum(1) / (mask.sum(1) )
loss = (-mean_log_prob_pos).mean()
return loss
def forward(self, x1, x2=None, t=0.1, cluster_labels=None):
"""labels are 1d tensors that indicating the labels of b"""
world_size = torch.distributed.get_world_size()
rank = torch.distributed.get_rank()
if x2 is None:
bakcbone_feat1 = self.net(x1)
feat1 = F.normalize(self.head1(bakcbone_feat1))
return feat1
b = x1.size(0)
bakcbone_feat1 = self.net(x1)
bakcbone_feat2 = self.net(x2)
feat1 = F.normalize(self.head1(bakcbone_feat1))
feat2 = F.normalize(self.head1(bakcbone_feat2))
other1 = concat_other_gather(feat1)
other2 = concat_other_gather(feat2)
prob = torch.cat([feat1, feat2]) @ torch.cat([feat1, feat2, other1, other2]).T / t
diagnal_mask = (1 - torch.eye(prob.size(0), prob.size(1))).bool().cuda(rank)
logits = torch.masked_select(prob, diagnal_mask).reshape(prob.size(0), -1)
first_half_label = torch.arange(b-1, 2*b-1).long().cuda(rank)
second_half_label = torch.arange(0, b).long().cuda(rank)
labels = torch.cat([first_half_label, second_half_label])
feat1 = F.normalize(self.head2(bakcbone_feat1))
feat2 = F.normalize(self.head2(bakcbone_feat2))
all_feat1 = concat_all_gather(feat1)
all_feat2 = concat_all_gather(feat2)
all_bs = all_feat1.size(0)
# similarly concate and gather all the labels
if cluster_labels is not None:
all_cluster_labels = concat_all_gather(cluster_labels) # all_bz
mask1_list = []
if rank == 0:
mask1 = self.build_mask_from_labels(all_cluster_labels, rank).float() # all_bz, all_bz
mask1_list = list(torch.chunk(mask1, world_size))
mask1 = mask1_list[0]
else:
mask1 = torch.zeros(b, all_bs).cuda(rank)
torch.distributed.scatter(mask1, mask1_list, 0)
diagnal_mask = torch.eye(all_bs, all_bs).cuda(rank)
diagnal_mask = torch.chunk(diagnal_mask, world_size)[rank]
loss1 = self.sup_contra(feat1 @ all_feat2.T / t, mask1)
loss1 += self.sup_contra(feat2 @ all_feat1.T / t, mask1)
loss1 /= 2
else:
loss1 = None
return logits, labels, loss1
# utils
@torch.no_grad()
def concat_other_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
rank = torch.distributed.get_rank()
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor)
other = torch.cat(tensors_gather[:rank] + tensors_gather[rank+1:], dim=0)
return other
@torch.no_grad()
def concat_all_gather(tensor, replace=True):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
rank = torch.distributed.get_rank()
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor)
if replace:
tensors_gather[rank] = tensor
other = torch.cat(tensors_gather, dim=0)
return other | network/clinfo.py | import torch
import torch.nn as nn
from network.head import *
from network.resnet import *
import torch.nn.functional as F
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
import numpy as np
class ClInfoNCE(nn.Module):
def __init__(self, dim_hidden=2048, dim=128, model='resnet50'):
super(ClInfoNCE, self).__init__()
if model == 'resnet50':
self.net = resnet50()
dim_in = 2048
elif model == 'resnet18':
self.net = resnet18()
dim_in = 512
else:
raise NotImplementedError
self.head1 = ProjectionHead(dim_in=dim_in, dim_out=dim, dim_hidden=dim_hidden)
self.head2 = ProjectionHead(dim_in=dim_in, dim_out=dim, dim_hidden=dim_hidden)
@torch.no_grad()
def build_connected_component(self, dist):
b = dist.size(0)
dist = dist - torch.eye(b, b, device='cuda') * 2
x = torch.arange(b, device='cuda').unsqueeze(1).repeat(1,1).flatten()
y = torch.topk(dist, 1, dim=1, sorted=False)[1].flatten()
rx = torch.cat([x, y]).cpu().numpy()
ry = torch.cat([y, x]).cpu().numpy()
v = np.ones(rx.shape[0])
graph = csr_matrix((v, (rx, ry)), shape=(b,b))
_, labels = connected_components(csgraph=graph, directed=False, return_labels=True)
labels = torch.tensor(labels, device='cuda')
mask = torch.eq(labels.unsqueeze(1), labels.unsqueeze(1).T)
return mask
def build_mask_from_labels(self, labels, rank):
"""build mask from labels,
labels: [all_bz,]
return mask [all_bz, all_bz]
"""
mask = torch.eq(labels.unsqueeze(1), labels.unsqueeze(1).T).float()
mask[range(mask.shape[0]), range(mask.shape[0])] = torch.FloatTensor([1.]).cuda(rank)
return mask
def sup_contra(self, logits, mask, diagnal_mask=None):
if diagnal_mask is not None:
diagnal_mask = 1 - diagnal_mask
mask = mask * diagnal_mask
exp_logits = torch.exp(logits) * diagnal_mask
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
else:
exp_logits = torch.exp(logits)
log_prob = logits - torch.log(exp_logits.sum(1, keepdim=True))
mean_log_prob_pos = (mask * log_prob).sum(1) / (mask.sum(1) )
loss = (-mean_log_prob_pos).mean()
return loss
def forward(self, x1, x2=None, t=0.1, cluster_labels=None):
"""labels are 1d tensors that indicating the labels of b"""
world_size = torch.distributed.get_world_size()
rank = torch.distributed.get_rank()
if x2 is None:
bakcbone_feat1 = self.net(x1)
feat1 = F.normalize(self.head1(bakcbone_feat1))
return feat1
b = x1.size(0)
bakcbone_feat1 = self.net(x1)
bakcbone_feat2 = self.net(x2)
feat1 = F.normalize(self.head1(bakcbone_feat1))
feat2 = F.normalize(self.head1(bakcbone_feat2))
other1 = concat_other_gather(feat1)
other2 = concat_other_gather(feat2)
prob = torch.cat([feat1, feat2]) @ torch.cat([feat1, feat2, other1, other2]).T / t
diagnal_mask = (1 - torch.eye(prob.size(0), prob.size(1))).bool().cuda(rank)
logits = torch.masked_select(prob, diagnal_mask).reshape(prob.size(0), -1)
first_half_label = torch.arange(b-1, 2*b-1).long().cuda(rank)
second_half_label = torch.arange(0, b).long().cuda(rank)
labels = torch.cat([first_half_label, second_half_label])
feat1 = F.normalize(self.head2(bakcbone_feat1))
feat2 = F.normalize(self.head2(bakcbone_feat2))
all_feat1 = concat_all_gather(feat1)
all_feat2 = concat_all_gather(feat2)
all_bs = all_feat1.size(0)
# similarly concate and gather all the labels
if cluster_labels is not None:
all_cluster_labels = concat_all_gather(cluster_labels) # all_bz
mask1_list = []
if rank == 0:
mask1 = self.build_mask_from_labels(all_cluster_labels, rank).float() # all_bz, all_bz
mask1_list = list(torch.chunk(mask1, world_size))
mask1 = mask1_list[0]
else:
mask1 = torch.zeros(b, all_bs).cuda(rank)
torch.distributed.scatter(mask1, mask1_list, 0)
diagnal_mask = torch.eye(all_bs, all_bs).cuda(rank)
diagnal_mask = torch.chunk(diagnal_mask, world_size)[rank]
loss1 = self.sup_contra(feat1 @ all_feat2.T / t, mask1)
loss1 += self.sup_contra(feat2 @ all_feat1.T / t, mask1)
loss1 /= 2
else:
loss1 = None
return logits, labels, loss1
# utils
@torch.no_grad()
def concat_other_gather(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
rank = torch.distributed.get_rank()
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor)
other = torch.cat(tensors_gather[:rank] + tensors_gather[rank+1:], dim=0)
return other
@torch.no_grad()
def concat_all_gather(tensor, replace=True):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
rank = torch.distributed.get_rank()
tensors_gather = [torch.ones_like(tensor)
for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, tensor)
if replace:
tensors_gather[rank] = tensor
other = torch.cat(tensors_gather, dim=0)
return other | 0.853303 | 0.45538 |
from Config import Config
from src.orm.SqlUtil import SqlUtil
from flask import Flask, request
from src.Handler.MetricHandler import MetricHandler
from src.Handler.MainHandler import MainHandler
from src.Handler.StatusHandler import StatusHandler
from src.Handler.GetHandler import GetHandler
import os
import sys
from src.auth.Auth import Auth
from src.tools.CronTools import CronCluster, CronMonitor, CronDataExpire
# 初始化参数
conf = Config()
sep = os.path.sep
# flask 初始化
app = Flask(__name__)
web_host = "0.0.0.0"
web_port = 9200
app.static_folder = conf.abs_path + sep + "src" + sep + "static"
app.template_folder = conf.abs_path + sep + "src" + sep + "static" + sep + "html"
# 主界面
@app.route('/', methods=["GET"])
def web_main():
return MainHandler.main()
# 验证
@app.route('/login', methods=['POST', 'GET'])
def login():
url = request.args.get("url")
if request.method == "GET":
return MainHandler.login(url)
else:
data = request.form
ip = request.remote_addr
return MainHandler.login_verify(data.to_dict(), ip)
# 添加集群到私有化监控平台
@app.route('/add', methods=["GET", "POST"])
def add():
ip = request.remote_addr
if request.method == "GET":
return MainHandler.return_add_html(ip)
elif request.method == "POST":
data = request.form
return MainHandler.add_cluster(data.to_dict(), ip)
else:
return u'方法不允许!'
# 从私有化监控平台中删除集群
@app.route("/delete/<cluster_id>", methods=["POST"])
def delete_cluster(cluster_id):
ip = request.remote_addr
return MainHandler.delete_cluster(cluster_id, ip)
# 更新私有化监控平台中的集群
@app.route("/update/<cluster_id>", methods=["GET", "POST"])
def update(cluster_id):
ip = request.remote_addr
if __name__ == '__main__':
if request.method == "GET":
return MainHandler.get_update_cluster(cluster_id, ip)
elif request.method == "POST":
data = request.form
return MainHandler.update_cluster(cluster_id, data.to_dict(), ip)
else:
return u"方法不允许!"
# 监控
@app.route('/metrics', methods=["GET"])
def metrics():
return MetricHandler.metric()
# 健康检查
@app.route('/health', methods=['GET'])
def health():
return u"Health"
# 获取其他信息
@app.route('/get/<type_id>', methods=["GET", "POST"])
def get(type_id):
if request.method == "GET":
return GetHandler.get(type_id)
elif request.method == "POST":
return GetHandler.post(type_id)
else:
return u'方法不允许!'
# 接收其他子监控的报告
@app.route('/status/<cluster>', methods=["POST"])
def get_status(cluster):
try:
data = request.get_json()
return StatusHandler.get_status(cluster, data)
except Exception:
return u'参数错误'
# 程序入口
if __name__ == "__main__":
# 加载配置
conf.parse_from_config_ini()
if not conf.check_config():
print "Error: 参数配置不正确, 请查看config.ini"
sys.exit(1)
# 创建数据库
su = SqlUtil()
su.create_tables_all()
# 启动报告cron任务
CronMonitor.start()
# 启动服务端cron任务
CronCluster.start()
# 启动数据自动清理
CronDataExpire.start()
# 启动用户超时检验
Auth().cron_start()
# 运行web
app.run(host=web_host, port=web_port, debug=False) | PrivateMonitorServer/main.py |
from Config import Config
from src.orm.SqlUtil import SqlUtil
from flask import Flask, request
from src.Handler.MetricHandler import MetricHandler
from src.Handler.MainHandler import MainHandler
from src.Handler.StatusHandler import StatusHandler
from src.Handler.GetHandler import GetHandler
import os
import sys
from src.auth.Auth import Auth
from src.tools.CronTools import CronCluster, CronMonitor, CronDataExpire
# 初始化参数
conf = Config()
sep = os.path.sep
# flask 初始化
app = Flask(__name__)
web_host = "0.0.0.0"
web_port = 9200
app.static_folder = conf.abs_path + sep + "src" + sep + "static"
app.template_folder = conf.abs_path + sep + "src" + sep + "static" + sep + "html"
# 主界面
@app.route('/', methods=["GET"])
def web_main():
return MainHandler.main()
# 验证
@app.route('/login', methods=['POST', 'GET'])
def login():
url = request.args.get("url")
if request.method == "GET":
return MainHandler.login(url)
else:
data = request.form
ip = request.remote_addr
return MainHandler.login_verify(data.to_dict(), ip)
# 添加集群到私有化监控平台
@app.route('/add', methods=["GET", "POST"])
def add():
ip = request.remote_addr
if request.method == "GET":
return MainHandler.return_add_html(ip)
elif request.method == "POST":
data = request.form
return MainHandler.add_cluster(data.to_dict(), ip)
else:
return u'方法不允许!'
# 从私有化监控平台中删除集群
@app.route("/delete/<cluster_id>", methods=["POST"])
def delete_cluster(cluster_id):
ip = request.remote_addr
return MainHandler.delete_cluster(cluster_id, ip)
# 更新私有化监控平台中的集群
@app.route("/update/<cluster_id>", methods=["GET", "POST"])
def update(cluster_id):
ip = request.remote_addr
if __name__ == '__main__':
if request.method == "GET":
return MainHandler.get_update_cluster(cluster_id, ip)
elif request.method == "POST":
data = request.form
return MainHandler.update_cluster(cluster_id, data.to_dict(), ip)
else:
return u"方法不允许!"
# 监控
@app.route('/metrics', methods=["GET"])
def metrics():
return MetricHandler.metric()
# 健康检查
@app.route('/health', methods=['GET'])
def health():
return u"Health"
# 获取其他信息
@app.route('/get/<type_id>', methods=["GET", "POST"])
def get(type_id):
if request.method == "GET":
return GetHandler.get(type_id)
elif request.method == "POST":
return GetHandler.post(type_id)
else:
return u'方法不允许!'
# 接收其他子监控的报告
@app.route('/status/<cluster>', methods=["POST"])
def get_status(cluster):
try:
data = request.get_json()
return StatusHandler.get_status(cluster, data)
except Exception:
return u'参数错误'
# 程序入口
if __name__ == "__main__":
# 加载配置
conf.parse_from_config_ini()
if not conf.check_config():
print "Error: 参数配置不正确, 请查看config.ini"
sys.exit(1)
# 创建数据库
su = SqlUtil()
su.create_tables_all()
# 启动报告cron任务
CronMonitor.start()
# 启动服务端cron任务
CronCluster.start()
# 启动数据自动清理
CronDataExpire.start()
# 启动用户超时检验
Auth().cron_start()
# 运行web
app.run(host=web_host, port=web_port, debug=False) | 0.197715 | 0.067393 |