code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if isinstance(value, (HostVolume, SharedVolume)): return value elif isinstance(value, six.string_types): return SharedVolume(value, False) elif isinstance(value, (list, tuple)): return _shared_host_volume_from_tuple(*value) elif isinstance(val...
def get_type_item(self, value)
Converts the input to a ``SharedVolume`` or ``HostVolume`` tuple for a host bind. Input can be a single string, a list or tuple, or a single-entry dictionary. Single values are assumed to be volume aliases for read-write access. Tuples or lists with two elements, can be ``(alias, read-only indic...
2.853893
2.451726
1.164034
if isinstance(value, (UsedVolume, SharedVolume)): if value.readonly: raise ValueError("Attached volumes should not be read-only.") return value elif isinstance(value, six.string_types): return SharedVolume(value) elif isinstance(value,...
def get_type_item(self, value)
Converts the given value to a ``UsedVolume`` or ``SharedVolume`` tuple for attached volumes. It accepts strings, lists, tuples, and dicts as input. For strings and collections of a single element, the first item is considered to be an alias for lookup on the map. It is converted to a ``SharedVo...
2.852251
2.319635
1.229612
if isinstance(value, ExecCommand): return value elif isinstance(value, six.string_types + (lazy_type,)): return ExecCommand(value) elif isinstance(value, (list, tuple)): v_len = len(value) if 1 <= v_len <= 3: return ExecCom...
def get_type_item(self, value)
Converts the input to a ExecCommand tuple. It can be from a single string, list, or tuple. Single values (also single-element lists or tuples) are considered a command string, whereas two-element items are read as ``(command string, user name)``. :param value: Input value for conversion. ...
3.425375
2.89994
1.181188
sub_types = six.string_types + six.integer_types if isinstance(value, PortBinding): return value elif isinstance(value, sub_types): # Port only return PortBinding(value) elif isinstance(value, (list, tuple)): # Exposed port, host port, and possibly inte...
def get_type_item(self, value)
Converts the given value to a ``PortBinding`` tuple. Input may come as a single value (exposed port for container linking only), a two-element tuple/list (port published on all host interfaces) or a three-element tuple/list (port published on a particular host interface). It can also be a dictionary wit...
3.5322
3.051225
1.157633
if isinstance(value, NetworkEndpoint): return value elif isinstance(value, six.string_types + (lazy_type,)): return NetworkEndpoint(value) elif isinstance(value, (list, tuple)): v_len = len(value) if v_len == 2 and isinstance(value[1], dic...
def get_type_item(self, value)
Converts the input to a NetworkEndpoint tuple. It can be from a single-entry dictionary, single string, list, or tuple. Single values (also single-element lists or tuples) are considered a network name. Dictionaries can also contain nested dictionaries with keyword arguments to the NetworkEndpoint. List...
2.426114
2.189914
1.107858
if isinstance(value, InputConfigId): return value elif isinstance(value, MapConfigId): if value.instance_name: v_instances = value.instance_name, else: v_instances = None return InputConfigId(value.config_type, valu...
def get_type_item(self, value, map_name=None, instances=None)
Converts the input to a InputConfigId tuple. It can be from a single string, list, or tuple. Single values (also single-element lists or tuples) are considered to be a container configuration on the default map. A string with two elements separated by a dot or two-element lists / tuples are considered t...
2.152383
1.931878
1.11414
for config_id in config_ids: if config_id.map_name == '__all__': c_maps = six.iteritems(maps) else: c_maps = (config_id.map_name, maps[config_id.map_name]), if isinstance(config_id, InputConfigId): instance_name = config_id.instance_names elif...
def expand_groups(config_ids, maps)
Iterates over a list of container configuration ids, expanding groups of container configurations. :param config_ids: List of container configuration ids. :type config_ids: collections.Iterable[dockermap.map.input.InputConfigId | dockermap.map.input.MapConfigId] :param maps: Extended container maps. :t...
2.307828
2.157509
1.069673
for type_map_config, items in itertools.groupby(sorted(config_ids, key=get_map_config), get_map_config): config_type, map_name, config_name = type_map_config instances = _get_nested_instances(items) c_map = ext_maps[map_name] try: c_instances = _get_config_instances(...
def expand_instances(config_ids, ext_maps)
Iterates over a list of input configuration ids, expanding configured instances if ``None`` is specified. Otherwise where instance names are specified as a tuple, they are expanded. :param config_ids: Iterable of container configuration ids or (map, config, instance names) tuples. :type config_ids: collect...
3.159862
2.88566
1.095022
input_ids = InputConfigIdList(value, map_name=default_map_name, instances=default_instances) return list(expand_instances(expand_groups(input_ids, maps), maps))
def get_map_config_ids(value, maps, default_map_name=None, default_instances=None)
From a value, which can be a string, a iterable of strings, or MapConfigId tuple(s), generates a list of MapConfigId tuples with expanded groups, listing all input or configured instances, and sorted by map and configuration. :param value: Input value(s). :type value: str | unicode | dockermap.map.input.In...
7.112172
6.645123
1.070285
c_kwargs = self.get_network_create_kwargs(action, n_name, **kwargs) res = action.client.create_network(**c_kwargs) self._policy.network_names[action.client_name][n_name] = res['Id'] return res
def create_network(self, action, n_name, **kwargs)
Creates a configured network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param n_name: Network name. :type n_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the configuration-based values. ...
4.172945
4.567047
0.913707
c_kwargs = self.get_network_remove_kwargs(action, n_name, **kwargs) res = action.client.remove_network(**c_kwargs) del self._policy.network_names[action.client_name][n_name] return res
def remove_network(self, action, n_name, **kwargs)
Removes a network. :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param n_name: Network name or id. :type n_name: unicode | str :param kwargs: Additional keyword arguments. :type kwargs: dict
4.570535
5.061136
0.903065
policy = self._policy client_config = action.client_config container_map = action.container_map container_config = action.config image_tag = container_map.get_image(container_config.image or action.config_id.config_name) default_paths = policy.default_volume_path...
def get_container_create_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to create a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or overri...
3.122375
3.120209
1.000694
container_map = action.container_map container_config = action.config client_config = action.client_config config_id = action.config_id map_name = config_id.map_name policy = self._policy cname = policy.cname supports_volumes = client_config.featu...
def get_container_host_config_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type container_na...
3.442487
3.484587
0.987918
client_config = action.client_config policy = self._policy config_id = action.config_id path = resolve_value(policy.default_volume_paths[config_id.map_name][config_id.instance_name]) user = extract_user(action.config.user) c_kwargs = dict( name=contai...
def get_attached_container_create_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to create an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement...
4.418214
4.323954
1.0218
if container_name: c_kwargs = {'container': container_name} else: c_kwargs = {} update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_attached_container_host_config_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to set up the HostConfig or start an attached container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. Set ``None`` when included in kwargs for ``create_container``. :type co...
3.25064
4.005926
0.811458
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, update_values, kwargs) return c_kwargs
def get_container_update_kwargs(self, action, container_name, update_values, kwargs=None)
Generates keyword arguments for the Docker client to update the HostConfig of an existing container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param update_values: Dictionary ...
4.722469
5.986927
0.788797
c_kwargs = dict(container=container_name) timeout = action.client_config.get('wait_timeout') if timeout is not None: c_kwargs['timeout'] = timeout update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_container_wait_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to wait for a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement o...
3.603814
3.884489
0.927745
c_kwargs = dict( container=container_name, ) stop_timeout = action.config.stop_timeout if stop_timeout is NotSet: timeout = action.client_config.get('stop_timeout') if timeout is not None: c_kwargs['timeout'] = timeout ...
def get_container_stop_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to stop a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or ov...
3.033263
3.120678
0.971988
c_kwargs = dict(container=container_name) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_container_remove_kwargs(self, action, container_name, kwargs=None)
Generates keyword arguments for the Docker client to remove a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arguments to complement or ...
4.7144
6.166225
0.764552
config = action.config c_kwargs = dict( name=network_name, driver=config.driver, options=config.driver_options, ) if config.internal: c_kwargs['internal'] = True driver_opts = init_options(config.driver_options) if ...
def get_network_create_kwargs(self, action, network_name, kwargs=None)
Generates keyword arguments for the Docker client to create a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param kwargs: Additional keyword arguments to complement or override...
3.388878
3.278167
1.033772
c_kwargs = dict(net_id=network_name) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_network_remove_kwargs(self, action, network_name, kwargs=None)
Generates keyword arguments for the Docker client to remove a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param kwargs: Additional keyword arguments to complement or override...
5.26029
6.350049
0.828386
map_name = action.config_id.map_name policy = self._policy c_kwargs = dict( ipv4_address=resolve_value(endpoint_config.ipv4_address), ipv6_address=resolve_value(endpoint_config.ipv6_address), ) if endpoint_config.aliases: c_kwargs['ali...
def get_network_create_endpoint_kwargs(self, action, endpoint_config, kwargs=None)
Generates keyword arguments for Docker's ``create_endpoint_config`` utility / ``EndpointConfig`` type as well as for ``connect_container_to_network``. :param action: Action configuration. :type action: ActionConfig :param endpoint_config: Network endpoint configuration. :type en...
2.975111
2.796485
1.063875
c_kwargs = dict( container=container_name, net_id=network_name, ) if endpoint_config: c_kwargs.update(self.get_network_create_endpoint_kwargs(action, endpoint_config)) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_network_connect_kwargs(self, action, network_name, container_name, endpoint_config=None, kwargs=None)
Generates keyword arguments for the Docker client to add a container to a network. :param action: Action configuration. :type action: ActionConfig :param network_name: Network name or id. :type network_name: unicode | str :param container_name: Container name or id. :typ...
3.069338
3.49349
0.878588
c_kwargs = dict( container=container_name, net_id=network_name, ) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_network_disconnect_kwargs(self, action, network_name, container_name, kwargs=None)
Generates keyword arguments for the Docker client to remove a container from a network. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param network_name: Network name or id. ...
4.14703
4.414388
0.939435
c_kwargs = dict( container=container_name, cmd=resolve_value(exec_cmd), ) if exec_user is not None: c_kwargs['user'] = text_type(resolve_value(exec_user)) elif action.config.user is not NotSet: c_kwargs['user'] = extract_user(actio...
def get_exec_create_kwargs(self, action, container_name, exec_cmd, exec_user, kwargs=None)
Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arg...
3.284534
3.729169
0.880768
c_kwargs = dict(exec_id=exec_id) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_exec_start_kwargs(self, action, container_name, exec_id, kwargs=None)
Generates keyword arguments for the Docker client to set up the HostConfig or start a container. :param action: Action configuration. :type action: ActionConfig :param container_name: Container name or id. :type container_name: unicode | str :param kwargs: Additional keyword arg...
4.384956
5.670444
0.7733
config = action.config c_kwargs = dict(name=volume_name) if config: c_kwargs['driver'] = config.driver driver_opts = init_options(config.driver_options) if driver_opts: c_kwargs['driver_opts'] = {option_name: resolve_value(option_value...
def get_volume_create_kwargs(self, action, volume_name, kwargs=None)
Generates keyword arguments for the Docker client to create a volume. :param action: Action configuration. :type action: ActionConfig :param volume_name: Volume name. :type volume_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the confi...
3.433295
3.190298
1.076168
c_kwargs = dict(name=volume_name) update_kwargs(c_kwargs, kwargs) return c_kwargs
def get_volume_remove_kwargs(self, action, volume_name, kwargs=None)
Generates keyword arguments for the Docker client to remove a volume. :param action: Action configuration. :type action: ActionConfig :param volume_name: Volume name. :type volume_name: unicode | str :param kwargs: Additional keyword arguments to complement or override the confi...
5.082311
5.894551
0.862205
if instance: return '{0}.{1}.{2}'.format(map_name, container, instance) return '{0}.{1}'.format(map_name, container)
def cname(cls, map_name, container, instance=None)
Generates a container name that should be used for creating new containers and checking the status of existing containers. In this implementation, the format will be ``<map name>.<container name>.<instance>``. If no instance is provided, it is just ``<map name>.<container name>``. :par...
2.267473
2.224984
1.019096
if parent_name: return '{0}.{1}.{2}'.format(map_name, parent_name, attached_name) return '{0}.{1}'.format(map_name, attached_name)
def aname(cls, map_name, attached_name, parent_name=None)
Generates a container name that should be used for creating new attached volume containers and checking the status of existing containers. In this implementation, the format will be ``<map name>.<attached>``, or ``<map name>.<parent name>.<attached>`` if the parent container configuration name ...
1.954483
1.982222
0.986006
if network_name in DEFAULT_PRESET_NETWORKS: return network_name return '{0}.{1}'.format(map_name, network_name)
def nname(cls, map_name, network_name)
Generates a network name that should be used for creating new networks and checking the status of existing networks on the client. In this implementation, the format will be ``<map name>.<network name>``. :param map_name: Container map name. :type map_name: unicode | str :param...
4.414159
4.364502
1.011377
base_name = container_name for old, new in cls.hostname_replace: base_name = base_name.replace(old, new) if not client_name or client_name == cls.default_client_name: return base_name client_suffix = client_name for old, new in cls.hostname_replac...
def get_hostname(cls, container_name, client_name=None)
Determines the host name of a container. In this implementation, replaces all dots and underscores of a container name with a dash; then attaches another dash with the client name, unless there is just one default client. :param container_name: Name of the container. :type container_nam...
2.249787
2.141276
1.050676
return _format_cmd('adduser', username, __system=bool(system), __uid=uid, __group=bool(group), __gid=uid, no_login=(no_login, _NO_CREATE_HOME, _NO_LOGIN), __disabled_password=no_login or bool(no_password), __gecos=gecos, **kwargs)
def adduser(username, uid=None, system=False, no_login=True, no_password=False, group=False, gecos=None, **kwargs)
Formats an ``adduser`` command. :param username: User name. :type username: unicode | str :param uid: Optional user id to use. :type uid: long | int :param system: Create a system user account. :type system: bool :param no_login: Disable the login for this user. Not compatible with CentOS. ...
6.321058
5.41791
1.166697
if isinstance(user_group, tuple): return '{0}:{1}'.format(*user_group) elif isinstance(user_group, six.integer_types) or ':' not in user_group: return '{0}:{0}'.format(user_group) return user_group
def get_user_group(user_group)
Formats a user and group in the format ``user:group``, as needed for `chown`. If user_group is a tuple, this is used for the fomatting. If a string or integer is given, it will be formatted as ``user:user``. Otherwise the input is returned - this method does not perform any more checks. :param user_group: ...
2.751693
2.446069
1.124945
group = addgroup(username, uid, system) user = adduser(username, uid, system, no_login, no_password, False, gecos, **kwargs) prefix = 'sudo ' if sudo else '' if groupnames: usermod = assignuser(username, groupnames) return '{0}{1} && {0}{2} && {0}{3}'.format(prefix, group, user, use...
def addgroupuser(username, uid, groupnames=None, system=False, no_login=True, no_password=False, gecos=None, sudo=False, **kwargs)
Generates a unix command line for creating user and group with the same name, assigning the user to the group. Has the same effect as combining :func:`~addgroup`, :func:`~adduser`, and :func:`~assignuser`. :param username: User name to create. :type username: unicode | str :param uid: User id to use. ...
3.099798
3.017066
1.027421
cmd = _format_cmd('mkdir', path, _p=create_parent) if check_if_exists: return 'if [[ ! -d {0} ]]; then {1}; fi'.format(path, cmd) return cmd
def mkdir(path, create_parent=True, check_if_exists=False)
Generates a unix command line for creating a directory. :param path: Directory path. :type path: unicode | str :param create_parent: Create parent directories, if necessary. Default is ``True``. :type create_parent: bool :param check_if_exists: Prepend a check if the directory exists; in that case,...
4.383908
4.287709
1.022436
def _generate_str(path): mkdir_str = mkdir(path, create_parent, check_if_exists) chown_str = chown(user_group, path, recursive) if user_group else None chmod_str = chmod(permissions, path, recursive) if permissions else None return ' && '.join(n for n in (mkdir_str, chown_str, ...
def mkdir_chown(paths, user_group=None, permissions='ug=rwX,o=rX', create_parent=True, check_if_exists=False, recursive=False)
Generates a unix command line for creating a directory and assigning permissions to it. Shortcut to a combination of :func:`~mkdir`, :func:`~chown`, and :func:`~chmod`. Note that if `check_if_exists` has been set to ``True``, and the directory is found, `mkdir` is not called, but `user_group` and `permissi...
2.663025
2.416795
1.101883
super(TranslatedFieldsField, self).bind(field_name, parent) # Expect 1-on-1 for now. Allow using source as alias, # but it should not be a dotted path for now related_name = self.source or field_name # This could all be done in __init__(), but by moving the code here, ...
def bind(self, field_name, parent)
Create translation serializer dynamically. Takes translatable model class (shared_model) from parent serializer and it may create a serializer class on the fly if no custom class was specified.
4.453924
4.148174
1.073707
if value is None: return # Only need one serializer to create the native objects serializer = self.serializer_class( instance=self.parent.instance, # Typically None context=self.context, partial=self.parent.partial ) # D...
def to_representation(self, value)
Serialize translated fields. Simply iterate over available translations and, for each language, delegate serialization logic to the translation model serializer. Output languages can be selected by passing a list of language codes, `languages`, within the serialization context.
5.3468
5.091482
1.050146
if data is None: return if not isinstance(data, dict): self.fail('invalid') if not self.allow_empty and len(data) == 0: self.fail('empty') result, errors = {}, {} for lang_code, model_fields in data.items(): serializer = ...
def to_internal_value(self, data)
Deserialize data from translations fields. For each received language, delegate validation logic to the translation model serializer.
2.262572
2.107442
1.073611
params = { "text": text, "key": self.key, } if layers is not None: # if it's string if isinstance(layers, six.string_types): params["layers"] = layers # if it's another iterable object elif isinsta...
def parse(self, text, layers=None)
Parsing passed text to json. Args: text: Text to parse. layers (optional): Special fields. Only one string or iterable object (e.g "Data", ("Data", "Fio")). Only these fields will be returned. Returns: The parsed text into a json obj...
2.898194
3.349511
0.865259
if not text: raise Exception("No text to speak") if len(text) >= self.MAX_CHARS: raise Exception("Number of characters must be less than 2000") params = self.__params.copy() params["text"] = text self._data = requests.get(self.TTS_URL, params=pa...
def generate(self, text)
Try to get the generated file. Args: text: The text that you want to generate.
4.25743
4.721279
0.901754
if self._data is None: raise Exception("There's nothing to save") extension = "." + self.__params["format"] if os.path.splitext(path)[1] != extension: path += extension with open(path, "wb") as f: for d in self._data: f.write...
def save(self, path="speech")
Save data in file. Args: path (optional): A path to save file. Defaults to "speech". File extension is optional. Absolute path is allowed. Returns: The path to the saved file.
3.366957
3.447723
0.976574
if not related_name: translated_model = shared_model._parler_meta.root_model else: translated_model = shared_model._parler_meta[related_name].model # Define inner Meta class if not meta: meta = {} meta['model'] = translated_model meta.setdefault('fields', ['language...
def create_translated_fields_serializer(shared_model, meta=None, related_name=None, **fields)
Create a Rest Framework serializer class for a translated fields model. :param shared_model: The shared model. :type shared_model: :class:`parler.models.TranslatableModel`
3.518311
3.38466
1.039487
translated_data = self._pop_translated_data() instance = super(TranslatableModelSerializer, self).save(**kwargs) self.save_translations(instance, translated_data) return instance
def save(self, **kwargs)
Extract the translations and save them after main object save. By default all translations will be saved no matter if creating or updating an object. Users with more complex needs might define their own save and handle translation saving themselves.
4.835817
4.319234
1.119601
translated_data = {} for meta in self.Meta.model._parler_meta: translations = self.validated_data.pop(meta.rel_name, {}) if translations: translated_data[meta.rel_name] = translations return translated_data
def _pop_translated_data(self)
Separate data of translated fields from other data.
5.096061
4.318425
1.180074
for meta in self.Meta.model._parler_meta: translations = translated_data.get(meta.rel_name, {}) for lang_code, model_fields in translations.items(): translation = instance._get_translated_model(lang_code, auto_create=True, meta=meta) for field, va...
def save_translations(self, instance, translated_data)
Save translation data into translation objects.
5.201901
4.99698
1.041009
global config try: cfg = open(cfg_path, 'r') except Exception as ex: if verbose: print("Unable to open {0}".format(cfg_path)) print(str(ex)) return False # Read the entire contents of the conf file cfg_json = cfg.read() cfg.close() # prin...
def load_conf(cfg_path)
Try to load the given conf file.
2.822107
2.742928
1.028866
int_values = map(int, values) cv_dict[values_key][name] = int_values
def add_values(name, values)
Adds an alias with list of values to the channel/value dictionary.
10.423736
8.396583
1.241426
try: int_values = map(int, values) for v in int_values: if (v >= 0) and (v <= 255): continue else: return False except Exception as ex: # print(ex) return False return True
def are_valid_values(values)
Determines if a list of values are valid DMX values (0-255).
2.703279
2.432601
1.111271
# If an rc file is named in the config, use it. # Otherwise, fall back to looking in the HOME directory. # The fall back won't work under RPi because HOME will be root. if "uDMXrc" in config: rcfile = config["uDMXrc"] else: if os.name == "nt": # Windows r...
def load_rc_file()
Load the contents of the resource file ~/.uDMXrc
3.025963
2.809708
1.076967
trans_tokens = [] if message_tokens[0] in cv_dict[channels_key]: trans_tokens.append(cv_dict[channels_key][message_tokens[0]]) else: trans_tokens.append(int(message_tokens[0])) for token in message_tokens[1:]: if token in cv_dict[values_key]: trans_tokens.extend...
def translate_message_tokens(message_tokens)
Translates alias references to their defined values. The first token is a channel alias. The remaining tokens are value aliases.
2.34479
2.142678
1.094327
# Open the uDMX USB device dev = pyudmx.uDMXDevice() if not dev.open(): print("Unable to find and open uDMX interface") return False # Translate the tokens into integers. # trans_tokens[0] will be the one-based channel number (1-512) as an integer. # The remaining tokens w...
def send_dmx_message(message_tokens)
Send the DMX message defined by the command line arguments (message tokens). The first argument/token is the DMX channel. The remaining argument(s).token(s) are DMX values.
3.423987
3.300132
1.03753
return list(email.parser.Parser().parsestr(msg).items())
def parse_headers(cls, msg)
Parse HTTP headers. Args: msg (str): HTTP message. Returns: (List[Tuple[str, str]): List of header tuples.
8.983461
12.982973
0.691942
lines = msg.splitlines() version, status_code, reason = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, status_code=status_code, reason=reason, headers=headers)
def parse(cls, msg)
Parse message string to response object.
2.858432
2.531767
1.129026
lines = msg.splitlines() method, uri, version = lines[0].split() headers = cls.parse_headers('\r\n'.join(lines[1:])) return cls(version=version, uri=uri, method=method, headers=headers)
def parse(cls, msg)
Parse message string to request object.
2.879376
2.563073
1.123408
msg = bytes(self) + b'\r\n' logger.debug("%s:%s < %s", *(addr + (self,))) transport.sendto(msg, addr)
def sendto(self, transport, addr)
Send request to a given address via given transport. Args: transport (asyncio.DatagramTransport): Write transport to send the message on. addr (Tuple[str, int]): IP address and port pair to send the message to.
5.133079
6.690612
0.767206
kwargs = {} if vendor_id: kwargs["idVendor"] = vendor_id if product_id: kwargs["idProduct"] = product_id if bus: kwargs["bus"] = bus if address: kwargs["address"] = address # Find the uDMX interface self._de...
def open(self, vendor_id: int = 0x16c0, product_id: int = 0x5dc, bus: int = None, address: int = None) -> bool
Open the first device that matches the search criteria. Th default parameters are set up for the likely most common case of a single uDMX interface. However, for the case of multiple uDMX interfaces, you can use the bus and address paramters to further specifiy the uDMX interface to be o...
2.926619
2.222776
1.31665
# This may not be absolutely necessary, but it is safe. # It's the closest thing to a close() method. if self._dev is not None: usb.util.dispose_resources(self._dev) self._dev = None
def close(self)
Close and release the current usb device. :return: None
6.604598
5.446548
1.212621
if self._dev is None: raise ValueError("No usb device opened") # All data transfers use this request type. This is more for # the PyUSB package than for the uDMX as the uDMX does not # use it.. bmRequestType = usb.util.CTRL_TYPE_VENDOR | usb.util.CTRL_RECIP...
def _send_control_message(self, cmd: int, value_or_length: int = 1, channel: int = 1, data_or_length: Union[int, bytearray] = 1) -> int
Sends a control transfer to the current device. :param cmd: 1 for single value transfer, 2 for multi-value transfer :param value_or_length: for single value transfer, the value. For multi-value transfer, the length of the data bytearray. :param channel: DMX channel number, 1- 512 ...
5.551902
4.895487
1.134086
SetSingleChannel = 1 n = self._send_control_message(SetSingleChannel, value_or_length=value, channel=channel, data_or_length=1) return n
def send_single_value(self, channel: int, value: int) -> int
Send a single value to the uDMX :param channel: DMX channel number, 1-512 :param value: Value to be sent to channel, 0-255 :return: number of bytes actually sent
10.582467
9.704171
1.090507
SetMultiChannel = 2 if isinstance(values, bytearray): ba = values else: ba = bytearray(values) n = self._send_control_message(SetMultiChannel, value_or_length=len(ba), channel=channel, data_or_length=ba) retu...
def send_multi_value(self, channel: int, values: Union[List[int], bytearray]) -> int
Send multiple consecutive bytes to the uDMX :param channel: The starting DMX channel number, 1-512 :param values: any sequence of integer values that can be converted to a bytearray (e.g a list). Each value 0-255. :return: number of bytes actually sent
5.423841
5.398252
1.00474
group = parser.add_mutually_exclusive_group() group.add_argument('--set', action='store_true', dest=name, default=default) group.add_argument('--unset', action='store_false', dest=name, default=default)
def add_boolean_argument(parser, name, default=False)
Add a boolean argument to an ArgumentParser instance.
2.182518
2.3053
0.946739
cv = [0 for v in range(0, 512)] cv[0] = red cv[1] = green cv[2] = blue cv[6] = dimmer sent = dev.send_multi_value(1, cv) return sent
def send_rgb(dev, red, green, blue, dimmer)
Send a set of RGB values to the light
4.063118
3.999448
1.01592
# Channel value list for channels 1-512 cv = [0 for v in range(0, 512)] # Create an instance of the DMX controller and open it print("Opening DMX controller...") dev = pyudmx.uDMXDevice() # This will automagically find a single Anyma-type USB DMX controller dev.open() # For in...
def main()
How to control a DMX light through an Anyma USB controller
3.22234
3.02203
1.066283
try: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) if self.config['no_ssl_verify']: requests.packages.urllib3.disable_warnings() context.verify_mode = ssl.CERT_NONE self.si = SmartConnectNoSSL( host=self.config...
def connect(self)
Connect to vCenter server
2.014155
1.910552
1.054227
vimtype = self.config['type'] vim_obj = "vim.%s" % vimtype try: container = self.content.viewManager.CreateContainerView( self.content.rootFolder, [eval(vim_obj)], True) except AttributeError: print("%s is not a Managed Object Type. See ...
def list_objects(self)
Command Section: list List available VMware objects
3.330246
3.068494
1.085303
vm = self.get_vm_failfast(self.config['name']) extra = self.config['extra'] parserFriendly = self.config['parserFriendly'] status_to_print = [] if extra: status_to_print = \ [["vmname", "powerstate", "ipaddress", "hostname", "memory", ...
def status(self)
Check power status
3.466342
3.336024
1.039064
vm = self.get_vm_failfast(self.config['name']) if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff: print("%s already poweredOff" % vm.name) else: if self.guestToolsRunning(vm): timeout_minutes = 10 print("waiting ...
def shutdown(self)
Shutdown guest fallback to power off if guest tools aren't installed
4.306117
3.889442
1.10713
pool_obj = None # get a list of all resource pools in this cluster cluster_pools_list = cluster.resourcePool.resourcePool # get list of all resource pools with a given text name pool_selections = self.get_obj( [vim.ResourcePool], pool_name, ...
def get_resource_pool(self, cluster, pool_name)
Find a resource pool given a pool name for desired cluster
4.461133
4.269301
1.044933
obj = list() if path: obj_folder = self.content.searchIndex.FindByInventoryPath(path) container = self.content.viewManager.CreateContainerView( obj_folder, vimtype, True ) else: container = self.content.viewManager.CreateCo...
def get_obj(self, vimtype, name, return_all=False, path="")
Get the vsphere object associated with a given text name or MOID
2.425652
2.37335
1.022037
if verbose: print("Finding HostSystem named %s..." % name) hs = self.get_host_system(name) if hs is None: print("Error: %s '%s' does not exist" % (host_system_term, name)) sys.exit(1) if verbose: print("Found HostSystem: {0} Nam...
def get_host_system_failfast( self, name, verbose=False, host_system_term='HS' )
Get a HostSystem object fail fast if the object isn't a valid reference
3.224773
2.892311
1.114947
if path: return self.get_obj([vim.VirtualMachine], name, path=path) else: return self.get_obj([vim.VirtualMachine], name)
def get_vm(self, name, path="")
Get a VirtualMachine object
3.008059
2.69028
1.118121
if verbose: print("Finding VirtualMachine named %s..." % name) if path: vm = self.get_vm(name, path=path) else: vm = self.get_vm(name) if vm is None: print("Error: %s '%s' does not exist" % (vm_term, name)) sys.exit(1) ...
def get_vm_failfast(self, name, verbose=False, vm_term='VM', path="")
Get a VirtualMachine object fail fast if the object isn't a valid reference
2.492624
2.371598
1.051031
seconds_waited = 0 # wait counter while seconds_waited < timeout_seconds: # sleep first, since nothing shuts down instantly seconds_waited += sleep_period time.sleep(sleep_period) vm = self.get_vm(vm_to_poll.name) if vm.runtime.power...
def WaitForVirtualMachineShutdown( self, vm_to_poll, timeout_seconds, sleep_period=5 )
Guest shutdown requests do not run a task we can wait for. So, we must poll and wait for status to be poweredOff. Returns True if shutdown, False if poll expired.
3.674518
3.482722
1.055071
func = sup = super(FuturesSession, self).request background_callback = kwargs.pop('background_callback', None) if background_callback: def wrap(*args_, **kwargs_): resp = sup(*args_, **kwargs_) # Patch the closure to return the callback. return background_ca...
def request_patch(self, *args, **kwargs)
Maintains the existing api for Session.request. Used by all of the higher level methods, e.g. Session.get. The background_callback param allows you to do some processing on the response in the background, e.g. call resp.json() so that json parsing happens in the background thread.
5.789188
5.297572
1.0928
api_logger.debug("Starting new HTTP session...") self.session = FuturesSession(executor=self.executor, max_workers=self.max_workers) self.session.headers.update({"User-Agent": self.user_agent}) if self.username and self.password: api_logger.debug("Requests will use a...
def _start_http_session(self)
Start a new requests HTTP session, clearing cookies and session data. :return: None
2.952149
3.0066
0.98189
api_logger.debug("Sending request: {} ({})".format(sub_uri, request_type)) if not self.session: self._start_http_session() uri = urljoin(self.uri_base, sub_uri) if params: kwargs.update(params=params) if callback: def base_callback(_, ...
def _service_request(self, request_type, sub_uri, params=None, callback=None, raise_for_status=True, raw=False, **kwargs)
Base method for handling HTTP requests via the current requests session. :param request_type: The request type as a string (e.g. "POST", "GET", "PUT", etc.) :param sub_uri: The REST end point (sub-uri) to communicate with. :param params: (Optional) HTTP Request parameters. Default: none ...
2.488689
2.413522
1.031144
''' Get geolocation data for a given IP address If field is specified, get specific field as text Else get complete location data as JSON ''' if field and (field not in field_list): return 'Invalid field' if field: if ip: url = 'https://ipapi.co/{}/{}/'.fo...
def location(ip=None, key=None, field=None)
Get geolocation data for a given IP address If field is specified, get specific field as text Else get complete location data as JSON
2.945974
2.178767
1.352129
VAR['sma'] = pysma.SMA(session, ip, password=password, group=user) await VAR['sma'].new_session() if VAR['sma'].sma_sid is None: _LOGGER.info("No session ID") return _LOGGER.info("NEW SID: %s", VAR['sma'].sma_sid) VAR['running'] = True cnt = 5 ...
async def main_loop(loop, password, user, ip): # pylint: disable=invalid-name async with aiohttp.ClientSession(loop=loop) as session
Main loop.
4.871441
4.708312
1.034647
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) parser = argparse.ArgumentParser( description='Test the SMA webconnect library.') parser.add_argument( 'ip', type=str, help='IP address of the Webconnect module') parser.add_argument( 'user', help='installer/user')...
def main()
Main example.
3.21156
3.184272
1.00857
result = self.api.github_api(*self._apicall_parameters()) if result is None: # an error occurred, try again after BACKOFF self._next_update = datetime.now() + timedelta(seconds=self.BACKOFF) # assume an empty result until the error disappears self...
def update(self)
Connect to GitHub API endpoint specified by `_apicall_parameters()`, postprocess the result using `_apiresult_postprocess()` and trigger a cache update if the API call was successful. If an error occurs, cache the empty result generated by `_apiresult_error()`. Additionally, set up retr...
8.475639
5.906322
1.435012
if self._next_update and datetime.now() > self._next_update: self.update() return self._data
def data(self)
Get a cached post-processed result of a GitHub API call. Uses Trac cache to avoid constant querying of the remote API. If a previous API call did not succeed, automatically retries after a timeout.
5.932646
4.711769
1.259112
teams = self._teamlist.teams() # find out which teams have been added or removed since the last sync current_teams = set(self._teamobjects.keys()) new_teams = set(teams.keys()) # pylint: disable=no-member added = new_teams - current_teams removed = current_teams...
def teams(self)
Return a sequence of `GitHubTeam` objects, one for each team in this org.
3.361884
3.058132
1.099326
allmembers = set() for team in self.teams(): allmembers.update(team.members()) return sorted(allmembers)
def members(self)
Return a list of all users in this organization. Users are identified by their login name. Note that this is computed from the teams in the organization, because GitHub does not currently offer a WebHook for organization membership, so converting org membership would lead to stale data.
4.214382
3.550641
1.186935
if slug not in self._teamobjects: # This case is checked and handled further up, but better be safe # than sorry. return False # pragma: no cover return self._teamobjects[slug].update()
def update_team(self, slug)
Trigger an update and cache invalidation for the team identified by the given `slug`. Returns `True` on success, `False` otherwise. :param slug: The GitHub 'slug' that identifies the team in URLs
9.719945
11.249022
0.86407
import requests import urllib github_api_url = os.environ.get("TRAC_GITHUB_API_URL", "https://api.github.com/") formatted_url = github_api_url + url.format(*(urllib.quote(str(x)) for x in args)) access_token = _config_secret(self.access_token) self.log.debug("Hi...
def github_api(self, url, *args)
Connect to the given GitHub API URL template by replacing all placeholders with the given parameters and return the decoded JSON result on success. On error, return `None`. :param url: The path to request from the GitHub API. Contains format string placeholders that will be ...
2.452729
2.476604
0.99036
if self._org: if not self._org.has_team(slug): return self._org.update() return self._org.update_team(slug) # self._org is created during Trac startup, so there should never # be a case where we try to update an org before it's created; this ...
def update_team(self, slug)
Trigger update and cache invalidation for the team identified by the given `slug`, if any. Returns `True` if the update was successful, `False` otherwise. :param slug: GitHub 'slug' name for the team to be updated.
7.397164
7.846942
0.942681
if not self.organization or not self.username or not self.access_token: return [] elif (self.username_prefix and not username.startswith(self.username_prefix)): return [] data = self._fetch_groups() if not data: self.log.error...
def get_permission_groups(self, username)
Return a list of names of the groups that the user with the specified name is a member of. Implements an `IPermissionGroupProvider` API. This specific implementation connects to GitHub with a dedicated user, fetches and caches the teams and their users configured at GitHub and converts ...
4.752562
4.477121
1.061522
match = self._request_re.match(req.path_info) if match: return True if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGING', None) is not None: debug_match = self._debug_request_re.match(req.path_info) if debug_match: return True
def match_request(self, req)
Return whether the handler wants to process the given request. Implements an `IRequestHandler` API.
3.492709
3.500351
0.997817
req.send(json.dumps(self._fetch_groups()).encode('utf-8'), 'application/json', 200)
def process_debug_request(self, req)
Debgging helper used for testing, processes the given request and dumps the internal state of cached user to group mappings. Note that this is only callable if TRAC_GITHUB_ENABLE_DEBUGGING is set in the environment.
7.815901
6.650478
1.175239
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGING', None) is not None: debug_match = self._debug_request_re.match(req.path_info) if debug_match: self.process_debug_request(req) if req.method != 'POST': msg = u'Endpoint is ready to accept GitHub...
def process_request(self, req)
Process the given request `req`, implements an `IRequestHandler` API. Normally, `process_request` would return a tuple, but since none of these requests will return an HTML page, they will all terminate without a return value and directly send a response.
2.431542
2.451942
0.99168
kwargs = kwargs.copy() pos, outer_limit = 0, kwargs.get('limit', 0) or sys.maxsize while True: response = api_call(*args, **kwargs) for item in response.get('results', []): pos += 1 if pos > outer_limit: return yield item ##pri...
def all_of(api_call, *args, **kwargs)
Generator that iterates over all results of an API call that requires limit/start pagination. If the `limit` keyword argument is set, it is used to stop the generator after the given number of result items. >>> for i, v in enumerate(all_of(api.get_content)): >>> v = bunchify(v) >>> print('...
3.326006
3.283711
1.01288
api_logger.debug("Starting new HTTP session...") self.session = requests.Session() self.session.headers.update({"User-Agent": self.user_agent}) if self.username and self.password: api_logger.debug("Requests will use authorization.") self.session.auth = HT...
def _start_http_session(self)
Start a new requests HTTP session, clearing cookies and session data. :return: None
2.900901
3.003831
0.965734
params = {} if content_type: params["type"] = content_type if space_key: params["spaceKey"] = space_key if title: params["title"] = title if status: params["status"] = status if posting_day: params["post...
def get_content(self, content_type=None, space_key=None, title=None, status=None, posting_day=None, expand=None, start=None, limit=None, callback=None)
Returns a paginated list of Content. :param content_type (string): OPTIONAL: The content type to return. Default value: "page". Valid values: "page","blogpost". :param space_key (string): OPTIONAL: The space key to find content under. :param title (string): ...
1.550077
1.693533
0.915292
params = {} if status: params["status"] = status if version is not None: params["version"] = int(version) if expand: params["expand"] = expand return self._service_get_request("rest/api/content/{id}".format(id=content_id), params=param...
def get_content_by_id(self, content_id, status=None, version=None, expand=None, callback=None)
Returns a piece of Content. :param content_id (string): The id of the content. :param status (string): OPTIONAL: List of Content statuses to filter results on. Default value: [current] :param version (int): OPTIONAL: The content version to retrieve. Default: Latest. :param expand (string...
2.707921
2.781463
0.97356
return self._service_get_request("rest/api/content/{id}/history/{version}/macro/hash/{hash}" "".format(id=content_id, version=version, hash=macro_hash), callback=callback)
def get_content_macro_by_hash(self, content_id, version, macro_hash, callback=None)
Returns the body of a macro (in storage format) with the given hash. This resource is primarily used by connect applications that require the body of macro to perform their work. The hash is generated by connect during render time of the local macro holder and is usually only relevant during th...
4.419753
4.393414
1.005995
return self._service_get_request("rest/api/content/{id}/history/{version}/macro/id/{macro_id}" "".format(id=content_id, version=int(version), macro_id=macro_id), callback=callback)
def get_content_macro_by_macro_id(self, content_id, version, macro_id, callback=None)
Returns the body of a macro (in storage format) with the given id. This resource is primarily used by connect applications that require the body of macro to perform their work. When content is created, if no macroId is specified, then Confluence will generate a random id. The id is persisted as...
4.204488
4.208871
0.998959
params = {} if cql_str: params["cql"] = cql_str if cql_context: params["cqlcontext"] = json.dumps(cql_context) if expand: params["expand"] = expand if start is not None: params["start"] = int(start) if limit is not ...
def search_content(self, cql_str=None, cql_context=None, expand=None, start=0, limit=None, callback=None)
Fetch a list of content using the Confluence Query Language (CQL). See: Advanced searching using CQL (https://developer.atlassian.com/display/CONFDEV/Advanced+Searching+using+CQL) :param cql_str (string): OPTIONAL: A cql query string to use to locate content. :param cql_context (string): OPTIONA...
1.998555
1.949725
1.025045
params = {} if expand: params["expand"] = expand if parent_version: params["parentVersion"] = parent_version return self._service_get_request("rest/api/content/{id}/child".format(id=content_id), params=params, call...
def get_content_children(self, content_id, expand=None, parent_version=None, callback=None)
Returns a map of the direct children of a piece of Content. Content can have multiple types of children - for example a Page can have children that are also Pages, but it can also have Comments and Attachments. The {@link ContentType}(s) of the children returned is specified by the "expand" query param...
2.772295
3.090144
0.897141