repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
ellmetha/django-machina
machina/apps/forum/abstract_models.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L175-L195
def update_trackers(self): """ Updates the denormalized trackers associated with the forum instance. """ direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on') # Compute the direct topics count and the direct posts count. self.direct_topics_count = direct_a...
[ "def", "update_trackers", "(", "self", ")", ":", "direct_approved_topics", "=", "self", ".", "topics", ".", "filter", "(", "approved", "=", "True", ")", ".", "order_by", "(", "'-last_post_on'", ")", "# Compute the direct topics count and the direct posts count.", "sel...
Updates the denormalized trackers associated with the forum instance.
[ "Updates", "the", "denormalized", "trackers", "associated", "with", "the", "forum", "instance", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L13604-L13632
def surfpt(positn, u, a, b, c): """ Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of floats ...
[ "def", "surfpt", "(", "positn", ",", "u", ",", "a", ",", "b", ",", "c", ")", ":", "a", "=", "ctypes", ".", "c_double", "(", "a", ")", "b", "=", "ctypes", ".", "c_double", "(", "b", ")", "c", "=", "ctypes", ".", "c_double", "(", "c", ")", "p...
Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of floats :param u: Vector from the observer in so...
[ "Determine", "the", "intersection", "of", "a", "line", "-", "of", "-", "sight", "vector", "with", "the", "surface", "of", "an", "ellipsoid", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/build/build.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L311-L320
def validate_target(self, target): """Make sure that the specified target only contains architectures that we know about.""" archs = target.split('/') for arch in archs: if not arch in self.archs: return False return True
[ "def", "validate_target", "(", "self", ",", "target", ")", ":", "archs", "=", "target", ".", "split", "(", "'/'", ")", "for", "arch", "in", "archs", ":", "if", "not", "arch", "in", "self", ".", "archs", ":", "return", "False", "return", "True" ]
Make sure that the specified target only contains architectures that we know about.
[ "Make", "sure", "that", "the", "specified", "target", "only", "contains", "architectures", "that", "we", "know", "about", "." ]
python
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L284-L310
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config,...
[ "def", "replace_vars", "(", "config", ",", "env", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ...
Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env.
[ "Replace", "variable", "references", "in", "config", "using", "the", "supplied", "env", "dictionary", "." ]
python
train
openego/eDisGo
edisgo/grid/tools.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/tools.py#L362-L452
def get_gen_info(network, level='mvlv', fluctuating=False): """ Gets all the installed generators with some additional information. Parameters ---------- network : :class:`~.grid.network.Network` Network object holding the grid data. level : :obj:`str` Defines which generators a...
[ "def", "get_gen_info", "(", "network", ",", "level", "=", "'mvlv'", ",", "fluctuating", "=", "False", ")", ":", "gens_w_id", "=", "[", "]", "if", "'mv'", "in", "level", ":", "gens", "=", "network", ".", "mv_grid", ".", "generators", "gens_voltage_level", ...
Gets all the installed generators with some additional information. Parameters ---------- network : :class:`~.grid.network.Network` Network object holding the grid data. level : :obj:`str` Defines which generators are returned. Possible options are: * 'mv' Only genera...
[ "Gets", "all", "the", "installed", "generators", "with", "some", "additional", "information", "." ]
python
train
cloud9ers/pylxc
lxc/__init__.py
https://github.com/cloud9ers/pylxc/blob/588961dd37ce6e14fd7c1cc76d1970e48fccba34/lxc/__init__.py#L265-L272
def freeze(name): ''' freezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-freeze', '-n', name] subprocess.check_call(cmd)
[ "def", "freeze", "(", "name", ")", ":", "if", "not", "exists", "(", "name", ")", ":", "raise", "ContainerNotExists", "(", "\"The container (%s) does not exist!\"", "%", "name", ")", "cmd", "=", "[", "'lxc-freeze'", ",", "'-n'", ",", "name", "]", "subprocess"...
freezes the container
[ "freezes", "the", "container" ]
python
train
common-workflow-language/cwltool
cwltool/utils.py
https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/utils.py#L112-L127
def docker_windows_reverse_fileuri_adjust(fileuri): # type: (Text) -> (Text) r""" On docker in windows fileuri do not contain : in path To convert this file uri to windows compatible add : after drive letter, so file:///E/var becomes file:///E:/var """ if fileuri is not None and onWindows():...
[ "def", "docker_windows_reverse_fileuri_adjust", "(", "fileuri", ")", ":", "# type: (Text) -> (Text)", "if", "fileuri", "is", "not", "None", "and", "onWindows", "(", ")", ":", "if", "urllib", ".", "parse", ".", "urlsplit", "(", "fileuri", ")", ".", "scheme", "=...
r""" On docker in windows fileuri do not contain : in path To convert this file uri to windows compatible add : after drive letter, so file:///E/var becomes file:///E:/var
[ "r", "On", "docker", "in", "windows", "fileuri", "do", "not", "contain", ":", "in", "path", "To", "convert", "this", "file", "uri", "to", "windows", "compatible", "add", ":", "after", "drive", "letter", "so", "file", ":", "///", "E", "/", "var", "becom...
python
train
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1825-L1877
def from_trajectory(self, traj, frame=-1, coords_only=False): """Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- traj : mdtraj.Trajectory ...
[ "def", "from_trajectory", "(", "self", ",", "traj", ",", "frame", "=", "-", "1", ",", "coords_only", "=", "False", ")", ":", "if", "coords_only", ":", "if", "traj", ".", "n_atoms", "!=", "self", ".", "n_particles", ":", "raise", "ValueError", "(", "'Nu...
Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- traj : mdtraj.Trajectory The trajectory to load. frame : int, optional, default=-...
[ "Extract", "atoms", "and", "bonds", "from", "a", "md", ".", "Trajectory", "." ]
python
train
dcos/shakedown
shakedown/dcos/package.py
https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L46-L144
def install_package( package_name, package_version=None, service_name=None, options_file=None, options_json=None, wait_for_completion=False, timeout_sec=600, expected_running_tasks=0 ): """ Install a package via the DC/OS library :param packag...
[ "def", "install_package", "(", "package_name", ",", "package_version", "=", "None", ",", "service_name", "=", "None", ",", "options_file", "=", "None", ",", "options_json", "=", "None", ",", "wait_for_completion", "=", "False", ",", "timeout_sec", "=", "600", ...
Install a package via the DC/OS library :param package_name: name of the package :type package_name: str :param package_version: version of the package (defaults to latest) :type package_version: str :param service_name: unique service name for the package :type service_...
[ "Install", "a", "package", "via", "the", "DC", "/", "OS", "library" ]
python
train
google/prettytensor
prettytensor/pretty_tensor_class.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_class.py#L303-L325
def join_pretty_tensors(tensors, output, join_function=None, name='join'): """Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A functio...
[ "def", "join_pretty_tensors", "(", "tensors", ",", "output", ",", "join_function", "=", "None", ",", "name", "=", "'join'", ")", ":", "if", "not", "tensors", ":", "raise", "ValueError", "(", "'pretty_tensors must be a non-empty sequence.'", ")", "with", "output", ...
Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A function to join the tensors, defaults to concat on the last dimension. name:...
[ "Joins", "the", "list", "of", "pretty_tensors", "and", "sets", "head", "of", "output_pretty_tensor", "." ]
python
train
proycon/clam
clam/common/data.py
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1889-L1963
def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None): """Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples""" project = os.path.basename(projectpath) if self.parent: #pylint: disable=too-many-nested-blocks #We have a parent, inf...
[ "def", "generate", "(", "self", ",", "profile", ",", "parameters", ",", "projectpath", ",", "inputfiles", ",", "provenancedata", "=", "None", ")", ":", "project", "=", "os", ".", "path", ".", "basename", "(", "projectpath", ")", "if", "self", ".", "paren...
Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples
[ "Yields", "(", "inputtemplate", "inputfilename", "outputfilename", "metadata", ")", "tuples" ]
python
train
SeleniumHQ/selenium
py/selenium/webdriver/common/action_chains.py
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L112-L128
def click_and_hold(self, on_element=None): """ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) i...
[ "def", "click_and_hold", "(", "self", ",", "on_element", "=", "None", ")", ":", "if", "on_element", ":", "self", ".", "move_to_element", "(", "on_element", ")", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "pointer_action...
Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position.
[ "Holds", "down", "the", "left", "mouse", "button", "on", "an", "element", "." ]
python
train
codeinthehole/purl
purl/url.py
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L100-L129
def parse(url_str): """ Extract all parts from a URL string and return them as a dictionary """ url_str = to_unicode(url_str) result = urlparse(url_str) netloc_parts = result.netloc.rsplit('@', 1) if len(netloc_parts) == 1: username = password = None host = netloc_parts[0] ...
[ "def", "parse", "(", "url_str", ")", ":", "url_str", "=", "to_unicode", "(", "url_str", ")", "result", "=", "urlparse", "(", "url_str", ")", "netloc_parts", "=", "result", ".", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "if", "len", "(", "ne...
Extract all parts from a URL string and return them as a dictionary
[ "Extract", "all", "parts", "from", "a", "URL", "string", "and", "return", "them", "as", "a", "dictionary" ]
python
train
saltstack/salt
salt/modules/aptly.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptly.py#L295-L344
def new_repo(name, config_path=_DEFAULT_CONFIG_PATH, comment=None, component=None, distribution=None, uploaders_file=None, from_snapshot=None, saltenv='base'): ''' Create a new local package repository. :param str name: The name of the local repository. :param str config_path:...
[ "def", "new_repo", "(", "name", ",", "config_path", "=", "_DEFAULT_CONFIG_PATH", ",", "comment", "=", "None", ",", "component", "=", "None", ",", "distribution", "=", "None", ",", "uploaders_file", "=", "None", ",", "from_snapshot", "=", "None", ",", "salten...
Create a new local package repository. :param str name: The name of the local repository. :param str config_path: The path to the configuration file for the aptly instance. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :pa...
[ "Create", "a", "new", "local", "package", "repository", "." ]
python
train
marshmallow-code/apispec
src/apispec/ext/marshmallow/__init__.py
https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L213-L222
def warn_if_schema_already_in_spec(self, schema_key): """Method to warn the user if the schema has already been added to the spec. """ if schema_key in self.openapi.refs: warnings.warn( "{} has already been added to the spec. Adding it twice may " ...
[ "def", "warn_if_schema_already_in_spec", "(", "self", ",", "schema_key", ")", ":", "if", "schema_key", "in", "self", ".", "openapi", ".", "refs", ":", "warnings", ".", "warn", "(", "\"{} has already been added to the spec. Adding it twice may \"", "\"cause references to n...
Method to warn the user if the schema has already been added to the spec.
[ "Method", "to", "warn", "the", "user", "if", "the", "schema", "has", "already", "been", "added", "to", "the", "spec", "." ]
python
train
Mindwerks/worldengine
worldengine/simulations/precipitation.py
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/simulations/precipitation.py#L33-L111
def _calculate(seed, world): """Precipitation is a value in [-1,1]""" rng = numpy.random.RandomState(seed) # create our own random generator base = rng.randint(0, 4096) curve_gamma = world.gamma_curve curve_bonus = world.curve_offset height = world.height width ...
[ "def", "_calculate", "(", "seed", ",", "world", ")", ":", "rng", "=", "numpy", ".", "random", ".", "RandomState", "(", "seed", ")", "# create our own random generator", "base", "=", "rng", ".", "randint", "(", "0", ",", "4096", ")", "curve_gamma", "=", "...
Precipitation is a value in [-1,1]
[ "Precipitation", "is", "a", "value", "in", "[", "-", "1", "1", "]" ]
python
train
timothydmorton/obliquity
obliquity/kappa_inference.py
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L46-L49
def cosi_pdf(z,k=1): """Equation (11) of Morton & Winn (2014) """ return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0]
[ "def", "cosi_pdf", "(", "z", ",", "k", "=", "1", ")", ":", "return", "2", "*", "k", "/", "(", "np", ".", "pi", "*", "np", ".", "sinh", "(", "k", ")", ")", "*", "quad", "(", "cosi_integrand", ",", "z", ",", "1", ",", "args", "=", "(", "k",...
Equation (11) of Morton & Winn (2014)
[ "Equation", "(", "11", ")", "of", "Morton", "&", "Winn", "(", "2014", ")" ]
python
train
glyph/txsni
txsni/snimap.py
https://github.com/glyph/txsni/blob/5014c141a7acef63e20fcf6c36fa07f0cd754ce1/txsni/snimap.py#L56-L62
def get_context(self): """ A basic override of get_context to ensure that the appropriate proxy object is returned. """ ctx = self._obj.get_context() return _ContextProxy(ctx, self._factory)
[ "def", "get_context", "(", "self", ")", ":", "ctx", "=", "self", ".", "_obj", ".", "get_context", "(", ")", "return", "_ContextProxy", "(", "ctx", ",", "self", ".", "_factory", ")" ]
A basic override of get_context to ensure that the appropriate proxy object is returned.
[ "A", "basic", "override", "of", "get_context", "to", "ensure", "that", "the", "appropriate", "proxy", "object", "is", "returned", "." ]
python
train
nugget/python-anthemav
anthemav/tools.py
https://github.com/nugget/python-anthemav/blob/c3cee38f2d452c1ab1335d9885e0769ec24d5f90/anthemav/tools.py#L60-L65
def monitor(): """Wrapper to call console with a loop.""" log = logging.getLogger(__name__) loop = asyncio.get_event_loop() asyncio.ensure_future(console(loop, log)) loop.run_forever()
[ "def", "monitor", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "asyncio", ".", "ensure_future", "(", "console", "(", "loop", ",", "log", ")", ")", "loop", ".", ...
Wrapper to call console with a loop.
[ "Wrapper", "to", "call", "console", "with", "a", "loop", "." ]
python
train
tradenity/python-sdk
tradenity/resources/brand.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/brand.py#L500-L520
def get_brand_by_id(cls, brand_id, **kwargs): """Find Brand Return single instance of Brand by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_brand_by_id(brand_id, async=True) ...
[ "def", "get_brand_by_id", "(", "cls", ",", "brand_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_get_brand_by_id_with_http_inf...
Find Brand Return single instance of Brand by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_brand_by_id(brand_id, async=True) >>> result = thread.get() :param async bool...
[ "Find", "Brand" ]
python
train
ktbyers/netmiko
netmiko/fortinet/fortinet_ssh.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/fortinet/fortinet_ssh.py#L74-L84
def cleanup(self): """Re-enable paging globally.""" if self.allow_disable_global: # Return paging state output_mode_cmd = "set output {}".format(self._output_mode) enable_paging_commands = ["config system console", output_mode_cmd, "end"] if self.vdoms: ...
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "allow_disable_global", ":", "# Return paging state", "output_mode_cmd", "=", "\"set output {}\"", ".", "format", "(", "self", ".", "_output_mode", ")", "enable_paging_commands", "=", "[", "\"config system ...
Re-enable paging globally.
[ "Re", "-", "enable", "paging", "globally", "." ]
python
train
juju-solutions/jujuresources
jujuresources/backend.py
https://github.com/juju-solutions/jujuresources/blob/7d2c5f50981784cc4b5cde216b930f6d59c951a4/jujuresources/backend.py#L65-L74
def get(cls, name, definition, output_dir): """ Dispatch to the right subclass based on the definition. """ if 'url' in definition: return URLResource(name, definition, output_dir) elif 'pypi' in definition: return PyPIResource(name, definition, output_dir...
[ "def", "get", "(", "cls", ",", "name", ",", "definition", ",", "output_dir", ")", ":", "if", "'url'", "in", "definition", ":", "return", "URLResource", "(", "name", ",", "definition", ",", "output_dir", ")", "elif", "'pypi'", "in", "definition", ":", "re...
Dispatch to the right subclass based on the definition.
[ "Dispatch", "to", "the", "right", "subclass", "based", "on", "the", "definition", "." ]
python
train
kipe/enocean
enocean/decorators.py
https://github.com/kipe/enocean/blob/99fa03f47004eef74c7987545c33ecd01af0de07/enocean/decorators.py#L8-L38
def timing(rounds=1, limit=None): ''' Wrapper to implement simple timing of tests. Allows running multiple rounds to calculate average time. Limit (in milliseconds) can be set to assert, if (average) duration is too high. ''' def decorator(method): @functools.wraps(method) def f(...
[ "def", "timing", "(", "rounds", "=", "1", ",", "limit", "=", "None", ")", ":", "def", "decorator", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "f", "(", ")", ":", "if", "rounds", "==", "1", ":", "start", ...
Wrapper to implement simple timing of tests. Allows running multiple rounds to calculate average time. Limit (in milliseconds) can be set to assert, if (average) duration is too high.
[ "Wrapper", "to", "implement", "simple", "timing", "of", "tests", ".", "Allows", "running", "multiple", "rounds", "to", "calculate", "average", "time", ".", "Limit", "(", "in", "milliseconds", ")", "can", "be", "set", "to", "assert", "if", "(", "average", "...
python
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L379-L396
def _compute_diplomacy(self): """Compute diplomacy.""" self._diplomacy = { 'teams': self.teams(), 'ffa': len(self.teams()) == (self._player_num + self._computer_num and self._player_num + self._computer_num > 2), 'TG': len(sel...
[ "def", "_compute_diplomacy", "(", "self", ")", ":", "self", ".", "_diplomacy", "=", "{", "'teams'", ":", "self", ".", "teams", "(", ")", ",", "'ffa'", ":", "len", "(", "self", ".", "teams", "(", ")", ")", "==", "(", "self", ".", "_player_num", "+",...
Compute diplomacy.
[ "Compute", "diplomacy", "." ]
python
train
gijzelaerr/python-snap7
snap7/client.py
https://github.com/gijzelaerr/python-snap7/blob/a6db134c7a3a2ef187b9eca04669221d6fc634c3/snap7/client.py#L349-L353
def set_session_password(self, password): """Send the password to the PLC to meet its security level.""" assert len(password) <= 8, 'maximum password length is 8' return self.library.Cli_SetSessionPassword(self.pointer, c_char_p(six.b(password))...
[ "def", "set_session_password", "(", "self", ",", "password", ")", ":", "assert", "len", "(", "password", ")", "<=", "8", ",", "'maximum password length is 8'", "return", "self", ".", "library", ".", "Cli_SetSessionPassword", "(", "self", ".", "pointer", ",", "...
Send the password to the PLC to meet its security level.
[ "Send", "the", "password", "to", "the", "PLC", "to", "meet", "its", "security", "level", "." ]
python
train
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py#L43-L74
def forward(self, x): """ Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first. """ last_inner = getattr(self, self...
[ "def", "forward", "(", "self", ",", "x", ")", ":", "last_inner", "=", "getattr", "(", "self", ",", "self", ".", "inner_blocks", "[", "-", "1", "]", ")", "(", "x", "[", "-", "1", "]", ")", "results", "=", "[", "]", "results", ".", "append", "(",...
Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first.
[ "Arguments", ":", "x", "(", "list", "[", "Tensor", "]", ")", ":", "feature", "maps", "for", "each", "feature", "level", ".", "Returns", ":", "results", "(", "tuple", "[", "Tensor", "]", ")", ":", "feature", "maps", "after", "FPN", "layers", ".", "The...
python
train
gabstopper/smc-python
smc/policy/policy.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/policy.py#L78-L109
def search_rule(self, search): """ Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str sea...
[ "def", "search_rule", "(", "self", ",", "search", ")", ":", "result", "=", "self", ".", "make_request", "(", "resource", "=", "'search_rule'", ",", "params", "=", "{", "'filter'", ":", "search", "}", ")", "if", "result", ":", "results", "=", "[", "]", ...
Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements m...
[ "Search", "a", "rule", "for", "a", "rule", "tag", "or", "name", "value", "Result", "will", "be", "the", "meta", "data", "for", "rule", "(", "name", "href", "type", ")" ]
python
train
revelc/pyaccumulo
pyaccumulo/proxy/AccumuloProxy.py
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L2021-L2028
def pingTabletServer(self, login, tserver): """ Parameters: - login - tserver """ self.send_pingTabletServer(login, tserver) self.recv_pingTabletServer()
[ "def", "pingTabletServer", "(", "self", ",", "login", ",", "tserver", ")", ":", "self", ".", "send_pingTabletServer", "(", "login", ",", "tserver", ")", "self", ".", "recv_pingTabletServer", "(", ")" ]
Parameters: - login - tserver
[ "Parameters", ":", "-", "login", "-", "tserver" ]
python
train
stlehmann/pyads
pyads/pyads_ex.py
https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L133-L150
def adsAddRoute(net_id, ip_address): # type: (SAmsNetId, str) -> None """Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restyp...
[ "def", "adsAddRoute", "(", "net_id", ",", "ip_address", ")", ":", "# type: (SAmsNetId, str) -> None", "add_route", "=", "_adsDLL", ".", "AdsAddRoute", "add_route", ".", "restype", "=", "ctypes", ".", "c_long", "# Convert ip address to bytes (PY3) and get pointer.", "ip_ad...
Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint
[ "Establish", "a", "new", "route", "in", "the", "AMS", "Router", "." ]
python
valid
tonysimpson/nanomsg-python
nanomsg/__init__.py
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L359-L366
def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn]
[ "def", "recv", "(", "self", ",", "buf", "=", "None", ",", "flags", "=", "0", ")", ":", "if", "buf", "is", "None", ":", "rtn", ",", "out_buf", "=", "wrapper", ".", "nn_recv", "(", "self", ".", "fd", ",", "flags", ")", "else", ":", "rtn", ",", ...
Recieve a message.
[ "Recieve", "a", "message", "." ]
python
train
quantumlib/Cirq
cirq/optimizers/decompositions.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L118-L143
def single_qubit_op_to_framed_phase_form( mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]: """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's ph...
[ "def", "single_qubit_op_to_framed_phase_form", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "complex", ",", "complex", "]", ":", "vals", ",", "vecs", "=", "np", ".", "linalg", ".", "eig", "(", "mat", ")", ...
Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's phase is the amount of rotation around M's rotation axis. This decomposition can be used to decompose controlle...
[ "Decomposes", "a", "2x2", "unitary", "M", "into", "U^", "-", "1", "*", "diag", "(", "1", "r", ")", "*", "U", "*", "diag", "(", "g", "g", ")", "." ]
python
train
bspaans/python-mingus
mingus/midi/midi_file_in.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L243-L259
def parse_track(self, fp): """Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read. """ events = [] chunk_size = self.parse_track_header(fp) bytes = chunk_size while chunk_size > 0: (delta_ti...
[ "def", "parse_track", "(", "self", ",", "fp", ")", ":", "events", "=", "[", "]", "chunk_size", "=", "self", ".", "parse_track_header", "(", "fp", ")", "bytes", "=", "chunk_size", "while", "chunk_size", ">", "0", ":", "(", "delta_time", ",", "chunk_delta"...
Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read.
[ "Parse", "a", "MIDI", "track", "from", "its", "header", "to", "its", "events", "." ]
python
train
python-rope/rope
rope/base/libutils.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/libutils.py#L85-L94
def get_string_module(project, code, resource=None, force_errors=False): """Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config. """ return pyob...
[ "def", "get_string_module", "(", "project", ",", "code", ",", "resource", "=", "None", ",", "force_errors", "=", "False", ")", ":", "return", "pyobjectsdef", ".", "PyModule", "(", "project", ".", "pycore", ",", "code", ",", "resource", ",", "force_errors", ...
Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config.
[ "Returns", "a", "PyObject", "object", "for", "the", "given", "code" ]
python
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L252-L271
def delete_request(self, container, resource=None, query_items=None, accept=None): """Send a DELETE request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): ...
[ "def", "delete_request", "(", "self", ",", "container", ",", "resource", "=", "None", ",", "query_items", "=", "None", ",", "accept", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "headers", "=", "s...
Send a DELETE request.
[ "Send", "a", "DELETE", "request", "." ]
python
train
reingart/pyafipws
wslpg.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2057-L2068
def AnularCertificacion(self, coe): "Anular liquidación activa" ret = self.client.cgSolicitarAnulacion( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, coe=coe, ...
[ "def", "AnularCertificacion", "(", "self", ",", "coe", ")", ":", "ret", "=", "self", ".", "client", ".", "cgSolicitarAnulacion", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'", ":", ...
Anular liquidación activa
[ "Anular", "liquidación", "activa" ]
python
train
padelt/temper-python
temperusb/temper.py
https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L207-L281
def get_data(self, reset_device=False): """ Get data from the USB device. """ try: if reset_device: self._device.reset() # detach kernel driver from both interfaces if attached, so we can set_configuration() for interface in [0,1]: ...
[ "def", "get_data", "(", "self", ",", "reset_device", "=", "False", ")", ":", "try", ":", "if", "reset_device", ":", "self", ".", "_device", ".", "reset", "(", ")", "# detach kernel driver from both interfaces if attached, so we can set_configuration()", "for", "interf...
Get data from the USB device.
[ "Get", "data", "from", "the", "USB", "device", "." ]
python
valid
hobson/aima
aima/learning.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L545-L547
def leave1out(learner, dataset): "Leave one out cross-validation over the dataset." return cross_validation(learner, dataset, k=len(dataset.examples))
[ "def", "leave1out", "(", "learner", ",", "dataset", ")", ":", "return", "cross_validation", "(", "learner", ",", "dataset", ",", "k", "=", "len", "(", "dataset", ".", "examples", ")", ")" ]
Leave one out cross-validation over the dataset.
[ "Leave", "one", "out", "cross", "-", "validation", "over", "the", "dataset", "." ]
python
valid
boriel/zxbasic
zxbpp.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L596-L602
def p_exprle(p): """ expr : expr LE expr """ a = int(p[1]) if p[1].isdigit() else 0 b = int(p[3]) if p[3].isdigit() else 0 p[0] = '1' if a <= b else '0'
[ "def", "p_exprle", "(", "p", ")", ":", "a", "=", "int", "(", "p", "[", "1", "]", ")", "if", "p", "[", "1", "]", ".", "isdigit", "(", ")", "else", "0", "b", "=", "int", "(", "p", "[", "3", "]", ")", "if", "p", "[", "3", "]", ".", "isdi...
expr : expr LE expr
[ "expr", ":", "expr", "LE", "expr" ]
python
train
dmbee/seglearn
seglearn/transform.py
https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/transform.py#L922-L1009
def transform(self, X, y=None, sample_weight=None): ''' Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : a...
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "sample_weight", "=", "None", ")", ":", "check_ts_data", "(", "X", ",", "y", ")", "xt", ",", "xc", "=", "get_ts_data_parts", "(", "X", ")", "yt", "=", "y", "swt", "=", "sample...
Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (option...
[ "Transforms", "the", "time", "series", "data", "with", "linear", "direct", "value", "interpolation", "If", "y", "is", "a", "time", "series", "and", "passed", "it", "will", "be", "transformed", "as", "well", "The", "time", "dimension", "is", "removed", "from"...
python
train
Duke-GCB/DukeDSClient
ddsc/sdk/client.py
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/sdk/client.py#L102-L111
def create_project(self, name, description): """ Create a new project with the specified name and description :param name: str: name of the project to create :param description: str: description of the project to create :return: Project """ return self._create_ite...
[ "def", "create_project", "(", "self", ",", "name", ",", "description", ")", ":", "return", "self", ".", "_create_item_response", "(", "self", ".", "data_service", ".", "create_project", "(", "name", ",", "description", ")", ",", "Project", ")" ]
Create a new project with the specified name and description :param name: str: name of the project to create :param description: str: description of the project to create :return: Project
[ "Create", "a", "new", "project", "with", "the", "specified", "name", "and", "description", ":", "param", "name", ":", "str", ":", "name", "of", "the", "project", "to", "create", ":", "param", "description", ":", "str", ":", "description", "of", "the", "p...
python
train
gwastro/pycbc
pycbc/waveform/spa_tmplt.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/spa_tmplt.py#L80-L94
def spa_length_in_time(**kwds): """ Returns the length in time of the template, based on the masses, PN order, and low-frequency cut-off. """ m1 = kwds['mass1'] m2 = kwds['mass2'] flow = kwds['f_lower'] porder = int(kwds['phase_order']) # For now, we call the swig-wrapped functi...
[ "def", "spa_length_in_time", "(", "*", "*", "kwds", ")", ":", "m1", "=", "kwds", "[", "'mass1'", "]", "m2", "=", "kwds", "[", "'mass2'", "]", "flow", "=", "kwds", "[", "'f_lower'", "]", "porder", "=", "int", "(", "kwds", "[", "'phase_order'", "]", ...
Returns the length in time of the template, based on the masses, PN order, and low-frequency cut-off.
[ "Returns", "the", "length", "in", "time", "of", "the", "template", "based", "on", "the", "masses", "PN", "order", "and", "low", "-", "frequency", "cut", "-", "off", "." ]
python
train
saltstack/salt
salt/modules/cron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L778-L801
def rm_env(user, name): ''' Remove cron environment variable for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_env root MAILTO ''' lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['env'])): if name == lst['env'][ind]['n...
[ "def", "rm_env", "(", "user", ",", "name", ")", ":", "lst", "=", "list_tab", "(", "user", ")", "ret", "=", "'absent'", "rm_", "=", "None", "for", "ind", "in", "range", "(", "len", "(", "lst", "[", "'env'", "]", ")", ")", ":", "if", "name", "=="...
Remove cron environment variable for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_env root MAILTO
[ "Remove", "cron", "environment", "variable", "for", "a", "specified", "user", "." ]
python
train
cloudendpoints/endpoints-management-python
endpoints_management/control/metric_descriptor.py
https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_descriptor.py#L276-L289
def matches(self, desc): """Determines if a given metric descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `Fa...
[ "def", "matches", "(", "self", ",", "desc", ")", ":", "return", "(", "self", ".", "metric_name", "==", "desc", ".", "name", "and", "self", ".", "kind", "==", "desc", ".", "metricKind", "and", "self", ".", "value_type", "==", "desc", ".", "valueType", ...
Determines if a given metric descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `False`
[ "Determines", "if", "a", "given", "metric", "descriptor", "matches", "this", "enum", "instance" ]
python
train
SHDShim/pytheos
pytheos/eqn_bm3.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L65-L82
def bm3_v(p, v0, k0, k0p, p_ref=0.0, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different condi...
[ "def", "bm3_v", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "p_ref", "=", "0.0", ",", "min_strain", "=", "0.01", ")", ":", "if", "isuncertainties", "(", "[", "p", ",", "v0", ",", "k0", ",", "k0p", "]", ")", ":", "f_u", "=", "np", ".", ...
find volume at given pressure using brenth in scipy.optimize :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param...
[ "find", "volume", "at", "given", "pressure", "using", "brenth", "in", "scipy", ".", "optimize" ]
python
train
tomnor/channelpack
channelpack/pack.py
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pack.py#L1206-L1237
def txtpack(fn, **kwargs): """Return a ChannelPack instance loaded with text data file fn. Attempt to read out custom channel names from the file and call instance.set_channel_names(). Then return the pack. This is a lazy function to get a loaded instance, using the cleverness provided by pulltxt ...
[ "def", "txtpack", "(", "fn", ",", "*", "*", "kwargs", ")", ":", "loadfunc", "=", "pulltxt", ".", "loadtxt_asdict", "cp", "=", "ChannelPack", "(", "loadfunc", ")", "cp", ".", "load", "(", "fn", ",", "*", "*", "kwargs", ")", "names", "=", "pulltxt", ...
Return a ChannelPack instance loaded with text data file fn. Attempt to read out custom channel names from the file and call instance.set_channel_names(). Then return the pack. This is a lazy function to get a loaded instance, using the cleverness provided by pulltxt module. No delimiter or rows-to-sk...
[ "Return", "a", "ChannelPack", "instance", "loaded", "with", "text", "data", "file", "fn", "." ]
python
train
pypa/pipenv
pipenv/vendor/delegator.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L290-L314
def _expand_args(command): """Parses command strings and returns a Popen-ready list.""" # Prepare arguments. if isinstance(command, STR_TYPES): if sys.version_info[0] == 2: splitter = shlex.shlex(command.encode("utf-8")) elif sys.version_info[0] == 3: splitter = shle...
[ "def", "_expand_args", "(", "command", ")", ":", "# Prepare arguments.", "if", "isinstance", "(", "command", ",", "STR_TYPES", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "splitter", "=", "shlex", ".", "shlex", "(", "comman...
Parses command strings and returns a Popen-ready list.
[ "Parses", "command", "strings", "and", "returns", "a", "Popen", "-", "ready", "list", "." ]
python
train
openpaperwork/paperwork-backend
paperwork_backend/docsearch.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/docsearch.py#L224-L230
def commit(self, index_update=True, label_guesser_update=True): """ Apply the changes to the index """ logger.info("Index: Commiting changes") self.docsearch.index.commit(index_update=index_update, label_guesser_update=label_guesser_update)
[ "def", "commit", "(", "self", ",", "index_update", "=", "True", ",", "label_guesser_update", "=", "True", ")", ":", "logger", ".", "info", "(", "\"Index: Commiting changes\"", ")", "self", ".", "docsearch", ".", "index", ".", "commit", "(", "index_update", "...
Apply the changes to the index
[ "Apply", "the", "changes", "to", "the", "index" ]
python
train
sosreport/sos
sos/plugins/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1448-L1467
def convert_cmd_scl(self, scl, cmd): """wrapping command in "scl enable" call and adds proper PATH """ # load default SCL prefix to PATH prefix = self.policy.get_default_scl_prefix() # read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n' try: pref...
[ "def", "convert_cmd_scl", "(", "self", ",", "scl", ",", "cmd", ")", ":", "# load default SCL prefix to PATH", "prefix", "=", "self", ".", "policy", ".", "get_default_scl_prefix", "(", ")", "# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\\n'", "try", ":",...
wrapping command in "scl enable" call and adds proper PATH
[ "wrapping", "command", "in", "scl", "enable", "call", "and", "adds", "proper", "PATH" ]
python
train
odlgroup/odl
odl/space/fspace.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L610-L636
def zero(self): """Function mapping anything to zero.""" # Since `FunctionSpace.lincomb` may be slow, we implement this # function directly. # The unused **kwargs are needed to support combination with # functions that take parameters. def zero_vec(x, out=None, **kwargs):...
[ "def", "zero", "(", "self", ")", ":", "# Since `FunctionSpace.lincomb` may be slow, we implement this", "# function directly.", "# The unused **kwargs are needed to support combination with", "# functions that take parameters.", "def", "zero_vec", "(", "x", ",", "out", "=", "None",...
Function mapping anything to zero.
[ "Function", "mapping", "anything", "to", "zero", "." ]
python
train
aws/aws-encryption-sdk-python
src/aws_encryption_sdk/internal/formatting/__init__.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L111-L122
def ciphertext_length(header, plaintext_length): """Calculates the complete ciphertext message length, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int plaintext_length: Length of plaintext in bytes :rtype: i...
[ "def", "ciphertext_length", "(", "header", ",", "plaintext_length", ")", ":", "ciphertext_length", "=", "header_length", "(", "header", ")", "ciphertext_length", "+=", "body_length", "(", "header", ",", "plaintext_length", ")", "ciphertext_length", "+=", "footer_lengt...
Calculates the complete ciphertext message length, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int plaintext_length: Length of plaintext in bytes :rtype: int
[ "Calculates", "the", "complete", "ciphertext", "message", "length", "given", "a", "complete", "header", "." ]
python
train
lowandrew/OLCTools
spadespipeline/quality.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/quality.py#L653-L665
def perform_pilon(self): """ Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the sample is contaminated or if there are > 500 contigs """ for sample in self.metadata: try: if sample[self.analysisty...
[ "def", "perform_pilon", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "try", ":", "if", "sample", "[", "self", ".", "analysistype", "]", ".", "num_contigs", ">", "500", "or", "sample", ".", "confindr", ".", "contam_status", ...
Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the sample is contaminated or if there are > 500 contigs
[ "Determine", "if", "pilon", "polishing", "should", "be", "attempted", ".", "Do", "not", "perform", "polishing", "if", "confindr", "determines", "that", "the", "sample", "is", "contaminated", "or", "if", "there", "are", ">", "500", "contigs" ]
python
train
edx/opaque-keys
opaque_keys/edx/locator.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L996-L1012
def to_deprecated_son(self, prefix='', tag='i4x'): """ Returns a SON object that represents this location """ # This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'), # because that format was used to store data historically in mongo # ...
[ "def", "to_deprecated_son", "(", "self", ",", "prefix", "=", "''", ",", "tag", "=", "'i4x'", ")", ":", "# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),", "# because that format was used to store data historically in mongo", "# adding tag b/...
Returns a SON object that represents this location
[ "Returns", "a", "SON", "object", "that", "represents", "this", "location" ]
python
train
ming060/robotframework-uiautomatorlibrary
uiautomatorlibrary/Mobile.py
https://github.com/ming060/robotframework-uiautomatorlibrary/blob/b70202b6a8aa68b4efd9d029c2845407fb33451a/uiautomatorlibrary/Mobile.py#L500-L508
def scroll_backward_vertically(self, steps=10, *args, **selectors): """ Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. """ retur...
[ "def", "scroll_backward_vertically", "(", "self", ",", "steps", "=", "10", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "self", ".", "device", "(", "*", "*", "selectors", ")", ".", "scroll", ".", "vert", ".", "backward", "(", "st...
Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details.
[ "Perform", "scroll", "backward", "(", "vertically", ")", "action", "on", "the", "object", "which", "has", "*", "selectors", "*", "attributes", "." ]
python
train
radjkarl/imgProcessor
imgProcessor/camera/LensDistortion.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/LensDistortion.py#L129-L144
def addImg(self, img): ''' add one chessboard image for detection lens distortion ''' # self.opts['imgs'].append(img) self.img = imread(img, 'gray', 'uint8') didFindCorners, corners = self.method() self.opts['foundPattern'].append(didFindCorners) ...
[ "def", "addImg", "(", "self", ",", "img", ")", ":", "# self.opts['imgs'].append(img)\r", "self", ".", "img", "=", "imread", "(", "img", ",", "'gray'", ",", "'uint8'", ")", "didFindCorners", ",", "corners", "=", "self", ".", "method", "(", ")", "self", "....
add one chessboard image for detection lens distortion
[ "add", "one", "chessboard", "image", "for", "detection", "lens", "distortion" ]
python
train
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/_kvlayer_keyword_search.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_kvlayer_keyword_search.py#L212-L236
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a ...
[ "def", "lookup", "(", "self", ",", "h", ")", ":", "for", "(", "_", ",", "k1", ",", "k2", ")", "in", "self", ".", "client", ".", "scan_keys", "(", "HASH_TF_INDEX_TABLE", ",", "(", "(", "h", ",", ")", ",", "(", "h", ",", ")", ")", ")", ":", "...
Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a large number of stream I...
[ "Get", "stream", "IDs", "for", "a", "single", "hash", "." ]
python
test
watson-developer-cloud/python-sdk
ibm_watson/websocket/recognize_listener.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/websocket/recognize_listener.py#L89-L97
def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT): """ Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ self.ws_client.se...
[ "def", "send", "(", "self", ",", "data", ",", "opcode", "=", "websocket", ".", "ABNF", ".", "OPCODE_TEXT", ")", ":", "self", ".", "ws_client", ".", "send", "(", "data", ",", "opcode", ")" ]
Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT.
[ "Send", "message", "to", "server", "." ]
python
train
jpype-project/jpype
jpype/_jvmfinder.py
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L177-L187
def _get_from_known_locations(self): """ Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None """ for home in self.find_possible_homes(self._locations): jvm = self.find_libjvm(home) ...
[ "def", "_get_from_known_locations", "(", "self", ")", ":", "for", "home", "in", "self", ".", "find_possible_homes", "(", "self", ".", "_locations", ")", ":", "jvm", "=", "self", ".", "find_libjvm", "(", "home", ")", "if", "jvm", "is", "not", "None", ":",...
Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None
[ "Retrieves", "the", "first", "existing", "Java", "library", "path", "in", "the", "predefined", "known", "locations" ]
python
train
funilrys/PyFunceble
PyFunceble/check.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/check.py#L196-L350
def is_domain_valid( self, domain=None, subdomain_check=False ): # pylint:disable=too-many-return-statements, too-many-branches """ Check if the given domain is a valid. :param domain: The domain to validate. :type domain: str :param subdomain_check: Ac...
[ "def", "is_domain_valid", "(", "self", ",", "domain", "=", "None", ",", "subdomain_check", "=", "False", ")", ":", "# pylint:disable=too-many-return-statements, too-many-branches", "# We initate our regex which will match for valid domains.", "regex_valid_domains", "=", "r\"^(?=....
Check if the given domain is a valid. :param domain: The domain to validate. :type domain: str :param subdomain_check: Activate the subdomain checking. :type subdomain_check: bool :return: The validity of the sub-domain. :rtype: bool
[ "Check", "if", "the", "given", "domain", "is", "a", "valid", "." ]
python
test
iotile/coretools
iotileemulate/iotile/emulate/virtual/emulation_mixin.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulation_mixin.py#L96-L111
def save_state(self, out_path): """Save the current state of this emulated object to a file. Args: out_path (str): The path to save the dumped state of this emulated object. """ state = self.dump_state() # Remove all IntEnums from state since they c...
[ "def", "save_state", "(", "self", ",", "out_path", ")", ":", "state", "=", "self", ".", "dump_state", "(", ")", "# Remove all IntEnums from state since they cannot be json-serialized on python 2.7", "# See https://bitbucket.org/stoneleaf/enum34/issues/17/difference-between-enum34-and...
Save the current state of this emulated object to a file. Args: out_path (str): The path to save the dumped state of this emulated object.
[ "Save", "the", "current", "state", "of", "this", "emulated", "object", "to", "a", "file", "." ]
python
train
sorgerlab/indra
indra/databases/cbio_client.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L350-L377
def get_ccle_lines_for_mutation(gene, amino_acid_change): """Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbo...
[ "def", "get_ccle_lines_for_mutation", "(", "gene", ",", "amino_acid_change", ")", ":", "data", "=", "{", "'cmd'", ":", "'getMutationData'", ",", "'case_set_id'", ":", "ccle_study", ",", "'genetic_profile_id'", ":", "ccle_study", "+", "'_mutations'", ",", "'gene_list...
Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbol of the mutated gene in whose product the amino acid cha...
[ "Return", "cell", "lines", "with", "a", "given", "point", "mutation", "in", "a", "given", "gene", "." ]
python
train
Aluriak/bubble-tools
bubbletools/converter.py
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/converter.py#L43-L58
def tree_to_dot(tree:BubbleTree, dotfile:str=None, render:bool=False): """Write in dotfile a graph equivalent to those depicted in bubble file See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py for graphviz API """ graph = tree_to_graph(tree) path = None if dotfile: # f...
[ "def", "tree_to_dot", "(", "tree", ":", "BubbleTree", ",", "dotfile", ":", "str", "=", "None", ",", "render", ":", "bool", "=", "False", ")", ":", "graph", "=", "tree_to_graph", "(", "tree", ")", "path", "=", "None", "if", "dotfile", ":", "# first save...
Write in dotfile a graph equivalent to those depicted in bubble file See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py for graphviz API
[ "Write", "in", "dotfile", "a", "graph", "equivalent", "to", "those", "depicted", "in", "bubble", "file" ]
python
train
bcbio/bcbio-nextgen
bcbio/cwl/create.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/create.py#L208-L221
def _write_expressiontool(step_dir, name, inputs, outputs, expression, parallel): """Create an ExpressionTool output for the given inputs """ out_file = os.path.join(step_dir, "%s.cwl" % name) out = {"class": "ExpressionTool", "cwlVersion": "v1.0", "requirements": [{"class": "Inlin...
[ "def", "_write_expressiontool", "(", "step_dir", ",", "name", ",", "inputs", ",", "outputs", ",", "expression", ",", "parallel", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "step_dir", ",", "\"%s.cwl\"", "%", "name", ")", "out", "=", ...
Create an ExpressionTool output for the given inputs
[ "Create", "an", "ExpressionTool", "output", "for", "the", "given", "inputs" ]
python
train
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L282-L312
def service_changed(self, event): """ Called by the framework when a service event occurs """ if ( self._ipopo_instance is None or not self._ipopo_instance.check_event(event) ): # stop() and clean() may have been called after we have been put ...
[ "def", "service_changed", "(", "self", ",", "event", ")", ":", "if", "(", "self", ".", "_ipopo_instance", "is", "None", "or", "not", "self", ".", "_ipopo_instance", ".", "check_event", "(", "event", ")", ")", ":", "# stop() and clean() may have been called after...
Called by the framework when a service event occurs
[ "Called", "by", "the", "framework", "when", "a", "service", "event", "occurs" ]
python
train
etingof/apacheconfig
apacheconfig/lexer.py
https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L236-L240
def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = True
[ "def", "t_multiline_NEWLINE", "(", "self", ",", "t", ")", ":", "if", "t", ".", "lexer", ".", "multiline_newline_seen", ":", "return", "self", ".", "t_multiline_OPTION_AND_VALUE", "(", "t", ")", "t", ".", "lexer", ".", "multiline_newline_seen", "=", "True" ]
r'\r\n|\n|\r
[ "r", "\\", "r", "\\", "n|", "\\", "n|", "\\", "r" ]
python
train
trailofbits/manticore
manticore/core/workspace.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L376-L384
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x...
[ "def", "load_state", "(", "self", ",", "state_id", ",", "delete", "=", "True", ")", ":", "return", "self", ".", "_store", ".", "load_state", "(", "f'{self._prefix}{state_id:08x}{self._suffix}'", ",", "delete", "=", "delete", ")" ]
Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State
[ "Load", "a", "state", "from", "storage", "identified", "by", "state_id", "." ]
python
valid
ConsenSys/mythril-classic
mythril/ethereum/interface/leveldb/client.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/ethereum/interface/leveldb/client.py#L251-L261
def contract_hash_to_address(self, contract_hash): """Try to find corresponding account address. :param contract_hash: :return: """ address_hash = binascii.a2b_hex(utils.remove_0x_head(contract_hash)) indexer = AccountIndexer(self) return _encode_hex(indexer.ge...
[ "def", "contract_hash_to_address", "(", "self", ",", "contract_hash", ")", ":", "address_hash", "=", "binascii", ".", "a2b_hex", "(", "utils", ".", "remove_0x_head", "(", "contract_hash", ")", ")", "indexer", "=", "AccountIndexer", "(", "self", ")", "return", ...
Try to find corresponding account address. :param contract_hash: :return:
[ "Try", "to", "find", "corresponding", "account", "address", "." ]
python
train
MozillaSecurity/dharma
dharma/core/dharma.py
https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L239-L242
def process_settings(self, settings): """A lazy way of feeding Dharma with configuration settings.""" logging.debug("Using configuration from: %s", settings.name) exec(compile(settings.read(), settings.name, 'exec'), globals(), locals())
[ "def", "process_settings", "(", "self", ",", "settings", ")", ":", "logging", ".", "debug", "(", "\"Using configuration from: %s\"", ",", "settings", ".", "name", ")", "exec", "(", "compile", "(", "settings", ".", "read", "(", ")", ",", "settings", ".", "n...
A lazy way of feeding Dharma with configuration settings.
[ "A", "lazy", "way", "of", "feeding", "Dharma", "with", "configuration", "settings", "." ]
python
train
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1771-L1780
def translate(self, by): """Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float """ new_positions = _translate(self.xyz_with_ports, by) self.xyz_with_ports = new_positions
[ "def", "translate", "(", "self", ",", "by", ")", ":", "new_positions", "=", "_translate", "(", "self", ".", "xyz_with_ports", ",", "by", ")", "self", ".", "xyz_with_ports", "=", "new_positions" ]
Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float
[ "Translate", "the", "Compound", "by", "a", "vector" ]
python
train
GoogleCloudPlatform/compute-image-packages
packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py#L50-L57
def _GetGsScopes(self): """Return all Google Storage scopes available on this VM.""" service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key) try: scopes = service_accounts[self.service_account]['scopes'] return list(GS_SCOPES.intersection(set(scopes))) if scopes else None ...
[ "def", "_GetGsScopes", "(", "self", ")", ":", "service_accounts", "=", "self", ".", "watcher", ".", "GetMetadata", "(", "metadata_key", "=", "self", ".", "metadata_key", ")", "try", ":", "scopes", "=", "service_accounts", "[", "self", ".", "service_account", ...
Return all Google Storage scopes available on this VM.
[ "Return", "all", "Google", "Storage", "scopes", "available", "on", "this", "VM", "." ]
python
train
ranaroussi/qtpylib
qtpylib/broker.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L196-L205
def add_instruments(self, *instruments): """ add instruments after initialization """ for instrument in instruments: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) contractString = self.ibConn.contractS...
[ "def", "add_instruments", "(", "self", ",", "*", "instruments", ")", ":", "for", "instrument", "in", "instruments", ":", "if", "isinstance", "(", "instrument", ",", "ezibpy", ".", "utils", ".", "Contract", ")", ":", "instrument", "=", "self", ".", "ibConn"...
add instruments after initialization
[ "add", "instruments", "after", "initialization" ]
python
train
radjkarl/imgProcessor
imgProcessor/interpolate/polyfit2d.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/interpolate/polyfit2d.py#L8-L19
def polyfit2d(x, y, z, order=3 #bounds=None ): ''' fit unstructured data ''' ncols = (order + 1)**2 G = np.zeros((x.size, ncols)) ij = itertools.product(list(range(order+1)), list(range(order+1))) for k, (i,j) in enumerate(ij): G[:,k] = x**i * y**j m = np...
[ "def", "polyfit2d", "(", "x", ",", "y", ",", "z", ",", "order", "=", "3", "#bounds=None\r", ")", ":", "ncols", "=", "(", "order", "+", "1", ")", "**", "2", "G", "=", "np", ".", "zeros", "(", "(", "x", ".", "size", ",", "ncols", ")", ")", "i...
fit unstructured data
[ "fit", "unstructured", "data" ]
python
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/__init__.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L1594-L1641
def tense_id(*args, **kwargs): """ Returns the tense id for a given (tense, person, number, mood, aspect, negated). Aliases and compound forms (e.g., IMPERFECT) are disambiguated. """ # Unpack tense given as a tuple, e.g., tense((PRESENT, 1, SG)): if len(args) == 1 and isinstance(args[0], (list,...
[ "def", "tense_id", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Unpack tense given as a tuple, e.g., tense((PRESENT, 1, SG)):", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tu...
Returns the tense id for a given (tense, person, number, mood, aspect, negated). Aliases and compound forms (e.g., IMPERFECT) are disambiguated.
[ "Returns", "the", "tense", "id", "for", "a", "given", "(", "tense", "person", "number", "mood", "aspect", "negated", ")", ".", "Aliases", "and", "compound", "forms", "(", "e", ".", "g", ".", "IMPERFECT", ")", "are", "disambiguated", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L189-L195
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
[ "def", "peer_ips", "(", "peer_relation", "=", "'cluster'", ",", "addr_key", "=", "'private-address'", ")", ":", "peers", "=", "{", "}", "for", "r_id", "in", "relation_ids", "(", "peer_relation", ")", ":", "for", "unit", "in", "relation_list", "(", "r_id", ...
Return a dict of peers and their private-address
[ "Return", "a", "dict", "of", "peers", "and", "their", "private", "-", "address" ]
python
train
google/grr
grr/server/grr_response_server/aff4_objects/security.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/security.py#L405-L408
def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id): """Build an approval symlink URN.""" return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add( approval_type).Add(subject_id).Add(approval_id)
[ "def", "ApprovalSymlinkUrnBuilder", "(", "approval_type", ",", "subject_id", ",", "user", ",", "approval_id", ")", ":", "return", "aff4", ".", "ROOT_URN", ".", "Add", "(", "\"users\"", ")", ".", "Add", "(", "user", ")", ".", "Add", "(", "\"approvals\"", ")...
Build an approval symlink URN.
[ "Build", "an", "approval", "symlink", "URN", "." ]
python
train
raiden-network/raiden
raiden/transfer/views.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L453-L465
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: """Return the secret for the transfer, None on EMPTY_SECRET.""" assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfe...
[ "def", "secret_from_transfer_task", "(", "transfer_task", ":", "Optional", "[", "TransferTask", "]", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "Secret", "]", ":", "assert", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")...
Return the secret for the transfer, None on EMPTY_SECRET.
[ "Return", "the", "secret", "for", "the", "transfer", "None", "on", "EMPTY_SECRET", "." ]
python
train
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3084-L3114
def is_number_match(num1, num2): """Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain f...
[ "def", "is_number_match", "(", "num1", ",", "num2", ")", ":", "if", "isinstance", "(", "num1", ",", "PhoneNumber", ")", "and", "isinstance", "(", "num2", ",", "PhoneNumber", ")", ":", "return", "_is_number_match_OO", "(", "num1", ",", "num2", ")", "elif", ...
Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have co...
[ "Takes", "two", "phone", "numbers", "and", "compares", "them", "for", "equality", "." ]
python
train
inasafe/inasafe
safe/utilities/settings.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L173-L207
def export_setting(file_path, qsettings=None): """Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.P...
[ "def", "export_setting", "(", "file_path", ",", "qsettings", "=", "None", ")", ":", "inasafe_settings", "=", "{", "}", "if", "not", "qsettings", ":", "qsettings", "=", "QSettings", "(", ")", "qsettings", ".", "beginGroup", "(", "'inasafe'", ")", "all_keys", ...
Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: A dictionary of th...
[ "Export", "InaSAFE", "s", "setting", "to", "a", "file", "." ]
python
train
mrallen1/pygett
pygett/base.py
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L115-L133
def get_share(self, sharename): """ Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds") """ response ...
[ "def", "get_share", "(", "self", ",", "sharename", ")", ":", "response", "=", "GettRequest", "(", ")", ".", "get", "(", "\"/shares/%s\"", "%", "sharename", ")", "if", "response", ".", "http_status", "==", "200", ":", "return", "GettShare", "(", "self", "...
Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds")
[ "Get", "a", "specific", "share", ".", "Does", "not", "require", "authentication", "." ]
python
train
basho/riak-python-client
riak/codecs/pbuf.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/codecs/pbuf.py#L372-L387
def encode_modfun(self, props, msg=None): """ Encodes a dict with 'mod' and 'fun' keys into a protobuf modfun pair. Used in bucket properties. :param props: the module/function pair :type props: dict :param msg: the protobuf message to fill :type msg: riak.pb.ria...
[ "def", "encode_modfun", "(", "self", ",", "props", ",", "msg", "=", "None", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "riak", ".", "pb", ".", "riak_pb2", ".", "RpbModFun", "(", ")", "msg", ".", "module", "=", "str_to_bytes", "(", "props...
Encodes a dict with 'mod' and 'fun' keys into a protobuf modfun pair. Used in bucket properties. :param props: the module/function pair :type props: dict :param msg: the protobuf message to fill :type msg: riak.pb.riak_pb2.RpbModFun :rtype riak.pb.riak_pb2.RpbModFun
[ "Encodes", "a", "dict", "with", "mod", "and", "fun", "keys", "into", "a", "protobuf", "modfun", "pair", ".", "Used", "in", "bucket", "properties", "." ]
python
train
spacetelescope/stsci.imagestats
stsci/imagestats/histogram1d.py
https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L55-L68
def _populateHistogram(self): """Call the C-code that actually populates the histogram""" try : buildHistogram.populate1DHist(self._data, self.histogram, self.minValue, self.maxValue, self.binWidth) except: if ((self._data.max() - self._data.min()) < self....
[ "def", "_populateHistogram", "(", "self", ")", ":", "try", ":", "buildHistogram", ".", "populate1DHist", "(", "self", ".", "_data", ",", "self", ".", "histogram", ",", "self", ".", "minValue", ",", "self", ".", "maxValue", ",", "self", ".", "binWidth", "...
Call the C-code that actually populates the histogram
[ "Call", "the", "C", "-", "code", "that", "actually", "populates", "the", "histogram" ]
python
train
jlmadurga/permabots
permabots/views/api/bot.py
https://github.com/jlmadurga/permabots/blob/781a91702529a23fe7bc2aa84c5d88e961412466/permabots/views/api/bot.py#L319-L328
def get(self, request, bot_id, id, format=None): """ Get MessengerBot by id --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated """ return super(MessengerBotDetail, self).get(request, bo...
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "MessengerBotDetail", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
Get MessengerBot by id --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated
[ "Get", "MessengerBot", "by", "id", "---", "serializer", ":", "MessengerBotSerializer", "responseMessages", ":", "-", "code", ":", "401", "message", ":", "Not", "authenticated" ]
python
train
Clinical-Genomics/scout
scout/server/blueprints/cases/controllers.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/cases/controllers.py#L413-L434
def rerun(store, mail, current_user, institute_id, case_name, sender, recipient): """Request a rerun by email.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) user_obj = store.user(current_user.email) link = url_for('cases.case', institute_id=institute_id, case_name=case_...
[ "def", "rerun", "(", "store", ",", "mail", ",", "current_user", ",", "institute_id", ",", "case_name", ",", "sender", ",", "recipient", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ...
Request a rerun by email.
[ "Request", "a", "rerun", "by", "email", "." ]
python
test
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/configer/configer.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/configer/configer.py#L186-L200
def doc_modified_prompt(self, ): """Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button of qmessagebox that has been pressed. Either Yes or Cancel. :rtype: QtGui.QMessageBox.StandardButton :raises: None ""...
[ "def", "doc_modified_prompt", "(", "self", ",", ")", ":", "msgbox", "=", "QtGui", ".", "QMessageBox", "(", ")", "msgbox", ".", "setWindowTitle", "(", "\"Discard changes?\"", ")", "msgbox", ".", "setText", "(", "\"Documents have been modified.\"", ")", "msgbox", ...
Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button of qmessagebox that has been pressed. Either Yes or Cancel. :rtype: QtGui.QMessageBox.StandardButton :raises: None
[ "Create", "a", "message", "box", "that", "asks", "the", "user", "to", "continue", "although", "files", "have", "been", "modified" ]
python
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L182-L188
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
[ "def", "is_touched", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "t", "=", "self", ".", "touched", "(", ")", "return", "(", "t", "&", "(", "1", "<<", "pin", ")...
Return True if the specified pin is being touched, otherwise returns False.
[ "Return", "True", "if", "the", "specified", "pin", "is", "being", "touched", "otherwise", "returns", "False", "." ]
python
train
ARMmbed/mbed-cloud-sdk-python
scripts/generate_news.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/generate_news.py#L35-L61
def main(): """Writes out newsfile if significant version bump""" last_known = '0' if os.path.isfile(metafile): with open(metafile) as fh: last_known = fh.read() import mbed_cloud current = mbed_cloud.__version__ # how significant a change in version scheme should trigger a...
[ "def", "main", "(", ")", ":", "last_known", "=", "'0'", "if", "os", ".", "path", ".", "isfile", "(", "metafile", ")", ":", "with", "open", "(", "metafile", ")", "as", "fh", ":", "last_known", "=", "fh", ".", "read", "(", ")", "import", "mbed_cloud"...
Writes out newsfile if significant version bump
[ "Writes", "out", "newsfile", "if", "significant", "version", "bump" ]
python
train
Pylons/plaster
src/plaster/uri.py
https://github.com/Pylons/plaster/blob/e70e55c182a8300d7ccf67e54d47740c72e72cd8/src/plaster/uri.py#L59-L125
def parse_uri(config_uri): """ Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` ...
[ "def", "parse_uri", "(", "config_uri", ")", ":", "if", "isinstance", "(", "config_uri", ",", "PlasterURL", ")", ":", "return", "config_uri", "# force absolute paths to look like a uri for more accurate parsing", "# we throw away the dummy scheme later and parse it from the resolved...
Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` registered with the system. Alte...
[ "Parse", "the", "config_uri", "into", "a", ":", "class", ":", "plaster", ".", "PlasterURL", "object", "." ]
python
train
apache/spark
python/pyspark/ml/param/__init__.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L467-L486
def _copyValues(self, to, extra=None): """ Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied """ ...
[ "def", "_copyValues", "(", "self", ",", "to", ",", "extra", "=", "None", ")", ":", "paramMap", "=", "self", ".", "_paramMap", ".", "copy", "(", ")", "if", "extra", "is", "not", "None", ":", "paramMap", ".", "update", "(", "extra", ")", "for", "para...
Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied
[ "Copies", "param", "values", "from", "this", "instance", "to", "another", "instance", "for", "params", "shared", "by", "them", "." ]
python
train
CyberInt/dockermon
dockermon.py
https://github.com/CyberInt/dockermon/blob/a8733b9395cb1b551971f17c31d7f4a8268bb969/dockermon.py#L71-L106
def watch(callback, url=default_sock_url): """Watch docker events. Will call callback with each new event (dict). url can be either tcp://<host>:port or ipc://<path> """ sock, hostname = connect(url) request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname request = request.encode('utf-8')...
[ "def", "watch", "(", "callback", ",", "url", "=", "default_sock_url", ")", ":", "sock", ",", "hostname", "=", "connect", "(", "url", ")", "request", "=", "'GET /events HTTP/1.1\\nHost: %s\\n\\n'", "%", "hostname", "request", "=", "request", ".", "encode", "(",...
Watch docker events. Will call callback with each new event (dict). url can be either tcp://<host>:port or ipc://<path>
[ "Watch", "docker", "events", ".", "Will", "call", "callback", "with", "each", "new", "event", "(", "dict", ")", "." ]
python
train
saltstack/salt
salt/modules/x509.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1732-L1761
def verify_signature(certificate, signing_pub_key=None, signing_pub_key_passphrase=None): ''' Verify that ``certificate`` has been signed by ``signing_pub_key`` certificate: The certificate to verify. Can be a path or string containing a PEM formatted certificate. ...
[ "def", "verify_signature", "(", "certificate", ",", "signing_pub_key", "=", "None", ",", "signing_pub_key_passphrase", "=", "None", ")", ":", "cert", "=", "_get_certificate_obj", "(", "certificate", ")", "if", "signing_pub_key", ":", "signing_pub_key", "=", "get_pub...
Verify that ``certificate`` has been signed by ``signing_pub_key`` certificate: The certificate to verify. Can be a path or string containing a PEM formatted certificate. signing_pub_key: The public key to verify, can be a string or path to a PEM formatted certificate, csr, or ...
[ "Verify", "that", "certificate", "has", "been", "signed", "by", "signing_pub_key" ]
python
train
rvswift/EB
EB/builder/exhaustive/exhaustive.py
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/exhaustive/exhaustive.py#L119-L132
def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None): """ Evaluate VS performance of each ensemble in ensemble_chunk """ results = {} # {('receptor_1', ..., 'receptor_n') : ensemble storage object} for ensemble in ensemble_chunk: results[ensemble] = calculate_perfor...
[ "def", "evaluate", "(", "molecules", ",", "ensemble_chunk", ",", "sort_order", ",", "options", ",", "output_queue", "=", "None", ")", ":", "results", "=", "{", "}", "# {('receptor_1', ..., 'receptor_n') : ensemble storage object}", "for", "ensemble", "in", "ensemble_c...
Evaluate VS performance of each ensemble in ensemble_chunk
[ "Evaluate", "VS", "performance", "of", "each", "ensemble", "in", "ensemble_chunk" ]
python
train
limodou/uliweb
uliweb/utils/common.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L619-L627
def get_uuid(type=4): """ Get uuid value """ import uuid name = 'uuid'+str(type) u = getattr(uuid, name) return u().hex
[ "def", "get_uuid", "(", "type", "=", "4", ")", ":", "import", "uuid", "name", "=", "'uuid'", "+", "str", "(", "type", ")", "u", "=", "getattr", "(", "uuid", ",", "name", ")", "return", "u", "(", ")", ".", "hex" ]
Get uuid value
[ "Get", "uuid", "value" ]
python
train
morse-talk/morse-talk
morse_talk/encoding.py
https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/encoding.py#L128-L142
def _encode_to_binary_string(message, on, off): """ >>> message = "SOS" >>> _encode_to_binary_string(message, on='1', off='0') '101010001110111011100010101' >>> message = " SOS" >>> _encode_to_binary_string(message, on='1', off='0') '0000000101010001110111011100010101' """ def to_st...
[ "def", "_encode_to_binary_string", "(", "message", ",", "on", ",", "off", ")", ":", "def", "to_string", "(", "i", ",", "s", ")", ":", "if", "i", "==", "0", "and", "s", "==", "off", ":", "return", "off", "*", "4", "return", "s", "return", "''", "....
>>> message = "SOS" >>> _encode_to_binary_string(message, on='1', off='0') '101010001110111011100010101' >>> message = " SOS" >>> _encode_to_binary_string(message, on='1', off='0') '0000000101010001110111011100010101'
[ ">>>", "message", "=", "SOS", ">>>", "_encode_to_binary_string", "(", "message", "on", "=", "1", "off", "=", "0", ")", "101010001110111011100010101" ]
python
train
python-gitlab/python-gitlab
gitlab/v4/objects.py
https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/v4/objects.py#L1819-L1841
def create(self, data, **kwargs): """Create a new object. Args: data (dict): parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo) Returns: RESTObject, RESTObject: The sourc...
[ "def", "create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_missing_create_attrs", "(", "data", ")", "server_data", "=", "self", ".", "gitlab", ".", "http_post", "(", "self", ".", "path", ",", "post_data", "=", "d...
Create a new object. Args: data (dict): parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo) Returns: RESTObject, RESTObject: The source and target issues Raises: ...
[ "Create", "a", "new", "object", "." ]
python
train
nvdv/vprof
vprof/memory_profiler.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/memory_profiler.py#L180-L186
def profile_function(self): """Returns memory stats for a function.""" target_modules = {self._run_object.__code__.co_filename} with _CodeEventsTracker(target_modules) as prof: prof.compute_mem_overhead() result = self._run_object(*self._run_args, **self._run_kwargs) ...
[ "def", "profile_function", "(", "self", ")", ":", "target_modules", "=", "{", "self", ".", "_run_object", ".", "__code__", ".", "co_filename", "}", "with", "_CodeEventsTracker", "(", "target_modules", ")", "as", "prof", ":", "prof", ".", "compute_mem_overhead", ...
Returns memory stats for a function.
[ "Returns", "memory", "stats", "for", "a", "function", "." ]
python
test
Gandi/gandi.cli
gandi/cli/commands/webacc.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L215-L240
def delete(gandi, webacc, vhost, backend, port): """ Delete a webaccelerator, a vhost or a backend """ result = [] if webacc: result = gandi.webacc.delete(webacc) if backend: backends = backend for backend in backends: if 'port' not in backend: if not...
[ "def", "delete", "(", "gandi", ",", "webacc", ",", "vhost", ",", "backend", ",", "port", ")", ":", "result", "=", "[", "]", "if", "webacc", ":", "result", "=", "gandi", ".", "webacc", ".", "delete", "(", "webacc", ")", "if", "backend", ":", "backen...
Delete a webaccelerator, a vhost or a backend
[ "Delete", "a", "webaccelerator", "a", "vhost", "or", "a", "backend" ]
python
train
ianmiell/shutit
shutit_class.py
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4412-L4435
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between...
[ "def", "check_conflicts", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now consider conflicts", "self", ".", "log", "(", "'PHASE: conflicts'", ",", "level", "=", "logging"...
Checks for any conflicts between modules configured to be built.
[ "Checks", "for", "any", "conflicts", "between", "modules", "configured", "to", "be", "built", "." ]
python
train
openfisca/openfisca-core
openfisca_core/simulations.py
https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L94-L104
def data_storage_dir(self): """ Temporary folder used to store intermediate calculation data in case the memory is saturated """ if self._data_storage_dir is None: self._data_storage_dir = tempfile.mkdtemp(prefix = "openfisca_") log.warn(( "Interme...
[ "def", "data_storage_dir", "(", "self", ")", ":", "if", "self", ".", "_data_storage_dir", "is", "None", ":", "self", ".", "_data_storage_dir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "\"openfisca_\"", ")", "log", ".", "warn", "(", "(", "\"Inte...
Temporary folder used to store intermediate calculation data in case the memory is saturated
[ "Temporary", "folder", "used", "to", "store", "intermediate", "calculation", "data", "in", "case", "the", "memory", "is", "saturated" ]
python
train
MacHu-GWU/angora-project
angora/gadget/configuration.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L276-L287
def set_section(self, section): """Set a section. If section already exists, overwrite the old one. """ if not isinstance(section, Section): raise Exception("You") try: self.remove_section(section.name) except: pass self._sections[sec...
[ "def", "set_section", "(", "self", ",", "section", ")", ":", "if", "not", "isinstance", "(", "section", ",", "Section", ")", ":", "raise", "Exception", "(", "\"You\"", ")", "try", ":", "self", ".", "remove_section", "(", "section", ".", "name", ")", "e...
Set a section. If section already exists, overwrite the old one.
[ "Set", "a", "section", ".", "If", "section", "already", "exists", "overwrite", "the", "old", "one", "." ]
python
train
LordSputnik/mutagen
mutagen/ogg.py
https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L165-L177
def size(self): """Total frame size.""" header_size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) header_size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is n...
[ "def", "size", "(", "self", ")", ":", "header_size", "=", "27", "# Initial header size", "for", "datum", "in", "self", ".", "packets", ":", "quot", ",", "rem", "=", "divmod", "(", "len", "(", "datum", ")", ",", "255", ")", "header_size", "+=", "quot", ...
Total frame size.
[ "Total", "frame", "size", "." ]
python
test
pettarin/ipapy
ipapy/ipachar.py
https://github.com/pettarin/ipapy/blob/ede4b3c40636f6eb90068369d31a2e75c7115324/ipapy/ipachar.py#L797-L805
def backness(self, value): """ Set the backness of the vowel. :param str value: the value to be set """ if (value is not None) and (not value in DG_V_BACKNESS): raise ValueError("Unrecognized value for backness: '%s'" % value) self.__backness = value
[ "def", "backness", "(", "self", ",", "value", ")", ":", "if", "(", "value", "is", "not", "None", ")", "and", "(", "not", "value", "in", "DG_V_BACKNESS", ")", ":", "raise", "ValueError", "(", "\"Unrecognized value for backness: '%s'\"", "%", "value", ")", "...
Set the backness of the vowel. :param str value: the value to be set
[ "Set", "the", "backness", "of", "the", "vowel", "." ]
python
train