function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def load(
pipette_model: PipetteModel,
pipette_id: str = None) -> PipetteConfig:
"""
Load pipette config data
This function loads from a combination of
- the pipetteModelSpecs.json file in the wheel (should never be edited)
- the pipetteNameSpecs.json file in the wheel (should never be edited)
- any config overrides found in
``opentrons.config.CONFIG['pipette_config_overrides_dir']``
This function reads from disk each time, so changes to the overrides
will be picked up in subsequent calls.
:param str pipette_model: The pipette model name (i.e. "p10_single_v1.3")
for which to load configuration
:param pipette_id: An (optional) unique ID for the pipette to locate
config overrides. If the ID is not specified, the system
assumes this is a simulated pipette and does not
save settings. If the ID is specified but no overrides
corresponding to the ID are found, the system creates a
new overrides file for it.
:type pipette_id: str or None
:raises KeyError: if ``pipette_model`` is not in the top-level keys of
the pipetteModelSpecs.json file (and therefore not in
:py:attr:`configs`)
:returns PipetteConfig: The configuration, loaded and checked
"""
# Load the model config and update with the name config
cfg = fuse_specs(pipette_model)
# Load overrides if we have a pipette id
if pipette_id:
try:
override = load_overrides(pipette_id)
if 'quirks' in override.keys():
override['quirks'] = [
qname for qname, qval in override['quirks'].items()
if qval]
for legacy_key in (
'defaultAspirateFlowRate',
'defaultDispenseFlowRate',
'defaultBlowOutFlowRate'):
override.pop(legacy_key, None)
except FileNotFoundError:
save_overrides(pipette_id, {}, pipette_model)
log.info(
"Save defaults for pipette model {} and id {}".format(
pipette_model, pipette_id))
else:
cfg.update(override) # type: ignore
# the ulPerMm functions are structured in pipetteModelSpecs.json as
# a list sorted from oldest to newest. That means the latest functions
# are always the last element and, as of right now, the older ones are
# the first element (for models that only have one function, the first
# and last elements are the same, which is fine). If we add more in the
# future, we’ll have to change this code to select items more
# intelligently
if ff.use_old_aspiration_functions():
log.debug("Using old aspiration functions")
ul_per_mm = cfg['ulPerMm'][0]
else:
ul_per_mm = cfg['ulPerMm'][-1]
smoothie_configs = cfg['smoothieConfigs']
res = PipetteConfig(
top=ensure_value(
cfg, 'top', MUTABLE_CONFIGS),
bottom=ensure_value(
cfg, 'bottom', MUTABLE_CONFIGS),
blow_out=ensure_value(
cfg, 'blowout', MUTABLE_CONFIGS),
drop_tip=ensure_value(
cfg, 'dropTip', MUTABLE_CONFIGS),
pick_up_current=ensure_value(cfg, 'pickUpCurrent', MUTABLE_CONFIGS),
pick_up_distance=ensure_value(cfg, 'pickUpDistance', MUTABLE_CONFIGS),
pick_up_increment=ensure_value(
cfg, 'pickUpIncrement', MUTABLE_CONFIGS),
pick_up_presses=ensure_value(cfg, 'pickUpPresses', MUTABLE_CONFIGS),
pick_up_speed=ensure_value(cfg, 'pickUpSpeed', MUTABLE_CONFIGS),
aspirate_flow_rate=cfg['defaultAspirateFlowRate']['value'],
dispense_flow_rate=cfg['defaultDispenseFlowRate']['value'],
channels=ensure_value(cfg, 'channels', MUTABLE_CONFIGS),
model_offset=ensure_value(cfg, 'modelOffset', MUTABLE_CONFIGS),
plunger_current=ensure_value(cfg, 'plungerCurrent', MUTABLE_CONFIGS),
drop_tip_current=ensure_value(cfg, 'dropTipCurrent', MUTABLE_CONFIGS),
drop_tip_speed=ensure_value(cfg, 'dropTipSpeed', MUTABLE_CONFIGS),
min_volume=ensure_value(cfg, 'minVolume', MUTABLE_CONFIGS),
max_volume=ensure_value(cfg, 'maxVolume', MUTABLE_CONFIGS),
ul_per_mm=ul_per_mm,
quirks=validate_quirks(ensure_value(cfg, 'quirks', MUTABLE_CONFIGS)),
tip_overlap=cfg['tipOverlap'],
tip_length=ensure_value(cfg, 'tipLength', MUTABLE_CONFIGS),
display_name=ensure_value(cfg, 'displayName', MUTABLE_CONFIGS),
name=cfg['name'],
back_compat_names=cfg.get('backCompatNames', []),
return_tip_height=cfg.get('returnTipHeight', 0.5),
blow_out_flow_rate=cfg['defaultBlowOutFlowRate']['value'],
max_travel=smoothie_configs['travelDistance'],
home_position=smoothie_configs['homePosition'],
steps_per_mm=smoothie_configs['stepsPerMM'],
idle_current=cfg.get('idleCurrent', LOW_CURRENT_DEFAULT),
default_blow_out_flow_rates=cfg['defaultBlowOutFlowRate'].get(
'valuesByApiLevel',
{'2.0': cfg['defaultBlowOutFlowRate']['value']}),
default_dispense_flow_rates=cfg['defaultDispenseFlowRate'].get(
'valuesByApiLevel',
{'2.0': cfg['defaultDispenseFlowRate']['value']}),
default_aspirate_flow_rates=cfg['defaultAspirateFlowRate'].get(
'valuesByApiLevel',
{'2.0': cfg['defaultAspirateFlowRate']['value']}),
model=pipette_model,
)
return res | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def validate_overrides(data: TypeOverrides,
config_model: Dict) -> None:
"""
Check that override fields are valid.
:param data: a dict of field name to value
:param config_model: the configuration for the chosen model
:raises ValueError: If a value is invalid
"""
for key, value in data.items():
field_config = config_model.get(key)
is_quirk = key in config_model['quirks']
if is_quirk:
# If it's a quirk it must be a bool or None
if value is not None and not isinstance(value, bool):
raise ValueError(f'{value} is invalid for {key}')
elif not field_config:
# If it's not a quirk we must have a field config
raise ValueError(f'Unknown field {key}')
elif value is not None:
# If value is not None it must be numeric and between min and max
if not isinstance(value, numbers.Number):
raise ValueError(f'{value} is invalid for {key}')
elif value < field_config['min'] or value > field_config['max']:
raise ValueError(f'{key} out of range with {value}') | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def save_overrides(pipette_id: str,
overrides: TypeOverrides,
model: PipetteModel):
"""
Save overrides for the pipette.
:param pipette_id: The pipette id
:param overrides: The incoming values
:param model: The model of pipette
:return: None
"""
override_dir = config.CONFIG['pipette_config_overrides_dir']
model_configs = configs[model]
model_configs_quirks = {key: True for key in model_configs['quirks']}
try:
existing = load_overrides(pipette_id)
# Add quirks setting for pipettes already with a pipette id file
if 'quirks' not in existing.keys():
existing['quirks'] = model_configs_quirks
except FileNotFoundError:
existing = model_configs_quirks # type: ignore
for key, value in overrides.items():
# If an existing override is saved as null from endpoint, remove from
# overrides file
if value is None:
if existing.get(key):
del existing[key]
elif isinstance(value, bool):
existing, model_configs = change_quirks(
{key: value}, existing, model_configs)
else:
# type ignores are here because mypy needs typed dict accesses to
# be string literals sadly enough
model_config_value = model_configs[key] # type: ignore
if not model_config_value.get('default'):
model_config_value['default']\
= model_config_value['value']
model_config_value['value'] = value
existing[key] = model_config_value
assert model in config_models
existing['model'] = model
json.dump(existing, (override_dir/f'{pipette_id}.json').open('w')) | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def load_overrides(pipette_id: str) -> Dict[str, Any]:
overrides = config.CONFIG['pipette_config_overrides_dir']
fi = (overrides/f'{pipette_id}.json').open()
try:
return json.load(fi)
except json.JSONDecodeError as e:
log.warning(f'pipette override for {pipette_id} is corrupt: {e}')
(overrides/f'{pipette_id}.json').unlink()
raise FileNotFoundError(str(overrides/f'{pipette_id}.json')) | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def ensure_value(
config: PipetteFusedSpec,
name: Union[str, Tuple[str, ...]],
mutable_config_list: List[str]):
"""
Pull value of config data from file. Shape can either be a dictionary with
a value key -- indicating that it can be changed -- or another
data structure such as an array.
"""
if not isinstance(name, tuple):
path: Tuple[str, ...] = (name,)
else:
path = name
for element in path[:-1]:
config = config[element] # type: ignore
value = config[path[-1]] # type: ignore
if path[-1] != 'quirks' and path[-1] in mutable_config_list:
value = value['value']
return value | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def add_default(cfg):
if isinstance(cfg, dict):
if 'value' in cfg.keys():
cfg['default'] = cfg['value']
else:
for top_level_key in cfg.keys():
add_default(cfg[top_level_key]) | Opentrons/labware | [
323,
152,
323,
668,
1436215261
] |
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback') | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_all_policy_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_all_policy = ET.Element("maps_get_all_policy")
config = maps_get_all_policy
input = ET.SubElement(maps_get_all_policy, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_all_policy_output_policy_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_all_policy = ET.Element("maps_get_all_policy")
config = maps_get_all_policy
output = ET.SubElement(maps_get_all_policy, "output")
policy = ET.SubElement(output, "policy")
policyname = ET.SubElement(policy, "policyname")
policyname.text = kwargs.pop('policyname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
input = ET.SubElement(maps_get_rules, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_rbridgeid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
rbridgeid = ET.SubElement(rules, "rbridgeid")
rbridgeid.text = kwargs.pop('rbridgeid')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_rulename(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
rulename = ET.SubElement(rules, "rulename")
rulename.text = kwargs.pop('rulename')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_groupname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
groupname = ET.SubElement(rules, "groupname")
groupname.text = kwargs.pop('groupname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_monitor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
monitor = ET.SubElement(rules, "monitor")
monitor.text = kwargs.pop('monitor')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_op(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
op = ET.SubElement(rules, "op")
op.text = kwargs.pop('op')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
value = ET.SubElement(rules, "value")
value.text = kwargs.pop('value')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
action = ET.SubElement(rules, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_timebase(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
timebase = ET.SubElement(rules, "timebase")
timebase.text = kwargs.pop('timebase')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
policyname = ET.SubElement(rules, "policyname")
policyname.text = kwargs.pop('policyname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_all_policy_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_all_policy = ET.Element("maps_get_all_policy")
config = maps_get_all_policy
input = ET.SubElement(maps_get_all_policy, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_all_policy_output_policy_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_all_policy = ET.Element("maps_get_all_policy")
config = maps_get_all_policy
output = ET.SubElement(maps_get_all_policy, "output")
policy = ET.SubElement(output, "policy")
policyname = ET.SubElement(policy, "policyname")
policyname.text = kwargs.pop('policyname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
input = ET.SubElement(maps_get_rules, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_rbridgeid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
rbridgeid = ET.SubElement(rules, "rbridgeid")
rbridgeid.text = kwargs.pop('rbridgeid')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_rulename(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
rulename = ET.SubElement(rules, "rulename")
rulename.text = kwargs.pop('rulename')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_groupname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
groupname = ET.SubElement(rules, "groupname")
groupname.text = kwargs.pop('groupname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_monitor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
monitor = ET.SubElement(rules, "monitor")
monitor.text = kwargs.pop('monitor')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_op(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
op = ET.SubElement(rules, "op")
op.text = kwargs.pop('op')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
value = ET.SubElement(rules, "value")
value.text = kwargs.pop('value')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
action = ET.SubElement(rules, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_timebase(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
timebase = ET.SubElement(rules, "timebase")
timebase.text = kwargs.pop('timebase')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def maps_get_rules_output_rules_policyname(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
maps_get_rules = ET.Element("maps_get_rules")
config = maps_get_rules
output = ET.SubElement(maps_get_rules, "output")
rules = ET.SubElement(output, "rules")
policyname = ET.SubElement(rules, "policyname")
policyname.text = kwargs.pop('policyname')
callback = kwargs.pop('callback', self._callback)
return callback(config) | BRCDcomm/pynos | [
16,
8,
16,
2,
1437520628
] |
def xpath_tokenizer(pattern, namespaces=None):
# ElementTree uses '', lxml used None originally.
default_namespace = (namespaces.get(None) or namespaces.get('')) if namespaces else None
parsing_attribute = False
for token in xpath_tokenizer_re.findall(pattern):
ttype, tag = token
if tag and tag[0] != "{":
if ":" in tag:
prefix, uri = tag.split(":", 1)
try:
if not namespaces:
raise KeyError
yield ttype, "{%s}%s" % (namespaces[prefix], uri)
except KeyError:
raise SyntaxError("prefix %r not found in prefix map" % prefix)
elif default_namespace and not parsing_attribute:
yield ttype, "{%s}%s" % (default_namespace, tag)
else:
yield token
parsing_attribute = False
else:
yield token
parsing_attribute = ttype == '@' | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def select(result):
for elem in result:
for e in elem.iterchildren(tag):
yield e | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def prepare_star(next, token):
def select(result):
for elem in result:
for e in elem.iterchildren('*'):
yield e
return select | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def select(result):
return result | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def prepare_descendant(next, token):
token = next()
if token[0] == "*":
tag = "*"
elif not token[0]:
tag = token[1]
else:
raise SyntaxError("invalid descendant")
def select(result):
for elem in result:
for e in elem.iterdescendants(tag):
yield e
return select | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def select(result):
for elem in result:
parent = elem.getparent()
if parent is not None:
yield parent | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def prepare_predicate(next, token):
# FIXME: replace with real parser!!! refs:
# http://effbot.org/zone/simple-iterator-parser.htm
# http://javascript.crockford.com/tdop/tdop.html
signature = ''
predicate = []
while 1:
token = next()
if token[0] == "]":
break
if token == ('', ''):
# ignore whitespace
continue
if token[0] and token[0][:1] in "'\"":
token = "'", token[0][1:-1]
signature += token[0] or "-"
predicate.append(token[1])
# use signature to determine predicate type
if signature == "@-":
# [@attribute] predicate
key = predicate[1]
def select(result):
for elem in result:
if elem.get(key) is not None:
yield elem
return select
if signature == "@-='":
# [@attribute='value']
key = predicate[1]
value = predicate[-1]
def select(result):
for elem in result:
if elem.get(key) == value:
yield elem
return select
if signature == "-" and not re.match(r"-?\d+$", predicate[0]):
# [tag]
tag = predicate[0]
def select(result):
for elem in result:
for _ in elem.iterchildren(tag):
yield elem
break
return select
if signature == ".='" or (signature == "-='" and not re.match(r"-?\d+$", predicate[0])):
# [.='value'] or [tag='value']
tag = predicate[0]
value = predicate[-1]
if tag:
def select(result):
for elem in result:
for e in elem.iterchildren(tag):
if "".join(e.itertext()) == value:
yield elem
break
else:
def select(result):
for elem in result:
if "".join(elem.itertext()) == value:
yield elem
return select
if signature == "-" or signature == "-()" or signature == "-()-":
# [index] or [last()] or [last()-index]
if signature == "-":
# [index]
index = int(predicate[0]) - 1
if index < 0:
if index == -1:
raise SyntaxError(
"indices in path predicates are 1-based, not 0-based")
else:
raise SyntaxError("path index >= 1 expected")
else:
if predicate[0] != "last":
raise SyntaxError("unsupported function")
if signature == "-()-":
try:
index = int(predicate[2]) - 1
except ValueError:
raise SyntaxError("unsupported expression")
else:
index = -1
def select(result):
for elem in result:
parent = elem.getparent()
if parent is None:
continue
try:
# FIXME: what if the selector is "*" ?
elems = list(parent.iterchildren(elem.tag))
if elems[index] is elem:
yield elem
except IndexError:
pass
return select
raise SyntaxError("invalid predicate") | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def _build_path_iterator(path, namespaces):
"""compile selector pattern"""
if path[-1:] == "/":
path += "*" # implicit all (FIXME: keep this?)
cache_key = (path,)
if namespaces:
# lxml originally used None for the default namespace but ElementTree uses the
# more convenient (all-strings-dict) empty string, so we support both here,
# preferring the more convenient '', as long as they aren't ambiguous.
if None in namespaces:
if '' in namespaces and namespaces[None] != namespaces['']:
raise ValueError("Ambiguous default namespace provided: %r versus %r" % (
namespaces[None], namespaces['']))
cache_key += (namespaces[None],) + tuple(sorted(
item for item in namespaces.items() if item[0] is not None))
else:
cache_key += tuple(sorted(namespaces.items()))
try:
return _cache[cache_key]
except KeyError:
pass
if len(_cache) > 100:
_cache.clear()
if path[:1] == "/":
raise SyntaxError("cannot use absolute path on element")
stream = iter(xpath_tokenizer(path, namespaces))
try:
_next = stream.next
except AttributeError:
# Python 3
_next = stream.__next__
try:
token = _next()
except StopIteration:
raise SyntaxError("empty path expression")
selector = []
while 1:
try:
selector.append(ops[token[0]](_next, token))
except StopIteration:
raise SyntaxError("invalid path")
try:
token = _next()
if token[0] == "/":
token = _next()
except StopIteration:
break
_cache[cache_key] = selector
return selector | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def iterfind(elem, path, namespaces=None):
selector = _build_path_iterator(path, namespaces)
result = iter((elem,))
for select in selector:
result = select(result)
return result | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def find(elem, path, namespaces=None):
it = iterfind(elem, path, namespaces)
try:
return next(it)
except StopIteration:
return None | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def findall(elem, path, namespaces=None):
return list(iterfind(elem, path, namespaces)) | lxml/lxml | [
2302,
530,
2302,
22,
1297402991
] |
def test_traverse():
provider1 = providers.Provider()
provided = provider1.provided
method = provided.method
provider = method.call()
all_providers = list(provider.traverse())
assert len(all_providers) == 3
assert provider1 in all_providers
assert provided in all_providers
assert method in all_providers | ets-labs/python-dependency-injector | [
2723,
206,
2723,
132,
1420377785
] |
def test_traverse_kwargs():
provider1 = providers.Provider()
provided = provider1.provided
method = provided.method
provider2 = providers.Provider()
provider = method.call(foo="foo", bar=provider2)
all_providers = list(provider.traverse())
assert len(all_providers) == 4
assert provider1 in all_providers
assert provider2 in all_providers
assert provided in all_providers
assert method in all_providers | ets-labs/python-dependency-injector | [
2723,
206,
2723,
132,
1420377785
] |
def _TimeoutRetryWrapper(f, timeout_func, retries_func, pass_values=False):
""" Wraps a funcion with timeout and retry handling logic.
Args:
f: The function to wrap.
timeout_func: A callable that returns the timeout value.
retries_func: A callable that returns the retries value.
pass_values: If True, passes the values returned by |timeout_func| and
|retries_func| to the wrapped function as 'timeout' and
'retries' kwargs, respectively.
Returns:
The wrapped function.
"""
@functools.wraps(f)
def timeout_retry_wrapper(*args, **kwargs):
timeout = timeout_func(*args, **kwargs)
retries = retries_func(*args, **kwargs)
if pass_values:
kwargs['timeout'] = timeout
kwargs['retries'] = retries
@functools.wraps(f)
def impl():
return f(*args, **kwargs)
try:
if timeout_retry.CurrentTimeoutThreadGroup():
# Don't wrap if there's already an outer timeout thread.
return impl()
else:
desc = '%s(%s)' % (f.__name__, ', '.join(itertools.chain(
(str(a) for a in args),
('%s=%s' % (k, str(v)) for k, v in kwargs.iteritems()))))
return timeout_retry.Run(impl, timeout, retries, desc=desc)
except reraiser_thread.TimeoutError as e:
raise device_errors.CommandTimeoutError(str(e)), None, (
sys.exc_info()[2])
except cmd_helper.TimeoutError as e:
raise device_errors.CommandTimeoutError(str(e)), None, (
sys.exc_info()[2])
return timeout_retry_wrapper | Teamxrtc/webrtc-streaming-node | [
6,
5,
6,
2,
1449773735
] |
def WithExplicitTimeoutAndRetries(timeout, retries):
"""Returns a decorator that handles timeouts and retries.
The provided |timeout| and |retries| values are always used.
Args:
timeout: The number of seconds to wait for the decorated function to
return. Always used.
retries: The number of times the decorated function should be retried on
failure. Always used.
Returns:
The actual decorator.
"""
def decorator(f):
get_timeout = lambda *a, **kw: timeout
get_retries = lambda *a, **kw: retries
return _TimeoutRetryWrapper(f, get_timeout, get_retries)
return decorator | Teamxrtc/webrtc-streaming-node | [
6,
5,
6,
2,
1449773735
] |
def decorator(f):
get_timeout = lambda *a, **kw: kw.get('timeout', default_timeout)
get_retries = lambda *a, **kw: kw.get('retries', default_retries)
return _TimeoutRetryWrapper(f, get_timeout, get_retries, pass_values=True) | Teamxrtc/webrtc-streaming-node | [
6,
5,
6,
2,
1449773735
] |
def generateRecursorConfig(cls, confdir):
authzonepath = os.path.join(confdir, 'authzone.zone')
with open(authzonepath, 'w') as authzone:
authzone.write("""$ORIGIN authzone.example. | PowerDNS/pdns | [
3002,
827,
3002,
852,
1366975009
] |
def sendTCPQueryKeepOpen(cls, sock, query, timeout=2.0):
try:
wire = query.to_wire()
sock.send(struct.pack("!H", len(wire)))
sock.send(wire)
data = sock.recv(2)
if data:
(datalen,) = struct.unpack("!H", data)
data = sock.recv(datalen)
except socket.timeout as e:
print("Timeout: %s" % (str(e)))
data = None
except socket.error as e:
print("Network error: %s" % (str(e)))
data = None
message = None
if data:
message = dns.message.from_wire(data)
return message | PowerDNS/pdns | [
3002,
827,
3002,
852,
1366975009
] |
def autoreconf(self, spec, prefix):
autogen = Executable('./autogen.sh')
autogen() | LLNL/spack | [
3244,
1839,
3244,
2847,
1389172932
] |
def test_allow_any_authorization():
authorizer = get_authorizer(None)
authorization = authorizer.get_authorization('tool1')
authorization.authorize_setup()
authorization.authorize_tool_file('cow', '#!/bin/bash\necho "Hello World!"') | galaxyproject/pulsar | [
36,
43,
36,
69,
1403216408
] |
def setUp(self):
self.toolbox = get_test_toolbox()
self.authorizer = get_authorizer(self.toolbox) | galaxyproject/pulsar | [
36,
43,
36,
69,
1403216408
] |
def test_invalid_setup_fails(self):
with self.unauthorized_expectation():
self.authorizer.get_authorization('tool2').authorize_setup() | galaxyproject/pulsar | [
36,
43,
36,
69,
1403216408
] |
def test_invalid_tool_file_fails(self):
authorization = self.authorizer.get_authorization('tool1')
with self.unauthorized_expectation():
authorization.authorize_tool_file('tool1_wrapper.py', '#!/bin/sh\nrm -rf /valuable/data') | galaxyproject/pulsar | [
36,
43,
36,
69,
1403216408
] |
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=False)
### end Alembic commands ### | gateway4labs/labmanager | [
13,
9,
13,
31,
1354207127
] |
def get_movie(self, id):
return self.browser.get_movie(id) | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def iter_movies(self, pattern):
return self.browser.iter_movies(pattern.encode('utf-8')) | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def iter_movie_persons(self, id, role=None):
return self.browser.iter_movie_persons(id, role) | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def iter_person_movies_ids(self, id):
return self.browser.iter_person_movies_ids(id) | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def get_person_biography(self, id):
return self.browser.get_person_biography(id) | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def fill_person(self, person, fields):
if 'real_name' in fields or 'birth_place' in fields\
or 'death_date' in fields or 'nationality' in fields\
or 'short_biography' in fields or 'roles' in fields\
or 'birth_date' in fields or 'thumbnail_url' in fields\
or 'biography' in fields\
or 'gender' in fields or fields is None:
per = self.get_person(person.id)
person.real_name = per.real_name
person.birth_date = per.birth_date
person.death_date = per.death_date
person.birth_place = per.birth_place
person.gender = per.gender
person.nationality = per.nationality
person.short_biography = per.short_biography
person.short_description = per.short_description
person.roles = per.roles
person.biography = per.biography
person.thumbnail_url = per.thumbnail_url
return person | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def fill_video(self, video, fields):
if 'url' in fields:
with self.browser:
if not isinstance(video, BaseVideo):
video = self.get_video(self, video.id)
if hasattr(video, '_video_code'):
video.url = unicode(self.browser.get_video_url(video._video_code))
if 'thumbnail' in fields and video and video.thumbnail:
with self.browser:
video.thumbnail.data = self.browser.readurl(video.thumbnail.url)
return video | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def iter_resources(self, objs, split_path):
with self.browser:
if BaseVideo in objs:
collection = self.get_collection(objs, split_path)
if collection.path_level == 0:
yield Collection([u'comingsoon'], u'Films prochainement au cinéma')
yield Collection([u'nowshowing'], u'Films au cinéma')
yield Collection([u'acshow'], u'Émissions')
yield Collection([u'interview'], u'Interviews')
if collection.path_level == 1:
if collection.basename == u'acshow':
emissions = self.browser.get_emissions(collection.basename)
if emissions:
for emission in emissions:
yield emission
elif collection.basename == u'interview':
videos = self.browser.get_categories_videos(collection.basename)
if videos:
for video in videos:
yield video
else:
videos = self.browser.get_categories_movies(collection.basename)
if videos:
for video in videos:
yield video
if collection.path_level == 2:
videos = self.browser.get_categories_videos(':'.join(collection.split_path))
if videos:
for video in videos:
yield video | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def search_events(self, query):
with self.browser:
if CATEGORIES.CINE in query.categories:
if query.city and re.match('\d{5}', query.city):
events = list(self.browser.search_events(query))
events.sort(key=lambda x: x.start_date, reverse=False)
return events
raise UserError('You must enter a zip code in city field') | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def fill_event(self, event, fields):
if 'description' in fields:
movieCode = event.id.split('#')[2]
movie = self.get_movie(movieCode)
event.description = movie.pitch
return event | frankrousseau/weboob | [
4,
3,
4,
1,
1381825736
] |
def main():
colorama.init()
# gratuitous use of lambda.
pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
# draw a white border.
print(Back.WHITE, end='')
print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='')
# draw some blinky lights for a while.
for i in range(PASSES):
print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='')
# put cursor to top, left, and set color to white-on-black with normal brightness.
print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='') | Teamxrtc/webrtc-streaming-node | [
6,
5,
6,
2,
1449773735
] |
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != output:
if verbose:
print 'no'
print f, `input`, `output`, `value`
else:
if verbose:
print 'yes' | atmark-techno/atmark-dist | [
3,
2,
3,
4,
1476164728
] |
def __init__(self): self.seq = 'wxyz' | atmark-techno/atmark-dist | [
3,
2,
3,
4,
1476164728
] |
def __getitem__(self, i): return self.seq[i] | atmark-techno/atmark-dist | [
3,
2,
3,
4,
1476164728
] |
def batch_row_ids(data_batch):
""" Generate row ids based on the current mini-batch """
return {'weight': data_batch.data[0].indices} | dmlc/mxnet | [
20293,
6870,
20293,
1995,
1430410875
] |
def SOCKSProxyManager(*args, **kwargs):
raise InvalidSchema("Missing dependencies for SOCKS support.") | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def __init__(self):
super(BaseAdapter, self).__init__() | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def close(self):
"""Cleans up adapter specific items."""
raise NotImplementedError | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
self.max_retries = Retry.from_int(max_retries)
self.config = {}
self.proxy_manager = {}
super(HTTPAdapter, self).__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._pool_block = pool_block
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
# self.poolmanager uses a lambda function, which isn't pickleable.
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
block=self._pool_block) | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
:rtype: urllib3.ProxyManager
"""
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith('socks'):
username, password = get_auth_from_url(proxy)
manager = self.proxy_manager[proxy] = SOCKSProxyManager(
proxy,
username=username,
password=password,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs
)
else:
proxy_headers = self.proxy_headers(proxy)
manager = self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return manager | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
:rtype: requests.Response
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear() | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass | momm3/WelcomeBot | [
1,
1,
1,
1,
1500546203
] |
def _encode(input,errors='strict'):
# split to see if we have any 'extended' characters
runs=unicode_splitter.split(input) | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def _decode(input,errors='strict'):
# opposite of above, look for multibye 'marker'
# and handle it ourselves, pass the rest to the
# standard decoder | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def encode(self,input,errors='strict'):
return _encode(input,errors) | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def encode(self, input, final=False):
# just use the standard encoding as there is no need
# to hold state
return _encode(input,self.errors)[0] | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def __init__(self,errors='strict'):
codecs.IncrementalDecoder.__init__(self,errors)
self.last_saw_mark=False | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def reset(self):
self.last_saw_mark=False | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def getregentry():
return codecs.CodecInfo(
name='gsm0338',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
) | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def _inc_encode(ie):
encoded=list()
hop=17 # make it something odd
final=False
for i in range(0,len(gsm_alpha),hop):
end=i+hop
if end>=len(gsm_alpha): final=True
encoded.append(ie.encode(gsm_alpha[i:end],final))
return ''.join(encoded) | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def _inc_decode(idec):
decoded=list()
# define so we KNOW we hit a mark as last char
hop=gsm_alpha_gsm.index('\x1b')+1
final=False
for i in range(0,len(gsm_alpha_gsm),hop):
end=i+hop
if end>=len(gsm_alpha_gsm): final=True
decoded.append(idec.decode(gsm_alpha_gsm[i:end],final))
return ''.join(decoded) | developmentseed/slingshotSMS | [
55,
21,
55,
1,
1250476174
] |
def macroop INS_M_R {
# Find the constant we need to either add or subtract from rdi
ruflag t0, 10
movi t3, t3, dsz, flags=(CEZF,), dataSize=asz
subi t4, t0, dsz, dataSize=asz
mov t3, t3, t4, flags=(nCEZF,), dataSize=asz
zexti t2, reg, 15, dataSize=8
mfence
ld t6, intseg, [1, t2, t0], "IntAddrPrefixIO << 3", addressSize=8, \
nonSpec=True
st t6, es, [1, t0, rdi]
mfence
add rdi, rdi, t3, dataSize=asz | austinharris/gem5-riscv | [
11,
2,
11,
1,
1435967033
] |
def macroop INS_E_M_R {
and t0, rcx, rcx, flags=(EZF,), dataSize=asz
br label("end"), flags=(CEZF,)
# Find the constant we need to either add or subtract from rdi
ruflag t0, 10
movi t3, t3, dsz, flags=(CEZF,), dataSize=asz
subi t4, t0, dsz, dataSize=asz
mov t3, t3, t4, flags=(nCEZF,), dataSize=asz
zexti t2, reg, 15, dataSize=8
mfence | austinharris/gem5-riscv | [
11,
2,
11,
1,
1435967033
] |
def macroop OUTS_R_M {
# Find the constant we need to either add or subtract from rdi
ruflag t0, 10
movi t3, t3, dsz, flags=(CEZF,), dataSize=asz
subi t4, t0, dsz, dataSize=asz
mov t3, t3, t4, flags=(nCEZF,), dataSize=asz
zexti t2, reg, 15, dataSize=8
mfence
ld t6, ds, [1, t0, rsi]
st t6, intseg, [1, t2, t0], "IntAddrPrefixIO << 3", addressSize=8, \
nonSpec=True
mfence
add rsi, rsi, t3, dataSize=asz | austinharris/gem5-riscv | [
11,
2,
11,
1,
1435967033
] |
def macroop OUTS_E_R_M {
and t0, rcx, rcx, flags=(EZF,), dataSize=asz
br label("end"), flags=(CEZF,)
# Find the constant we need to either add or subtract from rdi
ruflag t0, 10
movi t3, t3, dsz, flags=(CEZF,), dataSize=asz
subi t4, t0, dsz, dataSize=asz
mov t3, t3, t4, flags=(nCEZF,), dataSize=asz
zexti t2, reg, 15, dataSize=8
mfence | austinharris/gem5-riscv | [
11,
2,
11,
1,
1435967033
] |
def __init__(self, config_section, defaults=None, config_path=None, secrets_dir=None,
throw_exception=False, allow_no_value=True):
"""
Config files will be checked in /etc/panw be default. If a PANW_CONFIG env exists, it will pull the path from
there When setting variable values, make sure that you can have an ALL_CAPS setting that will work without
colliding in an environment variable Settings and sections should be lower_case_underscore
"""
if defaults is None:
defaults = {}
if not secrets_dir and 'SECRETS_DIR' in os.environ:
secrets_dir = os.environ.get("SECRETS_DIR")
self.secrets_dir = secrets_dir
# GSRTTECH-5222
self.parser = configparser.ConfigParser(defaults, allow_no_value=allow_no_value)
if not config_path and 'PANW_CONFIG' in os.environ:
config_path = os.environ.get('PANW_CONFIG')
if not config_path:
for known_path in [os.path.expanduser("~") + "/.config/panw", "/opt/.config/panw", "/etc/panw/config"]:
if os.path.isfile(known_path):
config_path = known_path
break
self.config_path = config_path
# Only read the file if the config_path is a true value
if config_path:
if os.path.isfile(config_path):
self.parser.read(os.path.expanduser(config_path))
else:
raise Exception("PANW_CONFIG=%s is not a valid file" % config_path)
# We'll stub out a blank section in case it doesn't exist, this prevents exceptions from being thrown
if not self.parser.has_section(config_section):
self.parser.add_section(config_section)
self.config_section = config_section
self.throw_exception = throw_exception | PaloAltoNetworks-BD/autofocus-client-library | [
18,
12,
18,
4,
1443801109
] |
def get_int(self, *args, **kwargs):
""" Cast raw value to int
Returns:
int: value cast to int
"""
# TODO: Make this mimic the config parser behavior. Does it throw exceptions?
return int(self.get_setting(*args, **kwargs)) | PaloAltoNetworks-BD/autofocus-client-library | [
18,
12,
18,
4,
1443801109
] |
def get_boolean(self, *args, **kwargs):
""" Returns boolean for parsed value. Parsed value must be one of
["1", "yes", "on", "true", "0", "no", "off", "false"]
Returns:
bool: boolean value representation of provided value
Raises:
ValueError: value provided was not a known boolean string value.
"""
value = self.get_setting(*args, **kwargs)
value = str(value).lower()
if value in ["1", "yes", "on", "true"]:
return True
elif value in ["0", "no", "off", "false"]:
return False
else:
raise ValueError("unexpected value '%s' provided" % value) | PaloAltoNetworks-BD/autofocus-client-library | [
18,
12,
18,
4,
1443801109
] |
def get_setting(self, name, section=None, throw_exception=None):
"""
Setting names should always be lower_case_underscore
Well check the config and environment variables for the name. Environment variables will be made all caps
when checked
Args:
name (str): attribute name to get
section (Optional[str]): section name to retrieve attribute from, will default to self.config_section
throw_exception (Optional[bool]): throw exceptions or not if invalid, default to self.throw_exception
"""
if not section:
section = self.config_section
env_key = section.upper() + "_" + name.upper()
if env_key in os.environ:
return os.environ.get(env_key)
if self.secrets_dir:
secrets_file = os.path.join(self.secrets_dir,
"{}_{}".format(section, name))
if os.path.isfile(secrets_file):
with open(secrets_file, "r") as fh:
return fh.read().rstrip()
if throw_exception is None:
throw_exception = self.throw_exception
# ensure section exists - needed here in addition to init for cases where user specifies section in
# `get_setting()`
if not self.parser.has_section(section):
self.parser.add_section(section)
if throw_exception:
return self.parser.get(section, name)
if py2:
try:
return self.parser.get(section, name)
except configparser.NoOptionError:
return None
else:
return self.parser.get(section, name, fallback=None) | PaloAltoNetworks-BD/autofocus-client-library | [
18,
12,
18,
4,
1443801109
] |
def find_origin_coordinate(sites):
""" Find the coordinates of each site within the tile, and then subtract the
smallest coordinate to re-origin them all to be relative to the tile.
"""
if len(sites) == 0:
return 0, 0
def inner_():
for site in sites:
coordinate = SITE_COORDINATE_PATTERN.match(site['name'])
assert coordinate is not None, site
x_coord = int(coordinate.group(2))
y_coord = int(coordinate.group(3))
yield x_coord, y_coord
x_coords, y_coords = zip(*inner_())
min_x_coord = min(x_coords)
min_y_coord = min(y_coords)
return min_x_coord, min_y_coord | SymbiFlow/prjuray | [
48,
12,
48,
18,
1594844148
] |
def main():
site_pins = json5.load(sys.stdin)
output_site_pins = {}
output_site_pins["tile_type"] = site_pins["tile_type"]
output_site_pins["sites"] = copy.deepcopy(site_pins["sites"])
site_pin_to_wires = create_site_pin_to_wire_maps(site_pins['tile_name'],
site_pins['nodes'])
min_x_coord, min_y_coord = find_origin_coordinate(site_pins['sites'])
for site in output_site_pins['sites']:
orig_site_name = site['name']
coordinate = SITE_COORDINATE_PATTERN.match(orig_site_name)
x_coord = int(coordinate.group(2))
y_coord = int(coordinate.group(3))
site['name'] = 'X{}Y{}'.format(x_coord - min_x_coord,
y_coord - min_y_coord)
site['prefix'] = coordinate.group(1)
site['x_coord'] = x_coord - min_x_coord
site['y_coord'] = y_coord - min_y_coord
for site_pin in site['site_pins']:
assert site_pin['name'].startswith(orig_site_name + '/')
if site_pin['name'] in site_pin_to_wires:
site_pin['wire'] = site_pin_to_wires[site_pin['name']]
else:
print(
('***WARNING***: Site pin {} for tile type {} is not connected, '
'make sure all instaces of this tile type has this site_pin '
'disconnected.').format(site_pin['name'],
site_pins['tile_type']),
file=sys.stderr)
site_pin['name'] = site_pin['name'][len(orig_site_name) + 1:]
json.dumps(output_site_pins, indent=2, sort_keys=True) | SymbiFlow/prjuray | [
48,
12,
48,
18,
1594844148
] |
def __init__(self, isPercentageLimits=False, *args, **kw_args):
"""Initialises a new 'LimitSet' instance.
@param isPercentageLimits: Tells if the limit values are in percentage of normalValue or the specified Unit for Measurements and Controls.
"""
#: Tells if the limit values are in percentage of normalValue or the specified Unit for Measurements and Controls.
self.isPercentageLimits = isPercentageLimits
super(LimitSet, self).__init__(*args, **kw_args) | rwl/PyCIM | [
68,
33,
68,
7,
1238978196
] |
def __init__(
self,
plotly_name="sizesrc",
parent_name="scattermapbox.hoverlabel.font",
**kwargs | plotly/python-api | [
13052,
2308,
13052,
1319,
1385013188
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.