input
stringlengths 11
5.29k
| target
stringlengths 20
8.26k
|
---|---|
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def reset(cls):
cls.info = [
[
"Keyboard Control:",
" auto repeat: on key click percent: 0 LED mask: 00000002",
" XKB indicators:",
" 00: Caps Lock: off 01: Num Lock: on 02: Scroll Lock: off",
" 03: Compose: off 04: Kana: off 05: Sleep: off",
],
[
"Keyboard Control:",
" auto repeat: on key click percent: 0 LED mask: 00000002",
" XKB indicators:",
" 00: Caps Lock: on 01: Num Lock: on 02: Scroll Lock: off",
" 03: Compose: off 04: Kana: off 05: Sleep: off",
],
]
cls.index = 0
cls.is_error = False |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_conflicting_initializers(self):
class POINT(Structure):
_fields_ = [("x", c_int), ("y", c_int)]
# conflicting positional and keyword args
self.assertRaises(TypeError, POINT, 2, 3, x=4)
self.assertRaises(TypeError, POINT, 2, 3, y=4)
# too many initializers
self.assertRaises(TypeError, POINT, 2, 3, 4) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_invalid_field_types(self):
class POINT(Structure):
pass
self.assertRaises(TypeError, setattr, POINT, "_fields_", [("x", 1), ("y", 2)]) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get_except(self, func, *args):
try:
func(*args)
except Exception as detail:
return detail.__class__, str(detail) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_abstract_class(self):
class X(Structure):
_abstract_ = "something"
# try 'X()'
cls, msg = self.get_except(eval, "X()", locals())
self.assertEqual((cls, msg), (TypeError, "abstract class")) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_vice_versa(self):
class First(Structure):
pass
class Second(Structure):
pass
First._fields_ = [("second", Second)]
try:
Second._fields_ = [("first", First)]
except AttributeError as details:
self.assertTrue("_fields_ is final" in
str(details))
else:
self.fail("AttributeError not raised") |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def disable_plugin(plugin):
try:
plugin = get_plugin(plugin)
except KeyError:
flash(_("Plugin %(plugin)s not found.", plugin=plugin.name), "danger")
return redirect(url_for("management.plugins"))
try:
plugin.disable()
flash(_("Plugin %(plugin)s disabled. Please restart FlaskBB now.",
plugin=plugin.name), "success")
except OSError:
flash(_("It seems that FlaskBB does not have enough filesystem "
"permissions. Try creating the 'DISABLED' file by "
"yourself instead."), "danger")
return redirect(url_for("management.plugins")) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def with_status_check(obj, *args, **kwargs):
if obj.status not in valid_start_statuses:
exception_msg = (
u"Error calling {} {}: status is '{}', must be one of: {}"
).format(func, obj, obj.status, valid_start_statuses)
raise VerificationException(exception_msg)
return func(obj, *args, **kwargs) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def set_exception(self, exc=True):
self.exception = exc |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def serialize(self, value, display=False):
if value is not None and display:
return "********"
return super().serialize(value, display) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _add_implementor(rpc_code, blocking, fn):
# Validate the argument types.
if type(rpc_code) is not int:
raise TypeError("Expected int, got %r instead" % type(rpc_code))
if type(blocking) is not bool:
raise TypeError("Expected bool, got %r instead" % type(blocking))
if not callable(fn):
raise TypeError("Expected callable, got %r instead" % type(fn))
# Validate the RPC code.
if rpc_code in rpcMap:
try:
msg = "Duplicated RPC implementors for code %d: %s and %s"
msg %= (rpc_code, rpcMap[rpc_code][0].__name__, fn.__name__)
except Exception:
msg = "Duplicated RPC implementors for code: %d" % rpc_code
raise SyntaxError(msg)
# TODO: use introspection to validate the function signature
# Register the implementor.
rpcMap[rpc_code] = (fn, blocking)
# Return the implementor. No wrapping is needed! :)
return fn |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def clean(self, *args, **kwargs):
self.validate_unique()
return super(BaseChildFormSet, self).clean(*args, **kwargs) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def wrap_view(self, view):
"""
Wraps methods so they can be called in a more functional way as well
as handling exceptions better. |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_warning_in_aggregate_results_preprocessors(
caplog, results_preprocessor, expected_value
):
import logging
from copy import deepcopy
from ray.util import debug
caplog.at_level(logging.WARNING)
results1 = [{"a": 1}, {"a": 2}, {"a": 3}, {"a": 4}]
results2 = [{"a": 1}, {"a": "invalid"}, {"a": 3}, {"a": "invalid"}]
results3 = [{"a": "invalid"}, {"a": "invalid"}, {"a": "invalid"}, {"a": "invalid"}]
results4 = [{"a": 1}, {"a": 2}, {"a": 3}, {"c": 4}]
# test case 1: metric key `b` is missing from all workers
results_preprocessor1 = results_preprocessor(["b"])
results_preprocessor1.preprocess(results1)
assert "`b` is not reported from workers, so it is ignored." in caplog.text
# test case 2: some values of key `a` have invalid data type
results_preprocessor2 = results_preprocessor(["a"])
expected2 = deepcopy(results2)
aggregation_key = results_preprocessor2.aggregate_fn.wrap_key("a")
for res in expected2:
res.update({aggregation_key: expected_value})
assert results_preprocessor2.preprocess(results2) == expected2
# test case 3: all key `a` values are invalid
results_preprocessor2.preprocess(results3)
assert "`a` value type is not valid, so it is ignored." in caplog.text
# test case 4: some workers don't report key `a`
expected4 = deepcopy(results4)
aggregation_key = results_preprocessor2.aggregate_fn.wrap_key("a")
for res in expected4:
res.update({aggregation_key: expected_value})
assert results_preprocessor2.preprocess(results4) == expected4
for record in caplog.records:
assert record.levelname == "WARNING"
debug.reset_log_once("b")
debug.reset_log_once("a") |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def prepared_registry(self):
''' prepared_registry property '''
if not self.__prepared_registry:
results = self.prepare_registry()
if not results or ('returncode' in results and results['returncode'] != 0):
raise RegistryException('Could not perform registry preparation. {}'.format(results))
self.__prepared_registry = results
return self.__prepared_registry |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def create_by_id(
self,
policy_assignment_id: str,
parameters: "_models.PolicyAssignment",
**kwargs: Any
) -> "_models.PolicyAssignment":
"""Creates a policy assignment by ID.
Policy assignments are inherited by child resources. For example, when you apply a policy to a
resource group that policy is assigned to all resources in the group. When providing a scope
for the assignment, use '/subscriptions/{subscription-id}/' for subscriptions,
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups,
and
'/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}'
for resources.
:param policy_assignment_id: The ID of the policy assignment to create. Use the format
'/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'.
:type policy_assignment_id: str
:param parameters: Parameters for policy assignment.
:type parameters: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:keyword callable cls: A custom type or function that will be passed the direct response
:return: PolicyAssignment, or the result of cls(response)
:rtype: ~azure.mgmt.resource.policy.v2016_12_01.models.PolicyAssignment
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.PolicyAssignment"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop('content_type', "application/json") # type: Optional[str]
_json = self._serialize.body(parameters, 'PolicyAssignment')
request = build_create_by_id_request(
policy_assignment_id=policy_assignment_id,
content_type=content_type,
json=_json,
template_url=self.create_by_id.metadata['url'],
)
request = _convert_request(request)
request.url = self._client.format_url(request.url)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('PolicyAssignment', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _check_paynet_account_number(self):
for contract in self:
if not contract.is_paynet_contract:
continue
if not contract.paynet_account_number:
raise ValidationError(
_("The Paynet ID is required for a Paynet contract.")
) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def add_pilot (self, pid) :
"""
add (Compute or Data)-Pilot(s) to the pool
"""
raise Exception ("%s.add_pilot() is not implemented" % self.__class__.__name__) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def list_pilots (self, ptype=ANY) :
"""
List IDs of data and/or compute pilots
"""
raise Exception ("%s.list_pilots() is not implemented" % self.__class__.__name__) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def submit_unit (self, description) :
"""
Instantiate and return (Compute or Data)-Unit object(s)
"""
raise Exception ("%s.submit_unit() is not implemented" % self.__class__.__name__) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def list_units (self, utype=ANY) :
"""
List IDs of data and/or compute units
"""
raise Exception ("%s.list_units() is not implemented" % self.__class__.__name__) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_should_encode_map(self):
encoded = cypher_repr(OrderedDict([("one", 1), ("two", 2.0), ("number three", u"three")]))
assert encoded == u"{one: 1, two: 2.0, `number three`: 'three'}" |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:
dict.__init__(self, defaults or {})
self.root_path = root_path |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_parse_sections():
simple_mariofile_sections = dict(mariofile.parse_sections(SIMPLE_MARIOFILE.splitlines(True)))
assert len(simple_mariofile_sections) == 3
complex_mariofile_sections = dict(mariofile.parse_sections(COMPLEX_MARIOFILE.splitlines(True)))
assert len(complex_mariofile_sections) == 2
assert sorted(complex_mariofile_sections.keys()) == ['DEFAULT', 'section']
assert complex_mariofile_sections['DEFAULT'] == ['default text\n', '\n']
with pytest.raises(mariofile.ConfigurationFileError):
dict(mariofile.parse_sections(GARBAGE_MARIOFILE.splitlines(True)))
with pytest.raises(mariofile.ConfigurationFileError):
dict(mariofile.parse_sections(INVALID_SECTION_MARIOFILE.splitlines(True)))
more_complex_mariofile_sections = dict(
mariofile.parse_sections(MORE_COMPLEX_MARIOFILE.splitlines(True))
)
more_complex_mariofile_sections_keys = ['DEFAULT', 'section_one', 'section_two', 'three']
assert sorted(more_complex_mariofile_sections.keys()) == more_complex_mariofile_sections_keys
assert more_complex_mariofile_sections['three'] == [] |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __repr__(self):
return "<includematcher includes=%r>" % self._pats |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_execute(self):
opt = Optional(None, execute=dict)
self.assertEqual(deoption(opt), {})
self.assertEqual(deoption(opt, execute=dict), {})
self.assertEqual(deoption(None, execute=dict), {}) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_unions(self):
for code, tp in self.formats.items():
class X(Union):
_fields_ = [("x", c_char),
("y", tp)]
self.assertEqual((sizeof(X), code),
(calcsize("%c" % (code)), code)) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def begin(self):
self.append({'cbs': [], 'dirty': False}) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def push(self, item):
self[-1]['cbs'].append(item) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _deDuplicate(results):
found = dict()
deDuped = list()
for entry in results:
dn = entry.get("dn")
if not dn in found:
found[dn] = 1
deDuped.append(entry)
return deDuped |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def deserialize(self, value):
value = decode(value)
validators.validate_choice(value.lower(), self.levels.keys())
return self.levels.get(value.lower()) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def subset_examples(example_dict, indices_to_keep, create_new_dict=False):
"""Subsets examples in dictionary.
:param example_dict: See doc for `write_example_file`.
:param indices_to_keep: 1-D numpy array with indices of examples to keep.
:param create_new_dict: Boolean flag. If True, this method will create a
new dictionary, leaving the input dictionary untouched.
:return: example_dict: Same as input, but possibly with fewer examples.
"""
error_checking.assert_is_integer_numpy_array(indices_to_keep)
error_checking.assert_is_numpy_array(indices_to_keep, num_dimensions=1)
error_checking.assert_is_boolean(create_new_dict)
if not create_new_dict:
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return example_dict
new_example_dict = {}
for this_key in METADATA_KEYS:
sounding_key_missing = (
this_key in [SOUNDING_FIELDS_KEY, SOUNDING_HEIGHTS_KEY]
and this_key not in example_dict
)
if sounding_key_missing:
continue
if this_key == TARGET_NAMES_KEY:
if this_key in example_dict:
new_example_dict[this_key] = example_dict[this_key]
else:
new_example_dict[TARGET_NAME_KEY] = example_dict[
TARGET_NAME_KEY]
continue
new_example_dict[this_key] = example_dict[this_key]
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
new_example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
new_example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
new_example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
new_example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return new_example_dict |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get(self):
return self._method(self._key) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _from_python(self, key, value):
new_path = self._path + (key,)
if isinstance(value, dict):
value = self.custom_classes.get(new_path, ConfigDict)(value, new_path)
elif isinstance(value, list):
value = self.custom_classes.get(new_path, ConfigList)(value, new_path)
elif isinstance(value, str):
match = self.PROXY_VAR_RE.match(value)
if match:
value = self._make_proxy(key, match)
return value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __setitem__(self, key, value):
self._collection[key] = self._from_python(key, value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def pop(self, key, default=None):
value = self._collection.pop(key, default)
if isinstance(value, Proxy):
value = value.get()
return value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __iter__(self):
for element in self._collection:
yield self._to_python(element) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get(self, key, default=None):
try:
value = self[key]
except KeyError:
value = self._to_python(default)
return value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __iter__(self):
yield from self._collection |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def values(self):
for value in self._collection.values():
yield self._to_python(value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def items(self):
for key, value in self._collection.items():
yield key, self._to_python(value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def setdefault(self, key, default=None):
return self._collection.setdefault(key, self._from_python(key, default)) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def pop(self, key, default=None):
value = self._collection.pop(key, default)
return self._to_python(value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def popitem(self):
key, value = self._collection.popitem()
return key, self._to_python(value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def update(self, *args, **kwargs):
chain = []
for arg in args:
if isinstance(arg, dict):
iterator = arg.items()
else:
iterator = arg
chain = itertools.chain(chain, iterator)
if kwargs:
chain = itertools.chain(chain, kwargs.items())
for key, value in iterator:
self._collection[key] = self._from_python(key, value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __init__(self, p_str):
TodoBase.__init__(self, p_str)
self.attributes = {} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get_config(self):
config = super().get_config()
config['masked_tokens'] = tuple(self._masked_tokens)
return config |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __init__(self):
self._tokens = collections.defaultdict(int) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
raise
return result |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def introduced_elements(lab, award):
return {
'lab': lab['@id'],
'award': award['@id'],
'category': 'episome',
'purpose': 'characterization',
'nucleic_acid_delivery_method': ['transient transfection'],
'introduced_elements': 'genomic DNA regions'
} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get_reset_type_name(self, num):
""" Given a reset number, return a string reset name """
if num in list(self.reset_types.keys()):
return self.reset_types[num]
else:
return "UNKNOWN" |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | async def get_hw_switch_states(self):
"""Get initial hardware switch states.
This changes switches from active low to active high
"""
hw_states = dict()
for opp_inp in self.opp_inputs:
if not opp_inp.is_matrix:
curr_bit = 1
for index in range(0, 32):
if (curr_bit & opp_inp.mask) != 0:
if (curr_bit & opp_inp.old_state) == 0:
hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index)] = 1
else:
hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index)] = 0
curr_bit <<= 1
else:
for index in range(0, 64):
if ((1 << index) & opp_inp.old_state) == 0:
hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index + 32)] = 1
else:
hw_states[opp_inp.chain_serial + '-' + opp_inp.card_num + '-' + str(index + 32)] = 0
return hw_states |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server.get_meta_data(b'\x01x\02\x03') ==\
{'unit_id': 1} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _lines_to_dict(lines):
md = {}
errors = []
for line in lines:
# Skip a line if there is invalid value.
try:
line = line.decode("utf-8")
except UnicodeDecodeError as e:
errors.append("Invalid line '{}': {}".format(line, e))
continue
if line.startswith("EOF"):
break
if '=' not in line:
continue
key, value = line.split('=', 1)
md[key.strip()] = value.strip()
return md, errors |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __getitem__(self, item):
try:
value = getattr(self, self._fieldmap[item])
except AttributeError:
raise KeyError(item)
# Some fields needs to be converted to string
if item in (sc.CAPACITY, sc.CTIME):
value = str(value)
return value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __setitem__(self, item, value):
setattr(self, self._fieldmap[item], value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get(self, item, default=None):
try:
return self[item]
except KeyError:
return default |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __getitem__(self, index):
try: return list.__getitem__(self, index)
except IndexError: return self.default |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def yaml_dict(self):
''' getter method for yaml_dict '''
return self.__yaml_dict |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def yaml_dict(self, value):
''' setter method for yaml_dict '''
self.__yaml_dict = value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def add_entry(data, key, item=None, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a#b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes[:-1]:
if dict_key:
if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
data = data[dict_key]
continue
elif data and not isinstance(data, dict):
raise YeditException("Unexpected item type found while going through key " +
"path: {} (at key: {})".format(key, dict_key))
data[dict_key] = {}
data = data[dict_key]
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
raise YeditException("Unexpected item type found while going through key path: {}".format(key))
if key == '':
data = item
# process last index for add
# expected list entry
elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
data[int(key_indexes[-1][0])] = item
# expected dict entry
elif key_indexes[-1][1] and isinstance(data, dict):
data[key_indexes[-1][1]] = item
# didn't add/update to an existing list, nor add/update key to a dict
# so we must have been provided some syntax like a.b.c[<int>] = "data" for a
# non-existent array
else:
raise YeditException("Error adding to object at path: {}".format(key))
return data |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def get_entry(data, key, sep='.'):
''' Get an item from a dictionary with key notation a.b.c
d = {'a': {'b': 'c'}}}
key = a.b
return c
'''
if key == '':
pass
elif (not (key and Yedit.valid_key(key, sep)) and
isinstance(data, (list, dict))):
return None
key_indexes = Yedit.parse_key(key, sep)
for arr_ind, dict_key in key_indexes:
if dict_key and isinstance(data, dict):
data = data.get(dict_key)
elif (arr_ind and isinstance(data, list) and
int(arr_ind) <= len(data) - 1):
data = data[int(arr_ind)]
else:
return None
return data |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def load(self, content_type='yaml'):
''' return yaml file '''
contents = self.read()
if not contents and not self.content:
return None
if self.content:
if isinstance(self.content, dict):
self.yaml_dict = self.content
return self.yaml_dict
elif isinstance(self.content, str):
contents = self.content
# check if it is yaml
try:
if content_type == 'yaml' and contents:
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
# Try to use RoundTripLoader if supported.
try:
self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
except AttributeError:
self.yaml_dict = yaml.safe_load(contents)
# Try to set format attributes if supported
try:
self.yaml_dict.fa.set_block_style()
except AttributeError:
pass
elif content_type == 'json' and contents:
self.yaml_dict = json.loads(contents)
except yaml.YAMLError as err:
# Error loading yaml or json
raise YeditException('Problem with loading yaml file. {}'.format(err))
return self.yaml_dict |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def pop(self, path, key_or_item):
''' remove a key, value pair from a dict or an item for a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
return (False, self.yaml_dict)
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if key_or_item in entry:
entry.pop(key_or_item)
return (True, self.yaml_dict)
return (False, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
try:
ind = entry.index(key_or_item)
except ValueError:
return (False, self.yaml_dict)
entry.pop(ind)
return (True, self.yaml_dict)
return (False, self.yaml_dict) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def append(self, path, value):
'''append value to a list'''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry is None:
self.put(path, [])
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
if not isinstance(entry, list):
return (False, self.yaml_dict)
# AUDIT:maybe-no-member makes sense due to loading data from
# a serialized format.
# pylint: disable=maybe-no-member
entry.append(value)
return (True, self.yaml_dict) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def update(self, path, value, index=None, curr_value=None):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if isinstance(entry, dict):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
if not isinstance(value, dict):
raise YeditException('Cannot replace key, value entry in dict with non-dict type. ' +
'value=[{}] type=[{}]'.format(value, type(value)))
entry.update(value)
return (True, self.yaml_dict)
elif isinstance(entry, list):
# AUDIT:maybe-no-member makes sense due to fuzzy types
# pylint: disable=maybe-no-member
ind = None
if curr_value:
try:
ind = entry.index(curr_value)
except ValueError:
return (False, self.yaml_dict)
elif index is not None:
ind = index
if ind is not None and entry[ind] != value:
entry[ind] = value
return (True, self.yaml_dict)
# see if it exists in the list
try:
ind = entry.index(value)
except ValueError:
# doesn't exist, append it
entry.append(value)
return (True, self.yaml_dict)
# already exists, return
if ind is not None:
return (False, self.yaml_dict)
return (False, self.yaml_dict) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def put(self, path, value):
''' put path, value into a dict '''
try:
entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
except KeyError:
entry = None
if entry == value:
return (False, self.yaml_dict)
# deepcopy didn't work
# Try to use ruamel.yaml and fallback to pyyaml
try:
tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
default_flow_style=False),
yaml.RoundTripLoader)
except AttributeError:
tmp_copy = copy.deepcopy(self.yaml_dict)
# set the format attributes if available
try:
tmp_copy.fa.set_block_style()
except AttributeError:
pass
result = Yedit.add_entry(tmp_copy, path, value, self.separator)
if result is None:
return (False, self.yaml_dict)
# When path equals "" it is a special case.
# "" refers to the root of the document
# Only update the root path (entire document) when its a list or dict
if path == '':
if isinstance(result, list) or isinstance(result, dict):
self.yaml_dict = result
return (True, self.yaml_dict)
return (False, self.yaml_dict)
self.yaml_dict = tmp_copy
return (True, self.yaml_dict) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def to_option_list(self, ascommalist=''):
'''return all options as a string
if ascommalist is set to the name of a key, and
the value of that key is a dict, format the dict
as a list of comma delimited key=value pairs'''
return self.stringify(ascommalist) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def create_dict(self):
''' assign the correct properties for a secret dict '''
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Secret'
self.data['metadata'] = {}
self.data['metadata']['name'] = self.name
self.data['metadata']['namespace'] = self.namespace
self.data['data'] = {}
if self.secrets:
for key, value in self.secrets.items():
self.data['data'][key] = value |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def find_secret(self, key):
''' find secret'''
rval = None
try:
rval = self.secrets[key]
except KeyError as _:
return None
return {'key': key, 'value': rval} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def update_secret(self, key, value):
''' update a secret'''
if key in self.secrets:
self.secrets[key] = value
else:
self.add_secret(key, value)
return True |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_parse_rank_score_no_score():
## GIVEN a empty rank score string
rank_scores_info = ""
family_id = "123"
## WHEN parsing the rank score
parsed_rank_score = parse_rank_score(rank_scores_info, family_id)
## THEN assert that None is returned
assert parsed_rank_score == None |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _contributed_values(contributed_values_obj):
if not contributed_values_obj:
return {}
if not isinstance(contributed_values_obj, list):
contributed_values_obj = [contributed_values_obj]
ret = {}
try:
for obj in contributed_values_obj:
ret[obj.name.lower()] = obj.to_dict(exclude=["collection_id"])
except Exception as err:
pass
return ret |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def contributed_values(self, dict_values):
return dict_values |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _records(records_obj):
if not records_obj:
return []
if not isinstance(records_obj, list):
records_obj = [records_obj]
ret = []
try:
for rec in records_obj:
ret.append(rec.to_dict(exclude=["dataset_id"]))
except Exception as err:
# raises exception of first access!!
pass
return ret |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def records(self, dict_values):
return dict_values |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _records(records_obj):
if not records_obj:
return []
if not isinstance(records_obj, list):
records_obj = [records_obj]
ret = []
try:
for rec in records_obj:
ret.append(rec.to_dict(exclude=["reaction_dataset_id"]))
except Exception as err:
# raises exception of first access!!
pass
return ret |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __init__(self, value):
self.value = value
self.iface = {'typestr': '=f8'} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def test_collections_hashable(self):
x = np.array([])
self.assertFalse(isinstance(x, collections.Hashable)) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def the_variable_key_is_value(key, value):
variables[key] = eval(value) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def domXml( self ):
opts = {}
specs = [] |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __set__(self, instance, value):
instance.__dict__[self.field.name] = value
setattr(instance, self.field.attname, json.dumps(value)) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs):
# Anything passed in as self.name is assumed to come from a serializer and
# will be treated as a json string.
if self.name in kwargs:
value = kwargs.pop(self.name) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def __init__(self, db):
self.db = db
self.cache = {} |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def updateArgs(self, *args, **keywords):
"""
Call as::
C{I{ClassName}(I{info}, I{filterexp})}
or::
C{I{ClassName}(I{info}, exceptions=I{filterexp})}
where C{I{filterexp}} is either a regular expression or a
tuple of C{(regexp[, setmodes[, unsetmodes]])}
"""
if args:
args = list(args)
info = args.pop(0)
if args:
if not self.included:
self.included = {}
if info not in self.included:
self.included[info] = []
self.included[info].extend(args)
elif 'exceptions' in keywords:
# not the usual exception handling, this is an exception
if not self.excluded:
self.excluded = {}
if info not in self.excluded:
self.excluded[info] = []
self.excluded[info].append(keywords.pop('exceptions'))
else:
raise TypeError, 'no paths provided'
policy.Policy.updateArgs(self, **keywords) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def updateArgs(self, *args, **keywords):
for arg in args:
if type(arg) in (list, tuple, set):
self.found.update(arg)
else:
self.found.add(arg) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def remove_attributes(self, model):
"""
Removes the x and y attributes which were added by the forward handles
Recursively searches for non-container layers
"""
for child in model.children():
if 'nn.modules.container' in str(type(child)):
self.remove_attributes(child)
else:
try:
del child.x
except AttributeError:
pass
try:
del child.y
except AttributeError:
pass |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_comment(self):
"Delete the selected comment"
if self.get_selected_item()['type'] == 'Comment':
self.delete_item()
else:
self.term.flash() |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete(arg=None):
frappe.get_doc("Communication", frappe.form_dict['name']).delete() |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_snapshot(self, snapshot_id):
"""Delete Snapshot."""
return self.delete("snapshots/%s" % str(snapshot_id)) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_snapshot_metadata_item(self, snapshot_id, id):
"""Delete metadata item for the snapshot."""
url = "snapshots/%s/metadata/%s" % (str(snapshot_id), str(id))
resp, body = self.delete(url)
return resp, body |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def remove_from_device(self):
collection = self.client.api.cm.shared.licensing.pools_s.get_collection(
requests_params=dict(
params="$filter=name+eq+'{0}'".format(self.want.name)
)
)
resource = collection.pop()
if resource:
resource.delete() |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def on_btn_del_row_clicked(self):
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
self.delete_lines(min_row, max_row) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_lines(self, min_row, max_row):
if min_row == -1:
self.current_label.fuzz_values = self.current_label.fuzz_values[:-1]
else:
self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[
max_row + 1:]
_ = self.current_label # if user deleted all, this will restore a fuzz value
self.fuzz_table_model.update() |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_instance(
self,
) -> Callable[[appengine.DeleteInstanceRequest], operations_pb2.Operation]:
r"""Return a callable for the delete instance method over gRPC.
Stops a running instance.
The instance might be automatically recreated based on the
scaling settings of the version. For more information, see "How
Instances are Managed" (`standard
environment <https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed>`__
\| `flexible
environment <https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed>`__).
To ensure that instances are not re-created and avoid getting
billed, you can stop all instances within the target version by
changing the serving status of the version to ``STOPPED`` with
the
```apps.services.versions.patch`` <https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch>`__
method.
Returns:
Callable[[~.DeleteInstanceRequest],
~.Operation]:
A function that, when called, will call the underlying RPC
on the server.
"""
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization, so we just need
# to pass in the functions for each.
if "delete_instance" not in self._stubs:
self._stubs["delete_instance"] = self.grpc_channel.unary_unary(
"/google.appengine.v1.Instances/DeleteInstance",
request_serializer=appengine.DeleteInstanceRequest.serialize,
response_deserializer=operations_pb2.Operation.FromString,
)
return self._stubs["delete_instance"] |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def _Delete(self):
"""Delete the log group."""
delete_cmd = util.AWS_PREFIX + [
'--region', self.region,
'logs', 'delete-log-group',
'--log-group-name', self.name
]
vm_util.IssueCommand(delete_cmd, raise_on_failure=False) |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def rollback(self):
self.pop() |
def __init__(self):
self.filediff = None
meldsettings.connect('changed', self.on_setting_changed) | def delete_user(user_id=None):
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
for user in User.query.filter(User.id.in_(ids)).all():
# do not delete current user
if current_user.id == user.id:
continue
if user.delete():
data.append({
"id": user.id,
"type": "delete",
"reverse": False,
"reverse_name": None,
"reverse_url": None
})
return jsonify(
message="{} users deleted.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
if current_user.id == user.id:
flash(_("You cannot delete yourself.", "danger"))
return redirect(url_for("management.users"))
user.delete()
flash(_("User deleted."), "success")
return redirect(url_for("management.users")) |