Unnamed: 0
int64
0
10k
repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
5
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
100
30.3k
language
stringclasses
1 value
func_code_string
stringlengths
100
30.3k
func_code_tokens
stringlengths
138
33.2k
func_documentation_string
stringlengths
1
15k
func_documentation_tokens
stringlengths
5
5.14k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
7,900
pandemicsyn/statsdpy
statsdpy/statsd.py
StatsdServer.process_timer
def process_timer(self, key, fields): """ Process a received timer event :param key: Key of timer :param fields: Received fields """ try: if key not in self.timers: self.timers[key] = [] self.timers[key].append(float(fields[0])) ...
python
def process_timer(self, key, fields): """ Process a received timer event :param key: Key of timer :param fields: Received fields """ try: if key not in self.timers: self.timers[key] = [] self.timers[key].append(float(fields[0])) ...
['def', 'process_timer', '(', 'self', ',', 'key', ',', 'fields', ')', ':', 'try', ':', 'if', 'key', 'not', 'in', 'self', '.', 'timers', ':', 'self', '.', 'timers', '[', 'key', ']', '=', '[', ']', 'self', '.', 'timers', '[', 'key', ']', '.', 'append', '(', 'float', '(', 'fields', '[', '0', ']', ')', ')', 'if', 'self', '...
Process a received timer event :param key: Key of timer :param fields: Received fields
['Process', 'a', 'received', 'timer', 'event']
train
https://github.com/pandemicsyn/statsdpy/blob/9cfccf89121fd6a12df20f17fa3eb8f618a36455/statsdpy/statsd.py#L236-L254
7,901
crytic/slither
slither/printers/inheritance/inheritance_graph.py
PrinterInheritanceGraph._get_indirect_shadowing_information
def _get_indirect_shadowing_information(contract): """ Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists. :param var: The variable to collect shadowing information for. :param contract: The contract in which this variable is being analy...
python
def _get_indirect_shadowing_information(contract): """ Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists. :param var: The variable to collect shadowing information for. :param contract: The contract in which this variable is being analy...
['def', '_get_indirect_shadowing_information', '(', 'contract', ')', ':', "# If this variable is an overshadowing variable, we'll want to return information describing it.", 'result', '=', '[', ']', 'indirect_shadows', '=', 'detect_c3_function_shadowing', '(', 'contract', ')', 'if', 'indirect_shadows', ':', 'for', 'col...
Obtain a string that describes variable shadowing for the given variable. None if no shadowing exists. :param var: The variable to collect shadowing information for. :param contract: The contract in which this variable is being analyzed. :return: Returns a string describing variable shadowing fo...
['Obtain', 'a', 'string', 'that', 'describes', 'variable', 'shadowing', 'for', 'the', 'given', 'variable', '.', 'None', 'if', 'no', 'shadowing', 'exists', '.', ':', 'param', 'var', ':', 'The', 'variable', 'to', 'collect', 'shadowing', 'information', 'for', '.', ':', 'param', 'contract', ':', 'The', 'contract', 'in', 'w...
train
https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/inheritance/inheritance_graph.py#L82-L98
7,902
peterwittek/ncpol2sdpa
ncpol2sdpa/physics_utils.py
bosonic_constraints
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): ...
python
def bosonic_constraints(a): """Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions. """ substitutions = {} for i, ai in enumerate(a): ...
['def', 'bosonic_constraints', '(', 'a', ')', ':', 'substitutions', '=', '{', '}', 'for', 'i', ',', 'ai', 'in', 'enumerate', '(', 'a', ')', ':', 'substitutions', '[', 'ai', '*', 'Dagger', '(', 'ai', ')', ']', '=', '1.0', '+', 'Dagger', '(', 'ai', ')', '*', 'ai', 'for', 'aj', 'in', 'a', '[', 'i', '+', '1', ':', ']', ':'...
Return a set of constraints that define fermionic ladder operators. :param a: The non-Hermitian variables. :type a: list of :class:`sympy.physics.quantum.operator.Operator`. :returns: a dict of substitutions.
['Return', 'a', 'set', 'of', 'constraints', 'that', 'define', 'fermionic', 'ladder', 'operators', '.']
train
https://github.com/peterwittek/ncpol2sdpa/blob/bce75d524d0b9d0093f32e3a0a5611f8589351a7/ncpol2sdpa/physics_utils.py#L82-L99
7,903
scottjbarr/bitfinex
bitfinex/client.py
Client._convert_to_floats
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
python
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
['def', '_convert_to_floats', '(', 'self', ',', 'data', ')', ':', 'for', 'key', ',', 'value', 'in', 'data', '.', 'items', '(', ')', ':', 'data', '[', 'key', ']', '=', 'float', '(', 'value', ')', 'return', 'data']
Convert all values in a dict to floats
['Convert', 'all', 'values', 'in', 'a', 'dict', 'to', 'floats']
train
https://github.com/scottjbarr/bitfinex/blob/03f7c71615fe38c2e28be0ebb761d3106ef0a51a/bitfinex/client.py#L497-L504
7,904
hovren/crisp
crisp/camera.py
AtanCameraModel.invert
def invert(self, points): """Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points """ X = points if not points.ndim == 1 else points.r...
python
def invert(self, points): """Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points """ X = points if not points.ndim == 1 else points.r...
['def', 'invert', '(', 'self', ',', 'points', ')', ':', 'X', '=', 'points', 'if', 'not', 'points', '.', 'ndim', '==', '1', 'else', 'points', '.', 'reshape', '(', '(', 'points', '.', 'size', ',', '1', ')', ')', 'wx', ',', 'wy', '=', 'self', '.', 'wc', '# Switch to polar coordinates', 'rn', '=', 'np', '.', 'sqrt', '(', '...
Invert the distortion Parameters ------------------ points : ndarray Input image points Returns ----------------- ndarray Undistorted points
['Invert', 'the', 'distortion']
train
https://github.com/hovren/crisp/blob/65cae19e7cfae5a397859096c9ef666e0f4e7f1b/crisp/camera.py#L160-L187
7,905
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
AtisWorld._update_grammar
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
python
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
['def', '_update_grammar', '(', 'self', ')', ':', '# This will give us a shallow copy. We have to be careful here because the ``Grammar`` object', '# contains ``Expression`` objects that have tuples containing the members of that expression.', '# We have to create new sub-expression objects so that original grammar is ...
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we don't have to create a new grammar from...
['We', 'create', 'a', 'new', 'Grammar', 'object', 'from', 'the', 'one', 'in', 'AtisSqlTableContext', 'that', 'also', 'has', 'the', 'new', 'entities', 'that', 'are', 'extracted', 'from', 'the', 'utterance', '.', 'Stitching', 'together', 'the', 'expressions', 'to', 'form', 'the', 'grammar', 'is', 'a', 'little', 'tedious'...
train
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L83-L183
7,906
fracpete/python-weka-wrapper3
python/weka/core/typeconv.py
string_array_to_list
def string_array_to_list(a): """ Turns the Java string array into Python unicode string list. :param a: the string array to convert :type a: JB_Object :return: the string list :rtype: list """ result = [] length = javabridge.get_env().get_array_length(a) wrapped = javabridge.get...
python
def string_array_to_list(a): """ Turns the Java string array into Python unicode string list. :param a: the string array to convert :type a: JB_Object :return: the string list :rtype: list """ result = [] length = javabridge.get_env().get_array_length(a) wrapped = javabridge.get...
['def', 'string_array_to_list', '(', 'a', ')', ':', 'result', '=', '[', ']', 'length', '=', 'javabridge', '.', 'get_env', '(', ')', '.', 'get_array_length', '(', 'a', ')', 'wrapped', '=', 'javabridge', '.', 'get_env', '(', ')', '.', 'get_object_array_elements', '(', 'a', ')', 'for', 'i', 'in', 'range', '(', 'length', '...
Turns the Java string array into Python unicode string list. :param a: the string array to convert :type a: JB_Object :return: the string list :rtype: list
['Turns', 'the', 'Java', 'string', 'array', 'into', 'Python', 'unicode', 'string', 'list', '.']
train
https://github.com/fracpete/python-weka-wrapper3/blob/d850ab1bdb25fbd5a8d86e99f34a397975425838/python/weka/core/typeconv.py#L25-L39
7,907
matthew-brett/delocate
delocate/libsana.py
tree_libs
def tree_libs(start_path, filt_func=None): """ Return analysis of library dependencies within `start_path` Parameters ---------- start_path : str root path of tree to search for libraries depending on other libraries. filt_func : None or callable, optional If None, inspect all files...
python
def tree_libs(start_path, filt_func=None): """ Return analysis of library dependencies within `start_path` Parameters ---------- start_path : str root path of tree to search for libraries depending on other libraries. filt_func : None or callable, optional If None, inspect all files...
['def', 'tree_libs', '(', 'start_path', ',', 'filt_func', '=', 'None', ')', ':', 'lib_dict', '=', '{', '}', 'for', 'dirpath', ',', 'dirnames', ',', 'basenames', 'in', 'os', '.', 'walk', '(', 'start_path', ')', ':', 'for', 'base', 'in', 'basenames', ':', 'depending_libpath', '=', 'realpath', '(', 'pjoin', '(', 'dirpath'...
Return analysis of library dependencies within `start_path` Parameters ---------- start_path : str root path of tree to search for libraries depending on other libraries. filt_func : None or callable, optional If None, inspect all files for library dependencies. If callable, acc...
['Return', 'analysis', 'of', 'library', 'dependencies', 'within', 'start_path']
train
https://github.com/matthew-brett/delocate/blob/ed48de15fce31c3f52f1a9f32cae1b02fc55aa60/delocate/libsana.py#L14-L65
7,908
jorisroovers/gitlint
gitlint/cli.py
build_config
def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug): """ Creates a LintConfig object based on a set of commandline parameters. """ config_builder = LintConfigBuilder() try: # Config precedence: # First, load default config or config from configfile ...
python
def build_config(ctx, target, config_path, c, extra_path, ignore, verbose, silent, debug): """ Creates a LintConfig object based on a set of commandline parameters. """ config_builder = LintConfigBuilder() try: # Config precedence: # First, load default config or config from configfile ...
['def', 'build_config', '(', 'ctx', ',', 'target', ',', 'config_path', ',', 'c', ',', 'extra_path', ',', 'ignore', ',', 'verbose', ',', 'silent', ',', 'debug', ')', ':', 'config_builder', '=', 'LintConfigBuilder', '(', ')', 'try', ':', '# Config precedence:', '# First, load default config or config from configfile', 'i...
Creates a LintConfig object based on a set of commandline parameters.
['Creates', 'a', 'LintConfig', 'object', 'based', 'on', 'a', 'set', 'of', 'commandline', 'parameters', '.']
train
https://github.com/jorisroovers/gitlint/blob/6248bd6cbc20c1be3bb6d196a5ec0425af99733b/gitlint/cli.py#L57-L93
7,909
lord63/tldr.py
tldr/cli.py
parse_man_page
def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
python
def parse_man_page(command, platform): """Parse the man page and return the parsed lines.""" page_path = find_page_location(command, platform) output_lines = parse_page(page_path) return output_lines
['def', 'parse_man_page', '(', 'command', ',', 'platform', ')', ':', 'page_path', '=', 'find_page_location', '(', 'command', ',', 'platform', ')', 'output_lines', '=', 'parse_page', '(', 'page_path', ')', 'return', 'output_lines']
Parse the man page and return the parsed lines.
['Parse', 'the', 'man', 'page', 'and', 'return', 'the', 'parsed', 'lines', '.']
train
https://github.com/lord63/tldr.py/blob/73cf9f86254691b2476910ea6a743b6d8bd04963/tldr/cli.py#L22-L26
7,910
jsommers/switchyard
switchyard/lib/topo/util.py
unhumanize_bandwidth
def unhumanize_bandwidth(bitsstr): ''' Take a string representing a link capacity, e.g., 10 Mb/s, and return an integer representing the number of bits/sec. Recognizes: - 'bits/sec' or 'b/s' are treated as plain bits per second - 'Kb' or 'kb' as thousand bits/sec - 'Mb' or 'mb' a...
python
def unhumanize_bandwidth(bitsstr): ''' Take a string representing a link capacity, e.g., 10 Mb/s, and return an integer representing the number of bits/sec. Recognizes: - 'bits/sec' or 'b/s' are treated as plain bits per second - 'Kb' or 'kb' as thousand bits/sec - 'Mb' or 'mb' a...
['def', 'unhumanize_bandwidth', '(', 'bitsstr', ')', ':', 'if', 'isinstance', '(', 'bitsstr', ',', 'int', ')', ':', 'return', 'bitsstr', 'mobj', '=', 're', '.', 'match', '(', "'^\\s*([\\d\\.]+)\\s*(.*)\\s*$'", ',', 'bitsstr', ')', 'if', 'not', 'mobj', ':', 'return', 'None', 'value', ',', 'units', '=', 'mobj', '.', 'gro...
Take a string representing a link capacity, e.g., 10 Mb/s, and return an integer representing the number of bits/sec. Recognizes: - 'bits/sec' or 'b/s' are treated as plain bits per second - 'Kb' or 'kb' as thousand bits/sec - 'Mb' or 'mb' as million bits/sec - 'Gb' or 'gb' as bi...
['Take', 'a', 'string', 'representing', 'a', 'link', 'capacity', 'e', '.', 'g', '.', '10', 'Mb', '/', 's', 'and', 'return', 'an', 'integer', 'representing', 'the', 'number', 'of', 'bits', '/', 'sec', '.', 'Recognizes', ':', '-', 'bits', '/', 'sec', 'or', 'b', '/', 's', 'are', 'treated', 'as', 'plain', 'bits', 'per', 's...
train
https://github.com/jsommers/switchyard/blob/fdcb3869c937dcedbd6ea7a7822ebd412bf1e2b0/switchyard/lib/topo/util.py#L40-L72
7,911
drslump/pyshould
pyshould/expectation.py
Expectation._assertion
def _assertion(self, matcher, value): """ Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError. """ # To support the synt...
python
def _assertion(self, matcher, value): """ Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError. """ # To support the synt...
['def', '_assertion', '(', 'self', ',', 'matcher', ',', 'value', ')', ':', '# To support the syntax `any_of(subject) | should ...` we check if the', '# value to check is an Expectation object and if it is we use the descriptor', "# protocol to bind the value's assertion logic to this expectation.", 'if', 'isinstance', ...
Perform the actual assertion for the given matcher and value. Override this method to apply a special configuration when performing the assertion. If the assertion fails it should raise an AssertionError.
['Perform', 'the', 'actual', 'assertion', 'for', 'the', 'given', 'matcher', 'and', 'value', '.', 'Override', 'this', 'method', 'to', 'apply', 'a', 'special', 'configuration', 'when', 'performing', 'the', 'assertion', '.', 'If', 'the', 'assertion', 'fails', 'it', 'should', 'raise', 'an', 'AssertionError', '.']
train
https://github.com/drslump/pyshould/blob/7210859d4c84cfbaa64f91b30c2a541aea788ddf/pyshould/expectation.py#L102-L114
7,912
jaredLunde/vital-tools
vital/security/__init__.py
aes_b64_encrypt
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
python
def aes_b64_encrypt(value, secret, block_size=AES.block_size): """ AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt ...
['def', 'aes_b64_encrypt', '(', 'value', ',', 'secret', ',', 'block_size', '=', 'AES', '.', 'block_size', ')', ':', '# iv = randstr(block_size * 2, rng=random)', 'iv', '=', 'randstr', '(', 'block_size', '*', '2', ')', 'cipher', '=', 'AES', '.', 'new', '(', 'secret', '[', ':', '32', ']', ',', 'AES', '.', 'MODE_CFB', ','...
AES encrypt @value with @secret using the |CFB| mode of AES with a cryptographically secure initialization vector. -> (#str) AES encrypted @value .. from vital.security import aes_encrypt, aes_decrypt aes_encrypt("Hello, world", "aLWEFlwgwlreWELF...
['AES', 'encrypt', '@value', 'with', '@secret', 'using', 'the', '|CFB|', 'mode', 'of', 'AES', 'with', 'a', 'cryptographically', 'secure', 'initialization', 'vector', '.']
train
https://github.com/jaredLunde/vital-tools/blob/ea924c9bbb6ec22aa66f8095f018b1ee0099ac04/vital/security/__init__.py#L31-L52
7,913
lrq3000/pyFileFixity
pyFileFixity/lib/gooey/gui/components.py
Counter.GetValue
def GetValue(self): ''' NOTE: Added on plane. Cannot remember exact implementation of counter objects. I believe that they count sequentail pairings of options e.g. -vvvvv But I'm not sure. That's what I'm going with for now. Returns str(action.options_string[0]) * DropDown Valu...
python
def GetValue(self): ''' NOTE: Added on plane. Cannot remember exact implementation of counter objects. I believe that they count sequentail pairings of options e.g. -vvvvv But I'm not sure. That's what I'm going with for now. Returns str(action.options_string[0]) * DropDown Valu...
['def', 'GetValue', '(', 'self', ')', ':', 'dropdown_value', '=', 'self', '.', '_widget', '.', 'GetValue', '(', ')', 'if', 'not', 'str', '(', 'dropdown_value', ')', '.', 'isdigit', '(', ')', ':', 'return', 'None', 'arg', '=', 'str', '(', 'self', '.', '_action', '.', 'option_strings', '[', '0', ']', ')', '.', 'replace',...
NOTE: Added on plane. Cannot remember exact implementation of counter objects. I believe that they count sequentail pairings of options e.g. -vvvvv But I'm not sure. That's what I'm going with for now. Returns str(action.options_string[0]) * DropDown Value
['NOTE', ':', 'Added', 'on', 'plane', '.', 'Cannot', 'remember', 'exact', 'implementation', 'of', 'counter', 'objects', '.', 'I', 'believe', 'that', 'they', 'count', 'sequentail', 'pairings', 'of', 'options', 'e', '.', 'g', '.', '-', 'vvvvv', 'But', 'I', 'm', 'not', 'sure', '.', 'That', 's', 'what', 'I', 'm', 'going', ...
train
https://github.com/lrq3000/pyFileFixity/blob/fd5ef23bb13835faf1e3baa773619b86a1cc9bdf/pyFileFixity/lib/gooey/gui/components.py#L429-L446
7,914
pazz/alot
alot/db/utils.py
add_signature_headers
def add_signature_headers(mail, sigs, error_msg): '''Add pseudo headers to the mail indicating whether the signature verification was successful. :param mail: :class:`email.message.Message` the message to entitle :param sigs: list of :class:`gpg.results.Signature` :param error_msg: An error message...
python
def add_signature_headers(mail, sigs, error_msg): '''Add pseudo headers to the mail indicating whether the signature verification was successful. :param mail: :class:`email.message.Message` the message to entitle :param sigs: list of :class:`gpg.results.Signature` :param error_msg: An error message...
['def', 'add_signature_headers', '(', 'mail', ',', 'sigs', ',', 'error_msg', ')', ':', 'sig_from', '=', "''", 'sig_known', '=', 'True', 'uid_trusted', '=', 'False', 'assert', 'error_msg', 'is', 'None', 'or', 'isinstance', '(', 'error_msg', ',', 'str', ')', 'if', 'not', 'sigs', ':', 'error_msg', '=', 'error_msg', 'or', ...
Add pseudo headers to the mail indicating whether the signature verification was successful. :param mail: :class:`email.message.Message` the message to entitle :param sigs: list of :class:`gpg.results.Signature` :param error_msg: An error message if there is one, or None :type error_msg: :class:`st...
['Add', 'pseudo', 'headers', 'to', 'the', 'mail', 'indicating', 'whether', 'the', 'signature', 'verification', 'was', 'successful', '.']
train
https://github.com/pazz/alot/blob/d0297605c0ec1c6b65f541d0fd5b69ac5a0f4ded/alot/db/utils.py#L38-L79
7,915
vijaykatam/django-cache-manager
django_cache_manager/mixins.py
CacheInvalidateMixin.invalidate_model_cache
def invalidate_model_cache(self): """ Invalidate model cache by generating new key for the model. """ logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model....
python
def invalidate_model_cache(self): """ Invalidate model cache by generating new key for the model. """ logger.info('Invalidating cache for table {0}'.format(self.model._meta.db_table)) if django.VERSION >= (1, 8): related_tables = set( [f.related_model....
['def', 'invalidate_model_cache', '(', 'self', ')', ':', 'logger', '.', 'info', '(', "'Invalidating cache for table {0}'", '.', 'format', '(', 'self', '.', 'model', '.', '_meta', '.', 'db_table', ')', ')', 'if', 'django', '.', 'VERSION', '>=', '(', '1', ',', '8', ')', ':', 'related_tables', '=', 'set', '(', '[', 'f', '...
Invalidate model cache by generating new key for the model.
['Invalidate', 'model', 'cache', 'by', 'generating', 'new', 'key', 'for', 'the', 'model', '.']
train
https://github.com/vijaykatam/django-cache-manager/blob/05142c44eb349d3f24f962592945888d9d367375/django_cache_manager/mixins.py#L66-L84
7,916
SoftwareDefinedBuildings/XBOS
apps/Data_quality_analysis/Wrapper.py
Wrapper.clean_data
def clean_data(self, data, rename_col=None, drop_col=None, resample=True, freq='h', resampler='mean', interpolate=True, limit=1, method='linear', remove_na=True, remove_na_how='any', remove_outliers=True, sd_val=3, remov...
python
def clean_data(self, data, rename_col=None, drop_col=None, resample=True, freq='h', resampler='mean', interpolate=True, limit=1, method='linear', remove_na=True, remove_na_how='any', remove_outliers=True, sd_val=3, remov...
['def', 'clean_data', '(', 'self', ',', 'data', ',', 'rename_col', '=', 'None', ',', 'drop_col', '=', 'None', ',', 'resample', '=', 'True', ',', 'freq', '=', "'h'", ',', 'resampler', '=', "'mean'", ',', 'interpolate', '=', 'True', ',', 'limit', '=', '1', ',', 'method', '=', "'linear'", ',', 'remove_na', '=', 'True', ',...
Cleans dataframe according to user specifications and stores result in self.cleaned_data. Parameters ---------- data : pd.DataFrame() Dataframe to be cleaned. rename_col : list(str) List of new column names. drop_col ...
['Cleans', 'dataframe', 'according', 'to', 'user', 'specifications', 'and', 'stores', 'result', 'in', 'self', '.', 'cleaned_data', '.']
train
https://github.com/SoftwareDefinedBuildings/XBOS/blob/c12d4fb14518ea3ae98c471c28e0710fdf74dd25/apps/Data_quality_analysis/Wrapper.py#L439-L543
7,917
hobson/pug-dj
pug/dj/miner/management/commands/modeldb.py
Command.normalize_col_name
def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.app...
python
def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.app...
['def', 'normalize_col_name', '(', 'self', ',', 'col_name', ',', 'used_column_names', ',', 'is_relation', ')', ':', 'field_params', '=', '{', '}', 'field_notes', '=', '[', ']', 'new_name', '=', 'col_name', '.', 'lower', '(', ')', 'if', 'new_name', '!=', 'col_name', ':', 'field_notes', '.', 'append', '(', "'Field name m...
Modify the column name to make it Python-compatible as a field name
['Modify', 'the', 'column', 'name', 'to', 'make', 'it', 'Python', '-', 'compatible', 'as', 'a', 'field', 'name']
train
https://github.com/hobson/pug-dj/blob/55678b08755a55366ce18e7d3b8ea8fa4491ab04/pug/dj/miner/management/commands/modeldb.py#L129-L183
7,918
ucsb-cs/submit
submit/models.py
User.classes_can_admin
def classes_can_admin(self): """Return all the classes (sorted) that this user can admin.""" if self.is_admin: return sorted(Session.query(Class).all()) else: return sorted(self.admin_for)
python
def classes_can_admin(self): """Return all the classes (sorted) that this user can admin.""" if self.is_admin: return sorted(Session.query(Class).all()) else: return sorted(self.admin_for)
['def', 'classes_can_admin', '(', 'self', ')', ':', 'if', 'self', '.', 'is_admin', ':', 'return', 'sorted', '(', 'Session', '.', 'query', '(', 'Class', ')', '.', 'all', '(', ')', ')', 'else', ':', 'return', 'sorted', '(', 'self', '.', 'admin_for', ')']
Return all the classes (sorted) that this user can admin.
['Return', 'all', 'the', 'classes', '(', 'sorted', ')', 'that', 'this', 'user', 'can', 'admin', '.']
train
https://github.com/ucsb-cs/submit/blob/92810c81255a4fc6bbebac1ac8aae856fd576ffe/submit/models.py#L965-L970
7,919
PSPC-SPAC-buyandsell/von_agent
von_agent/agent/issuer.py
Issuer.send_cred_def
async def send_cred_def(self, s_id: str, revocation: bool = True, rr_size: int = None) -> str: """ Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to sen...
python
async def send_cred_def(self, s_id: str, revocation: bool = True, rr_size: int = None) -> str: """ Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to sen...
['async', 'def', 'send_cred_def', '(', 'self', ',', 's_id', ':', 'str', ',', 'revocation', ':', 'bool', '=', 'True', ',', 'rr_size', ':', 'int', '=', 'None', ')', '->', 'str', ':', 'LOGGER', '.', 'debug', '(', "'Issuer.send_cred_def >>> s_id: %s, revocation: %s, rr_size: %s'", ',', 's_id', ',', 'revocation', ',', 'rr_s...
Create a credential definition as Issuer, store it in its wallet, and send it to the ledger. Raise CorruptWallet for wallet not pertaining to current ledger, BadLedgerTxn on failure to send credential definition to ledger if need be, or IndyError for any other failure to create and store creden...
['Create', 'a', 'credential', 'definition', 'as', 'Issuer', 'store', 'it', 'in', 'its', 'wallet', 'and', 'send', 'it', 'to', 'the', 'ledger', '.']
train
https://github.com/PSPC-SPAC-buyandsell/von_agent/blob/0b1c17cca3bd178b6e6974af84dbac1dfce5cf45/von_agent/agent/issuer.py#L190-L275
7,920
log2timeline/dfvfs
dfvfs/encryption/aes_decrypter.py
AESDecrypter.Decrypt
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encr...
python
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % AES.block_size) if index_split: remaining_encr...
['def', 'Decrypt', '(', 'self', ',', 'encrypted_data', ')', ':', 'index_split', '=', '-', '(', 'len', '(', 'encrypted_data', ')', '%', 'AES', '.', 'block_size', ')', 'if', 'index_split', ':', 'remaining_encrypted_data', '=', 'encrypted_data', '[', 'index_split', ':', ']', 'encrypted_data', '=', 'encrypted_data', '[', '...
Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes, bytes]: decrypted data and remaining encrypted data.
['Decrypts', 'the', 'encrypted', 'data', '.']
train
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/encryption/aes_decrypter.py#L57-L75
7,921
twilio/twilio-python
twilio/rest/video/v1/composition_hook.py
CompositionHookList.list
def list(self, enabled=values.unset, date_created_after=values.unset, date_created_before=values.unset, friendly_name=values.unset, limit=None, page_size=None): """ Lists CompositionHookInstance records from the API as a list. Unlike stream(), this operation is eager an...
python
def list(self, enabled=values.unset, date_created_after=values.unset, date_created_before=values.unset, friendly_name=values.unset, limit=None, page_size=None): """ Lists CompositionHookInstance records from the API as a list. Unlike stream(), this operation is eager an...
['def', 'list', '(', 'self', ',', 'enabled', '=', 'values', '.', 'unset', ',', 'date_created_after', '=', 'values', '.', 'unset', ',', 'date_created_before', '=', 'values', '.', 'unset', ',', 'friendly_name', '=', 'values', '.', 'unset', ',', 'limit', '=', 'None', ',', 'page_size', '=', 'None', ')', ':', 'return', 'lis...
Lists CompositionHookInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param bool enabled: Only show Composition Hooks enabled or disabled. :param datetime date_created_after: Only show Composit...
['Lists', 'CompositionHookInstance', 'records', 'from', 'the', 'API', 'as', 'a', 'list', '.', 'Unlike', 'stream', '()', 'this', 'operation', 'is', 'eager', 'and', 'will', 'load', 'limit', 'records', 'into', 'memory', 'before', 'returning', '.']
train
https://github.com/twilio/twilio-python/blob/c867895f55dcc29f522e6e8b8868d0d18483132f/twilio/rest/video/v1/composition_hook.py#L73-L102
7,922
mitsei/dlkit
dlkit/services/learning.py
ObjectiveBank.use_isolated_objective_bank_view
def use_isolated_objective_bank_view(self): """Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view""" self._objective_bank_view = ISOLATED # self._get_provider_session('objective_lookup_session') # To make sure the session is tracked for session in self._get_...
python
def use_isolated_objective_bank_view(self): """Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view""" self._objective_bank_view = ISOLATED # self._get_provider_session('objective_lookup_session') # To make sure the session is tracked for session in self._get_...
['def', 'use_isolated_objective_bank_view', '(', 'self', ')', ':', 'self', '.', '_objective_bank_view', '=', 'ISOLATED', "# self._get_provider_session('objective_lookup_session') # To make sure the session is tracked", 'for', 'session', 'in', 'self', '.', '_get_provider_sessions', '(', ')', ':', 'try', ':', 'session', ...
Pass through to provider ObjectiveLookupSession.use_isolated_objective_bank_view
['Pass', 'through', 'to', 'provider', 'ObjectiveLookupSession', '.', 'use_isolated_objective_bank_view']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/services/learning.py#L1575-L1583
7,923
spacetelescope/drizzlepac
drizzlepac/adrizzle.py
do_driz
def do_driz(insci, input_wcs, inwht, output_wcs, outsci, outwht, outcon, expin, in_units, wt_scl, wcslin_pscale=1.0,uniqid=1, pixfrac=1.0, kernel='square', fillval="INDEF", stepsize=10,wcsmap=None): """ Core routine for performing 'drizzle' operation on a single i...
python
def do_driz(insci, input_wcs, inwht, output_wcs, outsci, outwht, outcon, expin, in_units, wt_scl, wcslin_pscale=1.0,uniqid=1, pixfrac=1.0, kernel='square', fillval="INDEF", stepsize=10,wcsmap=None): """ Core routine for performing 'drizzle' operation on a single i...
['def', 'do_driz', '(', 'insci', ',', 'input_wcs', ',', 'inwht', ',', 'output_wcs', ',', 'outsci', ',', 'outwht', ',', 'outcon', ',', 'expin', ',', 'in_units', ',', 'wt_scl', ',', 'wcslin_pscale', '=', '1.0', ',', 'uniqid', '=', '1', ',', 'pixfrac', '=', '1.0', ',', 'kernel', '=', "'square'", ',', 'fillval', '=', '"IND...
Core routine for performing 'drizzle' operation on a single input image All input values will be Python objects such as ndarrays, instead of filenames. File handling (input and output) will be performed by calling routine.
['Core', 'routine', 'for', 'performing', 'drizzle', 'operation', 'on', 'a', 'single', 'input', 'image', 'All', 'input', 'values', 'will', 'be', 'Python', 'objects', 'such', 'as', 'ndarrays', 'instead', 'of', 'filenames', '.', 'File', 'handling', '(', 'input', 'and', 'output', ')', 'will', 'be', 'performed', 'by', 'call...
train
https://github.com/spacetelescope/drizzlepac/blob/15bec3c929a6a869d9e71b9398ced43ede0620f1/drizzlepac/adrizzle.py#L1011-L1101
7,924
scot-dev/scot
scot/xvschema.py
singletrial
def singletrial(num_trials, skipstep=1): """ Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns -----...
python
def singletrial(num_trials, skipstep=1): """ Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns -----...
['def', 'singletrial', '(', 'num_trials', ',', 'skipstep', '=', '1', ')', ':', 'for', 't', 'in', 'range', '(', '0', ',', 'num_trials', ',', 'skipstep', ')', ':', 'trainset', '=', '[', 't', ']', 'testset', '=', '[', 'i', 'for', 'i', 'in', 'range', '(', 'trainset', '[', '0', ']', ')', ']', '+', '[', 'i', 'for', 'i', 'in'...
Single-trial cross-validation schema Use one trial for training, all others for testing. Parameters ---------- num_trials : int Total number of trials skipstep : int only use every `skipstep` trial for training Returns ------- gen : generator object the generat...
['Single', '-', 'trial', 'cross', '-', 'validation', 'schema']
train
https://github.com/scot-dev/scot/blob/48598b79d4400dad893b134cd2194715511facda/scot/xvschema.py#L14-L36
7,925
lemieuxl/pyGenClean
pyGenClean/run_data_clean_up.py
run_duplicated_snps
def run_duplicated_snps(in_prefix, in_type, out_prefix, base_dir, options): """Runs step2 (duplicated snps). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options:...
python
def run_duplicated_snps(in_prefix, in_type, out_prefix, base_dir, options): """Runs step2 (duplicated snps). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options:...
['def', 'run_duplicated_snps', '(', 'in_prefix', ',', 'in_type', ',', 'out_prefix', ',', 'base_dir', ',', 'options', ')', ':', '# Creating the output directory', 'os', '.', 'mkdir', '(', 'out_prefix', ')', '# We know we need a tfile', 'required_type', '=', '"tfile"', 'check_input_files', '(', 'in_prefix', ',', 'in_type...
Runs step2 (duplicated snps). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :type in_prefix: str :type in_type: str :type out...
['Runs', 'step2', '(', 'duplicated', 'snps', ')', '.']
train
https://github.com/lemieuxl/pyGenClean/blob/6173a48ccc0cf3a3bd711b1f2a1fa16248b8bf55/pyGenClean/run_data_clean_up.py#L496-L731
7,926
djgagne/hagelslag
hagelslag/processing/STObject.py
STObject.get_corner
def get_corner(self, time): """ Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner inde...
python
def get_corner(self, time): """ Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner inde...
['def', 'get_corner', '(', 'self', ',', 'time', ')', ':', 'if', 'self', '.', 'start_time', '<=', 'time', '<=', 'self', '.', 'end_time', ':', 'diff', '=', 'time', '-', 'self', '.', 'start_time', 'return', 'self', '.', 'i', '[', 'diff', ']', '[', '0', ',', '0', ']', ',', 'self', '.', 'j', '[', 'diff', ']', '[', '0', ',',...
Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner index.
['Gets', 'the', 'corner', 'array', 'indices', 'of', 'the', 'STObject', 'at', 'a', 'given', 'time', 'that', 'corresponds', 'to', 'the', 'upper', 'left', 'corner', 'of', 'the', 'bounding', 'box', 'for', 'the', 'STObject', '.']
train
https://github.com/djgagne/hagelslag/blob/6fb6c3df90bf4867e13a97d3460b14471d107df1/hagelslag/processing/STObject.py#L155-L170
7,927
mitsei/dlkit
dlkit/aws_adapter/repository/sessions.py
AssetCompositionDesignSession.order_assets
def order_assets(self, asset_ids, composition_id): """Reorders a set of assets in a composition. arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of ``Assets`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``comp...
python
def order_assets(self, asset_ids, composition_id): """Reorders a set of assets in a composition. arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of ``Assets`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``comp...
['def', 'order_assets', '(', 'self', ',', 'asset_ids', ',', 'composition_id', ')', ':', 'self', '.', '_provider_session', '.', 'order_assets', '(', 'self', ',', 'asset_ids', ',', 'composition_id', ')']
Reorders a set of assets in a composition. arg: asset_ids (osid.id.Id[]): ``Ids`` for a set of ``Assets`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` raise: NotFound - ``composition_id`` not found or, an ``asset_id`` not...
['Reorders', 'a', 'set', 'of', 'assets', 'in', 'a', 'composition', '.']
train
https://github.com/mitsei/dlkit/blob/445f968a175d61c8d92c0f617a3c17dc1dc7c584/dlkit/aws_adapter/repository/sessions.py#L2097-L2113
7,928
PyHDI/Pyverilog
pyverilog/vparser/parser.py
VerilogParser.p_ioport_head
def p_ioport_head(self, p): 'ioport_head : sigtypes portname' p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2)) p.set_lineno(0, p.lineno(1))
python
def p_ioport_head(self, p): 'ioport_head : sigtypes portname' p[0] = self.create_ioport(p[1], p[2], lineno=p.lineno(2)) p.set_lineno(0, p.lineno(1))
['def', 'p_ioport_head', '(', 'self', ',', 'p', ')', ':', 'p', '[', '0', ']', '=', 'self', '.', 'create_ioport', '(', 'p', '[', '1', ']', ',', 'p', '[', '2', ']', ',', 'lineno', '=', 'p', '.', 'lineno', '(', '2', ')', ')', 'p', '.', 'set_lineno', '(', '0', ',', 'p', '.', 'lineno', '(', '1', ')', ')']
ioport_head : sigtypes portname
['ioport_head', ':', 'sigtypes', 'portname']
train
https://github.com/PyHDI/Pyverilog/blob/b852cc5ed6a7a2712e33639f9d9782d0d1587a53/pyverilog/vparser/parser.py#L418-L421
7,929
openego/ding0
ding0/core/network/__init__.py
RingDing0.lv_load_areas
def lv_load_areas(self): """ #TODO: description """ for lv_load_area in self._grid._graph.nodes(): if isinstance(lv_load_area, LVLoadAreaDing0): if lv_load_area.ring == self: yield lv_load_area
python
def lv_load_areas(self): """ #TODO: description """ for lv_load_area in self._grid._graph.nodes(): if isinstance(lv_load_area, LVLoadAreaDing0): if lv_load_area.ring == self: yield lv_load_area
['def', 'lv_load_areas', '(', 'self', ')', ':', 'for', 'lv_load_area', 'in', 'self', '.', '_grid', '.', '_graph', '.', 'nodes', '(', ')', ':', 'if', 'isinstance', '(', 'lv_load_area', ',', 'LVLoadAreaDing0', ')', ':', 'if', 'lv_load_area', '.', 'ring', '==', 'self', ':', 'yield', 'lv_load_area']
#TODO: description
['#TODO', ':', 'description']
train
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/network/__init__.py#L534-L540
7,930
siznax/wptools
wptools/wikidata.py
WPToolsWikidata._query
def _query(self, action, qobj): """ returns wikidata query string """ if action == 'labels': return qobj.labels(self._pop_entities()) elif action == 'wikidata': return qobj.wikidata(self.params.get('title'), self.params.get...
python
def _query(self, action, qobj): """ returns wikidata query string """ if action == 'labels': return qobj.labels(self._pop_entities()) elif action == 'wikidata': return qobj.wikidata(self.params.get('title'), self.params.get...
['def', '_query', '(', 'self', ',', 'action', ',', 'qobj', ')', ':', 'if', 'action', '==', "'labels'", ':', 'return', 'qobj', '.', 'labels', '(', 'self', '.', '_pop_entities', '(', ')', ')', 'elif', 'action', '==', "'wikidata'", ':', 'return', 'qobj', '.', 'wikidata', '(', 'self', '.', 'params', '.', 'get', '(', "'titl...
returns wikidata query string
['returns', 'wikidata', 'query', 'string']
train
https://github.com/siznax/wptools/blob/100eaea585c34aa9ad87a9eda8982bb4898f6ec9/wptools/wikidata.py#L103-L111
7,931
portantier/habu
habu/cli/cmd_shodan_open.py
cmd_shodan_open
def cmd_shodan_open(ip, no_cache, json_output, nmap_command, verbose, output): """Output the open ports for an IP against shodan (nmap format). Example: \b $ habu.shodan.open 8.8.8.8 T:53,U:53 """ habucfg = loadcfg() if 'SHODAN_APIKEY' not in habucfg: print('You must provide ...
python
def cmd_shodan_open(ip, no_cache, json_output, nmap_command, verbose, output): """Output the open ports for an IP against shodan (nmap format). Example: \b $ habu.shodan.open 8.8.8.8 T:53,U:53 """ habucfg = loadcfg() if 'SHODAN_APIKEY' not in habucfg: print('You must provide ...
['def', 'cmd_shodan_open', '(', 'ip', ',', 'no_cache', ',', 'json_output', ',', 'nmap_command', ',', 'verbose', ',', 'output', ')', ':', 'habucfg', '=', 'loadcfg', '(', ')', 'if', "'SHODAN_APIKEY'", 'not', 'in', 'habucfg', ':', 'print', '(', "'You must provide a shodan apikey. Use the ~/.habu.json file (variable SHODAN...
Output the open ports for an IP against shodan (nmap format). Example: \b $ habu.shodan.open 8.8.8.8 T:53,U:53
['Output', 'the', 'open', 'ports', 'for', 'an', 'IP', 'against', 'shodan', '(', 'nmap', 'format', ')', '.']
train
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_shodan_open.py#L22-L60
7,932
noahbenson/neuropythy
neuropythy/optimize/core.py
to_potential
def to_potential(f): ''' to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to a potential function, that conversion is performed then the result is yielded. to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the ide...
python
def to_potential(f): ''' to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to a potential function, that conversion is performed then the result is yielded. to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the ide...
['def', 'to_potential', '(', 'f', ')', ':', 'if', 'is_potential', '(', 'f', ')', ':', 'return', 'f', 'elif', 'f', 'is', 'Ellipsis', ':', 'return', 'identity', 'elif', 'pimms', '.', 'is_array', '(', 'f', ',', "'number'", ')', ':', 'return', 'const_potential', '(', 'f', ')', 'elif', 'isinstance', '(', 'f', ',', 'tuple', ...
to_potential(f) yields f if f is a potential function; if f is not, but f can be converted to a potential function, that conversion is performed then the result is yielded. to_potential(Ellipsis) yields a potential function whose output is simply its input (i.e., the identity function). to_potential...
['to_potential', '(', 'f', ')', 'yields', 'f', 'if', 'f', 'is', 'a', 'potential', 'function', ';', 'if', 'f', 'is', 'not', 'but', 'f', 'can', 'be', 'converted', 'to', 'a', 'potential', 'function', 'that', 'conversion', 'is', 'performed', 'then', 'the', 'result', 'is', 'yielded', '.', 'to_potential', '(', 'Ellipsis', ')...
train
https://github.com/noahbenson/neuropythy/blob/b588889f6db36ddb9602ae4a72c1c0d3f41586b2/neuropythy/optimize/core.py#L293-L310
7,933
lyft/python-kmsauth
kmsauth/__init__.py
KMSTokenValidator._get_key_alias_from_cache
def _get_key_alias_from_cache(self, key_arn): ''' Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked u...
python
def _get_key_alias_from_cache(self, key_arn): ''' Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked u...
['def', '_get_key_alias_from_cache', '(', 'self', ',', 'key_arn', ')', ':', 'for', 'alias', 'in', 'self', '.', 'KEY_METADATA', ':', 'if', 'self', '.', 'KEY_METADATA', '[', 'alias', ']', '[', "'KeyMetadata'", ']', '[', "'Arn'", ']', '==', 'key_arn', ':', 'return', 'alias', 'return', 'None']
Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked up back into its alias.
['Find', 'a', 'key', 's', 'alias', 'by', 'looking', 'up', 'its', 'key_arn', 'in', 'the', 'KEY_METADATA', 'cache', '.', 'This', 'function', 'will', 'only', 'work', 'after', 'a', 'key', 'has', 'been', 'lookedup', 'by', 'its', 'alias', 'and', 'is', 'meant', 'as', 'a', 'convenience', 'function', 'for', 'turning', 'an', 'AR...
train
https://github.com/lyft/python-kmsauth/blob/aa2dd957a5d3e58c89fe51a55c6053ff81d9191e/kmsauth/__init__.py#L156-L166
7,934
4Kaylum/Brickfront
brickfront/client.py
Client.getSet
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no ...
python
def getSet(self, setID): ''' Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no ...
['def', 'getSet', '(', 'self', ',', 'setID', ')', ':', 'params', '=', '{', "'apiKey'", ':', 'self', '.', 'apiKey', ',', "'userHash'", ':', 'self', '.', 'userHash', ',', "'setID'", ':', 'setID', '}', 'url', '=', 'Client', '.', 'ENDPOINT', '.', 'format', '(', "'getSet'", ')', 'returned', '=', 'get', '(', 'url', ',', 'par...
Gets the information of one specific build using its Brickset set ID. :param str setID: The ID of the build from Brickset. :returns: A single Build object. :rtype: :class:`brickfront.build.Build` :raises brickfront.errors.InvalidSetID: If no sets exist by that ID.
['Gets', 'the', 'information', 'of', 'one', 'specific', 'build', 'using', 'its', 'Brickset', 'set', 'ID', '.']
train
https://github.com/4Kaylum/Brickfront/blob/9545f2183249862b077677d48fcfb9b4bfe1f87d/brickfront/client.py#L144-L171
7,935
quantopian/zipline
zipline/utils/paths.py
zipline_root
def zipline_root(environ=None): """ Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns -...
python
def zipline_root(environ=None): """ Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns -...
['def', 'zipline_root', '(', 'environ', '=', 'None', ')', ':', 'if', 'environ', 'is', 'None', ':', 'environ', '=', 'os', '.', 'environ', 'root', '=', 'environ', '.', 'get', '(', "'ZIPLINE_ROOT'", ',', 'None', ')', 'if', 'root', 'is', 'None', ':', 'root', '=', 'expanduser', '(', "'~/.zipline'", ')', 'return', 'root']
Get the root directory for all zipline-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns ------- root : string Path to the...
['Get', 'the', 'root', 'directory', 'for', 'all', 'zipline', '-', 'managed', 'files', '.']
train
https://github.com/quantopian/zipline/blob/77ad15e6dc4c1cbcdc133653bac8a63fc704f7fe/zipline/utils/paths.py#L107-L131
7,936
iotile/coretools
iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslib.py
generate
def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('...
python
def generate(env): """Add Builders and construction variables for lib to an Environment.""" SCons.Tool.createStaticLibBuilder(env) # Set-up ms tools paths msvc_setup_env_once(env) env['AR'] = 'lib' env['ARFLAGS'] = SCons.Util.CLVar('/nologo') env['ARCOM'] = "${TEMPFILE('...
['def', 'generate', '(', 'env', ')', ':', 'SCons', '.', 'Tool', '.', 'createStaticLibBuilder', '(', 'env', ')', '# Set-up ms tools paths', 'msvc_setup_env_once', '(', 'env', ')', 'env', '[', "'AR'", ']', '=', "'lib'", 'env', '[', "'ARFLAGS'", ']', '=', 'SCons', '.', 'Util', '.', 'CLVar', '(', "'/nologo'", ')', 'env', '...
Add Builders and construction variables for lib to an Environment.
['Add', 'Builders', 'and', 'construction', 'variables', 'for', 'lib', 'to', 'an', 'Environment', '.']
train
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/config/scons-local-3.0.1/SCons/Tool/mslib.py#L44-L55
7,937
eventbrite/eventbrite-sdk-python
eventbrite/access_methods.py
AccessMethodsMixin.get_organizers_events
def get_organizers_events(self, id, **data): """ GET /organizers/:id/events/ Gets events of the :format:`organizer`. """ return self.get("/organizers/{0}/events/".format(id), data=data)
python
def get_organizers_events(self, id, **data): """ GET /organizers/:id/events/ Gets events of the :format:`organizer`. """ return self.get("/organizers/{0}/events/".format(id), data=data)
['def', 'get_organizers_events', '(', 'self', ',', 'id', ',', '*', '*', 'data', ')', ':', 'return', 'self', '.', 'get', '(', '"/organizers/{0}/events/"', '.', 'format', '(', 'id', ')', ',', 'data', '=', 'data', ')']
GET /organizers/:id/events/ Gets events of the :format:`organizer`.
['GET', '/', 'organizers', '/', ':', 'id', '/', 'events', '/', 'Gets', 'events', 'of', 'the', ':', 'format', ':', 'organizer', '.']
train
https://github.com/eventbrite/eventbrite-sdk-python/blob/f2e5dc5aa1aa3e45766de13f16fd65722163d91a/eventbrite/access_methods.py#L601-L607
7,938
pyapi-gitlab/pyapi-gitlab
gitlab/__init__.py
Gitlab.getfilearchive
def getfilearchive(self, project_id, filepath=None): """ Get an archive of the repository :param project_id: project id :param filepath: path to save the file to :return: True if the file was saved to the filepath """ if not filepath: filepath = '' ...
python
def getfilearchive(self, project_id, filepath=None): """ Get an archive of the repository :param project_id: project id :param filepath: path to save the file to :return: True if the file was saved to the filepath """ if not filepath: filepath = '' ...
['def', 'getfilearchive', '(', 'self', ',', 'project_id', ',', 'filepath', '=', 'None', ')', ':', 'if', 'not', 'filepath', ':', 'filepath', '=', "''", 'request', '=', 'requests', '.', 'get', '(', "'{0}/{1}/repository/archive'", '.', 'format', '(', 'self', '.', 'projects_url', ',', 'project_id', ')', ',', 'verify', '=',...
Get an archive of the repository :param project_id: project id :param filepath: path to save the file to :return: True if the file was saved to the filepath
['Get', 'an', 'archive', 'of', 'the', 'repository']
train
https://github.com/pyapi-gitlab/pyapi-gitlab/blob/f74b6fb5c13cecae9524997847e928905cc60acf/gitlab/__init__.py#L1655-L1680
7,939
panzarino/mlbgame
mlbgame/game.py
players
def players(game_id): """Gets player/coach/umpire information for the game with matching id.""" # get data data = mlbgame.data.get_players(game_id) # parse data parsed = etree.parse(data) root = parsed.getroot() output = {} output['game_id'] = game_id # get player/coach data fo...
python
def players(game_id): """Gets player/coach/umpire information for the game with matching id.""" # get data data = mlbgame.data.get_players(game_id) # parse data parsed = etree.parse(data) root = parsed.getroot() output = {} output['game_id'] = game_id # get player/coach data fo...
['def', 'players', '(', 'game_id', ')', ':', '# get data', 'data', '=', 'mlbgame', '.', 'data', '.', 'get_players', '(', 'game_id', ')', '# parse data', 'parsed', '=', 'etree', '.', 'parse', '(', 'data', ')', 'root', '=', 'parsed', '.', 'getroot', '(', ')', 'output', '=', '{', '}', 'output', '[', "'game_id'", ']', '=',...
Gets player/coach/umpire information for the game with matching id.
['Gets', 'player', '/', 'coach', '/', 'umpire', 'information', 'for', 'the', 'game', 'with', 'matching', 'id', '.']
train
https://github.com/panzarino/mlbgame/blob/0a2d10540de793fdc3b8476aa18f5cf3b53d0b54/mlbgame/game.py#L548-L587
7,940
gwastro/pycbc
pycbc/inject/inject.py
set_sim_data
def set_sim_data(inj, field, data): """Sets data of a SimInspiral instance.""" try: sim_field = sim_inspiral_map[field] except KeyError: sim_field = field # for tc, map to geocentric times if sim_field == 'tc': inj.geocent_end_time = int(data) inj.geocent_end_time_ns ...
python
def set_sim_data(inj, field, data): """Sets data of a SimInspiral instance.""" try: sim_field = sim_inspiral_map[field] except KeyError: sim_field = field # for tc, map to geocentric times if sim_field == 'tc': inj.geocent_end_time = int(data) inj.geocent_end_time_ns ...
['def', 'set_sim_data', '(', 'inj', ',', 'field', ',', 'data', ')', ':', 'try', ':', 'sim_field', '=', 'sim_inspiral_map', '[', 'field', ']', 'except', 'KeyError', ':', 'sim_field', '=', 'field', '# for tc, map to geocentric times', 'if', 'sim_field', '==', "'tc'", ':', 'inj', '.', 'geocent_end_time', '=', 'int', '(', ...
Sets data of a SimInspiral instance.
['Sets', 'data', 'of', 'a', 'SimInspiral', 'instance', '.']
train
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/inject/inject.py#L69-L80
7,941
MacHu-GWU/rolex-project
rolex/generator.py
rnd_date_list_high_performance
def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :par...
python
def rnd_date_list_high_performance(size, start=date(1970, 1, 1), end=None, **kwargs): """ Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :par...
['def', 'rnd_date_list_high_performance', '(', 'size', ',', 'start', '=', 'date', '(', '1970', ',', '1', ',', '1', ')', ',', 'end', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'if', 'end', 'is', 'None', ':', 'end', '=', 'date', '.', 'today', '(', ')', 'start_days', '=', 'to_ordinal', '(', 'parser', '.', 'parse_date...
Generate mass random date. :param size: int, number of :param start: date similar object, int / str / date / datetime :param end: date similar object, int / str / date / datetime, default today's date :param kwargs: args placeholder :return: list of datetime.date
['Generate', 'mass', 'random', 'date', '.']
train
https://github.com/MacHu-GWU/rolex-project/blob/a1111b410ed04b4b6eddd81df110fa2dacfa6537/rolex/generator.py#L295-L319
7,942
BerkeleyAutomation/autolab_core
autolab_core/learning_analysis.py
BinaryClassificationResult.app_score
def app_score(self): """ Computes the area under the app curve. """ # compute curve precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False) # compute area app = 0 total = 0 for k in range(len(precisions)-1): # read cur data ...
python
def app_score(self): """ Computes the area under the app curve. """ # compute curve precisions, pct_pred_pos, taus = self.precision_pct_pred_pos_curve(interval=False) # compute area app = 0 total = 0 for k in range(len(precisions)-1): # read cur data ...
['def', 'app_score', '(', 'self', ')', ':', '# compute curve', 'precisions', ',', 'pct_pred_pos', ',', 'taus', '=', 'self', '.', 'precision_pct_pred_pos_curve', '(', 'interval', '=', 'False', ')', '# compute area', 'app', '=', '0', 'total', '=', '0', 'for', 'k', 'in', 'range', '(', 'len', '(', 'precisions', ')', '-', '...
Computes the area under the app curve.
['Computes', 'the', 'area', 'under', 'the', 'app', 'curve', '.']
train
https://github.com/BerkeleyAutomation/autolab_core/blob/8f3813f6401972868cc5e3981ba1b4382d4418d5/autolab_core/learning_analysis.py#L467-L492
7,943
mswart/pyopenmensa
feed.py
extractDate
def extractDate(text): """ Tries to extract a date from a given :obj:`str`. :param str text: Input date. A :obj:`datetime.date` object is passed thought without modification. :rtype: :obj:`datetime.date`""" if type(text) is datetime.date: return text match = date_format...
python
def extractDate(text): """ Tries to extract a date from a given :obj:`str`. :param str text: Input date. A :obj:`datetime.date` object is passed thought without modification. :rtype: :obj:`datetime.date`""" if type(text) is datetime.date: return text match = date_format...
['def', 'extractDate', '(', 'text', ')', ':', 'if', 'type', '(', 'text', ')', 'is', 'datetime', '.', 'date', ':', 'return', 'text', 'match', '=', 'date_format', '.', 'search', '(', 'text', '.', 'lower', '(', ')', ')', 'if', 'not', 'match', ':', 'raise', 'ValueError', '(', "'unsupported date format: {0}'", '.', 'format'...
Tries to extract a date from a given :obj:`str`. :param str text: Input date. A :obj:`datetime.date` object is passed thought without modification. :rtype: :obj:`datetime.date`
['Tries', 'to', 'extract', 'a', 'date', 'from', 'a', 'given', ':', 'obj', ':', 'str', '.']
train
https://github.com/mswart/pyopenmensa/blob/c651da6ace33e2278349636daaa709d043dee6ff/feed.py#L47-L73
7,944
google/grr
grr/client/grr_response_client/vfs_handlers/files.py
File.GetMountPoint
def GetMountPoint(self, path=None): """Walk back from the path to find the mount point. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: path string of the mount point """ path = os.path.abspath( client_u...
python
def GetMountPoint(self, path=None): """Walk back from the path to find the mount point. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: path string of the mount point """ path = os.path.abspath( client_u...
['def', 'GetMountPoint', '(', 'self', ',', 'path', '=', 'None', ')', ':', 'path', '=', 'os', '.', 'path', '.', 'abspath', '(', 'client_utils', '.', 'CanonicalPathToLocalPath', '(', 'path', 'or', 'self', '.', 'path', ')', ')', 'while', 'not', 'os', '.', 'path', '.', 'ismount', '(', 'path', ')', ':', 'path', '=', 'os', '...
Walk back from the path to find the mount point. Args: path: a Unicode string containing the path or None. If path is None the value in self.path is used. Returns: path string of the mount point
['Walk', 'back', 'from', 'the', 'path', 'to', 'find', 'the', 'mount', 'point', '.']
train
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/client/grr_response_client/vfs_handlers/files.py#L313-L329
7,945
jason-weirather/py-seq-tools
seqtools/errors.py
BaseError.set_unobserved_after
def set_unobserved_after(self,tlen,qlen,nt,p): """Set the unobservable sequence data after this base :param tlen: target homopolymer length :param qlen: query homopolymer length :param nt: nucleotide :param p: p is the probability of attributing this base to the unobserved error :type tlen: int...
python
def set_unobserved_after(self,tlen,qlen,nt,p): """Set the unobservable sequence data after this base :param tlen: target homopolymer length :param qlen: query homopolymer length :param nt: nucleotide :param p: p is the probability of attributing this base to the unobserved error :type tlen: int...
['def', 'set_unobserved_after', '(', 'self', ',', 'tlen', ',', 'qlen', ',', 'nt', ',', 'p', ')', ':', 'self', '.', '_unobservable', '.', 'set_after', '(', 'tlen', ',', 'qlen', ',', 'nt', ',', 'p', ')']
Set the unobservable sequence data after this base :param tlen: target homopolymer length :param qlen: query homopolymer length :param nt: nucleotide :param p: p is the probability of attributing this base to the unobserved error :type tlen: int :type qlen: int :type nt: char :type p: f...
['Set', 'the', 'unobservable', 'sequence', 'data', 'after', 'this', 'base']
train
https://github.com/jason-weirather/py-seq-tools/blob/f642c2c73ffef2acc83656a78059a476fc734ca1/seqtools/errors.py#L375-L388
7,946
xav/Grapefruit
grapefruit.py
Color.from_xyz
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The col...
python
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The col...
['def', 'from_xyz', '(', 'x', ',', 'y', ',', 'z', ',', 'alpha', '=', '1.0', ',', 'wref', '=', '_DEFAULT_WREF', ')', ':', 'return', 'Color', '(', 'xyz_to_rgb', '(', 'x', ',', 'y', ',', 'z', ')', ',', "'rgb'", ',', 'alpha', ',', 'wref', ')']
Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: ...
['Create', 'a', 'new', 'instance', 'based', 'on', 'the', 'specifed', 'CIE', '-', 'XYZ', 'values', '.']
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1259-L1283
7,947
PythonCharmers/python-future
src/future/backports/urllib/request.py
FancyURLopener.http_error_307
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errm...
python
def http_error_307(self, url, fp, errcode, errmsg, headers, data=None): """Error 307 -- relocated, but turn POST into error.""" if data is None: return self.http_error_302(url, fp, errcode, errmsg, headers, data) else: return self.http_error_default(url, fp, errcode, errm...
['def', 'http_error_307', '(', 'self', ',', 'url', ',', 'fp', ',', 'errcode', ',', 'errmsg', ',', 'headers', ',', 'data', '=', 'None', ')', ':', 'if', 'data', 'is', 'None', ':', 'return', 'self', '.', 'http_error_302', '(', 'url', ',', 'fp', ',', 'errcode', ',', 'errmsg', ',', 'headers', ',', 'data', ')', 'else', ':', ...
Error 307 -- relocated, but turn POST into error.
['Error', '307', '--', 'relocated', 'but', 'turn', 'POST', 'into', 'error', '.']
train
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/urllib/request.py#L2115-L2120
7,948
cloudnull/cloudlib
cloudlib/package_installer.py
PackageInstaller.install
def install(self): """Install packages from the packages_dict.""" self.distro = distro_check() package_list = self.packages_dict.get(self.distro) self._installer(package_list=package_list.get('packages'))
python
def install(self): """Install packages from the packages_dict.""" self.distro = distro_check() package_list = self.packages_dict.get(self.distro) self._installer(package_list=package_list.get('packages'))
['def', 'install', '(', 'self', ')', ':', 'self', '.', 'distro', '=', 'distro_check', '(', ')', 'package_list', '=', 'self', '.', 'packages_dict', '.', 'get', '(', 'self', '.', 'distro', ')', 'self', '.', '_installer', '(', 'package_list', '=', 'package_list', '.', 'get', '(', "'packages'", ')', ')']
Install packages from the packages_dict.
['Install', 'packages', 'from', 'the', 'packages_dict', '.']
train
https://github.com/cloudnull/cloudlib/blob/5038111ce02521caa2558117e3bae9e1e806d315/cloudlib/package_installer.py#L101-L105
7,949
PmagPy/PmagPy
pmagpy/builder2.py
ErMagicBuilder.validate_items
def validate_items(self, item_list, item_type): """ Go through a list Pmag_objects and check for: parent errors, children errors, type errors. Return a dictionary of exceptions in this format: {sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1...
python
def validate_items(self, item_list, item_type): """ Go through a list Pmag_objects and check for: parent errors, children errors, type errors. Return a dictionary of exceptions in this format: {sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1...
['def', 'validate_items', '(', 'self', ',', 'item_list', ',', 'item_type', ')', ':', 'def', 'append_or_create_dict_item', '(', 'warning_type', ',', 'dictionary', ',', 'key', ',', 'value', ')', ':', '"""\n Add to dictionary with this format:\n {key1: {warning_type1: [value1, value2], warning_type2:...
Go through a list Pmag_objects and check for: parent errors, children errors, type errors. Return a dictionary of exceptions in this format: {sample1: {'parent': [warning1, warning2, warning3], 'child': [warning1, warning2]}, sample2: {'child': [warning1], 'type': [warni...
['Go', 'through', 'a', 'list', 'Pmag_objects', 'and', 'check', 'for', ':', 'parent', 'errors', 'children', 'errors', 'type', 'errors', '.', 'Return', 'a', 'dictionary', 'of', 'exceptions', 'in', 'this', 'format', ':', '{', 'sample1', ':', '{', 'parent', ':', '[', 'warning1', 'warning2', 'warning3', ']', 'child', ':', '...
train
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/pmagpy/builder2.py#L1210-L1302
7,950
foliant-docs/foliantcontrib.init
setup.py
get_templates
def get_templates(path: Path) -> List[str]: '''List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``. ''' result = [] for item in path.glob('**/*'): if item.is_file() and not item.name.star...
python
def get_templates(path: Path) -> List[str]: '''List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``. ''' result = [] for item in path.glob('**/*'): if item.is_file() and not item.name.star...
['def', 'get_templates', '(', 'path', ':', 'Path', ')', '->', 'List', '[', 'str', ']', ':', 'result', '=', '[', ']', 'for', 'item', 'in', 'path', '.', 'glob', '(', "'**/*'", ')', ':', 'if', 'item', '.', 'is_file', '(', ')', 'and', 'not', 'item', '.', 'name', '.', 'startswith', '(', "'_'", ')', ':', 'result', '.', 'appe...
List all files in ``templates`` directory, including all subdirectories. The resulting list contains UNIX-like relative paths starting with ``templates``.
['List', 'all', 'files', 'in', 'templates', 'directory', 'including', 'all', 'subdirectories', '.']
train
https://github.com/foliant-docs/foliantcontrib.init/blob/39aa38949b6270a750c800b79b4e71dd827f28d8/setup.py#L14-L26
7,951
gebn/nibble
nibble/expression/parser.py
Parser.p_information_duration_speed
def p_information_duration_speed(self, p): 'information : duration AT speed' logger.debug('information = duration %s at speed %s', p[1], p[3]) p[0] = p[3].for_duration(p[1])
python
def p_information_duration_speed(self, p): 'information : duration AT speed' logger.debug('information = duration %s at speed %s', p[1], p[3]) p[0] = p[3].for_duration(p[1])
['def', 'p_information_duration_speed', '(', 'self', ',', 'p', ')', ':', 'logger', '.', 'debug', '(', "'information = duration %s at speed %s'", ',', 'p', '[', '1', ']', ',', 'p', '[', '3', ']', ')', 'p', '[', '0', ']', '=', 'p', '[', '3', ']', '.', 'for_duration', '(', 'p', '[', '1', ']', ')']
information : duration AT speed
['information', ':', 'duration', 'AT', 'speed']
train
https://github.com/gebn/nibble/blob/e82a2c43509ed38f3d039040591cc630fa676cb0/nibble/expression/parser.py#L67-L70
7,952
log2timeline/dfvfs
dfvfs/vfs/bde_file_system.py
BDEFileSystem.GetRootFileEntry
def GetRootFileEntry(self): """Retrieves the root file entry. Returns: BDEFileEntry: file entry or None. """ path_spec = bde_path_spec.BDEPathSpec(parent=self._path_spec.parent) return self.GetFileEntryByPathSpec(path_spec)
python
def GetRootFileEntry(self): """Retrieves the root file entry. Returns: BDEFileEntry: file entry or None. """ path_spec = bde_path_spec.BDEPathSpec(parent=self._path_spec.parent) return self.GetFileEntryByPathSpec(path_spec)
['def', 'GetRootFileEntry', '(', 'self', ')', ':', 'path_spec', '=', 'bde_path_spec', '.', 'BDEPathSpec', '(', 'parent', '=', 'self', '.', '_path_spec', '.', 'parent', ')', 'return', 'self', '.', 'GetFileEntryByPathSpec', '(', 'path_spec', ')']
Retrieves the root file entry. Returns: BDEFileEntry: file entry or None.
['Retrieves', 'the', 'root', 'file', 'entry', '.']
train
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/dfvfs/vfs/bde_file_system.py#L98-L105
7,953
evhub/coconut
coconut/compiler/util.py
disable_inside
def disable_inside(item, *elems, **kwargs): """Prevent elems from matching inside of item. Returns (item with elem disabled, *new versions of elems). """ _invert = kwargs.get("_invert", False) internal_assert(set(kwargs.keys()) <= set(("_invert",)), "excess keyword arguments passed to disable_insid...
python
def disable_inside(item, *elems, **kwargs): """Prevent elems from matching inside of item. Returns (item with elem disabled, *new versions of elems). """ _invert = kwargs.get("_invert", False) internal_assert(set(kwargs.keys()) <= set(("_invert",)), "excess keyword arguments passed to disable_insid...
['def', 'disable_inside', '(', 'item', ',', '*', 'elems', ',', '*', '*', 'kwargs', ')', ':', '_invert', '=', 'kwargs', '.', 'get', '(', '"_invert"', ',', 'False', ')', 'internal_assert', '(', 'set', '(', 'kwargs', '.', 'keys', '(', ')', ')', '<=', 'set', '(', '(', '"_invert"', ',', ')', ')', ',', '"excess keyword argum...
Prevent elems from matching inside of item. Returns (item with elem disabled, *new versions of elems).
['Prevent', 'elems', 'from', 'matching', 'inside', 'of', 'item', '.']
train
https://github.com/evhub/coconut/blob/ff97177344e7604e89a0a98a977a87ed2a56fc6d/coconut/compiler/util.py#L533-L561
7,954
berkeley-cocosci/Wallace
wallace/command_line.py
setup
def setup(): """Walk the user though the Wallace setup.""" # Create the Wallace config file if it does not already exist. config_name = ".wallaceconfig" config_path = os.path.join(os.path.expanduser("~"), config_name) if os.path.isfile(config_path): log("Wallace config file already exists."...
python
def setup(): """Walk the user though the Wallace setup.""" # Create the Wallace config file if it does not already exist. config_name = ".wallaceconfig" config_path = os.path.join(os.path.expanduser("~"), config_name) if os.path.isfile(config_path): log("Wallace config file already exists."...
['def', 'setup', '(', ')', ':', '# Create the Wallace config file if it does not already exist.', 'config_name', '=', '".wallaceconfig"', 'config_path', '=', 'os', '.', 'path', '.', 'join', '(', 'os', '.', 'path', '.', 'expanduser', '(', '"~"', ')', ',', 'config_name', ')', 'if', 'os', '.', 'path', '.', 'isfile', '(', ...
Walk the user though the Wallace setup.
['Walk', 'the', 'user', 'though', 'the', 'Wallace', 'setup', '.']
train
https://github.com/berkeley-cocosci/Wallace/blob/3650c0bc3b0804d0adb1d178c5eba9992babb1b0/wallace/command_line.py#L66-L80
7,955
user-cont/conu
conu/utils/http_client.py
get_url
def get_url(path, host, port, method="http"): """ make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str """ return urlunsplit( (method, "%s:%s" % (host, port),...
python
def get_url(path, host, port, method="http"): """ make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str """ return urlunsplit( (method, "%s:%s" % (host, port),...
['def', 'get_url', '(', 'path', ',', 'host', ',', 'port', ',', 'method', '=', '"http"', ')', ':', 'return', 'urlunsplit', '(', '(', 'method', ',', '"%s:%s"', '%', '(', 'host', ',', 'port', ')', ',', 'path', ',', '""', ',', '""', ')', ')']
make url from path, host and port :param method: str :param path: str, path within the request, e.g. "/api/version" :param host: str :param port: str or int :return: str
['make', 'url', 'from', 'path', 'host', 'and', 'port']
train
https://github.com/user-cont/conu/blob/08caae7bb6bdd265b55bb106c3da6a7946a5a352/conu/utils/http_client.py#L20-L32
7,956
mushkevych/scheduler
synergy/system/process_helper.py
get_process_pid
def get_process_pid(process_name): """ check for process' pid file and returns pid from there """ try: pid_filename = get_pid_filename(process_name) with open(pid_filename, mode='r') as pid_file: pid = int(pid_file.read().strip()) except IOError: pid = None return pid
python
def get_process_pid(process_name): """ check for process' pid file and returns pid from there """ try: pid_filename = get_pid_filename(process_name) with open(pid_filename, mode='r') as pid_file: pid = int(pid_file.read().strip()) except IOError: pid = None return pid
['def', 'get_process_pid', '(', 'process_name', ')', ':', 'try', ':', 'pid_filename', '=', 'get_pid_filename', '(', 'process_name', ')', 'with', 'open', '(', 'pid_filename', ',', 'mode', '=', "'r'", ')', 'as', 'pid_file', ':', 'pid', '=', 'int', '(', 'pid_file', '.', 'read', '(', ')', '.', 'strip', '(', ')', ')', 'exce...
check for process' pid file and returns pid from there
['check', 'for', 'process', 'pid', 'file', 'and', 'returns', 'pid', 'from', 'there']
train
https://github.com/mushkevych/scheduler/blob/6740331360f49083c208085fb5a60ce80ebf418b/synergy/system/process_helper.py#L14-L22
7,957
anayjoshi/platypus
platypus/cfg/ast_to_cfg.py
get_cfg
def get_cfg(ast_func): """ Traverses the AST and returns the corresponding CFG :param ast_func: The AST representation of function :type ast_func: ast.Function :returns: The CFG representation of the function :rtype: cfg.Function """ cfg_func = cfg.Function() for ast_var in ast_fun...
python
def get_cfg(ast_func): """ Traverses the AST and returns the corresponding CFG :param ast_func: The AST representation of function :type ast_func: ast.Function :returns: The CFG representation of the function :rtype: cfg.Function """ cfg_func = cfg.Function() for ast_var in ast_fun...
['def', 'get_cfg', '(', 'ast_func', ')', ':', 'cfg_func', '=', 'cfg', '.', 'Function', '(', ')', 'for', 'ast_var', 'in', 'ast_func', '.', 'input_variable_list', ':', 'cfg_var', '=', 'cfg_func', '.', 'get_variable', '(', 'ast_var', '.', 'name', ')', 'cfg_func', '.', 'add_input_variable', '(', 'cfg_var', ')', 'for', 'ast...
Traverses the AST and returns the corresponding CFG :param ast_func: The AST representation of function :type ast_func: ast.Function :returns: The CFG representation of the function :rtype: cfg.Function
['Traverses', 'the', 'AST', 'and', 'returns', 'the', 'corresponding', 'CFG']
train
https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/ast_to_cfg.py#L4-L28
7,958
quantumlib/Cirq
cirq/google/sim/mem_manager.py
SharedMemManager._create_array
def _create_array(self, arr: np.ndarray) -> int: """Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported d...
python
def _create_array(self, arr: np.ndarray) -> int: """Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported d...
['def', '_create_array', '(', 'self', ',', 'arr', ':', 'np', '.', 'ndarray', ')', '->', 'int', ':', 'if', 'not', 'isinstance', '(', 'arr', ',', 'np', '.', 'ndarray', ')', ':', 'raise', 'ValueError', '(', "'Array is not a numpy ndarray.'", ')', 'try', ':', 'c_arr', '=', 'np', '.', 'ctypeslib', '.', 'as_ctypes', '(', 'ar...
Returns the handle of a RawArray created from the given numpy array. Args: arr: A numpy ndarray. Returns: The handle (int) of the array. Raises: ValueError: if arr is not a ndarray or of an unsupported dtype. If the array is of an unsupported type, us...
['Returns', 'the', 'handle', 'of', 'a', 'RawArray', 'created', 'from', 'the', 'given', 'numpy', 'array', '.']
train
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/google/sim/mem_manager.py#L53-L91
7,959
vnmabus/dcor
dcor/_dcor.py
_u_distance_covariance_sqr_naive
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_mat...
python
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_mat...
['def', '_u_distance_covariance_sqr_naive', '(', 'x', ',', 'y', ',', 'exponent', '=', '1', ')', ':', 'a', '=', '_u_distance_matrix', '(', 'x', ',', 'exponent', '=', 'exponent', ')', 'b', '=', '_u_distance_matrix', '(', 'y', ',', 'exponent', '=', 'exponent', ')', 'return', 'u_product', '(', 'a', ',', 'b', ')']
Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm.
['Naive', 'unbiased', 'estimator', 'for', 'distance', 'covariance', '.']
train
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L47-L57
7,960
CalebBell/fluids
fluids/jet_pump.py
liquid_jet_pump_ancillary
def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None, Qp=None, Qs=None, P1=None, P2=None): r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes f...
python
def liquid_jet_pump_ancillary(rhop, rhos, Kp, Ks, d_nozzle=None, d_mixing=None, Qp=None, Qs=None, P1=None, P2=None): r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes f...
['def', 'liquid_jet_pump_ancillary', '(', 'rhop', ',', 'rhos', ',', 'Kp', ',', 'Ks', ',', 'd_nozzle', '=', 'None', ',', 'd_mixing', '=', 'None', ',', 'Qp', '=', 'None', ',', 'Qs', '=', 'None', ',', 'P1', '=', 'None', ',', 'P2', '=', 'None', ')', ':', 'unknowns', '=', 'sum', '(', 'i', 'is', 'None', 'for', 'i', 'in', '('...
r'''Calculates the remaining variable in a liquid jet pump when solving for one if the inlet variables only and the rest of them are known. The equation comes from conservation of energy and momentum in the mixing chamber. The variable to be solved for must be one of `d_nozzle`, `d_mixing`, `Qp...
['r', 'Calculates', 'the', 'remaining', 'variable', 'in', 'a', 'liquid', 'jet', 'pump', 'when', 'solving', 'for', 'one', 'if', 'the', 'inlet', 'variables', 'only', 'and', 'the', 'rest', 'of', 'them', 'are', 'known', '.', 'The', 'equation', 'comes', 'from', 'conservation', 'of', 'energy', 'and', 'momentum', 'in', 'the',...
train
https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/jet_pump.py#L33-L163
7,961
thisfred/val
val/_val.py
And._validated
def _validated(self, data): """Validate data if all subschemas validate it.""" for sub in self.schemas: data = sub(data) return data
python
def _validated(self, data): """Validate data if all subschemas validate it.""" for sub in self.schemas: data = sub(data) return data
['def', '_validated', '(', 'self', ',', 'data', ')', ':', 'for', 'sub', 'in', 'self', '.', 'schemas', ':', 'data', '=', 'sub', '(', 'data', ')', 'return', 'data']
Validate data if all subschemas validate it.
['Validate', 'data', 'if', 'all', 'subschemas', 'validate', 'it', '.']
train
https://github.com/thisfred/val/blob/ba022e0c6c47acb3b8a45e7c44c84cc0f495c41c/val/_val.py#L339-L343
7,962
vertexproject/synapse
synapse/lib/hive.py
Hive.pop
async def pop(self, full): ''' Remove and return the value for the given node. ''' node = self.nodes.get(full) if node is None: return valu = await self._popHiveNode(node) return valu
python
async def pop(self, full): ''' Remove and return the value for the given node. ''' node = self.nodes.get(full) if node is None: return valu = await self._popHiveNode(node) return valu
['async', 'def', 'pop', '(', 'self', ',', 'full', ')', ':', 'node', '=', 'self', '.', 'nodes', '.', 'get', '(', 'full', ')', 'if', 'node', 'is', 'None', ':', 'return', 'valu', '=', 'await', 'self', '.', '_popHiveNode', '(', 'node', ')', 'return', 'valu']
Remove and return the value for the given node.
['Remove', 'and', 'return', 'the', 'value', 'for', 'the', 'given', 'node', '.']
train
https://github.com/vertexproject/synapse/blob/22e67c5a8f6d7caddbcf34b39ab1bd2d6c4a6e0b/synapse/lib/hive.py#L257-L267
7,963
rigetti/grove
grove/alpha/fermion_transforms/bktransform.py
BKTransform._operator_generator
def _operator_generator(self, index, conj): """ Internal method to generate the appropriate ladder operator at fermion orbital at 'index' If conj == -1 --> creation conj == +1 --> annihilation :param int index: fermion orbital to generate ladder operator at :p...
python
def _operator_generator(self, index, conj): """ Internal method to generate the appropriate ladder operator at fermion orbital at 'index' If conj == -1 --> creation conj == +1 --> annihilation :param int index: fermion orbital to generate ladder operator at :p...
['def', '_operator_generator', '(', 'self', ',', 'index', ',', 'conj', ')', ':', 'if', 'conj', '!=', '-', '1', 'and', 'conj', '!=', '+', '1', ':', 'raise', 'ValueError', '(', '"Improper conjugate coefficient"', ')', 'if', 'index', '>=', 'self', '.', 'n_qubits', 'or', 'index', '<', '0', ':', 'raise', 'IndexError', '(', ...
Internal method to generate the appropriate ladder operator at fermion orbital at 'index' If conj == -1 --> creation conj == +1 --> annihilation :param int index: fermion orbital to generate ladder operator at :param int conj: -1 for creation, +1 for annihilation
['Internal', 'method', 'to', 'generate', 'the', 'appropriate', 'ladder', 'operator', 'at', 'fermion', 'orbital', 'at', 'index', 'If', 'conj', '==', '-', '1', '--', '>', 'creation', 'conj', '==', '+', '1', '--', '>', 'annihilation']
train
https://github.com/rigetti/grove/blob/dc6bf6ec63e8c435fe52b1e00f707d5ce4cdb9b3/grove/alpha/fermion_transforms/bktransform.py#L89-L132
7,964
RI-imaging/nrefocus
nrefocus/metrics.py
spectral
def spectral(data, lambd, *kwargs): """ Compute spectral contrast of image Performs bandpass filtering in Fourier space according to optical limit of detection system, approximated by twice the wavelength. Parameters ---------- data : 2d ndarray the image to compute the norm from ...
python
def spectral(data, lambd, *kwargs): """ Compute spectral contrast of image Performs bandpass filtering in Fourier space according to optical limit of detection system, approximated by twice the wavelength. Parameters ---------- data : 2d ndarray the image to compute the norm from ...
['def', 'spectral', '(', 'data', ',', 'lambd', ',', '*', 'kwargs', ')', ':', '# Set up fast fourier transform', '# if not data.dtype == np.dtype(np.complex):', '# data = np.array(data, dtype=np.complex)', '# fftplan = fftw3.Plan(data.copy(), None, nthreads = _ncores,', '# direction="forward", fla...
Compute spectral contrast of image Performs bandpass filtering in Fourier space according to optical limit of detection system, approximated by twice the wavelength. Parameters ---------- data : 2d ndarray the image to compute the norm from lambd : float wavelength of the ligh...
['Compute', 'spectral', 'contrast', 'of', 'image']
train
https://github.com/RI-imaging/nrefocus/blob/ad09aeecace609ab8f9effcb662d2b7d50826080/nrefocus/metrics.py#L18-L52
7,965
72squared/redpipe
redpipe/fields.py
ListField.encode
def encode(cls, value): """ take a list and turn it into a utf-8 encoded byte-string for redis. :param value: list :return: bytes """ try: coerced = list(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) ...
python
def encode(cls, value): """ take a list and turn it into a utf-8 encoded byte-string for redis. :param value: list :return: bytes """ try: coerced = list(value) if coerced == value: return json.dumps(coerced).encode(cls._encoding) ...
['def', 'encode', '(', 'cls', ',', 'value', ')', ':', 'try', ':', 'coerced', '=', 'list', '(', 'value', ')', 'if', 'coerced', '==', 'value', ':', 'return', 'json', '.', 'dumps', '(', 'coerced', ')', '.', 'encode', '(', 'cls', '.', '_encoding', ')', 'except', 'TypeError', ':', 'pass', 'raise', 'InvalidValue', '(', "'not...
take a list and turn it into a utf-8 encoded byte-string for redis. :param value: list :return: bytes
['take', 'a', 'list', 'and', 'turn', 'it', 'into', 'a', 'utf', '-', '8', 'encoded', 'byte', '-', 'string', 'for', 'redis', '.']
train
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L225-L239
7,966
pywbem/pywbem
pywbem_mock/_wbemconnection_mock.py
FakedWBEMConnection._fake_modifyinstance
def _fake_modifyinstance(self, namespace, **params): """ Implements a server responder for :meth:`~pywbem.WBEMConnection.CreateInstance` Modify a CIM instance in the local repository. Raises: CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS """ ...
python
def _fake_modifyinstance(self, namespace, **params): """ Implements a server responder for :meth:`~pywbem.WBEMConnection.CreateInstance` Modify a CIM instance in the local repository. Raises: CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS """ ...
['def', '_fake_modifyinstance', '(', 'self', ',', 'namespace', ',', '*', '*', 'params', ')', ':', 'if', 'self', '.', '_repo_lite', ':', 'raise', 'CIMError', '(', 'CIM_ERR_NOT_SUPPORTED', ',', '"ModifyInstance not supported when repo_lite set."', ')', '# Validate namespace', 'instance_repo', '=', 'self', '.', '_get_inst...
Implements a server responder for :meth:`~pywbem.WBEMConnection.CreateInstance` Modify a CIM instance in the local repository. Raises: CIMError: CIM_ERR_ALREADY_EXISTS, CIM_ERR_INVALID_CLASS
['Implements', 'a', 'server', 'responder', 'for', ':', 'meth', ':', '~pywbem', '.', 'WBEMConnection', '.', 'CreateInstance']
train
https://github.com/pywbem/pywbem/blob/e54ecb82c2211e289a268567443d60fdd489f1e4/pywbem_mock/_wbemconnection_mock.py#L2207-L2362
7,967
MartinThoma/hwrt
hwrt/serve.py
_get_part
def _get_part(pointlist, strokes): """Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts """ result = [] strokes = sorted(strokes) for stroke_index in strokes: ...
python
def _get_part(pointlist, strokes): """Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts """ result = [] strokes = sorted(strokes) for stroke_index in strokes: ...
['def', '_get_part', '(', 'pointlist', ',', 'strokes', ')', ':', 'result', '=', '[', ']', 'strokes', '=', 'sorted', '(', 'strokes', ')', 'for', 'stroke_index', 'in', 'strokes', ':', 'result', '.', 'append', '(', 'pointlist', '[', 'stroke_index', ']', ')', 'return', 'result']
Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts
['Get', 'some', 'strokes', 'of', 'pointlist']
train
https://github.com/MartinThoma/hwrt/blob/725c21a3d0f5a30b8492cbc184b3688ceb364e1c/hwrt/serve.py#L164-L180
7,968
mikedh/trimesh
trimesh/transformations.py
quaternion_imag
def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.]) """ return np.array(quaternion[1:4], dtype=np.float64, copy=True)
python
def quaternion_imag(quaternion): """Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.]) """ return np.array(quaternion[1:4], dtype=np.float64, copy=True)
['def', 'quaternion_imag', '(', 'quaternion', ')', ':', 'return', 'np', '.', 'array', '(', 'quaternion', '[', '1', ':', '4', ']', ',', 'dtype', '=', 'np', '.', 'float64', ',', 'copy', '=', 'True', ')']
Return imaginary part of quaternion. >>> quaternion_imag([3, 0, 1, 2]) array([0., 1., 2.])
['Return', 'imaginary', 'part', 'of', 'quaternion', '.']
train
https://github.com/mikedh/trimesh/blob/25e059bf6d4caa74f62ffd58ce4f61a90ee4e518/trimesh/transformations.py#L1458-L1465
7,969
bcbio/bcbio-nextgen
bcbio/workflow/template.py
_retrieve_remote
def _retrieve_remote(fnames): """Retrieve remote inputs found in the same bucket as the template or metadata files. """ for fname in fnames: if objectstore.is_remote(fname): inputs = [] regions = [] remote_base = os.path.dirname(fname) for rfname in ob...
python
def _retrieve_remote(fnames): """Retrieve remote inputs found in the same bucket as the template or metadata files. """ for fname in fnames: if objectstore.is_remote(fname): inputs = [] regions = [] remote_base = os.path.dirname(fname) for rfname in ob...
['def', '_retrieve_remote', '(', 'fnames', ')', ':', 'for', 'fname', 'in', 'fnames', ':', 'if', 'objectstore', '.', 'is_remote', '(', 'fname', ')', ':', 'inputs', '=', '[', ']', 'regions', '=', '[', ']', 'remote_base', '=', 'os', '.', 'path', '.', 'dirname', '(', 'fname', ')', 'for', 'rfname', 'in', 'objectstore', '.',...
Retrieve remote inputs found in the same bucket as the template or metadata files.
['Retrieve', 'remote', 'inputs', 'found', 'in', 'the', 'same', 'bucket', 'as', 'the', 'template', 'or', 'metadata', 'files', '.']
train
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/workflow/template.py#L477-L493
7,970
molmod/molmod
molmod/transformations.py
Translation.inv
def inv(self): """The inverse translation""" result = Translation(-self.t) result._cache_inv = self return result
python
def inv(self): """The inverse translation""" result = Translation(-self.t) result._cache_inv = self return result
['def', 'inv', '(', 'self', ')', ':', 'result', '=', 'Translation', '(', '-', 'self', '.', 't', ')', 'result', '.', '_cache_inv', '=', 'self', 'return', 'result']
The inverse translation
['The', 'inverse', 'translation']
train
https://github.com/molmod/molmod/blob/a7b5b4364ed514ad4c465856c05b5eda1cb561e0/molmod/transformations.py#L94-L98
7,971
RudolfCardinal/pythonlib
cardinal_pythonlib/dogpile_cache.py
fkg_allowing_type_hints
def fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def te...
python
def fkg_allowing_type_hints( namespace: Optional[str], fn: Callable, to_str: Callable[[Any], str] = repr) -> Callable[[Any], str]: """ Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def te...
['def', 'fkg_allowing_type_hints', '(', 'namespace', ':', 'Optional', '[', 'str', ']', ',', 'fn', ':', 'Callable', ',', 'to_str', ':', 'Callable', '[', '[', 'Any', ']', ',', 'str', ']', '=', 'repr', ')', '->', 'Callable', '[', '[', 'Any', ']', ',', 'str', ']', ':', 'namespace', '=', 'get_namespace', '(', 'fn', ',', 'na...
Replacement for :func:`dogpile.cache.util.function_key_generator` that handles type-hinted functions like .. code-block:: python def testfunc(param: str) -> str: return param + "hello" ... at which :func:`inspect.getargspec` balks; plus :func:`inspect.getargspec` is deprecated in ...
['Replacement', 'for', ':', 'func', ':', 'dogpile', '.', 'cache', '.', 'util', '.', 'function_key_generator', 'that', 'handles', 'type', '-', 'hinted', 'functions', 'like']
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/dogpile_cache.py#L151-L210
7,972
OLC-Bioinformatics/sipprverse
pointsippr/pointsippr.py
PointSippr.runner
def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Initialise the GenObject for sample in self.runmetadata.samples: setattr(sample, self.analysistype, GenObject()) ...
python
def runner(self): """ Run the necessary methods in the correct order """ logging.info('Starting {} analysis pipeline'.format(self.analysistype)) # Initialise the GenObject for sample in self.runmetadata.samples: setattr(sample, self.analysistype, GenObject()) ...
['def', 'runner', '(', 'self', ')', ':', 'logging', '.', 'info', '(', "'Starting {} analysis pipeline'", '.', 'format', '(', 'self', '.', 'analysistype', ')', ')', '# Initialise the GenObject', 'for', 'sample', 'in', 'self', '.', 'runmetadata', '.', 'samples', ':', 'setattr', '(', 'sample', ',', 'self', '.', 'analysist...
Run the necessary methods in the correct order
['Run', 'the', 'necessary', 'methods', 'in', 'the', 'correct', 'order']
train
https://github.com/OLC-Bioinformatics/sipprverse/blob/d4f10cdf8e1a39dac0953db61c21c97efc6006de/pointsippr/pointsippr.py#L19-L39
7,973
cyberdelia/astrolabe
astrolabe/interval.py
Interval.stop
def stop(self): """Mark the stop of the interval. Calling stop on an already stopped interval has no effect. An interval can only be stopped once. :returns: the duration if the interval is truely stopped otherwise ``False``. """ if self._start_instant is None: ...
python
def stop(self): """Mark the stop of the interval. Calling stop on an already stopped interval has no effect. An interval can only be stopped once. :returns: the duration if the interval is truely stopped otherwise ``False``. """ if self._start_instant is None: ...
['def', 'stop', '(', 'self', ')', ':', 'if', 'self', '.', '_start_instant', 'is', 'None', ':', 'raise', 'IntervalException', '(', '"Attempt to stop an interval that has not started."', ')', 'if', 'self', '.', '_stop_instant', 'is', 'None', ':', 'self', '.', '_stop_instant', '=', 'instant', '(', ')', 'self', '.', '_dura...
Mark the stop of the interval. Calling stop on an already stopped interval has no effect. An interval can only be stopped once. :returns: the duration if the interval is truely stopped otherwise ``False``.
['Mark', 'the', 'stop', 'of', 'the', 'interval', '.']
train
https://github.com/cyberdelia/astrolabe/blob/c8496d330fd6fd6c7bb8f9912b684519ccb5c84e/astrolabe/interval.py#L68-L82
7,974
dnanexus/dx-toolkit
doc/examples/dx-apps/report_example/src/report_example.py
main
def main(**kwargs): """ Draw a couple of simple graphs and optionally generate an HTML file to upload them """ draw_lines() draw_histogram() draw_bar_chart() destination = "-r /report" if use_html: generate_html() command = "dx-build-report-html {h} {d}".format(h=html_fil...
python
def main(**kwargs): """ Draw a couple of simple graphs and optionally generate an HTML file to upload them """ draw_lines() draw_histogram() draw_bar_chart() destination = "-r /report" if use_html: generate_html() command = "dx-build-report-html {h} {d}".format(h=html_fil...
['def', 'main', '(', '*', '*', 'kwargs', ')', ':', 'draw_lines', '(', ')', 'draw_histogram', '(', ')', 'draw_bar_chart', '(', ')', 'destination', '=', '"-r /report"', 'if', 'use_html', ':', 'generate_html', '(', ')', 'command', '=', '"dx-build-report-html {h} {d}"', '.', 'format', '(', 'h', '=', 'html_filename', ',', '...
Draw a couple of simple graphs and optionally generate an HTML file to upload them
['Draw', 'a', 'couple', 'of', 'simple', 'graphs', 'and', 'optionally', 'generate', 'an', 'HTML', 'file', 'to', 'upload', 'them']
train
https://github.com/dnanexus/dx-toolkit/blob/74befb53ad90fcf902d8983ae6d74580f402d619/doc/examples/dx-apps/report_example/src/report_example.py#L37-L53
7,975
anuragkumarak95/wordnet
wordnet/word_net.py
generate_net
def generate_net(df,tf_idf,dump_path=None): '''Generate WordNetwork dict of Word() instance, and dump as a file if asked to. @Args: -- df : IDF value generated by find_tf_idf() tf_idf : TF-IDF value generated by find_tf_idf() dump_path : file_path where to dump network entities, stand...
python
def generate_net(df,tf_idf,dump_path=None): '''Generate WordNetwork dict of Word() instance, and dump as a file if asked to. @Args: -- df : IDF value generated by find_tf_idf() tf_idf : TF-IDF value generated by find_tf_idf() dump_path : file_path where to dump network entities, stand...
['def', 'generate_net', '(', 'df', ',', 'tf_idf', ',', 'dump_path', '=', 'None', ')', ':', '# error handling', 'if', 'dump_path', 'and', 'dump_path', '[', '-', '4', ':', ']', '!=', '__WRNT_FORMAT', ':', 'raise', 'Exception', '(', '__WRNG_FORMAT_MSG', ')', 'start_t', '=', 'datetime', '.', 'now', '(', ')', 'print', '(', ...
Generate WordNetwork dict of Word() instance, and dump as a file if asked to. @Args: -- df : IDF value generated by find_tf_idf() tf_idf : TF-IDF value generated by find_tf_idf() dump_path : file_path where to dump network entities, standart format is '.wrnt' (default=None) @returns:...
['Generate', 'WordNetwork', 'dict', 'of', 'Word', '()', 'instance', 'and', 'dump', 'as', 'a', 'file', 'if', 'asked', 'to', '.']
train
https://github.com/anuragkumarak95/wordnet/blob/7aba239ddebb0971e9e76124890373b60a2573c8/wordnet/word_net.py#L14-L73
7,976
mapnik/Cascadenik
cascadenik/parse.py
parse_rule
def parse_rule(tokens, variables, neighbors, parents, is_merc): """ Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the styl...
python
def parse_rule(tokens, variables, neighbors, parents, is_merc): """ Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the styl...
['def', 'parse_rule', '(', 'tokens', ',', 'variables', ',', 'neighbors', ',', 'parents', ',', 'is_merc', ')', ':', '#', '# Local helper function', '#', 'def', 'validate_selector_elements', '(', 'elements', ',', 'line', ',', 'col', ')', ':', 'if', 'len', '(', 'elements', ')', '>', '2', ':', 'raise', 'ParseException', '(...
Parse a rule set, return a list of declarations. Requires a dictionary of declared variables. Selectors in the neighbors list are simply grouped, and are generated from comma-delimited lists of selectors in the stylesheet. Selectors in the parents list should be combined with th...
['Parse', 'a', 'rule', 'set', 'return', 'a', 'list', 'of', 'declarations', '.', 'Requires', 'a', 'dictionary', 'of', 'declared', 'variables', '.', 'Selectors', 'in', 'the', 'neighbors', 'list', 'are', 'simply', 'grouped', 'and', 'are', 'generated', 'from', 'comma', '-', 'delimited', 'lists', 'of', 'selectors', 'in', 't...
train
https://github.com/mapnik/Cascadenik/blob/82f66859340a31dfcb24af127274f262d4f3ad85/cascadenik/parse.py#L498-L709
7,977
jjgomera/iapws
iapws/_iapws.py
_Tension
def _Tension(T): """Equation for the surface tension Parameters ---------- T : float Temperature, [K] Returns ------- σ : float Surface tension, [N/m] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 248.15 ≤ T ≤ 647 *...
python
def _Tension(T): """Equation for the surface tension Parameters ---------- T : float Temperature, [K] Returns ------- σ : float Surface tension, [N/m] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 248.15 ≤ T ≤ 647 *...
['def', '_Tension', '(', 'T', ')', ':', 'if', '248.15', '<=', 'T', '<=', 'Tc', ':', 'Tr', '=', 'T', '/', 'Tc', 'return', '1e-3', '*', '(', '235.8', '*', '(', '1', '-', 'Tr', ')', '**', '1.256', '*', '(', '1', '-', '0.625', '*', '(', '1', '-', 'Tr', ')', ')', ')', 'else', ':', 'raise', 'NotImplementedError', '(', '"Inco...
Equation for the surface tension Parameters ---------- T : float Temperature, [K] Returns ------- σ : float Surface tension, [N/m] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: * 248.15 ≤ T ≤ 647 * Estrapolate to -25ºC in...
['Equation', 'for', 'the', 'surface', 'tension']
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/_iapws.py#L872-L908
7,978
Opentrons/opentrons
api/src/opentrons/legacy_api/instruments/pipette.py
Pipette.touch_tip
def touch_tip(self, location=None, radius=1.0, v_offset=-1.0, speed=60.0): """ Touch the :any:`Pipette` tip to the sides of a well, with the intent of removing left-over droplets Notes ----- If no `location` is passed, the pipette will touch_tip from it's current...
python
def touch_tip(self, location=None, radius=1.0, v_offset=-1.0, speed=60.0): """ Touch the :any:`Pipette` tip to the sides of a well, with the intent of removing left-over droplets Notes ----- If no `location` is passed, the pipette will touch_tip from it's current...
['def', 'touch_tip', '(', 'self', ',', 'location', '=', 'None', ',', 'radius', '=', '1.0', ',', 'v_offset', '=', '-', '1.0', ',', 'speed', '=', '60.0', ')', ':', 'if', 'not', 'self', '.', 'tip_attached', ':', 'log', '.', 'warning', '(', '"Cannot touch tip without a tip attached."', ')', 'if', 'speed', '>', '80.0', ':',...
Touch the :any:`Pipette` tip to the sides of a well, with the intent of removing left-over droplets Notes ----- If no `location` is passed, the pipette will touch_tip from it's current position. Parameters ---------- location : :any:`Placeable` or tuple(...
['Touch', 'the', ':', 'any', ':', 'Pipette', 'tip', 'to', 'the', 'sides', 'of', 'a', 'well', 'with', 'the', 'intent', 'of', 'removing', 'left', '-', 'over', 'droplets']
train
https://github.com/Opentrons/opentrons/blob/a7c15cc2636ecb64ab56c7edc1d8a57163aaeadf/api/src/opentrons/legacy_api/instruments/pipette.py#L723-L817
7,979
ThreatConnect-Inc/tcex
app_init/playbook_utility/app.py
App.run
def run(self): """Run the App main logic. This method should contain the core logic of the App. """ # read inputs indent = int(self.tcex.playbook.read(self.args.indent)) json_data = self.tcex.playbook.read(self.args.json_data) # get the playbook variable type ...
python
def run(self): """Run the App main logic. This method should contain the core logic of the App. """ # read inputs indent = int(self.tcex.playbook.read(self.args.indent)) json_data = self.tcex.playbook.read(self.args.json_data) # get the playbook variable type ...
['def', 'run', '(', 'self', ')', ':', '# read inputs', 'indent', '=', 'int', '(', 'self', '.', 'tcex', '.', 'playbook', '.', 'read', '(', 'self', '.', 'args', '.', 'indent', ')', ')', 'json_data', '=', 'self', '.', 'tcex', '.', 'playbook', '.', 'read', '(', 'self', '.', 'args', '.', 'json_data', ')', '# get the playboo...
Run the App main logic. This method should contain the core logic of the App.
['Run', 'the', 'App', 'main', 'logic', '.']
train
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/playbook_utility/app.py#L25-L48
7,980
podio/podio-py
pypodio2/areas.py
Files.create
def create(self, filename, filedata): """Create a file from raw data""" attributes = {'filename': filename, 'source': filedata} return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
python
def create(self, filename, filedata): """Create a file from raw data""" attributes = {'filename': filename, 'source': filedata} return self.transport.POST(url='/file/v2/', body=attributes, type='multipart/form-data')
['def', 'create', '(', 'self', ',', 'filename', ',', 'filedata', ')', ':', 'attributes', '=', '{', "'filename'", ':', 'filename', ',', "'source'", ':', 'filedata', '}', 'return', 'self', '.', 'transport', '.', 'POST', '(', 'url', '=', "'/file/v2/'", ',', 'body', '=', 'attributes', ',', 'type', '=', "'multipart/form-dat...
Create a file from raw data
['Create', 'a', 'file', 'from', 'raw', 'data']
train
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/areas.py#L522-L526
7,981
Falkonry/falkonry-python-client
falkonryclient/service/falkonry.py
FalkonryService.get_assessment
def get_assessment(self, assessment): """ To get Assessment by id """ response = self.http.get('/Assessment/' + str(assessment)) assessment = Schemas.Assessment(assessment=response) return assessment
python
def get_assessment(self, assessment): """ To get Assessment by id """ response = self.http.get('/Assessment/' + str(assessment)) assessment = Schemas.Assessment(assessment=response) return assessment
['def', 'get_assessment', '(', 'self', ',', 'assessment', ')', ':', 'response', '=', 'self', '.', 'http', '.', 'get', '(', "'/Assessment/'", '+', 'str', '(', 'assessment', ')', ')', 'assessment', '=', 'Schemas', '.', 'Assessment', '(', 'assessment', '=', 'response', ')', 'return', 'assessment']
To get Assessment by id
['To', 'get', 'Assessment', 'by', 'id']
train
https://github.com/Falkonry/falkonry-python-client/blob/0aeb2b00293ee94944f1634e9667401b03da29c1/falkonryclient/service/falkonry.py#L82-L88
7,982
nccgroup/Scout2
AWSScout2/services/cloudwatch.py
CloudWatchRegionConfig.parse_alarm
def parse_alarm(self, global_params, region, alarm): """ Parse a single CloudWatch trail :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param alarm: Alarm """ alarm['arn'...
python
def parse_alarm(self, global_params, region, alarm): """ Parse a single CloudWatch trail :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param alarm: Alarm """ alarm['arn'...
['def', 'parse_alarm', '(', 'self', ',', 'global_params', ',', 'region', ',', 'alarm', ')', ':', 'alarm', '[', "'arn'", ']', '=', 'alarm', '.', 'pop', '(', "'AlarmArn'", ')', 'alarm', '[', "'name'", ']', '=', 'alarm', '.', 'pop', '(', "'AlarmName'", ')', '# Drop some data', 'for', 'k', 'in', '[', "'AlarmConfigurationUp...
Parse a single CloudWatch trail :param global_params: Parameters shared for all regions :param region: Name of the AWS region :param alarm: Alarm
['Parse', 'a', 'single', 'CloudWatch', 'trail']
train
https://github.com/nccgroup/Scout2/blob/5d86d46d7ed91a92000496189e9cfa6b98243937/AWSScout2/services/cloudwatch.py#L21-L35
7,983
wavycloud/pyboto3
pyboto3/elasticloadbalancingv2.py
modify_target_group
def modify_target_group(TargetGroupArn=None, HealthCheckProtocol=None, HealthCheckPort=None, HealthCheckPath=None, HealthCheckIntervalSeconds=None, HealthCheckTimeoutSeconds=None, HealthyThresholdCount=None, UnhealthyThresholdCount=None, Matcher=None): """ Modifies the health checks used when evaluating the hea...
python
def modify_target_group(TargetGroupArn=None, HealthCheckProtocol=None, HealthCheckPort=None, HealthCheckPath=None, HealthCheckIntervalSeconds=None, HealthCheckTimeoutSeconds=None, HealthyThresholdCount=None, UnhealthyThresholdCount=None, Matcher=None): """ Modifies the health checks used when evaluating the hea...
['def', 'modify_target_group', '(', 'TargetGroupArn', '=', 'None', ',', 'HealthCheckProtocol', '=', 'None', ',', 'HealthCheckPort', '=', 'None', ',', 'HealthCheckPath', '=', 'None', ',', 'HealthCheckIntervalSeconds', '=', 'None', ',', 'HealthCheckTimeoutSeconds', '=', 'None', ',', 'HealthyThresholdCount', '=', 'None', ...
Modifies the health checks used when evaluating the health state of the targets in the specified target group. To monitor the health of the targets, use DescribeTargetHealth . See also: AWS API Documentation Examples This example changes the configuration of the health checks used to evaluate the ...
['Modifies', 'the', 'health', 'checks', 'used', 'when', 'evaluating', 'the', 'health', 'state', 'of', 'the', 'targets', 'in', 'the', 'specified', 'target', 'group', '.', 'To', 'monitor', 'the', 'health', 'of', 'the', 'targets', 'use', 'DescribeTargetHealth', '.', 'See', 'also', ':', 'AWS', 'API', 'Documentation', 'Exam...
train
https://github.com/wavycloud/pyboto3/blob/924957ccf994303713a4eed90b775ff2ab95b2e5/pyboto3/elasticloadbalancingv2.py#L1532-L1619
7,984
senaite/senaite.core
bika/lims/browser/partition_magic.py
PartitionMagicView.get_sampletype_data
def get_sampletype_data(self): """Returns a list of SampleType data """ for obj in self.get_sampletypes(): info = self.get_base_info(obj) yield info
python
def get_sampletype_data(self): """Returns a list of SampleType data """ for obj in self.get_sampletypes(): info = self.get_base_info(obj) yield info
['def', 'get_sampletype_data', '(', 'self', ')', ':', 'for', 'obj', 'in', 'self', '.', 'get_sampletypes', '(', ')', ':', 'info', '=', 'self', '.', 'get_base_info', '(', 'obj', ')', 'yield', 'info']
Returns a list of SampleType data
['Returns', 'a', 'list', 'of', 'SampleType', 'data']
train
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/partition_magic.py#L155-L160
7,985
aouyar/PyMunin
pysysinfo/system.py
SystemInfo.getCPUuse
def getCPUuse(self): """Return cpu time utilization in seconds. @return: Dictionary of stats. """ hz = os.sysconf('SC_CLK_TCK') info_dict = {} try: fp = open(cpustatFile, 'r') line = fp.readline() fp.close() ex...
python
def getCPUuse(self): """Return cpu time utilization in seconds. @return: Dictionary of stats. """ hz = os.sysconf('SC_CLK_TCK') info_dict = {} try: fp = open(cpustatFile, 'r') line = fp.readline() fp.close() ex...
['def', 'getCPUuse', '(', 'self', ')', ':', 'hz', '=', 'os', '.', 'sysconf', '(', "'SC_CLK_TCK'", ')', 'info_dict', '=', '{', '}', 'try', ':', 'fp', '=', 'open', '(', 'cpustatFile', ',', "'r'", ')', 'line', '=', 'fp', '.', 'readline', '(', ')', 'fp', '.', 'close', '(', ')', 'except', ':', 'raise', 'IOError', '(', "'Fai...
Return cpu time utilization in seconds. @return: Dictionary of stats.
['Return', 'cpu', 'time', 'utilization', 'in', 'seconds', '.']
train
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pysysinfo/system.py#L78-L96
7,986
note35/sinon
sinon/lib/util/CollectionHandler.py
dict_partial_cmp
def dict_partial_cmp(target_dict, dict_list, ducktype): """ Whether partial dict are in dict_list or not """ for called_dict in dict_list: # ignore invalid test case if len(target_dict) > len(called_dict): continue # get the intersection of two dicts intersect...
python
def dict_partial_cmp(target_dict, dict_list, ducktype): """ Whether partial dict are in dict_list or not """ for called_dict in dict_list: # ignore invalid test case if len(target_dict) > len(called_dict): continue # get the intersection of two dicts intersect...
['def', 'dict_partial_cmp', '(', 'target_dict', ',', 'dict_list', ',', 'ducktype', ')', ':', 'for', 'called_dict', 'in', 'dict_list', ':', '# ignore invalid test case', 'if', 'len', '(', 'target_dict', ')', '>', 'len', '(', 'called_dict', ')', ':', 'continue', '# get the intersection of two dicts', 'intersection', '=',...
Whether partial dict are in dict_list or not
['Whether', 'partial', 'dict', 'are', 'in', 'dict_list', 'or', 'not']
train
https://github.com/note35/sinon/blob/f1d551b679b393d64d926a8a279320904c38d0f5/sinon/lib/util/CollectionHandler.py#L115-L136
7,987
NICTA/revrand
revrand/btypes.py
hstack
def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """ vals, b...
python
def hstack(tup): """ Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds """ vals, b...
['def', 'hstack', '(', 'tup', ')', ':', 'vals', ',', 'bounds', '=', 'zip', '(', '*', 'tup', ')', 'stackvalue', '=', 'np', '.', 'hstack', '(', 'vals', ')', 'stackbounds', '=', 'list', '(', 'chain', '(', '*', 'bounds', ')', ')', 'return', 'stackvalue', ',', 'stackbounds']
Horizontally stack a sequence of value bounds pairs. Parameters ---------- tup: sequence a sequence of value, ``Bound`` pairs Returns ------- value: ndarray a horizontally concatenated array1d bounds: a list of Bounds
['Horizontally', 'stack', 'a', 'sequence', 'of', 'value', 'bounds', 'pairs', '.']
train
https://github.com/NICTA/revrand/blob/4c1881b6c1772d2b988518e49dde954f165acfb6/revrand/btypes.py#L374-L394
7,988
fastai/fastai
fastai/vision/data.py
ImageImageList.show_xyzs
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs): "Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`." title = 'Input / Prediction / Target' axs = subplots(len(xs), 3, imgsize=imgsize, figsize=figsize, title=title, w...
python
def show_xyzs(self, xs, ys, zs, imgsize:int=4, figsize:Optional[Tuple[int,int]]=None, **kwargs): "Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`." title = 'Input / Prediction / Target' axs = subplots(len(xs), 3, imgsize=imgsize, figsize=figsize, title=title, w...
['def', 'show_xyzs', '(', 'self', ',', 'xs', ',', 'ys', ',', 'zs', ',', 'imgsize', ':', 'int', '=', '4', ',', 'figsize', ':', 'Optional', '[', 'Tuple', '[', 'int', ',', 'int', ']', ']', '=', 'None', ',', '*', '*', 'kwargs', ')', ':', 'title', '=', "'Input / Prediction / Target'", 'axs', '=', 'subplots', '(', 'len', '('...
Show `xs` (inputs), `ys` (targets) and `zs` (predictions) on a figure of `figsize`.
['Show', 'xs', '(', 'inputs', ')', 'ys', '(', 'targets', ')', 'and', 'zs', '(', 'predictions', ')', 'on', 'a', 'figure', 'of', 'figsize', '.']
train
https://github.com/fastai/fastai/blob/9fb84a5cdefe5a766cdb792b8f5d8971737b7e67/fastai/vision/data.py#L424-L431
7,989
aiogram/aiogram
aiogram/contrib/middlewares/i18n.py
I18nMiddleware.find_locales
def find_locales(self) -> Dict[str, gettext.GNUTranslations]: """ Load all compiled locales from path :return: dict with locales """ translations = {} for name in os.listdir(self.path): if not os.path.isdir(os.path.join(self.path, name)): con...
python
def find_locales(self) -> Dict[str, gettext.GNUTranslations]: """ Load all compiled locales from path :return: dict with locales """ translations = {} for name in os.listdir(self.path): if not os.path.isdir(os.path.join(self.path, name)): con...
['def', 'find_locales', '(', 'self', ')', '->', 'Dict', '[', 'str', ',', 'gettext', '.', 'GNUTranslations', ']', ':', 'translations', '=', '{', '}', 'for', 'name', 'in', 'os', '.', 'listdir', '(', 'self', '.', 'path', ')', ':', 'if', 'not', 'os', '.', 'path', '.', 'isdir', '(', 'os', '.', 'path', '.', 'join', '(', 'sel...
Load all compiled locales from path :return: dict with locales
['Load', 'all', 'compiled', 'locales', 'from', 'path']
train
https://github.com/aiogram/aiogram/blob/2af930149ce2482547721e2c8755c10307295e48/aiogram/contrib/middlewares/i18n.py#L45-L64
7,990
pecan/pecan
pecan/scaffolds/__init__.py
makedirs
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
python
def makedirs(directory): """ Resursively create a named directory. """ parent = os.path.dirname(os.path.abspath(directory)) if not os.path.exists(parent): makedirs(parent) os.mkdir(directory)
['def', 'makedirs', '(', 'directory', ')', ':', 'parent', '=', 'os', '.', 'path', '.', 'dirname', '(', 'os', '.', 'path', '.', 'abspath', '(', 'directory', ')', ')', 'if', 'not', 'os', '.', 'path', '.', 'exists', '(', 'parent', ')', ':', 'makedirs', '(', 'parent', ')', 'os', '.', 'mkdir', '(', 'directory', ')']
Resursively create a named directory.
['Resursively', 'create', 'a', 'named', 'directory', '.']
train
https://github.com/pecan/pecan/blob/833d0653fa0e6bbfb52545b091c30182105f4a82/pecan/scaffolds/__init__.py#L105-L110
7,991
openstack/proliantutils
proliantutils/ilo/ribcl.py
RIBCLOperations.init_model_based_tags
def init_model_based_tags(self, model): """Initializing the model based memory and NIC information tags. It should be called just after instantiating a RIBCL object. ribcl = ribcl.RIBCLOperations(host, login, password, timeout, port, cacert=cacert...
python
def init_model_based_tags(self, model): """Initializing the model based memory and NIC information tags. It should be called just after instantiating a RIBCL object. ribcl = ribcl.RIBCLOperations(host, login, password, timeout, port, cacert=cacert...
['def', 'init_model_based_tags', '(', 'self', ',', 'model', ')', ':', 'self', '.', 'model', '=', 'model', 'if', "'G7'", 'in', 'self', '.', 'model', ':', 'self', '.', 'MEMORY_SIZE_TAG', '=', '"MEMORY_SIZE"', 'self', '.', 'MEMORY_SIZE_NOT_PRESENT_TAG', '=', '"Not Installed"', 'self', '.', 'NIC_INFORMATION_TAG', '=', '"NI...
Initializing the model based memory and NIC information tags. It should be called just after instantiating a RIBCL object. ribcl = ribcl.RIBCLOperations(host, login, password, timeout, port, cacert=cacert) model = ribcl.get_product_name() ...
['Initializing', 'the', 'model', 'based', 'memory', 'and', 'NIC', 'information', 'tags', '.']
train
https://github.com/openstack/proliantutils/blob/86ef3b47b4eca97c221577e3570b0240d6a25f22/proliantutils/ilo/ribcl.py#L96-L118
7,992
DAI-Lab/Copulas
copulas/univariate/base.py
Univariate._replace_constant_methods
def _replace_constant_methods(self): """Replaces conventional distribution methods by its constant counterparts.""" self.cumulative_distribution = self._constant_cumulative_distribution self.percent_point = self._constant_percent_point self.probability_density = self._constant_probabilit...
python
def _replace_constant_methods(self): """Replaces conventional distribution methods by its constant counterparts.""" self.cumulative_distribution = self._constant_cumulative_distribution self.percent_point = self._constant_percent_point self.probability_density = self._constant_probabilit...
['def', '_replace_constant_methods', '(', 'self', ')', ':', 'self', '.', 'cumulative_distribution', '=', 'self', '.', '_constant_cumulative_distribution', 'self', '.', 'percent_point', '=', 'self', '.', '_constant_percent_point', 'self', '.', 'probability_density', '=', 'self', '.', '_constant_probability_density', 'se...
Replaces conventional distribution methods by its constant counterparts.
['Replaces', 'conventional', 'distribution', 'methods', 'by', 'its', 'constant', 'counterparts', '.']
train
https://github.com/DAI-Lab/Copulas/blob/821df61c3d36a6b81ef2883935f935c2eaaa862c/copulas/univariate/base.py#L192-L197
7,993
maas/python-libmaas
maas/client/viscera/machines.py
Machine.deploy
async def deploy( self, *, user_data: typing.Union[bytes, str] = None, distro_series: str = None, hwe_kernel: str = None, comment: str = None, wait: bool = False, wait_interval: int = 5): """Deploy this machine. :param user_data: User-data to provide to the machine w...
python
async def deploy( self, *, user_data: typing.Union[bytes, str] = None, distro_series: str = None, hwe_kernel: str = None, comment: str = None, wait: bool = False, wait_interval: int = 5): """Deploy this machine. :param user_data: User-data to provide to the machine w...
['async', 'def', 'deploy', '(', 'self', ',', '*', ',', 'user_data', ':', 'typing', '.', 'Union', '[', 'bytes', ',', 'str', ']', '=', 'None', ',', 'distro_series', ':', 'str', '=', 'None', ',', 'hwe_kernel', ':', 'str', '=', 'None', ',', 'comment', ':', 'str', '=', 'None', ',', 'wait', ':', 'bool', '=', 'False', ',', 'w...
Deploy this machine. :param user_data: User-data to provide to the machine when booting. If provided as a byte string, it will be base-64 encoded prior to transmission. If provided as a Unicode string it will be assumed to be already base-64 encoded. :param distro_se...
['Deploy', 'this', 'machine', '.']
train
https://github.com/maas/python-libmaas/blob/4092c68ef7fb1753efc843569848e2bcc3415002/maas/client/viscera/machines.py#L484-L528
7,994
photo/openphoto-python
trovebox/objects/action.py
Action.view
def view(self, **kwds): """ Endpoint: /action/<id>/view.json Requests the full contents of the action. Updates the action object's fields with the response. """ result = self._client.action.view(self, **kwds) self._replace_fields(result.get_fields()) self...
python
def view(self, **kwds): """ Endpoint: /action/<id>/view.json Requests the full contents of the action. Updates the action object's fields with the response. """ result = self._client.action.view(self, **kwds) self._replace_fields(result.get_fields()) self...
['def', 'view', '(', 'self', ',', '*', '*', 'kwds', ')', ':', 'result', '=', 'self', '.', '_client', '.', 'action', '.', 'view', '(', 'self', ',', '*', '*', 'kwds', ')', 'self', '.', '_replace_fields', '(', 'result', '.', 'get_fields', '(', ')', ')', 'self', '.', '_update_fields_with_objects', '(', ')']
Endpoint: /action/<id>/view.json Requests the full contents of the action. Updates the action object's fields with the response.
['Endpoint', ':', '/', 'action', '/', '<id', '>', '/', 'view', '.', 'json']
train
https://github.com/photo/openphoto-python/blob/209a1da27c8d8c88dbcf4ea6c6f57031ea1bc44b/trovebox/objects/action.py#L39-L48
7,995
thunder-project/thunder
thunder/series/series.py
Series.center
def center(self, axis=1): """ Subtract the mean either within or across records. Parameters ---------- axis : int, optional, default = 1 Which axis to center along, within (1) or across (0) records. """ if axis == 1: return self.map(lambda...
python
def center(self, axis=1): """ Subtract the mean either within or across records. Parameters ---------- axis : int, optional, default = 1 Which axis to center along, within (1) or across (0) records. """ if axis == 1: return self.map(lambda...
['def', 'center', '(', 'self', ',', 'axis', '=', '1', ')', ':', 'if', 'axis', '==', '1', ':', 'return', 'self', '.', 'map', '(', 'lambda', 'x', ':', 'x', '-', 'mean', '(', 'x', ')', ')', 'elif', 'axis', '==', '0', ':', 'meanval', '=', 'self', '.', 'mean', '(', ')', '.', 'toarray', '(', ')', 'return', 'self', '.', 'map'...
Subtract the mean either within or across records. Parameters ---------- axis : int, optional, default = 1 Which axis to center along, within (1) or across (0) records.
['Subtract', 'the', 'mean', 'either', 'within', 'or', 'across', 'records', '.']
train
https://github.com/thunder-project/thunder/blob/967ff8f3e7c2fabe1705743d95eb2746d4329786/thunder/series/series.py#L350-L365
7,996
planetarypy/planetaryimage
planetaryimage/image.py
PlanetaryImage.image
def image(self): """An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.re...
python
def image(self): """An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.re...
['def', 'image', '(', 'self', ')', ':', 'if', 'self', '.', 'bands', '==', '1', ':', 'return', 'self', '.', 'data', '.', 'squeeze', '(', ')', 'elif', 'self', '.', 'bands', '==', '3', ':', 'return', 'numpy', '.', 'dstack', '(', 'self', '.', 'data', ')']
An Image like array of ``self.data`` convenient for image processing tasks * 2D array for single band, grayscale image data * 3D array for three band, RGB image data Enables working with ``self.data`` as if it were a PIL image. See https://planetaryimage.readthedocs.io/en/latest/usage...
['An', 'Image', 'like', 'array', 'of', 'self', '.', 'data', 'convenient', 'for', 'image', 'processing', 'tasks']
train
https://github.com/planetarypy/planetaryimage/blob/ee9aef4746ff7a003b1457565acb13f5f1db0375/planetaryimage/image.py#L131-L146
7,997
alorence/pysvg-py3
pysvg/builders.py
ShapeBuilder.createPolygon
def createPolygon(self, points, strokewidth=1, stroke='black', fill='none'): """ Creates a Polygon @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the ...
python
def createPolygon(self, points, strokewidth=1, stroke='black', fill='none'): """ Creates a Polygon @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the ...
['def', 'createPolygon', '(', 'self', ',', 'points', ',', 'strokewidth', '=', '1', ',', 'stroke', '=', "'black'", ',', 'fill', '=', "'none'", ')', ':', 'style_dict', '=', '{', "'fill'", ':', 'fill', ',', "'stroke-width'", ':', 'strokewidth', ',', "'stroke'", ':', 'stroke', '}', 'myStyle', '=', 'StyleBuilder', '(', 'sty...
Creates a Polygon @type points: string in the form "x1,y1 x2,y2 x3,y3" @param points: all points relevant to the polygon @type strokewidth: string or int @param strokewidth: width of the pen used to draw @type stroke: string (either css constants like "black" or numerical va...
['Creates', 'a', 'Polygon']
train
https://github.com/alorence/pysvg-py3/blob/ce217a4da3ada44a71d3e2f391d37c67d95c724e/pysvg/builders.py#L100-L117
7,998
django-danceschool/django-danceschool
danceschool/core/models.py
Event.soldOutForRole
def soldOutForRole(self,role,includeTemporaryRegs=False): ''' Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event. ''' return self.numRegisteredForRole( role,includeTemporaryRegs=include...
python
def soldOutForRole(self,role,includeTemporaryRegs=False): ''' Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event. ''' return self.numRegisteredForRole( role,includeTemporaryRegs=include...
['def', 'soldOutForRole', '(', 'self', ',', 'role', ',', 'includeTemporaryRegs', '=', 'False', ')', ':', 'return', 'self', '.', 'numRegisteredForRole', '(', 'role', ',', 'includeTemporaryRegs', '=', 'includeTemporaryRegs', ')', '>=', '(', 'self', '.', 'capacityForRole', '(', 'role', ')', 'or', '0', ')']
Accepts a DanceRole object and responds if the number of registrations for that role exceeds the capacity for that role at this event.
['Accepts', 'a', 'DanceRole', 'object', 'and', 'responds', 'if', 'the', 'number', 'of', 'registrations', 'for', 'that', 'role', 'exceeds', 'the', 'capacity', 'for', 'that', 'role', 'at', 'this', 'event', '.']
train
https://github.com/django-danceschool/django-danceschool/blob/bb08cbf39017a812a5a94bdb4ea34170bf1a30ba/danceschool/core/models.py#L1024-L1030
7,999
openego/ding0
ding0/core/network/grids.py
MVGridDing0.add_ring
def add_ring(self, ring): """Adds a ring to _rings if not already existing""" if ring not in self._rings and isinstance(ring, RingDing0): self._rings.append(ring)
python
def add_ring(self, ring): """Adds a ring to _rings if not already existing""" if ring not in self._rings and isinstance(ring, RingDing0): self._rings.append(ring)
['def', 'add_ring', '(', 'self', ',', 'ring', ')', ':', 'if', 'ring', 'not', 'in', 'self', '.', '_rings', 'and', 'isinstance', '(', 'ring', ',', 'RingDing0', ')', ':', 'self', '.', '_rings', '.', 'append', '(', 'ring', ')']
Adds a ring to _rings if not already existing
['Adds', 'a', 'ring', 'to', '_rings', 'if', 'not', 'already', 'existing']
train
https://github.com/openego/ding0/blob/e2d6528f96255e4bb22ba15514a4f1883564ed5d/ding0/core/network/grids.py#L167-L170