code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def write_values(self):
return dict(((k, v.value) for k, v in self._inputs.items() if not v.is_secret and not v.is_empty(False))) | Return the dictionary with which to write values |
def add_inputs_from_inputstring(self, input_string):
raw_params = input_string.split('\n')
param_attributes = (self._parse_param_line(rp) for rp in raw_params if len(rp.strip(' \t')) > 0)
for param, attributes in param_attributes:
self.add_input(param, attributes) | Add inputs using the input string format:
gitroot==~/workspace
username
password?
main_branch==comp_main |
def _parse_param_line(self, line):
value = line.strip('\n \t')
if len(value) > 0:
i = Input()
if value.find('#') != -1:
value, extra_attributes = value.split('#')
try:
extra_attributes = eval(extra_attributes)
... | Parse a single param line. |
def extract_csv(zip_path, destination):
with zipfile.ZipFile(zip_path) as zf:
member_to_unzip = None
for member in zf.namelist():
if member.endswith('.csv'):
member_to_unzip = member
break
if not member_to_unzip:
raise LookupError... | Extract the first CSV file found in the given ``zip_path`` ZIP file to the
``destination`` file. Raises :class:`LookupError` if no CSV file can be
found in the ZIP. |
def download(self, overwrite=True):
if overwrite or not os.path.exists(self.file_path):
_, f = tempfile.mkstemp()
try:
urlretrieve(self.DOWNLOAD_URL, f)
extract_csv(f, self.file_path)
finally:
os.remove(f) | Download the zipcodes CSV file. If ``overwrite`` is set to False, the
file won't be downloaded if it already exists. |
def get_locations(self):
if not self.zipcode_mapping:
self.download(overwrite=False)
zipcode_mapping = {}
with UnicodeReader(self.file_path, delimiter=';', encoding='latin1') as csv_reader:
# Skip header
next(csv_reader)
... | Return the zipcodes mapping as a list of ``{zipcode: location}`` dicts.
The zipcodes file will be downloaded if necessary. |
def get_zipcodes_for_canton(self, canton):
zipcodes = [
zipcode for zipcode, location in self.get_locations().items()
if location.canton == canton
]
return zipcodes | Return the list of zipcodes for the given canton code. |
def get_cantons(self):
return sorted(list(set([
location.canton for location in self.get_locations().values()
]))) | Return the list of unique cantons, sorted by name. |
def get_municipalities(self):
return sorted(list(set([
location.municipality for location in self.get_locations().values()
]))) | Return the list of unique municipalities, sorted by name. |
def term_vector(self, params):
'''
params are either True/False, 'with_offsets', 'with_positions', 'with_positions_offsets'
'''
if params == True:
self[self.field]['term_vector'] = 'yes'
elif params == False:
self[self.field]['term_vector'] = 'no'
... | params are either True/False, 'with_offsets', 'with_positions', 'with_positions_offsets' |
def _get_formula_class(self, formula):
# recursive import otherwise
from sprinter.formula.base import FormulaBase
if formula in LEGACY_MAPPINGS:
formula = LEGACY_MAPPINGS[formula]
formula_class, formula_url = formula, None
if ':' in formula:
formu... | get a formula class object if it exists, else
create one, add it to the dict, and pass return it. |
def is_backup_class(cls):
return True if (
isclass(cls) and
issubclass(cls, Storable) and
get_mapping(cls, no_mapping_ok=True)
) else False | Return true if given class supports back up. Currently this means a
gludb.data.Storable-derived class that has a mapping as defined in
gludb.config |
def add_package(
self,
pkg_name,
recurse=True,
include_bases=True,
parent_pkg=None
):
if parent_pkg:
pkg = import_module('.' + pkg_name, parent_pkg)
else:
pkg = import_module(pkg_name)
for module_loader, name, ispkg in... | Add all classes to the backup in the specified package (including
all modules and all sub-packages) for which is_backup_class returns
True. Note that self.add_class is used, so base classes will added as
well.
Parameters:
* pkg_name - a string representing the package name. It m... |
def add_class(self, cls, include_bases=True):
if not is_backup_class(cls):
return 0
added = 0
cls_name = backup_name(cls)
if cls_name not in self.classes:
self.classes[cls_name] = cls
self.log("Added class for backup: %s", cls_name)
... | Add the specified class (which should be a class object, _not_ a
string). By default all base classes for which is_backup_class returns
True will also be added. `include_bases=False` may be spcified to
suppress this behavior. The total number of classes added is returned.
Note that if is... |
def log(self, entry, *args):
if args:
entry = entry % args
self.backup_log.append(entry) | Append the string supplied to the log (a list of strings). If
additional arguments are supplied, then first string is assumed to be
a format string and the other args are used for string interpolation.
For instance `backup.log("%d + %d == %d", 1, 1, 2)` would result in the
string `'1 + 1... |
def list_dir(sourceDir, include_source=None, include_file=True):
for cur_file in os.listdir(sourceDir):
if cur_file.lower() == ".ds_store":
continue
pathWithSource = os.path.join(sourceDir, cur_file)
if include_file or os.path.isdir(pathWithSource):
if include_so... | 与 :func:`os.listdir()` 类似,但提供一些筛选功能,且返回生成器对象。
:param str sourceDir: 待处理的文件夹。
:param bool include_source: 遍历结果中是否包含源文件夹的路径。
:param bool include_file: 是否包含文件。True 表示返回的内容中既包含文件,又
包含文件夹;Flase 代表仅包含文件夹。
:return: 一个生成器对象。 |
def copy_dir(sou_dir, dst_dir, del_dst=False, del_subdst=False):
if del_dst and os.path.isdir(del_dst):
shutil.rmtree(dst_dir)
os.makedirs(dst_dir, exist_ok=True)
for cur_file in list_dir(sou_dir):
dst_file = os.path.join(dst_dir, cur_file)
cur_file = os.path.join(sou_dir, cur_f... | :func:`shutil.copytree()` 也能实现类似功能,
但前者要求目标文件夹必须不存在。
而 copy_dir 没有这个要求,它可以将 sou_dir 中的文件合并到 dst_dir 中。
:param str sou_dir: 待复制的文件夹;
:param str dst_dir: 目标文件夹;
:param bool del_dst: 是否删除目标文件夹。
:param bool del_subdst: 是否删除目标子文件夹。 |
def get_files(path, ext=[], include=True):
has_ext = len(ext)>0
for p, d, fs in os.walk(path):
for f in fs:
if has_ext:
in_ext = False
for name in ext:
if f.endswith(name):
in_ext = True
... | 遍历提供的文件夹的所有子文件夹,饭后生成器对象。
:param str path: 待处理的文件夹。
:param list ext: 扩展名列表。
:param bool include: 若值为 True,代表 ext 提供的是包含列表;
否则是排除列表。
:returns: 一个生成器对象。 |
def read_file(file_path, **kws):
kw = {"mode":"r", "encoding":"utf-8"}
if kws:
for k,v in kws.items():
kw[k] = v
with open(file_path, **kw) as afile:
txt = afile.read()
return txt | 读取文本文件的内容。
:param str file_path: 文件路径。
:returns: 文件内容。
:rtype: str |
def write_file(file_path, txt, **kws):
if not os.path.exists(file_path):
upDir = os.path.dirname(file_path)
if not os.path.isdir(upDir):
os.makedirs(upDir)
kw = {"mode":"w", "encoding":"utf-8"}
if kws:
for k,v in kws.items():
kw[k] = v
with open(file... | 将文本内容写入文件。
:param str file_path: 文件路径。
:param str txt: 待写入的文件内容。 |
def write_by_templ(templ, target, sub_value, safe=False):
templ_txt = read_file(templ)
txt = None
if safe:
txt = Template(templ_txt).safe_substitute(sub_value)
else:
txt = Template(templ_txt).substitute(sub_value)
write_file(target, txt) | 根据模版写入文件。
:param str templ: 模版文件所在路径。
:param str target: 要写入的文件所在路径。
:param dict sub_value: 被替换的内容。 |
def get_md5(path):
with open(path,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
return md5obj.hexdigest()
raise FileNotFoundError("Error when get md5 for %s!"%path) | 获取文件的 MD5 值。
:param str path: 文件路径。
:returns: MD5 值。
:rtype: str |
def create_zip(files, trim_arcname=None, target_file=None, **zipfile_args):
zipname = None
azip = None
if not target_file:
azip = tempfile.NamedTemporaryFile(mode='wb', delete=False)
zipname = azip.name
else:
azip = target_file
zipname = target_file.name if hasattr(a... | 创建一个 zip 文件。
:param list files: 要创建zip 的文件列表。
:param int trim_arcname: 若提供这个值,则使用 ZipFile.write(filename, filename[trim_arcname:]) 进行调用。
:returns: zip 文件的路径。
:rtype: str |
def get_max_ver(fmt, filelist):
x, y, z = 0,0,0
verpat = fmt%'(\d+).(\d+).(\d+)'
verre = re.compile(r''+verpat+'', re.M)
for f in filelist:
match = verre.search(f)
if match:
x1 = int(match.group(1))
y1 = int(match.group(2))
z1 = int(match.group(3... | 有一堆字符串,文件名均包含 %d.%d.%d 形式版本号,返回其中版本号最大的那个。
我一般用它来检测一堆发行版中版本号最大的那个文件。
:param str fmt: 要检测测字符串形式,例如 rookout-%s.tar.gz ,其中 %s 会被正则替换。
:param list files: 字符串列表。
:returns: 版本号最大的字符串。
:rtype: str |
def merge_dicts(d1, d2):
for k in set(d1.keys()).union(d2.keys()):
if k in d1 and k in d2:
if isinstance(d1[k], dict) and isinstance(d2[k], dict):
yield (k, dict(merge_dicts(d1[k], d2[k])))
elif isinstance(d1[k], list):
if isinstance(d2[k], list):... | 合并两个无限深度的 dict
会自动合并 list 格式
:param dict d1: 被合并的 dict
:param dict d2: 待合并的 dict
:returns: 一个新的生成器对象
:rtype: generator |
def main(argv: Optional[Sequence[str]] = None) -> None:
parser = ArgumentParser(description="Convert Jupyter Notebook assignments to PDFs")
parser.add_argument(
"--hw",
type=int,
required=True,
help="Homework number to convert",
dest="hw_num",
)
parser.add_ar... | Parse arguments and process the homework assignment. |
def get_object_by_name(content, object_type, name, regex=False):
'''
Get the vsphere object associated with a given text name
Source: https://github.com/rreubenur/vmware-pyvmomi-examples/blob/master/create_template.py
'''
container = content.viewManager.CreateContainerView(
content.rootFolde... | Get the vsphere object associated with a given text name
Source: https://github.com/rreubenur/vmware-pyvmomi-examples/blob/master/create_template.py |
def get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regexf get_vm_by_name(content, name, regex=False):
'''
Get a VM by its name
'''
return get_object_by_name(content, vim.VirtualMachine, name, regex) | Get a VM by its name |
def get_all(content, container, object_type):
'''
Get all items of a certain type
Example: get_all(content, vim.Datastore) return all datastore objects
'''
obj_list = list()
view_manager = content.viewManager
object_view = view_manager.CreateContainerView(
container, [object_type], T... | Get all items of a certain type
Example: get_all(content, vim.Datastore) return all datastore objects |
def get_datacenter(content, obj):
'''
Get the datacenter to whom an object belongs
'''
datacenters = content.rootFolder.childEntity
for d in datacenters:
dch = get_all(content, d, type(obj))
if dch is not None and obj in dch:
return f get_datacenter(content, obj):
'''... | Get the datacenter to whom an object belongs |
def get_all_vswitches(content):
'''
Get all the virtual switches
'''
vswitches = []
hosts = get_all_hosts(content)
for h in hosts:
for s in h.config.network.vswitch:
vswitches.append(s)
return vswitchef get_all_vswitches(content):
'''
Get all the virtual switches
... | Get all the virtual switches |
def print_vm_info(vm):
'''
Print information for a particular virtual machine
'''
summary = vm.summary
print('Name : ', summary.config.name)
print('Path : ', summary.config.vmPathName)
print('Guest : ', summary.config.guestFullName)
annotation = summary.config.annotation
if annotat... | Print information for a particular virtual machine |
def module_import(module_path):
try:
# Import whole module path.
module = __import__(module_path)
# Split into components: ['contour',
# 'extras','appengine','ndb_persistence'].
components = module_path.split('.')
# Starting at the second component, set module ... | Imports the module indicated in name
Args:
module_path: string representing a module path such as
'app.config' or 'app.extras.my_module'
Returns:
the module matching name of the last component, ie: for
'app.extras.my_module' it returns a
reference to my_module
Raises... |
def find_contour_yaml(config_file=__file__, names=None):
checked = set()
contour_yaml = _find_countour_yaml(os.path.dirname(config_file), checked,
names=names)
if not contour_yaml:
contour_yaml = _find_countour_yaml(os.getcwd(), checked, names=names)
... | Traverse directory trees to find a contour.yaml file
Begins with the location of this file then checks the
working directory if not found
Args:
config_file: location of this file, override for
testing
Returns:
the path of contour.yaml or None if not found |
def _find_countour_yaml(start, checked, names=None):
extensions = []
if names:
for name in names:
if not os.path.splitext(name)[1]:
extensions.append(name + ".yaml")
extensions.append(name + ".yml")
yaml_names = (names or []) + CONTOUR_YAML_NAMES + ... | Traverse the directory tree identified by start
until a directory already in checked is encountered or the path
of countour.yaml is found.
Checked is present both to make the loop termination easy
to reason about and so the same directories do not get
rechecked
Args:
start: the path to... |
def _load_yaml_config(path=None):
countour_yaml_path = path or find_contour_yaml()
if countour_yaml_path is None:
logging.debug("countour.yaml not found.")
return None
with open(countour_yaml_path) as yaml_file:
return yaml_file.read() | Open and return the yaml contents. |
def build_parser():
parser = argparse.ArgumentParser(
description='dockerstache templating util'
)
parser.add_argument(
'--output', '-o',
help='Working directory to render dockerfile and templates',
dest='output',
default=None
)
parser.add_argument(
... | _build_parser_
Set up CLI parser options, parse the
CLI options an return the parsed results |
def main():
options = build_parser()
try:
run(**options)
except RuntimeError as ex:
msg = (
"An error occurred running dockerstache: {} "
"please see logging info above for details"
).format(ex)
LOGGER.error(msg)
sys.exit(1) | _main_
Create a CLI parser and use that to run
the template rendering process |
def _guess_type_from_validator(validator):
if isinstance(validator, _OptionalValidator):
# Optional : look inside
return _guess_type_from_validator(validator.validator)
elif isinstance(validator, _AndValidator):
# Sequence : try each of them
for v in validator.validators:
... | Utility method to return the declared type of an attribute or None. It handles _OptionalValidator and _AndValidator
in order to unpack the validators.
:param validator:
:return: the type of attribute declared in an inner 'instance_of' validator (if any is found, the first one is used)
or None if no inn... |
def is_optional(attr):
return isinstance(attr.validator, _OptionalValidator) or (attr.default is not None and attr.default is not NOTHING) | Helper method to find if an attribute is mandatory
:param attr:
:return: |
def get_attrs_declarations(item_type):
# this will raise an error if the type is not an attr-created type
attribs = fields(item_type)
res = dict()
for attr in attribs:
attr_name = attr.name
# -- is the attribute mandatory ?
optional = is_optional(attr)
# -- get a... | Helper method to return a dictionary of tuples. Each key is attr_name, and value is (attr_type, attr_is_optional)
:param item_type:
:return: |
def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
if not resources.get("global_content_filter", {}).get("include_raw", False):
keep_cells = []
for cell in nb.cells:
if cell.cell_type != "raw":
... | Remove any raw cells from the Notebook.
By default, exclude raw cells from the output. Change this by including
global_content_filter->include_raw = True in the resources dictionary.
This preprocessor is necessary because the NotebookExporter doesn't
include the exclude_raw config. |
def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
if "remove_solution" not in resources:
raise KeyError("The resources dictionary must have a remove_solution key.")
if resources["remove_solution"]:
keep_cells_idx = []... | Preprocess the entire notebook. |
def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
for index, cell in enumerate(nb.cells):
if "## Solution" in cell.source:
nb.cells[index + 1].source = ""
return nb, resources | Preprocess the entire Notebook. |
def preprocess(
self, nb: "NotebookNode", resources: dict
) -> Tuple["NotebookNode", dict]:
exam_num = resources["exam_num"]
time = resources["time"]
date = resources["date"]
nb.cells.insert(0, new_markdown_cell(source="---"))
nb.cells.insert(0, new_markdow... | Preprocess the entire Notebook. |
def parse_from_dict(json_dict):
order_columns = json_dict['columns']
order_list = MarketOrderList(
upload_keys=json_dict['uploadKeys'],
order_generator=json_dict['generator'],
)
for rowset in json_dict['rowsets']:
generated_at = parse_datetime(rowset['generatedAt'])
... | Given a Unified Uploader message, parse the contents and return a
MarketOrderList.
:param dict json_dict: A Unified Uploader message as a JSON dict.
:rtype: MarketOrderList
:returns: An instance of MarketOrderList, containing the orders
within. |
def encode_to_json(order_list):
rowsets = []
for items_in_region_list in order_list._orders.values():
region_id = items_in_region_list.region_id
type_id = items_in_region_list.type_id
generated_at = gen_iso_datetime_str(items_in_region_list.generated_at)
rows = []
f... | Encodes this list of MarketOrder instances to a JSON string.
:param MarketOrderList order_list: The order list to serialize.
:rtype: str |
def weather(query):
print 'Identifying the location . . .'
try:
response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-ner",
headers={
"X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP",
"Content-Type": "application/x-www-form-urlencoded"
},
param... | weather(query) -- use Name Entity Recogniser (nltk-stanford-ner), to
determine location entity in query and fetch weather info for that location
(using yahoo apis). |
def generic(query):
try:
response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-ner",
headers={
"X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP",
"Content-Type": "application/x-www-form-urlencoded"
},
params={
"text": query
}
)
exc... | generic(query) -- process a generic user query using the Stanford
NLTK NER and duckduckgo api. |
def _can_construct_from_str(strict_mode: bool, from_type: Type, to_type: Type) -> bool:
return to_type not in {int, float, bool} | Returns true if the provided types are valid for constructor_with_str_arg conversion
Explicitly declare that we are not able to convert primitive types (they already have their own converters)
:param strict_mode:
:param from_type:
:param to_type:
:return: |
def are_flags_valid(packet_type, flags):
if packet_type == MqttControlPacketType.publish:
rv = 0 <= flags <= 15
elif packet_type in (MqttControlPacketType.pubrel,
MqttControlPacketType.subscribe,
MqttControlPacketType.unsubscribe):
rv = flag... | True when flags comply with [MQTT-2.2.2-1] requirements based on
packet_type; False otherwise.
Parameters
----------
packet_type: MqttControlPacketType
flags: int
Integer representation of 4-bit MQTT header flags field.
Values outside of the range [0, 15] will certainly cause the
... |
def decode(f):
decoder = mqtt_io.FileDecoder(f)
(byte_0,) = decoder.unpack(mqtt_io.FIELD_U8)
packet_type_u4 = (byte_0 >> 4)
flags = byte_0 & 0x0f
try:
packet_type = MqttControlPacketType(packet_type_u4)
except ValueError:
raise DecodeErr... | Extract a `MqttFixedHeader` from ``f``.
Parameters
----------
f: file
Object with read method.
Raises
-------
DecodeError
When bytes decoded have values incompatible with a
`MqttFixedHeader` object.
UnderflowDecodeError
... |
def encode_body(self, f):
num_bytes_written = 0
num_bytes_written += self.__encode_name(f)
num_bytes_written += self.__encode_protocol_level(f)
num_bytes_written += self.__encode_connect_flags(f)
num_bytes_written += self.__encode_keep_alive(f)
num_bytes_written... | Parameters
----------
f: file
File-like object with a write method.
Returns
-------
int
Number of bytes written to ``f``. |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.subscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > decod... | Generates a `MqttSubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `subscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.suback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
results = []
while header.remaining_len > decoder... | Generates a `MqttSuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `suback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.publish
dupe = bool(header.flags & 0x08)
retain = bool(header.flags & 0x01)
qos = ((header.flags & 0x06) >> 1)
if qos == 0 and dupe:
# The DUP flag MUST be set to 0 for all ... | Generates a `MqttPublish` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `publish`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.pubrel
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_U16)
if header.remaining_len != decoder.num_bytes_consumed:
... | Generates a `MqttPubrel` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pubrel`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.unsubscribe
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
topics = []
while header.remaining_len > dec... | Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.unsuback
decoder = mqtt_io.FileDecoder(mqtt_io.LimitReader(f, header.remaining_len))
packet_id, = decoder.unpack(mqtt_io.FIELD_PACKET_ID)
if header.remaining_len != decoder.num_bytes_consumed:
... | Generates a `MqttUnsuback` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsuback`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.pingreq
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingreq() | Generates a `MqttPingreq` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingreq`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.pingresp
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttPingresp() | Generates a `MqttPingresp` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `pingresp`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def decode_body(cls, header, f):
assert header.packet_type == MqttControlPacketType.disconnect
if header.remaining_len != 0:
raise DecodeError('Extra bytes at end of packet.')
return 0, MqttDisconnect() | Generates a :class:`MqttDisconnect` packet given a
:class:`MqttFixedHeader`. This method asserts that
header.packet_type is :const:`MqttControlPacketType.disconnect`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
R... |
def getter(name, key=None):
if not key:
key = lambda x: x
def wrapper(self):
return key(getattr(self, name))
wrapper.__name__ = wrapper.__qualname__ = name
return property(wrapper) | Creates a read-only property for the attribute name *name*. If a *key*
function is provided, it can be used to post-process the value of the
attribute. |
def connect(self):
if self.token:
self.phab_session = {'token': self.token}
return
req = self.req_session.post('%s/api/conduit.connect' % self.host, data={
'params': json.dumps(self.connect_params),
'output': 'json',
'__conduit__': Tr... | Sets up your Phabricator session, it's not necessary to call
this directly |
def request(self, method, params=None):
if params is None:
params = {}
if not self.phab_session:
self.connect()
url = '%s/api/%s' % (self.host, method)
params['__conduit__'] = self.phab_session
req = self.req_session.post(url, data={
'... | Make a request to a method in the phabricator API
:param method: Name of the API method to call
:type method: basestring
:param params: Optional dict of params to pass
:type params: dict |
def get_musiclibrary():
lib_files = music_library.get_file_list(config.library_path)
global lib
lib = music_library.parse_library(lib_files)
return lib | :type :musiclibrary.MusicLibrary |
def install(force=False):
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
... | Install git hooks. |
def uninstall():
ret, git_dir, _ = run("git rev-parse --show-toplevel")
if ret != 0:
click.echo(
"ERROR: Please run from within a GIT repository.",
file=sys.stderr)
raise click.Abort
git_dir = git_dir[0]
hooks_dir = os.path.join(git_dir, HOOK_PATH)
for ... | Uninstall git hooks. |
def find_promulgation_date(line):
line = line.split(' du ')[1]
return format_date(re.search(r"(\d\d? \w\w\w+ \d\d\d\d)", line).group(1)) | >>> find_promulgation_date("Loi nº 2010-383 du 16 avril 2010 autorisant l'approbation de l'accord entre...")
'2010-04-16' |
def auto_need(form):
requirements = form.get_widget_requirements()
for library, version in requirements:
resources = resource_mapping[library]
if not isinstance(resources, list): # pragma: no cover (bw compat only)
resources = [resources]
for resource in resources:
... | Automatically ``need()`` the relevant Fanstatic resources for a form.
This function automatically utilises libraries in the ``js.*`` namespace
(such as ``js.jquery``, ``js.tinymce`` and so forth) to allow Fanstatic
to better manage these resources (caching, minifications) and avoid
duplication across t... |
def setup_logger():
logger = logging.getLogger('dockerstache')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger | setup basic logger |
def named_any(name):
assert name, 'Empty module name'
names = name.split('.')
topLevelPackage = None
moduleNames = names[:]
while not topLevelPackage:
if moduleNames:
trialname = '.'.join(moduleNames)
try:
topLevelPackage = __import__(trialname)
... | Retrieve a Python object by its fully qualified name from the global Python
module namespace. The first part of the name, that describes a module,
will be discovered and imported. Each subsequent part of the name is
treated as the name of an attribute of the object specified by all of the
name which c... |
def for_name(modpath, classname):
'''
Returns a class of "classname" from module "modname".
'''
module = __import__(modpath, fromlist=[classname])
classobj = getattr(module, classname)
return classobj(f for_name(modpath, classname):
'''
Returns a class of "classname" from module "modname... | Returns a class of "classname" from module "modname". |
def _convert(self, val):
if isinstance(val, dict) and not isinstance(val, DotDict):
return DotDict(val), True
elif isinstance(val, list) and not isinstance(val, DotList):
return DotList(val), True
return val, False | Convert the type if necessary and return if a conversion happened. |
def full_subgraph(self, vertices):
obj_map = {vertex.id: vertex for vertex in vertices}
edges = [
edge for vertex_id in obj_map
for edge in self._out_edges[vertex_id]
if edge.head in obj_map
]
return AnnotatedGraph(
vertices=obj_m... | Return the subgraph of this graph whose vertices
are the given ones and whose edges are the edges
of the original graph between those vertices. |
def to_json(self):
obj = {
"vertices": [
{
"id": vertex.id,
"annotation": vertex.annotation,
}
for vertex in self.vertices
],
"edges": [
{
"id"... | Convert to a JSON string. |
def from_json(cls, json_graph):
obj = json.loads(json_graph)
vertices = [
AnnotatedVertex(
id=vertex["id"],
annotation=vertex["annotation"],
)
for vertex in obj["vertices"]
]
edges = [
AnnotatedEdg... | Reconstruct the graph from a graph exported to JSON. |
def export_json(self, filename):
json_graph = self.to_json()
with open(filename, 'wb') as f:
f.write(json_graph.encode('utf-8')) | Export graph in JSON form to the given file. |
def import_json(cls, filename):
with open(filename, 'rb') as f:
json_graph = f.read().decode('utf-8')
return cls.from_json(json_graph) | Import graph from the given file. The file is expected
to contain UTF-8 encoded JSON data. |
def to_dot(self):
edge_labels = {
edge.id: edge.annotation
for edge in self._edges
}
edges = [self._format_edge(edge_labels, edge) for edge in self._edges]
vertices = [
DOT_VERTEX_TEMPLATE.format(
vertex=vertex.id,
... | Produce a graph in DOT format. |
def export_image(self, filename='refcycle.png', format=None,
dot_executable='dot'):
# Figure out what output format to use.
if format is None:
_, extension = os.path.splitext(filename)
if extension.startswith('.') and len(extension) > 1:
... | Export graph as an image.
This requires that Graphviz is installed and that the ``dot``
executable is in your path.
The *filename* argument specifies the output filename.
The *format* argument lets you specify the output format. It may be
any format that ``dot`` understands, ... |
def install_brew(target_path):
if not os.path.exists(target_path):
try:
os.makedirs(target_path)
except OSError:
logger.warn("Unable to create directory %s for brew." % target_path)
logger.warn("Skipping...")
return
extract_targz(HOMEBREW_URL,... | Install brew to the target path |
def scales(self, image):
# compute the minimum scale so that the patch size still fits into the given image
minimum_scale = max(self.m_patch_box.size_f[0] / image.shape[-2], self.m_patch_box.size_f[1] / image.shape[-1])
if self.m_lowest_scale:
maximum_scale = min(minimum_scale / self.m_lowest_sca... | scales(image) -> scale, shape
Computes the all possible scales for the given image and yields a tuple of the scale and the scaled image shape as an iterator.
**Parameters::**
``image`` : array_like(2D or 3D)
The image, for which the scales should be computed
**Yields:**
``scale`` : float
... |
def sample_scaled(self, shape):
for y in range(0, shape[-2]-self.m_patch_box.bottomright[0], self.m_distance):
for x in range(0, shape[-1]-self.m_patch_box.bottomright[1], self.m_distance):
# create bounding box for the current shift
yield self.m_patch_box.shift((y,x)) | sample_scaled(shape) -> bounding_box
Yields an iterator that iterates over all sampled bounding boxes in the given (scaled) image shape.
**Parameters:**
``shape`` : (int, int) or (int, int, int)
The (current) shape of the (scaled) image
**Yields:**
``bounding_box`` : :py:class:`BoundingBo... |
def sample(self, image):
for scale, scaled_image_shape in self.scales(image):
# prepare the feature extractor to extract features from the given image
for bb in self.sample_scaled(scaled_image_shape):
# extract features for
yield bb.scale(1./scale) | sample(image) -> bounding_box
Yields an iterator over all bounding boxes in different scales that are sampled for the given image.
**Parameters:**
``image`` : array_like(2D or 3D)
The image, for which the bounding boxes should be generated
**Yields:**
``bounding_box`` : :py:class:`Boundin... |
def iterate(self, image, feature_extractor, feature_vector):
for scale, scaled_image_shape in self.scales(image):
# prepare the feature extractor to extract features from the given image
feature_extractor.prepare(image, scale)
for bb in self.sample_scaled(scaled_image_shape):
# extrac... | iterate(image, feature_extractor, feature_vector) -> bounding_box
Scales the given image, and extracts features from all possible bounding boxes.
For each of the sampled bounding boxes, this function fills the given pre-allocated feature vector and yields the current bounding box.
**Parameters:**
``... |
def iterate_cascade(self, cascade, image, threshold = None):
for scale, scaled_image_shape in self.scales(image):
# prepare the feature extractor to extract features from the given image
cascade.prepare(image, scale)
for bb in self.sample_scaled(scaled_image_shape):
# return the pred... | iterate_cascade(self, cascade, image, [threshold]) -> prediction, bounding_box
Iterates over the given image and computes the cascade of classifiers.
This function will compute the cascaded classification result for the given ``image`` using the given ``cascade``.
It yields a tuple of prediction value and ... |
def pass_service(*names):
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
for name in names:
kwargs[name] = service_proxy(name)
return f(*args, **kwargs)
return wrapper
return decorator | Injects a service instance into the kwargs |
def get_conn():
if os.environ.get('DEBUG', False) or os.environ.get('travis', False):
# In DEBUG mode - use the local DynamoDB
# This also works for travis since we'll be running dynalite
conn = DynamoDBConnection(
host='localhost',
port=8000,
aws_acc... | Return a connection to DynamoDB. |
def map_index_val(index_val):
if index_val is None:
return DynamoMappings.NONE_VAL
index_val = str(index_val)
if not index_val:
return DynamoMappings.EMPTY_STR_VAL
return index_val | Xform index_val so that it can be stored/queried. |
def table_schema_call(self, target, cls):
index_defs = []
for name in cls.index_names() or []:
index_defs.append(GlobalIncludeIndex(
gsi_name(name),
parts=[HashKey(name)],
includes=['value']
))
return target(
... | Perform a table schema call.
We call the callable target with the args and keywords needed for the
table defined by cls. This is how we centralize the Table.create and
Table ctor calls. |
def ensure_table(self, cls):
exists = True
conn = get_conn()
try:
descrip = conn.describe_table(cls.get_table_name())
assert descrip is not None
except ResourceNotFoundException:
# Expected - this is what we get if there is no table
... | Required functionality. |
def find_one(self, cls, id):
try:
db_result = self.get_class_table(cls).lookup(id)
except ItemNotFound:
# according to docs, this shouldn't be required, but it IS
db_result = None
if not db_result:
return None
obj = cls.from_data... | Required functionality. |
def find_all(self, cls):
final_results = []
table = self.get_class_table(cls)
for db_result in table.scan():
obj = cls.from_data(db_result['value'])
final_results.append(obj)
return final_results | Required functionality. |
def find_by_index(self, cls, index_name, value):
query_args = {
index_name + '__eq': DynamoMappings.map_index_val(value),
'index': gsi_name(index_name)
}
final_results = []
for db_result in self.get_class_table(cls).query_2(**query_args):
obj... | Required functionality. |
def save(self, obj):
if not obj.id:
obj.id = uuid()
stored_data = {
'id': obj.id,
'value': obj.to_data()
}
index_vals = obj.indexes() or {}
for key in obj.__class__.index_names() or []:
val = index_vals.get(key, '')
... | Required functionality. |
def process_event(self, name, subject, data):
method_mapping = Registry.get_event(name)
if not method_mapping:
log.info('@{}.process_event no subscriber for event `{}`'
.format(self.__class__.__name__, name))
return
for event, methods in meth... | Process a single event.
:param name:
:param subject:
:param data: |
def thread(self):
log.info('@{}.thread starting'.format(self.__class__.__name__))
thread = threading.Thread(target=thread_wrapper(self.consume), args=())
thread.daemon = True
thread.start() | Start a thread for this consumer. |
def create(parser: Parser, obj: PersistedObject = None):
if obj is not None:
return _InvalidParserException('Error ' + str(obj) + ' cannot be parsed using ' + str(parser) + ' since '
+ ' this parser does not support ' + obj.get_pretty_file_mode())
... | Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parser:
:param obj:
:return: |
def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
pass | First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:
:param obj:
:param parsing_plan_for_children:
:param logger:
:param options:
:return: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.