repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_container_remove_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 con... | python | 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 con... | [
"def",
"get_container_remove_kwargs",
"(",
"self",
",",
"action",
",",
"container_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"container",
"=",
"container_name",
")",
"update_kwargs",
"(",
"c_kwargs",
",",
"kwargs",
")",
"return"... | 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 ... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"remove",
"a",
"container",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L405-L420 | train | 61,700 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_network_create_kwargs | 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:... | python | 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:... | [
"def",
"get_network_create_kwargs",
"(",
"self",
",",
"action",
",",
"network_name",
",",
"kwargs",
"=",
"None",
")",
":",
"config",
"=",
"action",
".",
"config",
"c_kwargs",
"=",
"dict",
"(",
"name",
"=",
"network_name",
",",
"driver",
"=",
"config",
".",... | 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... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"create",
"a",
"network",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L422-L448 | train | 61,701 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_network_remove_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:... | python | 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:... | [
"def",
"get_network_remove_kwargs",
"(",
"self",
",",
"action",
",",
"network_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"net_id",
"=",
"network_name",
")",
"update_kwargs",
"(",
"c_kwargs",
",",
"kwargs",
")",
"return",
"c_kw... | 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... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"remove",
"a",
"network",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L450-L465 | train | 61,702 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_network_connect_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_na... | python | 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_na... | [
"def",
"get_network_connect_kwargs",
"(",
"self",
",",
"action",
",",
"network_name",
",",
"container_name",
",",
"endpoint_config",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"container",
"=",
"container_name",
",",
"net_... | 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... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"add",
"a",
"container",
"to",
"a",
"network",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L497-L521 | train | 61,703 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_network_disconnect_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: Containe... | python | 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: Containe... | [
"def",
"get_network_disconnect_kwargs",
"(",
"self",
",",
"action",
",",
"network_name",
",",
"container_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"container",
"=",
"container_name",
",",
"net_id",
"=",
"network_name",
",",
")"... | 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.
... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"remove",
"a",
"container",
"from",
"a",
"network",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L523-L543 | train | 61,704 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_volume_create_kwargs | 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 | s... | python | 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 | s... | [
"def",
"get_volume_create_kwargs",
"(",
"self",
",",
"action",
",",
"volume_name",
",",
"kwargs",
"=",
"None",
")",
":",
"config",
"=",
"action",
".",
"config",
"c_kwargs",
"=",
"dict",
"(",
"name",
"=",
"volume_name",
")",
"if",
"config",
":",
"c_kwargs",... | 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... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"create",
"a",
"volume",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L597-L621 | train | 61,705 |
merll/docker-map | dockermap/map/runner/base.py | DockerConfigMixin.get_volume_remove_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 | s... | python | 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 | s... | [
"def",
"get_volume_remove_kwargs",
"(",
"self",
",",
"action",
",",
"volume_name",
",",
"kwargs",
"=",
"None",
")",
":",
"c_kwargs",
"=",
"dict",
"(",
"name",
"=",
"volume_name",
")",
"update_kwargs",
"(",
"c_kwargs",
",",
"kwargs",
")",
"return",
"c_kwargs"... | 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... | [
"Generates",
"keyword",
"arguments",
"for",
"the",
"Docker",
"client",
"to",
"remove",
"a",
"volume",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/runner/base.py#L623-L638 | train | 61,706 |
merll/docker-map | dockermap/map/policy/base.py | BasePolicy.cname | 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
... | python | 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
... | [
"def",
"cname",
"(",
"cls",
",",
"map_name",
",",
"container",
",",
"instance",
"=",
"None",
")",
":",
"if",
"instance",
":",
"return",
"'{0}.{1}.{2}'",
".",
"format",
"(",
"map_name",
",",
"container",
",",
"instance",
")",
"return",
"'{0}.{1}'",
".",
"... | 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... | [
"Generates",
"a",
"container",
"name",
"that",
"should",
"be",
"used",
"for",
"creating",
"new",
"containers",
"and",
"checking",
"the",
"status",
"of",
"existing",
"containers",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/policy/base.py#L85-L104 | train | 61,707 |
merll/docker-map | dockermap/map/policy/base.py | BasePolicy.aname | 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>... | python | 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>... | [
"def",
"aname",
"(",
"cls",
",",
"map_name",
",",
"attached_name",
",",
"parent_name",
"=",
"None",
")",
":",
"if",
"parent_name",
":",
"return",
"'{0}.{1}.{2}'",
".",
"format",
"(",
"map_name",
",",
"parent_name",
",",
"attached_name",
")",
"return",
"'{0}.... | 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 ... | [
"Generates",
"a",
"container",
"name",
"that",
"should",
"be",
"used",
"for",
"creating",
"new",
"attached",
"volume",
"containers",
"and",
"checking",
"the",
"status",
"of",
"existing",
"containers",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/policy/base.py#L107-L126 | train | 61,708 |
merll/docker-map | dockermap/map/policy/base.py | BasePolicy.nname | 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 ma... | python | 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 ma... | [
"def",
"nname",
"(",
"cls",
",",
"map_name",
",",
"network_name",
")",
":",
"if",
"network_name",
"in",
"DEFAULT_PRESET_NETWORKS",
":",
"return",
"network_name",
"return",
"'{0}.{1}'",
".",
"format",
"(",
"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... | [
"Generates",
"a",
"network",
"name",
"that",
"should",
"be",
"used",
"for",
"creating",
"new",
"networks",
"and",
"checking",
"the",
"status",
"of",
"existing",
"networks",
"on",
"the",
"client",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/policy/base.py#L129-L145 | train | 61,709 |
merll/docker-map | dockermap/map/policy/base.py | BasePolicy.get_hostname | 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.
... | python | 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.
... | [
"def",
"get_hostname",
"(",
"cls",
",",
"container_name",
",",
"client_name",
"=",
"None",
")",
":",
"base_name",
"=",
"container_name",
"for",
"old",
",",
"new",
"in",
"cls",
".",
"hostname_replace",
":",
"base_name",
"=",
"base_name",
".",
"replace",
"(",
... | 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... | [
"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",... | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/map/policy/base.py#L148-L169 | train | 61,710 |
merll/docker-map | dockermap/shortcuts.py | adduser | 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 ... | python | 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 ... | [
"def",
"adduser",
"(",
"username",
",",
"uid",
"=",
"None",
",",
"system",
"=",
"False",
",",
"no_login",
"=",
"True",
",",
"no_password",
"=",
"False",
",",
"group",
"=",
"False",
",",
"gecos",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"retu... | 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. ... | [
"Formats",
"an",
"adduser",
"command",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/shortcuts.py#L48-L75 | train | 61,711 |
merll/docker-map | dockermap/shortcuts.py | mkdir | 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... | python | 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... | [
"def",
"mkdir",
"(",
"path",
",",
"create_parent",
"=",
"True",
",",
"check_if_exists",
"=",
"False",
")",
":",
"cmd",
"=",
"_format_cmd",
"(",
"'mkdir'",
",",
"path",
",",
"_p",
"=",
"create_parent",
")",
"if",
"check_if_exists",
":",
"return",
"'if [[ ! ... | 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,... | [
"Generates",
"a",
"unix",
"command",
"line",
"for",
"creating",
"a",
"directory",
"."
] | e14fe86a6ff5c33d121eb2f9157e9359cb80dd02 | https://github.com/merll/docker-map/blob/e14fe86a6ff5c33d121eb2f9157e9359cb80dd02/dockermap/shortcuts.py#L132-L149 | train | 61,712 |
django-parler/django-parler-rest | parler_rest/fields.py | TranslatedFieldsField.bind | 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.
"""
super(TranslatedFieldsField, self... | python | 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.
"""
super(TranslatedFieldsField, self... | [
"def",
"bind",
"(",
"self",
",",
"field_name",
",",
"parent",
")",
":",
"super",
"(",
"TranslatedFieldsField",
",",
"self",
")",
".",
"bind",
"(",
"field_name",
",",
"parent",
")",
"# Expect 1-on-1 for now. Allow using source as alias,",
"# but it should not be a dott... | 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. | [
"Create",
"translation",
"serializer",
"dynamically",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/fields.py#L37-L75 | train | 61,713 |
django-parler/django-parler-rest | parler_rest/fields.py | TranslatedFieldsField.to_representation | 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,
... | python | 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,
... | [
"def",
"to_representation",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"# Only need one serializer to create the native objects",
"serializer",
"=",
"self",
".",
"serializer_class",
"(",
"instance",
"=",
"self",
".",
"parent",
... | 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. | [
"Serialize",
"translated",
"fields",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/fields.py#L81-L116 | train | 61,714 |
django-parler/django-parler-rest | parler_rest/fields.py | TranslatedFieldsField.to_internal_value | def to_internal_value(self, data):
"""
Deserialize data from translations fields.
For each received language, delegate validation logic to
the translation model serializer.
"""
if data is None:
return
if not isinstance(data, dict):
self.f... | python | def to_internal_value(self, data):
"""
Deserialize data from translations fields.
For each received language, delegate validation logic to
the translation model serializer.
"""
if data is None:
return
if not isinstance(data, dict):
self.f... | [
"def",
"to_internal_value",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"self",
".",
"fail",
"(",
"'invalid'",
")",
"if",
"not",
"self",
".",
"allow_emp... | Deserialize data from translations fields.
For each received language, delegate validation logic to
the translation model serializer. | [
"Deserialize",
"data",
"from",
"translations",
"fields",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/fields.py#L118-L143 | train | 61,715 |
art1415926535/yandex_speech | yandex_speech/nlu.py | NLU.parse | 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.
Retur... | python | 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.
Retur... | [
"def",
"parse",
"(",
"self",
",",
"text",
",",
"layers",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"text\"",
":",
"text",
",",
"\"key\"",
":",
"self",
".",
"key",
",",
"}",
"if",
"layers",
"is",
"not",
"None",
":",
"# if it's string",
"if",
"isi... | 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... | [
"Parsing",
"passed",
"text",
"to",
"json",
"."
] | 24820608b921e6ec3567a76a1ae6f3598a5b400b | https://github.com/art1415926535/yandex_speech/blob/24820608b921e6ec3567a76a1ae6f3598a5b400b/yandex_speech/nlu.py#L32-L60 | train | 61,716 |
art1415926535/yandex_speech | yandex_speech/tts.py | TTS.generate | def generate(self, text):
"""Try to get the generated file.
Args:
text: The text that you want to generate.
"""
if not text:
raise Exception("No text to speak")
if len(text) >= self.MAX_CHARS:
raise Exception("Number of characters must be les... | python | def generate(self, text):
"""Try to get the generated file.
Args:
text: The text that you want to generate.
"""
if not text:
raise Exception("No text to speak")
if len(text) >= self.MAX_CHARS:
raise Exception("Number of characters must be les... | [
"def",
"generate",
"(",
"self",
",",
"text",
")",
":",
"if",
"not",
"text",
":",
"raise",
"Exception",
"(",
"\"No text to speak\"",
")",
"if",
"len",
"(",
"text",
")",
">=",
"self",
".",
"MAX_CHARS",
":",
"raise",
"Exception",
"(",
"\"Number of characters ... | Try to get the generated file.
Args:
text: The text that you want to generate. | [
"Try",
"to",
"get",
"the",
"generated",
"file",
"."
] | 24820608b921e6ec3567a76a1ae6f3598a5b400b | https://github.com/art1415926535/yandex_speech/blob/24820608b921e6ec3567a76a1ae6f3598a5b400b/yandex_speech/tts.py#L30-L45 | train | 61,717 |
art1415926535/yandex_speech | yandex_speech/tts.py | TTS.save | 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.
"""
if self._data is None:
... | python | 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.
"""
if self._data is None:
... | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"\"speech\"",
")",
":",
"if",
"self",
".",
"_data",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"There's nothing to save\"",
")",
"extension",
"=",
"\".\"",
"+",
"self",
".",
"__params",
"[",
"\"format\"",
... | 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. | [
"Save",
"data",
"in",
"file",
"."
] | 24820608b921e6ec3567a76a1ae6f3598a5b400b | https://github.com/art1415926535/yandex_speech/blob/24820608b921e6ec3567a76a1ae6f3598a5b400b/yandex_speech/tts.py#L47-L68 | train | 61,718 |
django-parler/django-parler-rest | parler_rest/utils.py | create_translated_fields_serializer | 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`
"""
if not related_name:... | python | 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`
"""
if not related_name:... | [
"def",
"create_translated_fields_serializer",
"(",
"shared_model",
",",
"meta",
"=",
"None",
",",
"related_name",
"=",
"None",
",",
"*",
"*",
"fields",
")",
":",
"if",
"not",
"related_name",
":",
"translated_model",
"=",
"shared_model",
".",
"_parler_meta",
".",... | Create a Rest Framework serializer class for a translated fields model.
:param shared_model: The shared model.
:type shared_model: :class:`parler.models.TranslatableModel` | [
"Create",
"a",
"Rest",
"Framework",
"serializer",
"class",
"for",
"a",
"translated",
"fields",
"model",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/utils.py#L8-L32 | train | 61,719 |
django-parler/django-parler-rest | parler_rest/serializers.py | TranslatableModelSerializer.save | 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.... | python | 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.... | [
"def",
"save",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"translated_data",
"=",
"self",
".",
"_pop_translated_data",
"(",
")",
"instance",
"=",
"super",
"(",
"TranslatableModelSerializer",
",",
"self",
")",
".",
"save",
"(",
"*",
"*",
"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. | [
"Extract",
"the",
"translations",
"and",
"save",
"them",
"after",
"main",
"object",
"save",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/serializers.py#L17-L28 | train | 61,720 |
django-parler/django-parler-rest | parler_rest/serializers.py | TranslatableModelSerializer._pop_translated_data | def _pop_translated_data(self):
"""
Separate data of translated fields from other data.
"""
translated_data = {}
for meta in self.Meta.model._parler_meta:
translations = self.validated_data.pop(meta.rel_name, {})
if translations:
translated... | python | def _pop_translated_data(self):
"""
Separate data of translated fields from other data.
"""
translated_data = {}
for meta in self.Meta.model._parler_meta:
translations = self.validated_data.pop(meta.rel_name, {})
if translations:
translated... | [
"def",
"_pop_translated_data",
"(",
"self",
")",
":",
"translated_data",
"=",
"{",
"}",
"for",
"meta",
"in",
"self",
".",
"Meta",
".",
"model",
".",
"_parler_meta",
":",
"translations",
"=",
"self",
".",
"validated_data",
".",
"pop",
"(",
"meta",
".",
"r... | Separate data of translated fields from other data. | [
"Separate",
"data",
"of",
"translated",
"fields",
"from",
"other",
"data",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/serializers.py#L30-L39 | train | 61,721 |
django-parler/django-parler-rest | parler_rest/serializers.py | TranslatableModelSerializer.save_translations | def save_translations(self, instance, translated_data):
"""
Save translation data into translation objects.
"""
for meta in self.Meta.model._parler_meta:
translations = translated_data.get(meta.rel_name, {})
for lang_code, model_fields in translations.items():
... | python | def save_translations(self, instance, translated_data):
"""
Save translation data into translation objects.
"""
for meta in self.Meta.model._parler_meta:
translations = translated_data.get(meta.rel_name, {})
for lang_code, model_fields in translations.items():
... | [
"def",
"save_translations",
"(",
"self",
",",
"instance",
",",
"translated_data",
")",
":",
"for",
"meta",
"in",
"self",
".",
"Meta",
".",
"model",
".",
"_parler_meta",
":",
"translations",
"=",
"translated_data",
".",
"get",
"(",
"meta",
".",
"rel_name",
... | Save translation data into translation objects. | [
"Save",
"translation",
"data",
"into",
"translation",
"objects",
"."
] | 9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5 | https://github.com/django-parler/django-parler-rest/blob/9f9d469ece38aaf4e0e3d2152bb9e7824bb3d9f5/parler_rest/serializers.py#L41-L54 | train | 61,722 |
dhocker/udmx-pyusb | uDMX.py | load_conf | def load_conf(cfg_path):
"""
Try to load the given conf file.
"""
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 conte... | python | def load_conf(cfg_path):
"""
Try to load the given conf file.
"""
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 conte... | [
"def",
"load_conf",
"(",
"cfg_path",
")",
":",
"global",
"config",
"try",
":",
"cfg",
"=",
"open",
"(",
"cfg_path",
",",
"'r'",
")",
"except",
"Exception",
"as",
"ex",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Unable to open {0}\"",
".",
"format",
"(",... | Try to load the given conf file. | [
"Try",
"to",
"load",
"the",
"given",
"conf",
"file",
"."
] | ee7d10604ecd83857154ed6739793de3b7bd5fc1 | https://github.com/dhocker/udmx-pyusb/blob/ee7d10604ecd83857154ed6739793de3b7bd5fc1/uDMX.py#L37-L64 | train | 61,723 |
dhocker/udmx-pyusb | uDMX.py | translate_message_tokens | 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.
"""
trans_tokens = []
if message_tokens[0] in cv_dict[channels_key]:
trans_tokens.append(cv_dict[channels... | python | 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.
"""
trans_tokens = []
if message_tokens[0] in cv_dict[channels_key]:
trans_tokens.append(cv_dict[channels... | [
"def",
"translate_message_tokens",
"(",
"message_tokens",
")",
":",
"trans_tokens",
"=",
"[",
"]",
"if",
"message_tokens",
"[",
"0",
"]",
"in",
"cv_dict",
"[",
"channels_key",
"]",
":",
"trans_tokens",
".",
"append",
"(",
"cv_dict",
"[",
"channels_key",
"]",
... | Translates alias references to their defined values.
The first token is a channel alias.
The remaining tokens are value aliases. | [
"Translates",
"alias",
"references",
"to",
"their",
"defined",
"values",
".",
"The",
"first",
"token",
"is",
"a",
"channel",
"alias",
".",
"The",
"remaining",
"tokens",
"are",
"value",
"aliases",
"."
] | ee7d10604ecd83857154ed6739793de3b7bd5fc1 | https://github.com/dhocker/udmx-pyusb/blob/ee7d10604ecd83857154ed6739793de3b7bd5fc1/uDMX.py#L237-L255 | train | 61,724 |
codingjoe/ssdp | ssdp/__init__.py | SSDPMessage.parse_headers | def parse_headers(cls, msg):
"""
Parse HTTP headers.
Args:
msg (str): HTTP message.
Returns:
(List[Tuple[str, str]): List of header tuples.
"""
return list(email.parser.Parser().parsestr(msg).items()) | python | def parse_headers(cls, msg):
"""
Parse HTTP headers.
Args:
msg (str): HTTP message.
Returns:
(List[Tuple[str, str]): List of header tuples.
"""
return list(email.parser.Parser().parsestr(msg).items()) | [
"def",
"parse_headers",
"(",
"cls",
",",
"msg",
")",
":",
"return",
"list",
"(",
"email",
".",
"parser",
".",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"msg",
")",
".",
"items",
"(",
")",
")"
] | Parse HTTP headers.
Args:
msg (str): HTTP message.
Returns:
(List[Tuple[str, str]): List of header tuples. | [
"Parse",
"HTTP",
"headers",
"."
] | 84ff667c792608b221aa726cfd106b554884063d | https://github.com/codingjoe/ssdp/blob/84ff667c792608b221aa726cfd106b554884063d/ssdp/__init__.py#L39-L50 | train | 61,725 |
codingjoe/ssdp | ssdp/__init__.py | SSDPResponse.parse | def parse(cls, msg):
"""Parse message string to response object."""
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, ... | python | def parse(cls, msg):
"""Parse message string to response object."""
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, ... | [
"def",
"parse",
"(",
"cls",
",",
"msg",
")",
":",
"lines",
"=",
"msg",
".",
"splitlines",
"(",
")",
"version",
",",
"status_code",
",",
"reason",
"=",
"lines",
"[",
"0",
"]",
".",
"split",
"(",
")",
"headers",
"=",
"cls",
".",
"parse_headers",
"(",... | Parse message string to response object. | [
"Parse",
"message",
"string",
"to",
"response",
"object",
"."
] | 84ff667c792608b221aa726cfd106b554884063d | https://github.com/codingjoe/ssdp/blob/84ff667c792608b221aa726cfd106b554884063d/ssdp/__init__.py#L70-L76 | train | 61,726 |
codingjoe/ssdp | ssdp/__init__.py | SSDPRequest.parse | def parse(cls, msg):
"""Parse message string to request object."""
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) | python | def parse(cls, msg):
"""Parse message string to request object."""
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",
")",
":",
"lines",
"=",
"msg",
".",
"splitlines",
"(",
")",
"method",
",",
"uri",
",",
"version",
"=",
"lines",
"[",
"0",
"]",
".",
"split",
"(",
")",
"headers",
"=",
"cls",
".",
"parse_headers",
"(",
"'\\r... | Parse message string to request object. | [
"Parse",
"message",
"string",
"to",
"request",
"object",
"."
] | 84ff667c792608b221aa726cfd106b554884063d | https://github.com/codingjoe/ssdp/blob/84ff667c792608b221aa726cfd106b554884063d/ssdp/__init__.py#L98-L103 | train | 61,727 |
codingjoe/ssdp | ssdp/__init__.py | SSDPRequest.sendto | 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 m... | python | 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 m... | [
"def",
"sendto",
"(",
"self",
",",
"transport",
",",
"addr",
")",
":",
"msg",
"=",
"bytes",
"(",
"self",
")",
"+",
"b'\\r\\n'",
"logger",
".",
"debug",
"(",
"\"%s:%s < %s\"",
",",
"*",
"(",
"addr",
"+",
"(",
"self",
",",
")",
")",
")",
"transport",... | 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. | [
"Send",
"request",
"to",
"a",
"given",
"address",
"via",
"given",
"transport",
"."
] | 84ff667c792608b221aa726cfd106b554884063d | https://github.com/codingjoe/ssdp/blob/84ff667c792608b221aa726cfd106b554884063d/ssdp/__init__.py#L105-L118 | train | 61,728 |
dhocker/udmx-pyusb | example.py | send_rgb | def send_rgb(dev, red, green, blue, dimmer):
"""
Send a set of RGB values to the light
"""
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 | python | def send_rgb(dev, red, green, blue, dimmer):
"""
Send a set of RGB values to the light
"""
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",
")",
":",
"cv",
"=",
"[",
"0",
"for",
"v",
"in",
"range",
"(",
"0",
",",
"512",
")",
"]",
"cv",
"[",
"0",
"]",
"=",
"red",
"cv",
"[",
"1",
"]",
"=",
"gre... | Send a set of RGB values to the light | [
"Send",
"a",
"set",
"of",
"RGB",
"values",
"to",
"the",
"light"
] | ee7d10604ecd83857154ed6739793de3b7bd5fc1 | https://github.com/dhocker/udmx-pyusb/blob/ee7d10604ecd83857154ed6739793de3b7bd5fc1/example.py#L26-L36 | train | 61,729 |
dhocker/udmx-pyusb | example.py | main | def main():
"""
How to control a DMX light through an Anyma USB controller
"""
# 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... | python | def main():
"""
How to control a DMX light through an Anyma USB controller
"""
# 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... | [
"def",
"main",
"(",
")",
":",
"# 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...\"",
")",
... | How to control a DMX light through an Anyma USB controller | [
"How",
"to",
"control",
"a",
"DMX",
"light",
"through",
"an",
"Anyma",
"USB",
"controller"
] | ee7d10604ecd83857154ed6739793de3b7bd5fc1 | https://github.com/dhocker/udmx-pyusb/blob/ee7d10604ecd83857154ed6739793de3b7bd5fc1/example.py#L39-L96 | train | 61,730 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.connect | def connect(self):
"""Connect to vCenter server"""
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 = Smart... | python | def connect(self):
"""Connect to vCenter server"""
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 = Smart... | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"context",
"=",
"ssl",
".",
"SSLContext",
"(",
"ssl",
".",
"PROTOCOL_TLSv1_2",
")",
"if",
"self",
".",
"config",
"[",
"'no_ssl_verify'",
"]",
":",
"requests",
".",
"packages",
".",
"urllib3",
".",
"d... | Connect to vCenter server | [
"Connect",
"to",
"vCenter",
"server"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L109-L142 | train | 61,731 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.status | def status(self):
"""Check power status"""
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", ... | python | def status(self):
"""Check power status"""
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", ... | [
"def",
"status",
"(",
"self",
")",
":",
"vm",
"=",
"self",
".",
"get_vm_failfast",
"(",
"self",
".",
"config",
"[",
"'name'",
"]",
")",
"extra",
"=",
"self",
".",
"config",
"[",
"'extra'",
"]",
"parserFriendly",
"=",
"self",
".",
"config",
"[",
"'par... | Check power status | [
"Check",
"power",
"status"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L522-L546 | train | 61,732 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.shutdown | def shutdown(self):
"""
Shutdown guest
fallback to power off if guest tools aren't installed
"""
vm = self.get_vm_failfast(self.config['name'])
if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff:
print("%s already poweredOff" % vm.name)
... | python | def shutdown(self):
"""
Shutdown guest
fallback to power off if guest tools aren't installed
"""
vm = self.get_vm_failfast(self.config['name'])
if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOff:
print("%s already poweredOff" % vm.name)
... | [
"def",
"shutdown",
"(",
"self",
")",
":",
"vm",
"=",
"self",
".",
"get_vm_failfast",
"(",
"self",
".",
"config",
"[",
"'name'",
"]",
")",
"if",
"vm",
".",
"runtime",
".",
"powerState",
"==",
"vim",
".",
"VirtualMachinePowerState",
".",
"poweredOff",
":",... | Shutdown guest
fallback to power off if guest tools aren't installed | [
"Shutdown",
"guest",
"fallback",
"to",
"power",
"off",
"if",
"guest",
"tools",
"aren",
"t",
"installed"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L548-L577 | train | 61,733 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_resource_pool | def get_resource_pool(self, cluster, pool_name):
"""
Find a resource pool given a pool name for desired cluster
"""
pool_obj = None
# get a list of all resource pools in this cluster
cluster_pools_list = cluster.resourcePool.resourcePool
# get list of all resour... | python | def get_resource_pool(self, cluster, pool_name):
"""
Find a resource pool given a pool name for desired cluster
"""
pool_obj = None
# get a list of all resource pools in this cluster
cluster_pools_list = cluster.resourcePool.resourcePool
# get list of all resour... | [
"def",
"get_resource_pool",
"(",
"self",
",",
"cluster",
",",
"pool_name",
")",
":",
"pool_obj",
"=",
"None",
"# get a list of all resource pools in this cluster",
"cluster_pools_list",
"=",
"cluster",
".",
"resourcePool",
".",
"resourcePool",
"# get list of all resource po... | Find a resource pool given a pool name for desired cluster | [
"Find",
"a",
"resource",
"pool",
"given",
"a",
"pool",
"name",
"for",
"desired",
"cluster"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L778-L801 | train | 61,734 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_obj | def get_obj(self, vimtype, name, return_all=False, path=""):
"""Get the vsphere object associated with a given text name or MOID"""
obj = list()
if path:
obj_folder = self.content.searchIndex.FindByInventoryPath(path)
container = self.content.viewManager.CreateContainerVi... | python | def get_obj(self, vimtype, name, return_all=False, path=""):
"""Get the vsphere object associated with a given text name or MOID"""
obj = list()
if path:
obj_folder = self.content.searchIndex.FindByInventoryPath(path)
container = self.content.viewManager.CreateContainerVi... | [
"def",
"get_obj",
"(",
"self",
",",
"vimtype",
",",
"name",
",",
"return_all",
"=",
"False",
",",
"path",
"=",
"\"\"",
")",
":",
"obj",
"=",
"list",
"(",
")",
"if",
"path",
":",
"obj_folder",
"=",
"self",
".",
"content",
".",
"searchIndex",
".",
"F... | Get the vsphere object associated with a given text name or MOID | [
"Get",
"the",
"vsphere",
"object",
"associated",
"with",
"a",
"given",
"text",
"name",
"or",
"MOID"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L803-L827 | train | 61,735 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_host_system_failfast | 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
"""
if verbose:
print("Finding HostSystem named %s..." % n... | python | 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
"""
if verbose:
print("Finding HostSystem named %s..." % n... | [
"def",
"get_host_system_failfast",
"(",
"self",
",",
"name",
",",
"verbose",
"=",
"False",
",",
"host_system_term",
"=",
"'HS'",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Finding HostSystem named %s...\"",
"%",
"name",
")",
"hs",
"=",
"self",
".",
"ge... | Get a HostSystem object
fail fast if the object isn't a valid reference | [
"Get",
"a",
"HostSystem",
"object",
"fail",
"fast",
"if",
"the",
"object",
"isn",
"t",
"a",
"valid",
"reference"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L832-L854 | train | 61,736 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_vm | def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | python | def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
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",
"=",
"\"\"",
")",
":",
"if",
"path",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
",",
"path",
"=",
"path",
")",
"else",
":",
"return",
"s... | Get a VirtualMachine object | [
"Get",
"a",
"VirtualMachine",
"object"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L856-L861 | train | 61,737 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.get_vm_failfast | 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
"""
if verbose:
print("Finding VirtualMachine named %s..." % name)
if path:
vm = self.get_vm(name... | python | 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
"""
if verbose:
print("Finding VirtualMachine named %s..." % name)
if path:
vm = self.get_vm(name... | [
"def",
"get_vm_failfast",
"(",
"self",
",",
"name",
",",
"verbose",
"=",
"False",
",",
"vm_term",
"=",
"'VM'",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"Finding VirtualMachine named %s...\"",
"%",
"name",
")",
"if",
"path",... | Get a VirtualMachine object
fail fast if the object isn't a valid reference | [
"Get",
"a",
"VirtualMachine",
"object",
"fail",
"fast",
"if",
"the",
"object",
"isn",
"t",
"a",
"valid",
"reference"
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L863-L881 | train | 61,738 |
snobear/ezmomi | ezmomi/ezmomi.py | EZMomi.WaitForVirtualMachineShutdown | 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, Fal... | python | 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, Fal... | [
"def",
"WaitForVirtualMachineShutdown",
"(",
"self",
",",
"vm_to_poll",
",",
"timeout_seconds",
",",
"sleep_period",
"=",
"5",
")",
":",
"seconds_waited",
"=",
"0",
"# wait counter",
"while",
"seconds_waited",
"<",
"timeout_seconds",
":",
"# sleep first, since nothing s... | 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. | [
"Guest",
"shutdown",
"requests",
"do",
"not",
"run",
"a",
"task",
"we",
"can",
"wait",
"for",
".",
"So",
"we",
"must",
"poll",
"and",
"wait",
"for",
"status",
"to",
"be",
"poweredOff",
"."
] | c98e26dc2d32cd5c92134fdcbcb8353540ac0208 | https://github.com/snobear/ezmomi/blob/c98e26dc2d32cd5c92134fdcbcb8353540ac0208/ezmomi/ezmomi.py#L935-L958 | train | 61,739 |
ipapi-co/ipapi-python | ipapi/ipapi.py | location | 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
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | python | 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
'''
if field and (field not in field_list):
return 'Invalid field'
if field:
if ip:
... | [
"def",
"location",
"(",
"ip",
"=",
"None",
",",
"key",
"=",
"None",
",",
"field",
"=",
"None",
")",
":",
"if",
"field",
"and",
"(",
"field",
"not",
"in",
"field_list",
")",
":",
"return",
"'Invalid field'",
"if",
"field",
":",
"if",
"ip",
":",
"url... | Get geolocation data for a given IP address
If field is specified, get specific field as text
Else get complete location data as JSON | [
"Get",
"geolocation",
"data",
"for",
"a",
"given",
"IP",
"address",
"If",
"field",
"is",
"specified",
"get",
"specific",
"field",
"as",
"text",
"Else",
"get",
"complete",
"location",
"data",
"as",
"JSON"
] | 45896291d5e6a70fc6234c9e070dc9077ef45ccc | https://github.com/ipapi-co/ipapi-python/blob/45896291d5e6a70fc6234c9e070dc9077ef45ccc/ipapi/ipapi.py#L19-L47 | train | 61,740 |
kellerza/pysma | example.py | main | def main():
"""Main example."""
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(
... | python | def main():
"""Main example."""
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(
... | [
"def",
"main",
"(",
")",
":",
"logging",
".",
"basicConfig",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Test the SMA webconnect libra... | Main example. | [
"Main",
"example",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/example.py#L55-L80 | train | 61,741 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubCachedAPI.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.
"""
if self._next_update and datetime.now() > self._ne... | python | 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.
"""
if self._next_update and datetime.now() > self._ne... | [
"def",
"data",
"(",
"self",
")",
":",
"if",
"self",
".",
"_next_update",
"and",
"datetime",
".",
"now",
"(",
")",
">",
"self",
".",
"_next_update",
":",
"self",
".",
"update",
"(",
")",
"return",
"self",
".",
"_data"
] | 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. | [
"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",
"s... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L431-L439 | train | 61,742 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.teams | def teams(self):
"""
Return a sequence of `GitHubTeam` objects, one for each team in this
org.
"""
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... | python | def teams(self):
"""
Return a sequence of `GitHubTeam` objects, one for each team in this
org.
"""
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... | [
"def",
"teams",
"(",
"self",
")",
":",
"teams",
"=",
"self",
".",
"_teamlist",
".",
"teams",
"(",
")",
"# find out which teams have been added or removed since the last sync",
"current_teams",
"=",
"set",
"(",
"self",
".",
"_teamobjects",
".",
"keys",
"(",
")",
... | Return a sequence of `GitHubTeam` objects, one for each team in this
org. | [
"Return",
"a",
"sequence",
"of",
"GitHubTeam",
"objects",
"one",
"for",
"each",
"team",
"in",
"this",
"org",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L548-L566 | train | 61,743 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.members | 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 member... | python | 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 member... | [
"def",
"members",
"(",
"self",
")",
":",
"allmembers",
"=",
"set",
"(",
")",
"for",
"team",
"in",
"self",
".",
"teams",
"(",
")",
":",
"allmembers",
".",
"update",
"(",
"team",
".",
"members",
"(",
")",
")",
"return",
"sorted",
"(",
"allmembers",
"... | 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. | [
"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",
"Gi... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L588-L599 | train | 61,744 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubOrg.update_team | 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
"""
if slug not in self._teamobjects:
... | python | 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
"""
if slug not in self._teamobjects:
... | [
"def",
"update_team",
"(",
"self",
",",
"slug",
")",
":",
"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",
".",
... | 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 | [
"Trigger",
"an",
"update",
"and",
"cache",
"invalidation",
"for",
"the",
"team",
"identified",
"by",
"the",
"given",
"slug",
".",
"Returns",
"True",
"on",
"success",
"False",
"otherwise",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L610-L621 | train | 61,745 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.github_api | 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... | python | 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... | [
"def",
"github_api",
"(",
"self",
",",
"url",
",",
"*",
"args",
")",
":",
"import",
"requests",
"import",
"urllib",
"github_api_url",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"TRAC_GITHUB_API_URL\"",
",",
"\"https://api.github.com/\"",
")",
"formatted_url",... | 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 ... | [
"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",
"... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L648-L686 | train | 61,746 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.update_team | 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.
"""
if self._or... | python | 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.
"""
if self._or... | [
"def",
"update_team",
"(",
"self",
",",
"slug",
")",
":",
"if",
"self",
".",
"_org",
":",
"if",
"not",
"self",
".",
"_org",
".",
"has_team",
"(",
"slug",
")",
":",
"return",
"self",
".",
"_org",
".",
"update",
"(",
")",
"return",
"self",
".",
"_o... | 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. | [
"Trigger",
"update",
"and",
"cache",
"invalidation",
"for",
"the",
"team",
"identified",
"by",
"the",
"given",
"slug",
"if",
"any",
".",
"Returns",
"True",
"if",
"the",
"update",
"was",
"successful",
"False",
"otherwise",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L719-L734 | train | 61,747 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.get_permission_groups | 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 t... | python | 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 t... | [
"def",
"get_permission_groups",
"(",
"self",
",",
"username",
")",
":",
"if",
"not",
"self",
".",
"organization",
"or",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"access_token",
":",
"return",
"[",
"]",
"elif",
"(",
"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 ... | [
"Return",
"a",
"list",
"of",
"names",
"of",
"the",
"groups",
"that",
"the",
"user",
"with",
"the",
"specified",
"name",
"is",
"a",
"member",
"of",
".",
"Implements",
"an",
"IPermissionGroupProvider",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L737-L757 | train | 61,748 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.match_request | def match_request(self, req):
"""
Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API.
"""
match = self._request_re.match(req.path_info)
if match:
return True
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGIN... | python | def match_request(self, req):
"""
Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API.
"""
match = self._request_re.match(req.path_info)
if match:
return True
if os.environ.get('TRAC_GITHUB_ENABLE_DEBUGGIN... | [
"def",
"match_request",
"(",
"self",
",",
"req",
")",
":",
"match",
"=",
"self",
".",
"_request_re",
".",
"match",
"(",
"req",
".",
"path_info",
")",
"if",
"match",
":",
"return",
"True",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAC_GITHUB_ENABL... | Return whether the handler wants to process the given request.
Implements an `IRequestHandler` API. | [
"Return",
"whether",
"the",
"handler",
"wants",
"to",
"process",
"the",
"given",
"request",
".",
"Implements",
"an",
"IRequestHandler",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L763-L774 | train | 61,749 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.process_debug_request | 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.
"""
re... | python | 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.
"""
re... | [
"def",
"process_debug_request",
"(",
"self",
",",
"req",
")",
":",
"req",
".",
"send",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"_fetch_groups",
"(",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"'application/json'",
",",
"200",
")"
] | 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. | [
"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_ENA... | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L776-L783 | train | 61,750 |
trac-hacks/trac-github | tracext/github/__init__.py | GitHubGroupsProvider.process_request | 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... | python | 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... | [
"def",
"process_request",
"(",
"self",
",",
"req",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'TRAC_GITHUB_ENABLE_DEBUGGING'",
",",
"None",
")",
"is",
"not",
"None",
":",
"debug_match",
"=",
"self",
".",
"_debug_request_re",
".",
"match",
"(",... | 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. | [
"Process",
"the",
"given",
"request",
"req",
"implements",
"an",
"IRequestHandler",
"API",
"."
] | 004b382bb3c76c4d52a04aaaf57d00807e14f0d2 | https://github.com/trac-hacks/trac-github/blob/004b382bb3c76c4d52a04aaaf57d00807e14f0d2/tracext/github/__init__.py#L785-L841 | train | 61,751 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_children | 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 A... | python | 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 A... | [
"def",
"get_content_children",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"parent_version",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\"expand\"",
"]",
"=",
... | 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... | [
"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",
"Pa... | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L325-L351 | train | 61,752 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_descendants | def get_content_descendants(self, content_id, expand=None, callback=None):
"""
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
... | python | def get_content_descendants(self, content_id, expand=None, callback=None):
"""
Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
... | [
"def",
"get_content_descendants",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\"expand\"",
"]",
"=",
"expand",
"return",
"self",
".",
... | Returns a map of the descendants of a piece of Content. Content can have multiple types of descendants -
for example a Page can have descendants that are also Pages, but it can also have Comments and Attachments.
The {@link ContentType}(s) of the descendants returned is specified by the "expand" query ... | [
"Returns",
"a",
"map",
"of",
"the",
"descendants",
"of",
"a",
"piece",
"of",
"Content",
".",
"Content",
"can",
"have",
"multiple",
"types",
"of",
"descendants",
"-",
"for",
"example",
"a",
"Page",
"can",
"have",
"descendants",
"that",
"are",
"also",
"Pages... | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L385-L406 | train | 61,753 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_descendants_by_type | def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,
callback=None):
"""
Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descend... | python | def get_content_descendants_by_type(self, content_id, child_type, expand=None, start=None, limit=None,
callback=None):
"""
Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descend... | [
"def",
"get_content_descendants_by_type",
"(",
"self",
",",
"content_id",
",",
"child_type",
",",
"expand",
"=",
"None",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand"... | Returns the direct descendants of a piece of Content, limited to a single descendant type.
The {@link ContentType}(s) of the descendants returned is specified by the "type" path parameter in the request.
Currently the only supported descendants are comment descendants of non-comment Content.
:... | [
"Returns",
"the",
"direct",
"descendants",
"of",
"a",
"piece",
"of",
"Content",
"limited",
"to",
"a",
"single",
"descendant",
"type",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L408-L437 | train | 61,754 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.get_content_properties | def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-ser... | python | def get_content_properties(self, content_id, expand=None, start=None, limit=None, callback=None):
"""
Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-ser... | [
"def",
"get_content_properties",
"(",
"self",
",",
"content_id",
",",
"expand",
"=",
"None",
",",
"start",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"expand",
":",
"params",
"[",
"\... | Returns a paginated list of content properties.
Content properties are a key / value store of properties attached to a piece of Content.
The key is a string, and the value is a JSON-serializable object.
:param content_id (string): A string containing the id of the property content container.
... | [
"Returns",
"a",
"paginated",
"list",
"of",
"content",
"properties",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L536-L561 | train | 61,755 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.create_new_attachment_by_content_id | def create_new_attachment_by_content_id(self, content_id, attachments, callback=None):
"""
Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
... | python | def create_new_attachment_by_content_id(self, content_id, attachments, callback=None):
"""
Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
... | [
"def",
"create_new_attachment_by_content_id",
"(",
"self",
",",
"content_id",
",",
"attachments",
",",
"callback",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"attachments",
",",
"list",
")",
":",
"assert",
"all",
"(",
"isinstance",
"(",
"at",
",",
"dict... | Add one or more attachments to a Confluence Content entity, with optional comments.
Comments are optional, but if included there must be as many comments as there are files, and the comments must
be in the same order as the files.
:param content_id (string): A string containing the id of the at... | [
"Add",
"one",
"or",
"more",
"attachments",
"to",
"a",
"Confluence",
"Content",
"entity",
"with",
"optional",
"comments",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L797-L821 | train | 61,756 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.create_new_space | def create_new_space(self, space_definition, callback=None):
"""
Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys ... | python | def create_new_space(self, space_definition, callback=None):
"""
Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys ... | [
"def",
"create_new_space",
"(",
"self",
",",
"space_definition",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"space_definition",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"name\"",
",",
"\"description\"",
"}",
"<=",
"set",
"(",... | Creates a new Space.
The incoming Space does not include an id, but must include a Key and Name, and should include a Description.
:param space_definition (dict): The dictionary describing the new space. Must include keys "key", "name",
and "description".
... | [
"Creates",
"a",
"new",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L892-L918 | train | 61,757 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_content_by_id | def update_content_by_id(self, content_data, content_id, callback=None):
"""
Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed ... | python | def update_content_by_id(self, content_data, content_id, callback=None):
"""
Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed ... | [
"def",
"update_content_by_id",
"(",
"self",
",",
"content_data",
",",
"content_id",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"content_data",
",",
"dict",
")",
"and",
"set",
"(",
"content_data",
".",
"keys",
"(",
")",
")",
">=",
... | Updates a piece of Content, or restores if it is trashed.
The body contains the representation of the content. Must include the new version number.
To restore a piece of content that has the status of trashed the content must have it's version incremented,
and status set to current. No other f... | [
"Updates",
"a",
"piece",
"of",
"Content",
"or",
"restores",
"if",
"it",
"is",
"trashed",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L948-L990 | train | 61,758 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_attachment_metadata | def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None):
"""
Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string co... | python | def update_attachment_metadata(self, content_id, attachment_id, new_metadata, callback=None):
"""
Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string co... | [
"def",
"update_attachment_metadata",
"(",
"self",
",",
"content_id",
",",
"attachment_id",
",",
"new_metadata",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"new_metadata",
",",
"dict",
")",
"and",
"set",
"(",
"new_metadata",
".",
"keys... | Update the non-binary data of an Attachment.
This resource can be used to update an attachment's filename, media-type, comment, and parent container.
:param content_id (string): A string containing the ID of the attachments content container.
:param attachment_id (string): The ID of the attachm... | [
"Update",
"the",
"non",
"-",
"binary",
"data",
"of",
"an",
"Attachment",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L992-L1020 | train | 61,759 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_attachment | def update_attachment(self, content_id, attachment_id, attachment, callback=None):
"""
Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
Wh... | python | def update_attachment(self, content_id, attachment_id, attachment, callback=None):
"""
Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
Wh... | [
"def",
"update_attachment",
"(",
"self",
",",
"content_id",
",",
"attachment_id",
",",
"attachment",
",",
"callback",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"attachment",
",",
"dict",
")",
":",
"assert",
"\"file\"",
"in",
"list",
"(",
"attachment",
... | Update the binary data of an Attachment, and optionally the comment and the minor edit field.
This adds a new version of the attachment, containing the new binary data, filename, and content-type.
When updating the binary data of an attachment, the comment related to it together with the field that
... | [
"Update",
"the",
"binary",
"data",
"of",
"an",
"Attachment",
"and",
"optionally",
"the",
"comment",
"and",
"the",
"minor",
"edit",
"field",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1022-L1049 | train | 61,760 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_property | def update_property(self, content_id, property_key, new_property_data, callback=None):
"""
Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the... | python | def update_property(self, content_id, property_key, new_property_data, callback=None):
"""
Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the... | [
"def",
"update_property",
"(",
"self",
",",
"content_id",
",",
"property_key",
",",
"new_property_data",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"new_property_data",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"value\"",
",",
... | Updates a content property.
The body contains the representation of the content property. Must include the property id, and the new version
number. Attempts to create a new content property if the given version number is 1, just like
{@link #create(com.atlassian.confluence.api.model.content.id.... | [
"Updates",
"a",
"content",
"property",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1051-L1083 | train | 61,761 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.update_space | def update_space(self, space_key, space_definition, callback=None):
"""
Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing t... | python | def update_space(self, space_key, space_definition, callback=None):
"""
Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing t... | [
"def",
"update_space",
"(",
"self",
",",
"space_key",
",",
"space_definition",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"space_definition",
",",
"dict",
")",
"and",
"{",
"\"key\"",
",",
"\"name\"",
",",
"\"description\"",
"}",
"<=... | Updates a Space.
Currently only the Space name, description and homepage can be updated.
:param space_key (string): The key of the space to update.
:param space_definition (dict): The dictionary describing the updated space metadata. This should include
"... | [
"Updates",
"a",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1085-L1113 | train | 61,762 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.convert_contentbody_to_new_type | def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None):
"""
Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destinatio... | python | def convert_contentbody_to_new_type(self, content_data, old_representation, new_representation, callback=None):
"""
Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destinatio... | [
"def",
"convert_contentbody_to_new_type",
"(",
"self",
",",
"content_data",
",",
"old_representation",
",",
"new_representation",
",",
"callback",
"=",
"None",
")",
":",
"assert",
"{",
"old_representation",
",",
"new_representation",
"}",
"<",
"{",
"\"storage\"",
",... | Converts between content body representations.
Not all representations can be converted to/from other formats. Supported conversions:
Source Representation | Destination Representation Supported
--------------------------------------------------------------
"storage" | ... | [
"Converts",
"between",
"content",
"body",
"representations",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1115-L1141 | train | 61,763 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.delete_label_by_id | def delete_label_by_id(self, content_id, label_name, callback=None):
"""
Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more ... | python | def delete_label_by_id(self, content_id, label_name, callback=None):
"""
Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more ... | [
"def",
"delete_label_by_id",
"(",
"self",
",",
"content_id",
",",
"label_name",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"\"name\"",
":",
"label_name",
"}",
"return",
"self",
".",
"_service_delete_request",
"(",
"\"rest/api/content/{id}/label\""... | Deletes a labels to the specified content.
There is an alternative form of this delete method that is not implemented. A DELETE request to
/rest/api/content/{id}/label/{label} will also delete a label, but is more limited in the label name
that can be accepted (and has no real apparent upside).... | [
"Deletes",
"a",
"labels",
"to",
"the",
"specified",
"content",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1160-L1178 | train | 61,764 |
rpcope1/PythonConfluenceAPI | PythonConfluenceAPI/api.py | ConfluenceAPI.delete_space | def delete_space(self, space_key, callback=None):
"""
Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:para... | python | def delete_space(self, space_key, callback=None):
"""
Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:para... | [
"def",
"delete_space",
"(",
"self",
",",
"space_key",
",",
"callback",
"=",
"None",
")",
":",
"return",
"self",
".",
"_service_delete_request",
"(",
"\"rest/api/space/{key}\"",
".",
"format",
"(",
"key",
"=",
"space_key",
")",
",",
"callback",
"=",
"callback",... | Deletes a Space.
The space is deleted in a long running task, so the space cannot be considered deleted when this method returns.
Clients can follow the status link in the response and poll it until the task completes.
:param space_key (string): The key of the space to delete.
:param c... | [
"Deletes",
"a",
"Space",
"."
] | b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40 | https://github.com/rpcope1/PythonConfluenceAPI/blob/b7f0ca2a390f964715fdf3a60b5b0c5ef7116d40/PythonConfluenceAPI/api.py#L1195-L1209 | train | 61,765 |
kellerza/pysma | pysma/__init__.py | Sensors.add | def add(self, sensor):
"""Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)):
for sss in sensor:
self.add(sss)
return
if not isinstance(sensor, Sensor):
raise TypeError("pysma.Sensor expected")
if sensor.name ... | python | def add(self, sensor):
"""Add a sensor, warning if it exists."""
if isinstance(sensor, (list, tuple)):
for sss in sensor:
self.add(sss)
return
if not isinstance(sensor, Sensor):
raise TypeError("pysma.Sensor expected")
if sensor.name ... | [
"def",
"add",
"(",
"self",
",",
"sensor",
")",
":",
"if",
"isinstance",
"(",
"sensor",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"for",
"sss",
"in",
"sensor",
":",
"self",
".",
"add",
"(",
"sss",
")",
"return",
"if",
"not",
"isinstance",
"("... | Add a sensor, warning if it exists. | [
"Add",
"a",
"sensor",
"warning",
"if",
"it",
"exists",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L149-L167 | train | 61,766 |
kellerza/pysma | pysma/__init__.py | SMA._fetch_json | def _fetch_json(self, url, payload):
"""Fetch json data for requests."""
params = {
'data': json.dumps(payload),
'headers': {'content-type': 'application/json'},
'params': {'sid': self.sma_sid} if self.sma_sid else None,
}
for _ in range(3):
... | python | def _fetch_json(self, url, payload):
"""Fetch json data for requests."""
params = {
'data': json.dumps(payload),
'headers': {'content-type': 'application/json'},
'params': {'sid': self.sma_sid} if self.sma_sid else None,
}
for _ in range(3):
... | [
"def",
"_fetch_json",
"(",
"self",
",",
"url",
",",
"payload",
")",
":",
"params",
"=",
"{",
"'data'",
":",
"json",
".",
"dumps",
"(",
"payload",
")",
",",
"'headers'",
":",
"{",
"'content-type'",
":",
"'application/json'",
"}",
",",
"'params'",
":",
"... | Fetch json data for requests. | [
"Fetch",
"json",
"data",
"for",
"requests",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L190-L206 | train | 61,767 |
kellerza/pysma | pysma/__init__.py | SMA.new_session | def new_session(self):
"""Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
self.sma_sid = jmespath.search('result.sid', body)
if self.sma_sid:
return True
msg = 'Could not start session, %s, got {}'.format(body)
... | python | def new_session(self):
"""Establish a new session."""
body = yield from self._fetch_json(URL_LOGIN, self._new_session_data)
self.sma_sid = jmespath.search('result.sid', body)
if self.sma_sid:
return True
msg = 'Could not start session, %s, got {}'.format(body)
... | [
"def",
"new_session",
"(",
"self",
")",
":",
"body",
"=",
"yield",
"from",
"self",
".",
"_fetch_json",
"(",
"URL_LOGIN",
",",
"self",
".",
"_new_session_data",
")",
"self",
".",
"sma_sid",
"=",
"jmespath",
".",
"search",
"(",
"'result.sid'",
",",
"body",
... | Establish a new session. | [
"Establish",
"a",
"new",
"session",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L209-L225 | train | 61,768 |
kellerza/pysma | pysma/__init__.py | SMA.read | def read(self, sensors):
"""Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
if self.sma_sid is None:
yield from self.new_session()
if self.sma_sid is None:
return False
body = yield from self._fetch_jso... | python | def read(self, sensors):
"""Read a set of keys."""
payload = {'destDev': [], 'keys': list(set([s.key for s in sensors]))}
if self.sma_sid is None:
yield from self.new_session()
if self.sma_sid is None:
return False
body = yield from self._fetch_jso... | [
"def",
"read",
"(",
"self",
",",
"sensors",
")",
":",
"payload",
"=",
"{",
"'destDev'",
":",
"[",
"]",
",",
"'keys'",
":",
"list",
"(",
"set",
"(",
"[",
"s",
".",
"key",
"for",
"s",
"in",
"sensors",
"]",
")",
")",
"}",
"if",
"self",
".",
"sma... | Read a set of keys. | [
"Read",
"a",
"set",
"of",
"keys",
"."
] | f7999f759963bcba5f4185922110a029b470bf23 | https://github.com/kellerza/pysma/blob/f7999f759963bcba5f4185922110a029b470bf23/pysma/__init__.py#L236-L257 | train | 61,769 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.media | def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
self._tags = metadata.tags
title = self._tags.get(TAG_TITLE, [])
... | python | def media(self, uri):
"""Play a media file."""
try:
local_path, _ = urllib.request.urlretrieve(uri)
metadata = mutagen.File(local_path, easy=True)
if metadata.tags:
self._tags = metadata.tags
title = self._tags.get(TAG_TITLE, [])
... | [
"def",
"media",
"(",
"self",
",",
"uri",
")",
":",
"try",
":",
"local_path",
",",
"_",
"=",
"urllib",
".",
"request",
".",
"urlretrieve",
"(",
"uri",
")",
"metadata",
"=",
"mutagen",
".",
"File",
"(",
"local_path",
",",
"easy",
"=",
"True",
")",
"i... | Play a media file. | [
"Play",
"a",
"media",
"file",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L99-L124 | train | 61,770 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.play | def play(self):
"""Change state to playing."""
if self.state == STATE_PAUSED:
self._player.set_state(Gst.State.PLAYING)
self.state = STATE_PLAYING | python | def play(self):
"""Change state to playing."""
if self.state == STATE_PAUSED:
self._player.set_state(Gst.State.PLAYING)
self.state = STATE_PLAYING | [
"def",
"play",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_PAUSED",
":",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PLAYING",
")",
"self",
".",
"state",
"=",
"STATE_PLAYING"
] | Change state to playing. | [
"Change",
"state",
"to",
"playing",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L126-L130 | train | 61,771 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.pause | def pause(self):
"""Change state to paused."""
if self.state == STATE_PLAYING:
self._player.set_state(Gst.State.PAUSED)
self.state = STATE_PAUSED | python | def pause(self):
"""Change state to paused."""
if self.state == STATE_PLAYING:
self._player.set_state(Gst.State.PAUSED)
self.state = STATE_PAUSED | [
"def",
"pause",
"(",
"self",
")",
":",
"if",
"self",
".",
"state",
"==",
"STATE_PLAYING",
":",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"PAUSED",
")",
"self",
".",
"state",
"=",
"STATE_PAUSED"
] | Change state to paused. | [
"Change",
"state",
"to",
"paused",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L132-L136 | train | 61,772 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.stop | def stop(self):
"""Stop pipeline."""
urllib.request.urlcleanup()
self._player.set_state(Gst.State.NULL)
self.state = STATE_IDLE
self._tags = {} | python | def stop(self):
"""Stop pipeline."""
urllib.request.urlcleanup()
self._player.set_state(Gst.State.NULL)
self.state = STATE_IDLE
self._tags = {} | [
"def",
"stop",
"(",
"self",
")",
":",
"urllib",
".",
"request",
".",
"urlcleanup",
"(",
")",
"self",
".",
"_player",
".",
"set_state",
"(",
"Gst",
".",
"State",
".",
"NULL",
")",
"self",
".",
"state",
"=",
"STATE_IDLE",
"self",
".",
"_tags",
"=",
"... | Stop pipeline. | [
"Stop",
"pipeline",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L138-L143 | train | 61,773 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.set_position | def set_position(self, position):
"""Set media position."""
if position > self._duration():
return
position_ns = position * _NANOSEC_MULT
self._manager[ATTR_POSITION] = position
self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns) | python | def set_position(self, position):
"""Set media position."""
if position > self._duration():
return
position_ns = position * _NANOSEC_MULT
self._manager[ATTR_POSITION] = position
self._player.seek_simple(_FORMAT_TIME, Gst.SeekFlags.FLUSH, position_ns) | [
"def",
"set_position",
"(",
"self",
",",
"position",
")",
":",
"if",
"position",
">",
"self",
".",
"_duration",
"(",
")",
":",
"return",
"position_ns",
"=",
"position",
"*",
"_NANOSEC_MULT",
"self",
".",
"_manager",
"[",
"ATTR_POSITION",
"]",
"=",
"positio... | Set media position. | [
"Set",
"media",
"position",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L145-L151 | train | 61,774 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess.state | def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | python | def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | [
"def",
"state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_manager",
"[",
"ATTR_STATE",
"]",
"=",
"state",
"_LOGGER",
".",
"info",
"(",
"'state changed to %s'",
",",
"state",
")"
] | Set state. | [
"Set",
"state",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L165-L169 | train | 61,775 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._duration | def _duration(self):
"""Get media duration."""
duration = 0
if self.state != STATE_IDLE:
resp = self._player.query_duration(_FORMAT_TIME)
duration = resp[1] // _NANOSEC_MULT
return duration | python | def _duration(self):
"""Get media duration."""
duration = 0
if self.state != STATE_IDLE:
resp = self._player.query_duration(_FORMAT_TIME)
duration = resp[1] // _NANOSEC_MULT
return duration | [
"def",
"_duration",
"(",
"self",
")",
":",
"duration",
"=",
"0",
"if",
"self",
".",
"state",
"!=",
"STATE_IDLE",
":",
"resp",
"=",
"self",
".",
"_player",
".",
"query_duration",
"(",
"_FORMAT_TIME",
")",
"duration",
"=",
"resp",
"[",
"1",
"]",
"//",
... | Get media duration. | [
"Get",
"media",
"duration",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L171-L177 | train | 61,776 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._position | def _position(self):
"""Get media position."""
position = 0
if self.state != STATE_IDLE:
resp = self._player.query_position(_FORMAT_TIME)
position = resp[1] // _NANOSEC_MULT
return position | python | def _position(self):
"""Get media position."""
position = 0
if self.state != STATE_IDLE:
resp = self._player.query_position(_FORMAT_TIME)
position = resp[1] // _NANOSEC_MULT
return position | [
"def",
"_position",
"(",
"self",
")",
":",
"position",
"=",
"0",
"if",
"self",
".",
"state",
"!=",
"STATE_IDLE",
":",
"resp",
"=",
"self",
".",
"_player",
".",
"query_position",
"(",
"_FORMAT_TIME",
")",
"position",
"=",
"resp",
"[",
"1",
"]",
"//",
... | Get media position. | [
"Get",
"media",
"position",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L179-L185 | train | 61,777 |
happyleavesaoc/gstreamer-player | gsp/__init__.py | GstreamerProcess._on_message | def _on_message(self, bus, message): # pylint: disable=unused-argument
"""When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS:
self.stop()
elif message.type == Gst.MessageType.ERROR:
self.stop()
err, _ = message.parse_error()
... | python | def _on_message(self, bus, message): # pylint: disable=unused-argument
"""When a message is received from Gstreamer."""
if message.type == Gst.MessageType.EOS:
self.stop()
elif message.type == Gst.MessageType.ERROR:
self.stop()
err, _ = message.parse_error()
... | [
"def",
"_on_message",
"(",
"self",
",",
"bus",
",",
"message",
")",
":",
"# pylint: disable=unused-argument",
"if",
"message",
".",
"type",
"==",
"Gst",
".",
"MessageType",
".",
"EOS",
":",
"self",
".",
"stop",
"(",
")",
"elif",
"message",
".",
"type",
"... | When a message is received from Gstreamer. | [
"When",
"a",
"message",
"is",
"received",
"from",
"Gstreamer",
"."
] | 750edd95d4be4d2f8eee3aa3cb86d4781758f5fb | https://github.com/happyleavesaoc/gstreamer-player/blob/750edd95d4be4d2f8eee3aa3cb86d4781758f5fb/gsp/__init__.py#L187-L194 | train | 61,778 |
spulec/pep8ify | pep8ify/fixes/fix_whitespace_before_inline_comment.py | get_previous_node | def get_previous_node(node):
"""
Return the node before this node.
"""
if node.prev_sibling:
return node.prev_sibling
if node.parent:
return get_previous_node(node.parent) | python | def get_previous_node(node):
"""
Return the node before this node.
"""
if node.prev_sibling:
return node.prev_sibling
if node.parent:
return get_previous_node(node.parent) | [
"def",
"get_previous_node",
"(",
"node",
")",
":",
"if",
"node",
".",
"prev_sibling",
":",
"return",
"node",
".",
"prev_sibling",
"if",
"node",
".",
"parent",
":",
"return",
"get_previous_node",
"(",
"node",
".",
"parent",
")"
] | Return the node before this node. | [
"Return",
"the",
"node",
"before",
"this",
"node",
"."
] | cf1815f7bad9882027289bdb2f77604b68962ca7 | https://github.com/spulec/pep8ify/blob/cf1815f7bad9882027289bdb2f77604b68962ca7/pep8ify/fixes/fix_whitespace_before_inline_comment.py#L6-L13 | train | 61,779 |
makinacorpus/django-screamshot | screamshot/utils.py | casperjs_command_kwargs | def casperjs_command_kwargs():
""" will construct kwargs for cmd
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'universal_newlines': True
}
phantom_js_cmd = app_settings['PHANTOMJS_CMD']
if phantom_js_cmd:
path = '{0}:{1}'.format(
... | python | def casperjs_command_kwargs():
""" will construct kwargs for cmd
"""
kwargs = {
'stdout': subprocess.PIPE,
'stderr': subprocess.PIPE,
'universal_newlines': True
}
phantom_js_cmd = app_settings['PHANTOMJS_CMD']
if phantom_js_cmd:
path = '{0}:{1}'.format(
... | [
"def",
"casperjs_command_kwargs",
"(",
")",
":",
"kwargs",
"=",
"{",
"'stdout'",
":",
"subprocess",
".",
"PIPE",
",",
"'stderr'",
":",
"subprocess",
".",
"PIPE",
",",
"'universal_newlines'",
":",
"True",
"}",
"phantom_js_cmd",
"=",
"app_settings",
"[",
"'PHANT... | will construct kwargs for cmd | [
"will",
"construct",
"kwargs",
"for",
"cmd"
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L40-L54 | train | 61,780 |
makinacorpus/django-screamshot | screamshot/utils.py | casperjs_capture | def casperjs_capture(stream, url, method=None, width=None, height=None,
selector=None, data=None, waitfor=None, size=None,
crop=None, render='png', wait=None):
"""
Captures web pages using ``casperjs``
"""
if isinstance(stream, six.string_types):
output ... | python | def casperjs_capture(stream, url, method=None, width=None, height=None,
selector=None, data=None, waitfor=None, size=None,
crop=None, render='png', wait=None):
"""
Captures web pages using ``casperjs``
"""
if isinstance(stream, six.string_types):
output ... | [
"def",
"casperjs_capture",
"(",
"stream",
",",
"url",
",",
"method",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"selector",
"=",
"None",
",",
"data",
"=",
"None",
",",
"waitfor",
"=",
"None",
",",
"size",
"=",
"None",
... | Captures web pages using ``casperjs`` | [
"Captures",
"web",
"pages",
"using",
"casperjs"
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L108-L158 | train | 61,781 |
makinacorpus/django-screamshot | screamshot/utils.py | process_casperjs_stdout | def process_casperjs_stdout(stdout):
"""Parse and digest capture script output.
"""
for line in stdout.splitlines():
bits = line.split(':', 1)
if len(bits) < 2:
bits = ('INFO', bits)
level, msg = bits
if level == 'FATAL':
logger.fatal(msg)
... | python | def process_casperjs_stdout(stdout):
"""Parse and digest capture script output.
"""
for line in stdout.splitlines():
bits = line.split(':', 1)
if len(bits) < 2:
bits = ('INFO', bits)
level, msg = bits
if level == 'FATAL':
logger.fatal(msg)
... | [
"def",
"process_casperjs_stdout",
"(",
"stdout",
")",
":",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
":",
"bits",
"=",
"line",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"bits",
"=",
"... | Parse and digest capture script output. | [
"Parse",
"and",
"digest",
"capture",
"script",
"output",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L161-L176 | train | 61,782 |
makinacorpus/django-screamshot | screamshot/utils.py | parse_url | def parse_url(request, url):
"""Parse url URL parameter."""
try:
validate = URLValidator()
validate(url)
except ValidationError:
if url.startswith('/'):
host = request.get_host()
scheme = 'https' if request.is_secure() else 'http'
url = '{scheme}:/... | python | def parse_url(request, url):
"""Parse url URL parameter."""
try:
validate = URLValidator()
validate(url)
except ValidationError:
if url.startswith('/'):
host = request.get_host()
scheme = 'https' if request.is_secure() else 'http'
url = '{scheme}:/... | [
"def",
"parse_url",
"(",
"request",
",",
"url",
")",
":",
"try",
":",
"validate",
"=",
"URLValidator",
"(",
")",
"validate",
"(",
"url",
")",
"except",
"ValidationError",
":",
"if",
"url",
".",
"startswith",
"(",
"'/'",
")",
":",
"host",
"=",
"request"... | Parse url URL parameter. | [
"Parse",
"url",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L198-L212 | train | 61,783 |
makinacorpus/django-screamshot | screamshot/utils.py | parse_render | def parse_render(render):
"""Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif'
"""
formats = {
'jpeg': guess_all_extensions('image... | python | def parse_render(render):
"""Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif'
"""
formats = {
'jpeg': guess_all_extensions('image... | [
"def",
"parse_render",
"(",
"render",
")",
":",
"formats",
"=",
"{",
"'jpeg'",
":",
"guess_all_extensions",
"(",
"'image/jpeg'",
")",
",",
"'png'",
":",
"guess_all_extensions",
"(",
"'image/png'",
")",
",",
"'gif'",
":",
"guess_all_extensions",
"(",
"'image/gif'... | Parse render URL parameter.
>>> parse_render(None)
'png'
>>> parse_render('html')
'png'
>>> parse_render('png')
'png'
>>> parse_render('jpg')
'jpeg'
>>> parse_render('gif')
'gif' | [
"Parse",
"render",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L215-L248 | train | 61,784 |
makinacorpus/django-screamshot | screamshot/utils.py | parse_size | def parse_size(size_raw):
""" Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None
"""
try:
width_str, height_str = size_raw.lower().spl... | python | def parse_size(size_raw):
""" Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None
"""
try:
width_str, height_str = size_raw.lower().spl... | [
"def",
"parse_size",
"(",
"size_raw",
")",
":",
"try",
":",
"width_str",
",",
"height_str",
"=",
"size_raw",
".",
"lower",
"(",
")",
".",
"split",
"(",
"'x'",
")",
"except",
"AttributeError",
":",
"size",
"=",
"None",
"except",
"ValueError",
":",
"size",... | Parse size URL parameter.
>>> parse_size((100,None))
None
>>> parse_size('300x100')
(300, 100)
>>> parse_size('300x')
None
>>> parse_size('x100')
None
>>> parse_size('x')
None | [
"Parse",
"size",
"URL",
"parameter",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L251-L285 | train | 61,785 |
makinacorpus/django-screamshot | screamshot/utils.py | build_absolute_uri | def build_absolute_uri(request, url):
"""
Allow to override printing url, not necessarily on the same
server instance.
"""
if app_settings.get('CAPTURE_ROOT_URL'):
return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url)
return request.build_absolute_uri(url) | python | def build_absolute_uri(request, url):
"""
Allow to override printing url, not necessarily on the same
server instance.
"""
if app_settings.get('CAPTURE_ROOT_URL'):
return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url)
return request.build_absolute_uri(url) | [
"def",
"build_absolute_uri",
"(",
"request",
",",
"url",
")",
":",
"if",
"app_settings",
".",
"get",
"(",
"'CAPTURE_ROOT_URL'",
")",
":",
"return",
"urljoin",
"(",
"app_settings",
".",
"get",
"(",
"'CAPTURE_ROOT_URL'",
")",
",",
"url",
")",
"return",
"reques... | Allow to override printing url, not necessarily on the same
server instance. | [
"Allow",
"to",
"override",
"printing",
"url",
"not",
"necessarily",
"on",
"the",
"same",
"server",
"instance",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L333-L340 | train | 61,786 |
makinacorpus/django-screamshot | screamshot/utils.py | render_template | def render_template(template_name, context, format='png',
output=None, using=None, **options):
"""
Render a template from django project, and return the
file object of the result.
"""
# output stream, as required by casperjs_capture
stream = BytesIO()
out_f = None
# t... | python | def render_template(template_name, context, format='png',
output=None, using=None, **options):
"""
Render a template from django project, and return the
file object of the result.
"""
# output stream, as required by casperjs_capture
stream = BytesIO()
out_f = None
# t... | [
"def",
"render_template",
"(",
"template_name",
",",
"context",
",",
"format",
"=",
"'png'",
",",
"output",
"=",
"None",
",",
"using",
"=",
"None",
",",
"*",
"*",
"options",
")",
":",
"# output stream, as required by casperjs_capture",
"stream",
"=",
"BytesIO",
... | Render a template from django project, and return the
file object of the result. | [
"Render",
"a",
"template",
"from",
"django",
"project",
"and",
"return",
"the",
"file",
"object",
"of",
"the",
"result",
"."
] | 28488599292f41c553aee7d63259e1f856f43b16 | https://github.com/makinacorpus/django-screamshot/blob/28488599292f41c553aee7d63259e1f856f43b16/screamshot/utils.py#L343-L399 | train | 61,787 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | go | def go(fn, *args, **kwargs):
"""Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from ba... | python | def go(fn, *args, **kwargs):
"""Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from ba... | [
"def",
"go",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"callable",
"(",
"fn",
")",
":",
"raise",
"TypeError",
"(",
"'go() requires a function, not %r'",
"%",
"(",
"fn",
",",
")",
")",
"result",
"=",
"[",
"None",
"... | Launch an operation on a thread and get a handle to its future result.
>>> from time import sleep
>>> def print_sleep_print(duration):
... sleep(duration)
... print('hello from background thread')
... sleep(duration)
... print('goodbye from background thread')
... return... | [
"Launch",
"an",
"operation",
"on",
"a",
"thread",
"and",
"get",
"a",
"handle",
"to",
"its",
"future",
"result",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L107-L153 | train | 61,788 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | going | def going(fn, *args, **kwargs):
"""Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "do... | python | def going(fn, *args, **kwargs):
"""Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "do... | [
"def",
"going",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"future",
"=",
"go",
"(",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"yield",
"future",
"except",
":",
"# We are raising an exception, just try to cl... | Launch a thread and wait for its result before exiting the code block.
>>> with going(lambda: 'return value') as future:
... pass
>>> future() # Won't block, the future is ready by now.
'return value'
Or discard the result:
>>> with going(lambda: "don't care"):
... pass
If an... | [
"Launch",
"a",
"thread",
"and",
"wait",
"for",
"its",
"result",
"before",
"exiting",
"the",
"code",
"block",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L157-L197 | train | 61,789 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | _get_c_string | def _get_c_string(data, position):
"""Decode a BSON 'C' string to python unicode string."""
end = data.index(b"\x00", position)
return _utf_8_decode(data[position:end], None, True)[0], end + 1 | python | def _get_c_string(data, position):
"""Decode a BSON 'C' string to python unicode string."""
end = data.index(b"\x00", position)
return _utf_8_decode(data[position:end], None, True)[0], end + 1 | [
"def",
"_get_c_string",
"(",
"data",
",",
"position",
")",
":",
"end",
"=",
"data",
".",
"index",
"(",
"b\"\\x00\"",
",",
"position",
")",
"return",
"_utf_8_decode",
"(",
"data",
"[",
"position",
":",
"end",
"]",
",",
"None",
",",
"True",
")",
"[",
"... | Decode a BSON 'C' string to python unicode string. | [
"Decode",
"a",
"BSON",
"C",
"string",
"to",
"python",
"unicode",
"string",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L286-L289 | train | 61,790 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | _synchronized | def _synchronized(meth):
"""Call method while holding a lock."""
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
with self._lock:
return meth(self, *args, **kwargs)
return wrapper | python | def _synchronized(meth):
"""Call method while holding a lock."""
@functools.wraps(meth)
def wrapper(self, *args, **kwargs):
with self._lock:
return meth(self, *args, **kwargs)
return wrapper | [
"def",
"_synchronized",
"(",
"meth",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"meth",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"_lock",
":",
"return",
"meth",
"(",
"self",
... | Call method while holding a lock. | [
"Call",
"method",
"while",
"holding",
"a",
"lock",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1120-L1128 | train | 61,791 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | mock_server_receive_request | def mock_server_receive_request(client, server):
"""Take a client socket and return a Request."""
header = mock_server_receive(client, 16)
length = _UNPACK_INT(header[:4])[0]
request_id = _UNPACK_INT(header[4:8])[0]
opcode = _UNPACK_INT(header[12:])[0]
msg_bytes = mock_server_receive(client, len... | python | def mock_server_receive_request(client, server):
"""Take a client socket and return a Request."""
header = mock_server_receive(client, 16)
length = _UNPACK_INT(header[:4])[0]
request_id = _UNPACK_INT(header[4:8])[0]
opcode = _UNPACK_INT(header[12:])[0]
msg_bytes = mock_server_receive(client, len... | [
"def",
"mock_server_receive_request",
"(",
"client",
",",
"server",
")",
":",
"header",
"=",
"mock_server_receive",
"(",
"client",
",",
"16",
")",
"length",
"=",
"_UNPACK_INT",
"(",
"header",
"[",
":",
"4",
"]",
")",
"[",
"0",
"]",
"request_id",
"=",
"_U... | Take a client socket and return a Request. | [
"Take",
"a",
"client",
"socket",
"and",
"return",
"a",
"Request",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1771-L1781 | train | 61,792 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | mock_server_receive | def mock_server_receive(sock, length):
"""Receive `length` bytes from a socket object."""
msg = b''
while length:
chunk = sock.recv(length)
if chunk == b'':
raise socket.error(errno.ECONNRESET, 'closed')
length -= len(chunk)
msg += chunk
return msg | python | def mock_server_receive(sock, length):
"""Receive `length` bytes from a socket object."""
msg = b''
while length:
chunk = sock.recv(length)
if chunk == b'':
raise socket.error(errno.ECONNRESET, 'closed')
length -= len(chunk)
msg += chunk
return msg | [
"def",
"mock_server_receive",
"(",
"sock",
",",
"length",
")",
":",
"msg",
"=",
"b''",
"while",
"length",
":",
"chunk",
"=",
"sock",
".",
"recv",
"(",
"length",
")",
"if",
"chunk",
"==",
"b''",
":",
"raise",
"socket",
".",
"error",
"(",
"errno",
".",... | Receive `length` bytes from a socket object. | [
"Receive",
"length",
"bytes",
"from",
"a",
"socket",
"object",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1793-L1804 | train | 61,793 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | make_docs | def make_docs(*args, **kwargs):
"""Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial.
... | python | def make_docs(*args, **kwargs):
"""Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial.
... | [
"def",
"make_docs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"err_msg",
"=",
"\"Can't interpret args: \"",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"return",
"[",
"]",
"if",
"not",
"args",
":",
"# OpReply(ok=1, ismaster=True).",
"return"... | Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial. | [
"Make",
"the",
"documents",
"for",
"a",
"Request",
"or",
"Reply",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1807-L1861 | train | 61,794 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | make_prototype_request | def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | python | def make_prototype_request(*args, **kwargs):
"""Make a prototype Request for a Matcher."""
if args and inspect.isclass(args[0]) and issubclass(args[0], Request):
request_cls, arg_list = args[0], args[1:]
return request_cls(*arg_list, **kwargs)
if args and isinstance(args[0], Request):
... | [
"def",
"make_prototype_request",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"args",
"and",
"inspect",
".",
"isclass",
"(",
"args",
"[",
"0",
"]",
")",
"and",
"issubclass",
"(",
"args",
"[",
"0",
"]",
",",
"Request",
")",
":",
"reque... | Make a prototype Request for a Matcher. | [
"Make",
"a",
"prototype",
"Request",
"for",
"a",
"Matcher",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1884-L1895 | train | 61,795 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | docs_repr | def docs_repr(*args):
"""Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)]... | python | def docs_repr(*args):
"""Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)]... | [
"def",
"docs_repr",
"(",
"*",
"args",
")",
":",
"sio",
"=",
"StringIO",
"(",
")",
"for",
"doc_idx",
",",
"doc",
"in",
"enumerate",
"(",
"args",
")",
":",
"if",
"doc_idx",
">",
"0",
":",
"sio",
".",
"write",
"(",
"u', '",
")",
"sio",
".",
"write",... | Stringify ordered dicts like a regular ones.
Preserve order, remove 'u'-prefix on unicodes in Python 2:
>>> print(docs_repr(OrderedDict([(u'_id', 2)])))
{"_id": 2}
>>> print(docs_repr(OrderedDict([(u'_id', 2), (u'a', u'b')]),
... OrderedDict([(u'a', 1)])))
{"_id": 2, "a": "b"},... | [
"Stringify",
"ordered",
"dicts",
"like",
"a",
"regular",
"ones",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1926-L1951 | train | 61,796 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | seq_match | def seq_match(seq0, seq1):
"""True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match(... | python | def seq_match(seq0, seq1):
"""True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match(... | [
"def",
"seq_match",
"(",
"seq0",
",",
"seq1",
")",
":",
"len_seq1",
"=",
"len",
"(",
"seq1",
")",
"if",
"len_seq1",
"<",
"len",
"(",
"seq0",
")",
":",
"return",
"False",
"seq1_idx",
"=",
"0",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"seq0",... | True if seq0 is a subset of seq1 and their elements are in same order.
>>> seq_match([], [])
True
>>> seq_match([1], [1])
True
>>> seq_match([1, 1], [1])
False
>>> seq_match([1], [1, 2])
True
>>> seq_match([1, 1], [1, 1])
True
>>> seq_match([3], [1, 2, 3])
True
>>> s... | [
"True",
"if",
"seq0",
"is",
"a",
"subset",
"of",
"seq1",
"and",
"their",
"elements",
"are",
"in",
"same",
"order",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L1954-L1987 | train | 61,797 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | raise_args_err | def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... | python | def raise_args_err(message='bad arguments', error_class=TypeError):
"""Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, ... | [
"def",
"raise_args_err",
"(",
"message",
"=",
"'bad arguments'",
",",
"error_class",
"=",
"TypeError",
")",
":",
"frame",
"=",
"inspect",
".",
"currentframe",
"(",
")",
".",
"f_back",
"raise",
"error_class",
"(",
"message",
"+",
"': '",
"+",
"format_call",
"... | Throw an error with standard message, displaying function call.
>>> def f(a, *args, **kwargs):
... raise_args_err()
...
>>> f(1, 2, x='y')
Traceback (most recent call last):
...
TypeError: bad arguments: f(1, 2, x='y') | [
"Throw",
"an",
"error",
"with",
"standard",
"message",
"displaying",
"function",
"call",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L2000-L2012 | train | 61,798 |
ajdavis/mongo-mockup-db | mockupdb/__init__.py | interactive_server | def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB',
ssl=False, uds_path=None):
"""A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {o... | python | def interactive_server(port=27017, verbose=True, all_ok=False, name='MockupDB',
ssl=False, uds_path=None):
"""A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {o... | [
"def",
"interactive_server",
"(",
"port",
"=",
"27017",
",",
"verbose",
"=",
"True",
",",
"all_ok",
"=",
"False",
",",
"name",
"=",
"'MockupDB'",
",",
"ssl",
"=",
"False",
",",
"uds_path",
"=",
"None",
")",
":",
"if",
"uds_path",
"is",
"not",
"None",
... | A `MockupDB` that the mongo shell can connect to.
Call `~.MockupDB.run` on the returned server, and clean it up with
`~.MockupDB.stop`.
If ``all_ok`` is True, replies {ok: 1} to anything unmatched by a specific
responder. | [
"A",
"MockupDB",
"that",
"the",
"mongo",
"shell",
"can",
"connect",
"to",
"."
] | ff8a3f793def59e9037397ef60607fbda6949dac | https://github.com/ajdavis/mongo-mockup-db/blob/ff8a3f793def59e9037397ef60607fbda6949dac/mockupdb/__init__.py#L2015-L2043 | train | 61,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.