repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
googleapis/google-cloud-python
bigquery/google/cloud/bigquery/client.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/bigquery/google/cloud/bigquery/client.py#L293-L309
def dataset(self, dataset_id, project=None): """Construct a reference to a dataset. :type dataset_id: str :param dataset_id: ID of the dataset. :type project: str :param project: (Optional) project ID for the dataset (defaults to the project of the clien...
[ "def", "dataset", "(", "self", ",", "dataset_id", ",", "project", "=", "None", ")", ":", "if", "project", "is", "None", ":", "project", "=", "self", ".", "project", "return", "DatasetReference", "(", "project", ",", "dataset_id", ")" ]
Construct a reference to a dataset. :type dataset_id: str :param dataset_id: ID of the dataset. :type project: str :param project: (Optional) project ID for the dataset (defaults to the project of the client). :rtype: :class:`google.cloud.bigquery.datas...
[ "Construct", "a", "reference", "to", "a", "dataset", "." ]
python
train
honzamach/pydgets
pydgets/widgets.py
https://github.com/honzamach/pydgets/blob/5ca4ce19fc2d9b5f41441fb9163810f8ca502e79/pydgets/widgets.py#L1294-L1308
def _render_content(self, content, **settings): """ Perform widget rendering, but do not print anything. """ bar_len = int(settings[self.SETTING_BAR_WIDTH]) if not bar_len: bar_len = TERMINAL_WIDTH - 10 percent = content progress = "" progress ...
[ "def", "_render_content", "(", "self", ",", "content", ",", "*", "*", "settings", ")", ":", "bar_len", "=", "int", "(", "settings", "[", "self", ".", "SETTING_BAR_WIDTH", "]", ")", "if", "not", "bar_len", ":", "bar_len", "=", "TERMINAL_WIDTH", "-", "10",...
Perform widget rendering, but do not print anything.
[ "Perform", "widget", "rendering", "but", "do", "not", "print", "anything", "." ]
python
train
alvations/pywsd
pywsd/utils.py
https://github.com/alvations/pywsd/blob/4c12394c8adbcfed71dd912bdbef2e36370821bf/pywsd/utils.py#L29-L34
def remove_tags(text: str) -> str: """ Removes <tags> in angled brackets from text. """ tags = {i:" " for i in re.findall("(<[^>\n]*>)",text.strip())} no_tag_text = reduce(lambda x, kv:x.replace(*kv), tags.iteritems(), text) return " ".join(no_tag_text.split())
[ "def", "remove_tags", "(", "text", ":", "str", ")", "->", "str", ":", "tags", "=", "{", "i", ":", "\" \"", "for", "i", "in", "re", ".", "findall", "(", "\"(<[^>\\n]*>)\"", ",", "text", ".", "strip", "(", ")", ")", "}", "no_tag_text", "=", "reduce",...
Removes <tags> in angled brackets from text.
[ "Removes", "<tags", ">", "in", "angled", "brackets", "from", "text", "." ]
python
train
frictionlessdata/tableschema-pandas-py
tableschema_pandas/mapper.py
https://github.com/frictionlessdata/tableschema-pandas-py/blob/ef941dbc12f5d346e9612f8fec1b4b356b8493ca/tableschema_pandas/mapper.py#L156-L176
def restore_row(self, row, schema, pk): """Restore row from Pandas """ result = [] for field in schema.fields: if schema.primary_key and schema.primary_key[0] == field.name: if field.type == 'number' and np.isnan(pk): pk = None ...
[ "def", "restore_row", "(", "self", ",", "row", ",", "schema", ",", "pk", ")", ":", "result", "=", "[", "]", "for", "field", "in", "schema", ".", "fields", ":", "if", "schema", ".", "primary_key", "and", "schema", ".", "primary_key", "[", "0", "]", ...
Restore row from Pandas
[ "Restore", "row", "from", "Pandas" ]
python
train
klen/muffin-debugtoolbar
muffin_debugtoolbar/tbtools/tbtools.py
https://github.com/klen/muffin-debugtoolbar/blob/b650b35fbe2035888f6bba5dac3073ef01c94dc6/muffin_debugtoolbar/tbtools/tbtools.py#L231-L256
def render_full(self, request, lodgeit_url=None): """Render the Full HTML page with the traceback info.""" app = request.app root_path = request.app.ps.debugtoolbar.cfg.prefix exc = escape(self.exception) summary = self.render_summary(include_title=False, request=request) ...
[ "def", "render_full", "(", "self", ",", "request", ",", "lodgeit_url", "=", "None", ")", ":", "app", "=", "request", ".", "app", "root_path", "=", "request", ".", "app", ".", "ps", ".", "debugtoolbar", ".", "cfg", ".", "prefix", "exc", "=", "escape", ...
Render the Full HTML page with the traceback info.
[ "Render", "the", "Full", "HTML", "page", "with", "the", "traceback", "info", "." ]
python
train
pypa/pipenv
pipenv/vendor/click/globals.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/click/globals.py#L39-L48
def resolve_color_default(color=None): """"Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context. """ if color is not None: return color ctx = get_current_context(silent=True) if ct...
[ "def", "resolve_color_default", "(", "color", "=", "None", ")", ":", "if", "color", "is", "not", "None", ":", "return", "color", "ctx", "=", "get_current_context", "(", "silent", "=", "True", ")", "if", "ctx", "is", "not", "None", ":", "return", "ctx", ...
Internal helper to get the default value of the color flag. If a value is passed it's returned unchanged, otherwise it's looked up from the current context.
[ "Internal", "helper", "to", "get", "the", "default", "value", "of", "the", "color", "flag", ".", "If", "a", "value", "is", "passed", "it", "s", "returned", "unchanged", "otherwise", "it", "s", "looked", "up", "from", "the", "current", "context", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/visual_recognition_v3.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/visual_recognition_v3.py#L789-L809
def _from_dict(cls, _dict): """Initialize a ClassifiedImage object from a json dictionary.""" args = {} if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: args['resolved_url'] = _dict.get('resolved_url') if '...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'source_url'", "in", "_dict", ":", "args", "[", "'source_url'", "]", "=", "_dict", ".", "get", "(", "'source_url'", ")", "if", "'resolved_url'", "in", "_dict", ":", ...
Initialize a ClassifiedImage object from a json dictionary.
[ "Initialize", "a", "ClassifiedImage", "object", "from", "a", "json", "dictionary", "." ]
python
train
PrefPy/prefpy
prefpy/mechanismMcmc.py
https://github.com/PrefPy/prefpy/blob/f395ba3782f05684fa5de0cece387a6da9391d02/prefpy/mechanismMcmc.py#L140-L171
def getRankingBruteForce(self, profile): """ Returns a list that orders all candidates from best to worst when we use brute force to compute Bayesian utilities for an election profile. This function assumes that getCandScoresMapBruteForce(profile) is implemented for the child Mechanism...
[ "def", "getRankingBruteForce", "(", "self", ",", "profile", ")", ":", "# We generate a map that associates each score with the candidates that have that score.", "candScoresMapBruteForce", "=", "self", ".", "getCandScoresMapBruteForce", "(", "profile", ")", "reverseCandScoresMap", ...
Returns a list that orders all candidates from best to worst when we use brute force to compute Bayesian utilities for an election profile. This function assumes that getCandScoresMapBruteForce(profile) is implemented for the child Mechanism class. Note that the returned list gives no indicati...
[ "Returns", "a", "list", "that", "orders", "all", "candidates", "from", "best", "to", "worst", "when", "we", "use", "brute", "force", "to", "compute", "Bayesian", "utilities", "for", "an", "election", "profile", ".", "This", "function", "assumes", "that", "ge...
python
train
ministryofjustice/money-to-prisoners-common
mtp_common/build_tasks/tasks.py
https://github.com/ministryofjustice/money-to-prisoners-common/blob/33c43a2912cb990d9148da7c8718f480f07d90a1/mtp_common/build_tasks/tasks.py#L131-L139
def python_dependencies(context: Context, common_path=None): """ Updates python dependencies """ context.pip_command('install', '-r', context.requirements_file) if common_path: context.pip_command('uninstall', '--yes', 'money-to-prisoners-common') context.pip_command('install', '--fo...
[ "def", "python_dependencies", "(", "context", ":", "Context", ",", "common_path", "=", "None", ")", ":", "context", ".", "pip_command", "(", "'install'", ",", "'-r'", ",", "context", ".", "requirements_file", ")", "if", "common_path", ":", "context", ".", "p...
Updates python dependencies
[ "Updates", "python", "dependencies" ]
python
train
flo-compbio/xlmhg
xlmhg/result.py
https://github.com/flo-compbio/xlmhg/blob/8e5929ee1dc91b95e343b7a2b1b1d6664c4540a1/xlmhg/result.py#L181-L188
def escore(self): """(property) Returns the E-score associated with the result.""" hg_pval_thresh = self.escore_pval_thresh or self.pval escore_tol = self.escore_tol or mhg_cython.get_default_tol() es = mhg_cython.get_xlmhg_escore( self.indices, self.N, self.K, self.X, self.L...
[ "def", "escore", "(", "self", ")", ":", "hg_pval_thresh", "=", "self", ".", "escore_pval_thresh", "or", "self", ".", "pval", "escore_tol", "=", "self", ".", "escore_tol", "or", "mhg_cython", ".", "get_default_tol", "(", ")", "es", "=", "mhg_cython", ".", "...
(property) Returns the E-score associated with the result.
[ "(", "property", ")", "Returns", "the", "E", "-", "score", "associated", "with", "the", "result", "." ]
python
train
KelSolaar/Foundations
foundations/exceptions.py
https://github.com/KelSolaar/Foundations/blob/5c141330faf09dad70a12bc321f4c564917d0a91/foundations/exceptions.py#L171-L196
def extract_locals(trcback): """ Extracts the frames locals of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frames locals. :rtype: list """ output = [] stack = extract_stack(get_inner_most_frame(trcback)) for frame, file_name, line_number, name,...
[ "def", "extract_locals", "(", "trcback", ")", ":", "output", "=", "[", "]", "stack", "=", "extract_stack", "(", "get_inner_most_frame", "(", "trcback", ")", ")", "for", "frame", ",", "file_name", ",", "line_number", ",", "name", ",", "context", ",", "index...
Extracts the frames locals of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frames locals. :rtype: list
[ "Extracts", "the", "frames", "locals", "of", "given", "traceback", "." ]
python
train
Nachtfeuer/pipeline
spline/tools/report/generator.py
https://github.com/Nachtfeuer/pipeline/blob/04ca18c4e95e4349532bb45b768206393e1f2c13/spline/tools/report/generator.py#L26-L45
def generate_html(store): """ Generating HTML report. Args: store (Store): report data. Returns: str: rendered HTML template. """ spline = { 'version': VERSION, 'url': 'https://github.com/Nachtfeuer/pipeline', 'generated': datetime.now().strftime("%A, %d...
[ "def", "generate_html", "(", "store", ")", ":", "spline", "=", "{", "'version'", ":", "VERSION", ",", "'url'", ":", "'https://github.com/Nachtfeuer/pipeline'", ",", "'generated'", ":", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%A, %d. %B %Y - %I...
Generating HTML report. Args: store (Store): report data. Returns: str: rendered HTML template.
[ "Generating", "HTML", "report", "." ]
python
train
rackerlabs/simpl
simpl/rest.py
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/rest.py#L169-L175
def validate_range_values(request, label, kwargs): """Ensure value contained in label is a positive integer.""" value = kwargs.get(label, request.query.get(label)) if value: kwargs[label] = int(value) if kwargs[label] < 0 or kwargs[label] > MAX_PAGE_SIZE: raise ValueError
[ "def", "validate_range_values", "(", "request", ",", "label", ",", "kwargs", ")", ":", "value", "=", "kwargs", ".", "get", "(", "label", ",", "request", ".", "query", ".", "get", "(", "label", ")", ")", "if", "value", ":", "kwargs", "[", "label", "]"...
Ensure value contained in label is a positive integer.
[ "Ensure", "value", "contained", "in", "label", "is", "a", "positive", "integer", "." ]
python
train
portantier/habu
habu/cli/cmd_hasher.py
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_hasher.py#L11-L43
def cmd_hasher(f, algorithm): """Compute various hashes for the input data, that can be a file or a stream. Example: \b $ habu.hasher README.rst md5 992a833cd162047daaa6a236b8ac15ae README.rst ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst sha1 d7dbfd2c5e...
[ "def", "cmd_hasher", "(", "f", ",", "algorithm", ")", ":", "data", "=", "f", ".", "read", "(", ")", "if", "not", "data", ":", "print", "(", "\"Empty file or string!\"", ")", "return", "1", "if", "algorithm", ":", "print", "(", "hasher", "(", "data", ...
Compute various hashes for the input data, that can be a file or a stream. Example: \b $ habu.hasher README.rst md5 992a833cd162047daaa6a236b8ac15ae README.rst ripemd160 0566f9141e65e57cae93e0e3b70d1d8c2ccb0623 README.rst sha1 d7dbfd2c5e2828eb22f776550c826e4166526253 README...
[ "Compute", "various", "hashes", "for", "the", "input", "data", "that", "can", "be", "a", "file", "or", "a", "stream", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/gui/controllers/graphical_editor_gaphas.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/gui/controllers/graphical_editor_gaphas.py#L380-L627
def state_machine_change_after(self, model, prop_name, info): """Called on any change within th state machine This method is called, when any state, transition, data flow, etc. within the state machine changes. This then typically requires a redraw of the graphical editor, to display these chan...
[ "def", "state_machine_change_after", "(", "self", ",", "model", ",", "prop_name", ",", "info", ")", ":", "if", "'method_name'", "in", "info", "and", "info", "[", "'method_name'", "]", "==", "'root_state_change'", ":", "method_name", ",", "model", ",", "result"...
Called on any change within th state machine This method is called, when any state, transition, data flow, etc. within the state machine changes. This then typically requires a redraw of the graphical editor, to display these changes immediately. :param rafcon.gui.models.state_machine.StateMac...
[ "Called", "on", "any", "change", "within", "th", "state", "machine" ]
python
train
eyeseast/propublica-congress
congress/members.py
https://github.com/eyeseast/propublica-congress/blob/03e519341063c5703080b4723112f1831816c77e/congress/members.py#L51-L60
def compare(self, first, second, chamber, type='votes', congress=CURRENT_CONGRESS): """ See how often two members voted together in a given Congress. Takes two member IDs, a chamber and a Congress number. """ check_chamber(chamber) path = "members/{first}/{type}/{second}/...
[ "def", "compare", "(", "self", ",", "first", ",", "second", ",", "chamber", ",", "type", "=", "'votes'", ",", "congress", "=", "CURRENT_CONGRESS", ")", ":", "check_chamber", "(", "chamber", ")", "path", "=", "\"members/{first}/{type}/{second}/{congress}/{chamber}....
See how often two members voted together in a given Congress. Takes two member IDs, a chamber and a Congress number.
[ "See", "how", "often", "two", "members", "voted", "together", "in", "a", "given", "Congress", ".", "Takes", "two", "member", "IDs", "a", "chamber", "and", "a", "Congress", "number", "." ]
python
train
MillionIntegrals/vel
vel/rl/algo/policy_gradient/trpo.py
https://github.com/MillionIntegrals/vel/blob/e0726e1f63742b728966ccae0c8b825ea0ba491a/vel/rl/algo/policy_gradient/trpo.py#L263-L272
def create(max_kl, cg_iters, line_search_iters, cg_damping, entropy_coef, vf_iters, discount_factor, gae_lambda=1.0, improvement_acceptance_ratio=0.1, max_grad_norm=0.5): """ Vel factory function """ return TrpoPolicyGradient( max_kl, int(cg_iters), int(line_search_iters), cg_damping, entropy...
[ "def", "create", "(", "max_kl", ",", "cg_iters", ",", "line_search_iters", ",", "cg_damping", ",", "entropy_coef", ",", "vf_iters", ",", "discount_factor", ",", "gae_lambda", "=", "1.0", ",", "improvement_acceptance_ratio", "=", "0.1", ",", "max_grad_norm", "=", ...
Vel factory function
[ "Vel", "factory", "function" ]
python
train
dereneaton/ipyrad
ipyrad/analysis/tetrad2.py
https://github.com/dereneaton/ipyrad/blob/5eeb8a178160f45faf71bf47cec4abe998a575d1/ipyrad/analysis/tetrad2.py#L1651-L1689
def find_clades(trees, names): """ A subfunc of consensus_tree(). Traverses trees to count clade occurrences. Names are ordered by names, else they are in the order of the first tree. """ ## index names from the first tree if not names: names = trees[0].get_leaf_names() ndict =...
[ "def", "find_clades", "(", "trees", ",", "names", ")", ":", "## index names from the first tree", "if", "not", "names", ":", "names", "=", "trees", "[", "0", "]", ".", "get_leaf_names", "(", ")", "ndict", "=", "{", "j", ":", "i", "for", "i", ",", "j", ...
A subfunc of consensus_tree(). Traverses trees to count clade occurrences. Names are ordered by names, else they are in the order of the first tree.
[ "A", "subfunc", "of", "consensus_tree", "()", ".", "Traverses", "trees", "to", "count", "clade", "occurrences", ".", "Names", "are", "ordered", "by", "names", "else", "they", "are", "in", "the", "order", "of", "the", "first", "tree", "." ]
python
valid
josiah-wolf-oberholtzer/uqbar
uqbar/sphinx/api.py
https://github.com/josiah-wolf-oberholtzer/uqbar/blob/eca7fefebbbee1e2ae13bf5d6baa838be66b1db6/uqbar/sphinx/api.py#L116-L134
def setup(app) -> Dict[str, Any]: """ Sets up Sphinx extension. """ app.add_config_value("uqbar_api_directory_name", "api", "env") app.add_config_value("uqbar_api_document_empty_modules", False, "env") app.add_config_value("uqbar_api_document_private_members", False, "env") app.add_config_va...
[ "def", "setup", "(", "app", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "app", ".", "add_config_value", "(", "\"uqbar_api_directory_name\"", ",", "\"api\"", ",", "\"env\"", ")", "app", ".", "add_config_value", "(", "\"uqbar_api_document_empty_modules\""...
Sets up Sphinx extension.
[ "Sets", "up", "Sphinx", "extension", "." ]
python
train
SKA-ScienceDataProcessor/integration-prototype
sip/tango_control/tango_subarray/app/subarray_device.py
https://github.com/SKA-ScienceDataProcessor/integration-prototype/blob/8c8006de6ad71dcd44114b0338780738079c87d4/sip/tango_control/tango_subarray/app/subarray_device.py#L16-L20
def init_device(self): """Initialise the device.""" Device.init_device(self) time.sleep(0.1) self.set_state(DevState.STANDBY)
[ "def", "init_device", "(", "self", ")", ":", "Device", ".", "init_device", "(", "self", ")", "time", ".", "sleep", "(", "0.1", ")", "self", ".", "set_state", "(", "DevState", ".", "STANDBY", ")" ]
Initialise the device.
[ "Initialise", "the", "device", "." ]
python
train
zetaops/zengine
zengine/messaging/views.py
https://github.com/zetaops/zengine/blob/b5bc32d3b37bca799f8985be916f04528ac79e4a/zengine/messaging/views.py#L794-L822
def edit_message(current): """ Edit a message a user own. .. code-block:: python # request: { 'view':'_zops_edit_message', 'message': { 'body': string, # message text 'key': key } } # response: ...
[ "def", "edit_message", "(", "current", ")", ":", "current", ".", "output", "=", "{", "'status'", ":", "'OK'", ",", "'code'", ":", "200", "}", "in_msg", "=", "current", ".", "input", "[", "'message'", "]", "try", ":", "msg", "=", "Message", "(", "curr...
Edit a message a user own. .. code-block:: python # request: { 'view':'_zops_edit_message', 'message': { 'body': string, # message text 'key': key } } # response: { 'status': string,...
[ "Edit", "a", "message", "a", "user", "own", "." ]
python
train
Atomistica/atomistica
src/python/atomistica/mdcore_io.py
https://github.com/Atomistica/atomistica/blob/5ed79d776c92b91a566be22615bfb304ecc75db7/src/python/atomistica/mdcore_io.py#L164-L190
def read_cyc(this, fn, conv=1.0): """ Read the lattice information from a cyc.dat file (i.e., tblmd input file) """ f = paropen(fn, "r") f.readline() f.readline() f.readline() f.readline() cell = np.array( [ [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ] ] ) l = f.readline()...
[ "def", "read_cyc", "(", "this", ",", "fn", ",", "conv", "=", "1.0", ")", ":", "f", "=", "paropen", "(", "fn", ",", "\"r\"", ")", "f", ".", "readline", "(", ")", "f", ".", "readline", "(", ")", "f", ".", "readline", "(", ")", "f", ".", "readli...
Read the lattice information from a cyc.dat file (i.e., tblmd input file)
[ "Read", "the", "lattice", "information", "from", "a", "cyc", ".", "dat", "file", "(", "i", ".", "e", ".", "tblmd", "input", "file", ")" ]
python
train
aouyar/PyMunin
pymunin/plugins/memcachedstats.py
https://github.com/aouyar/PyMunin/blob/4f58a64b6b37c85a84cc7e1e07aafaa0321b249d/pymunin/plugins/memcachedstats.py#L305-L440
def retrieveVals(self): """Retrieve values for graphs.""" if self._stats is None: serverInfo = MemcachedInfo(self._host, self._port, self._socket_file) stats = serverInfo.getStats() else: stats = self._stats if stats is None: raise Excepti...
[ "def", "retrieveVals", "(", "self", ")", ":", "if", "self", ".", "_stats", "is", "None", ":", "serverInfo", "=", "MemcachedInfo", "(", "self", ".", "_host", ",", "self", ".", "_port", ",", "self", ".", "_socket_file", ")", "stats", "=", "serverInfo", "...
Retrieve values for graphs.
[ "Retrieve", "values", "for", "graphs", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/assistant_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/assistant_v1.py#L5485-L5492
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'pagination') and self.pagination is not None: ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'intents'", ")", "and", "self", ".", "intents", "is", "not", "None", ":", "_dict", "[", "'intents'", "]", "=", "[", "x", ".", "_to_dict", "(", "...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
michael-lazar/rtv
rtv/packages/praw/__init__.py
https://github.com/michael-lazar/rtv/blob/ccef2af042566ad384977028cf0bde01bc524dda/rtv/packages/praw/__init__.py#L491-L500
def evict(self, urls): """Evict url(s) from the cache. :param urls: An iterable containing normalized urls. :returns: The number of items removed from the cache. """ if isinstance(urls, six.string_types): urls = (urls,) return self.handler.evict(urls)
[ "def", "evict", "(", "self", ",", "urls", ")", ":", "if", "isinstance", "(", "urls", ",", "six", ".", "string_types", ")", ":", "urls", "=", "(", "urls", ",", ")", "return", "self", ".", "handler", ".", "evict", "(", "urls", ")" ]
Evict url(s) from the cache. :param urls: An iterable containing normalized urls. :returns: The number of items removed from the cache.
[ "Evict", "url", "(", "s", ")", "from", "the", "cache", "." ]
python
train
evonove/django-stored-messages
stored_messages/api.py
https://github.com/evonove/django-stored-messages/blob/23b71f952d5d3fd03285f5e700879d05796ef7ba/stored_messages/api.py#L12-L28
def add_message_for(users, level, message_text, extra_tags='', date=None, url=None, fail_silently=False): """ Send a message to a list of users without passing through `django.contrib.messages` :param users: an iterable containing the recipients of the messages :param level: message level :param me...
[ "def", "add_message_for", "(", "users", ",", "level", ",", "message_text", ",", "extra_tags", "=", "''", ",", "date", "=", "None", ",", "url", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "BackendClass", "=", "stored_messages_settings", ".", ...
Send a message to a list of users without passing through `django.contrib.messages` :param users: an iterable containing the recipients of the messages :param level: message level :param message_text: the string containing the message :param extra_tags: like the Django api, a string containing extra ta...
[ "Send", "a", "message", "to", "a", "list", "of", "users", "without", "passing", "through", "django", ".", "contrib", ".", "messages" ]
python
valid
etcher-be/emiz
emiz/avwx/__init__.py
https://github.com/etcher-be/emiz/blob/1c3e32711921d7e600e85558ffe5d337956372de/emiz/avwx/__init__.py#L148-L154
def summary(self): # type: ignore """ Condensed summary for each forecast created from translations """ if not self.translations: self.update() return [summary.taf(trans) for trans in self.translations.forecast]
[ "def", "summary", "(", "self", ")", ":", "# type: ignore", "if", "not", "self", ".", "translations", ":", "self", ".", "update", "(", ")", "return", "[", "summary", ".", "taf", "(", "trans", ")", "for", "trans", "in", "self", ".", "translations", ".", ...
Condensed summary for each forecast created from translations
[ "Condensed", "summary", "for", "each", "forecast", "created", "from", "translations" ]
python
train
modin-project/modin
modin/pandas/indexing.py
https://github.com/modin-project/modin/blob/5b77d242596560c646b8405340c9ce64acb183cb/modin/pandas/indexing.py#L127-L140
def _compute_ndim(row_loc, col_loc): """Compute the ndim of result from locators """ row_scaler = is_scalar(row_loc) col_scaler = is_scalar(col_loc) if row_scaler and col_scaler: ndim = 0 elif row_scaler ^ col_scaler: ndim = 1 else: ndim = 2 return ndim
[ "def", "_compute_ndim", "(", "row_loc", ",", "col_loc", ")", ":", "row_scaler", "=", "is_scalar", "(", "row_loc", ")", "col_scaler", "=", "is_scalar", "(", "col_loc", ")", "if", "row_scaler", "and", "col_scaler", ":", "ndim", "=", "0", "elif", "row_scaler", ...
Compute the ndim of result from locators
[ "Compute", "the", "ndim", "of", "result", "from", "locators" ]
python
train
sampsyo/confuse
setup.py
https://github.com/sampsyo/confuse/blob/9ff0992e30470f6822824711950e6dd906e253fb/setup.py#L21-L30
def export_live_eggs(self, env=False): """Adds all of the eggs in the current environment to PYTHONPATH.""" path_eggs = [p for p in sys.path if p.endswith('.egg')] command = self.get_finalized_command("egg_info") egg_base = path.abspath(command.egg_base) unique_path_eggs = set(...
[ "def", "export_live_eggs", "(", "self", ",", "env", "=", "False", ")", ":", "path_eggs", "=", "[", "p", "for", "p", "in", "sys", ".", "path", "if", "p", ".", "endswith", "(", "'.egg'", ")", "]", "command", "=", "self", ".", "get_finalized_command", "...
Adds all of the eggs in the current environment to PYTHONPATH.
[ "Adds", "all", "of", "the", "eggs", "in", "the", "current", "environment", "to", "PYTHONPATH", "." ]
python
train
volafiled/python-volapi
volapi/volapi.py
https://github.com/volafiled/python-volapi/blob/5f0bc03dbde703264ac6ed494e2050761f688a3e/volapi/volapi.py#L232-L267
def on_message(self, new_data): """Processes incoming messages according to engine-io rules""" # https://github.com/socketio/engine.io-protocol LOGGER.debug("new frame [%r]", new_data) try: what = int(new_data[0]) data = new_data[1:] data = data and f...
[ "def", "on_message", "(", "self", ",", "new_data", ")", ":", "# https://github.com/socketio/engine.io-protocol", "LOGGER", ".", "debug", "(", "\"new frame [%r]\"", ",", "new_data", ")", "try", ":", "what", "=", "int", "(", "new_data", "[", "0", "]", ")", "data...
Processes incoming messages according to engine-io rules
[ "Processes", "incoming", "messages", "according", "to", "engine", "-", "io", "rules" ]
python
train
rflamary/POT
ot/dr.py
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L110-L203
def wda(X, y, p=2, reg=1, k=10, solver=None, maxiter=100, verbose=0, P0=None): """ Wasserstein Discriminant Analysis [11]_ The function solves the following optimization problem: .. math:: P = \\text{arg}\min_P \\frac{\\sum_i W(PX^i,PX^i)}{\\sum_{i,j\\neq i} W(PX^i,PX^j)} where : - :...
[ "def", "wda", "(", "X", ",", "y", ",", "p", "=", "2", ",", "reg", "=", "1", ",", "k", "=", "10", ",", "solver", "=", "None", ",", "maxiter", "=", "100", ",", "verbose", "=", "0", ",", "P0", "=", "None", ")", ":", "# noqa", "mx", "=", "np"...
Wasserstein Discriminant Analysis [11]_ The function solves the following optimization problem: .. math:: P = \\text{arg}\min_P \\frac{\\sum_i W(PX^i,PX^i)}{\\sum_{i,j\\neq i} W(PX^i,PX^j)} where : - :math:`P` is a linear projection operator in the Stiefel(p,d) manifold - :math:`W` is en...
[ "Wasserstein", "Discriminant", "Analysis", "[", "11", "]", "_" ]
python
train
ankitmathur3193/song-cli
song/commands/FileDownload.py
https://github.com/ankitmathur3193/song-cli/blob/ca8ccfe547e9d702313ff6d14e81ae4355989a67/song/commands/FileDownload.py#L27-L74
def file_download_using_requests(self,url): '''It will download file specified by url using requests module''' file_name=url.split('/')[-1] if os.path.exists(os.path.join(os.getcwd(),file_name)): print 'File already exists' return #print 'Downloading file %s '%file_name #print 'Downloading from %s'%url...
[ "def", "file_download_using_requests", "(", "self", ",", "url", ")", ":", "file_name", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "os", ".", "ge...
It will download file specified by url using requests module
[ "It", "will", "download", "file", "specified", "by", "url", "using", "requests", "module" ]
python
test
GoogleCloudPlatform/cloud-debug-python
src/googleclouddebugger/capture_collector.py
https://github.com/GoogleCloudPlatform/cloud-debug-python/blob/89ce3782c98b814838a3ecb5479ed3882368cbee/src/googleclouddebugger/capture_collector.py#L360-L383
def CaptureFrameLocals(self, frame): """Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple. """ # Capture all local variables (including method arguments). variables = {n: self.Captur...
[ "def", "CaptureFrameLocals", "(", "self", ",", "frame", ")", ":", "# Capture all local variables (including method arguments).", "variables", "=", "{", "n", ":", "self", ".", "CaptureNamedVariable", "(", "n", ",", "v", ",", "1", ",", "self", ".", "default_capture_...
Captures local variables and arguments of the specified frame. Args: frame: frame to capture locals and arguments. Returns: (arguments, locals) tuple.
[ "Captures", "local", "variables", "and", "arguments", "of", "the", "specified", "frame", "." ]
python
train
pyviz/holoviews
holoviews/core/data/interface.py
https://github.com/pyviz/holoviews/blob/ae0dd2f3de448b0ca5e9065aabd6ef8d84c7e655/holoviews/core/data/interface.py#L278-L314
def select_mask(cls, dataset, selection): """ Given a Dataset object and a dictionary with dimension keys and selection keys (i.e tuple ranges, slices, sets, lists or literals) return a boolean mask over the rows in the Dataset object that have been selected. """ ...
[ "def", "select_mask", "(", "cls", ",", "dataset", ",", "selection", ")", ":", "mask", "=", "np", ".", "ones", "(", "len", "(", "dataset", ")", ",", "dtype", "=", "np", ".", "bool", ")", "for", "dim", ",", "k", "in", "selection", ".", "items", "("...
Given a Dataset object and a dictionary with dimension keys and selection keys (i.e tuple ranges, slices, sets, lists or literals) return a boolean mask over the rows in the Dataset object that have been selected.
[ "Given", "a", "Dataset", "object", "and", "a", "dictionary", "with", "dimension", "keys", "and", "selection", "keys", "(", "i", ".", "e", "tuple", "ranges", "slices", "sets", "lists", "or", "literals", ")", "return", "a", "boolean", "mask", "over", "the", ...
python
train
gwastro/pycbc
pycbc/psd/analytical.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/psd/analytical.py#L124-L144
def flat_unity(length, delta_f, low_freq_cutoff): """ Returns a FrequencySeries of ones above the low_frequency_cutoff. Parameters ---------- length : int Length of output Frequencyseries. delta_f : float Frequency step for output FrequencySeries. low_freq_cutoff : int L...
[ "def", "flat_unity", "(", "length", ",", "delta_f", ",", "low_freq_cutoff", ")", ":", "fseries", "=", "FrequencySeries", "(", "numpy", ".", "ones", "(", "length", ")", ",", "delta_f", "=", "delta_f", ")", "kmin", "=", "int", "(", "low_freq_cutoff", "/", ...
Returns a FrequencySeries of ones above the low_frequency_cutoff. Parameters ---------- length : int Length of output Frequencyseries. delta_f : float Frequency step for output FrequencySeries. low_freq_cutoff : int Low-frequency cutoff for output FrequencySeries. Retur...
[ "Returns", "a", "FrequencySeries", "of", "ones", "above", "the", "low_frequency_cutoff", "." ]
python
train
projectatomic/atomic-reactor
atomic_reactor/util.py
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/util.py#L1584-L1592
def update_from_dict(self, source): """Update records of the digests of images from a dictionary (no validation is performed) :param dict source: data """ assert isinstance(source, dict) source_copy = deepcopy(source) # no mutable side effects self._images_diges...
[ "def", "update_from_dict", "(", "self", ",", "source", ")", ":", "assert", "isinstance", "(", "source", ",", "dict", ")", "source_copy", "=", "deepcopy", "(", "source", ")", "# no mutable side effects", "self", ".", "_images_digests", ".", "update", "(", "sour...
Update records of the digests of images from a dictionary (no validation is performed) :param dict source: data
[ "Update", "records", "of", "the", "digests", "of", "images", "from", "a", "dictionary", "(", "no", "validation", "is", "performed", ")" ]
python
train
internetarchive/brozzler
brozzler/model.py
https://github.com/internetarchive/brozzler/blob/411b3f266a38b9bb942021c0121ebd8e5ca66447/brozzler/model.py#L74-L108
def new_job(frontier, job_conf): '''Returns new Job.''' validate_conf(job_conf) job = Job(frontier.rr, { "conf": job_conf, "status": "ACTIVE", "started": doublethink.utcnow()}) if "id" in job_conf: job.id = job_conf["id"] if "max_claimed_sites" in job_conf: ...
[ "def", "new_job", "(", "frontier", ",", "job_conf", ")", ":", "validate_conf", "(", "job_conf", ")", "job", "=", "Job", "(", "frontier", ".", "rr", ",", "{", "\"conf\"", ":", "job_conf", ",", "\"status\"", ":", "\"ACTIVE\"", ",", "\"started\"", ":", "dou...
Returns new Job.
[ "Returns", "new", "Job", "." ]
python
train
threeML/astromodels
astromodels/core/model.py
https://github.com/threeML/astromodels/blob/9aac365a372f77603039533df9a6b694c1e360d5/astromodels/core/model.py#L392-L403
def remove_independent_variable(self, variable_name): """ Remove an independent variable which was added with add_independent_variable :param variable_name: name of variable to remove :return: """ self._remove_child(variable_name) # Remove also from the list of...
[ "def", "remove_independent_variable", "(", "self", ",", "variable_name", ")", ":", "self", ".", "_remove_child", "(", "variable_name", ")", "# Remove also from the list of independent variables", "self", ".", "_independent_variables", ".", "pop", "(", "variable_name", ")"...
Remove an independent variable which was added with add_independent_variable :param variable_name: name of variable to remove :return:
[ "Remove", "an", "independent", "variable", "which", "was", "added", "with", "add_independent_variable" ]
python
train
senaite/senaite.core
bika/lims/content/abstractanalysis.py
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/content/abstractanalysis.py#L1123-L1129
def getAttachmentUIDs(self): """Used to populate metadata, so that we don't need full objects of analyses when working with their attachments. """ attachments = self.getAttachment() uids = [att.UID() for att in attachments] return uids
[ "def", "getAttachmentUIDs", "(", "self", ")", ":", "attachments", "=", "self", ".", "getAttachment", "(", ")", "uids", "=", "[", "att", ".", "UID", "(", ")", "for", "att", "in", "attachments", "]", "return", "uids" ]
Used to populate metadata, so that we don't need full objects of analyses when working with their attachments.
[ "Used", "to", "populate", "metadata", "so", "that", "we", "don", "t", "need", "full", "objects", "of", "analyses", "when", "working", "with", "their", "attachments", "." ]
python
train
titusjan/argos
argos/utils/masks.py
https://github.com/titusjan/argos/blob/20d0a3cae26c36ea789a5d219c02ca7df21279dd/argos/utils/masks.py#L338-L367
def maskedEqual(array, missingValue): """ Mask an array where equal to a given (missing)value. Unfortunately ma.masked_equal does not work with structured arrays. See: https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html If the data is a structured array the mask is appl...
[ "def", "maskedEqual", "(", "array", ",", "missingValue", ")", ":", "if", "array_is_structured", "(", "array", ")", ":", "# Enforce the array to be masked", "if", "not", "isinstance", "(", "array", ",", "ma", ".", "MaskedArray", ")", ":", "array", "=", "ma", ...
Mask an array where equal to a given (missing)value. Unfortunately ma.masked_equal does not work with structured arrays. See: https://mail.scipy.org/pipermail/numpy-discussion/2011-July/057669.html If the data is a structured array the mask is applied for every field (i.e. forming a lo...
[ "Mask", "an", "array", "where", "equal", "to", "a", "given", "(", "missing", ")", "value", "." ]
python
train
agile-geoscience/striplog
striplog/legend.py
https://github.com/agile-geoscience/striplog/blob/8033b673a151f96c29802b43763e863519a3124c/striplog/legend.py#L637-L682
def to_csv(self): """ Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV. """ # We can't delegate this to Decor because we need to know the superset # of all Decor properties. There may be lots of blanks. header...
[ "def", "to_csv", "(", "self", ")", ":", "# We can't delegate this to Decor because we need to know the superset", "# of all Decor properties. There may be lots of blanks.", "header", "=", "[", "]", "component_header", "=", "[", "]", "for", "row", "in", "self", ":", "for", ...
Renders a legend as a CSV string. No arguments. Returns: str: The legend as a CSV.
[ "Renders", "a", "legend", "as", "a", "CSV", "string", "." ]
python
test
benedictpaten/sonLib
bioio.py
https://github.com/benedictpaten/sonLib/blob/1decb75bb439b70721ec776f685ce98e25217d26/bioio.py#L199-L213
def popenCatch(command, stdinString=None): """Runs a command and return standard out. """ logger.debug("Running the command: %s" % command) if stdinString != None: process = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bu...
[ "def", "popenCatch", "(", "command", ",", "stdinString", "=", "None", ")", ":", "logger", ".", "debug", "(", "\"Running the command: %s\"", "%", "command", ")", "if", "stdinString", "!=", "None", ":", "process", "=", "subprocess", ".", "Popen", "(", "command...
Runs a command and return standard out.
[ "Runs", "a", "command", "and", "return", "standard", "out", "." ]
python
train
jwodder/javaproperties
javaproperties/reading.py
https://github.com/jwodder/javaproperties/blob/8b48f040305217ebeb80c98c4354691bbb01429b/javaproperties/reading.py#L38-L66
def loads(s, object_pairs_hook=dict): """ Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. By defau...
[ "def", "loads", "(", "s", ",", "object_pairs_hook", "=", "dict", ")", ":", "fp", "=", "BytesIO", "(", "s", ")", "if", "isinstance", "(", "s", ",", "binary_type", ")", "else", "StringIO", "(", "s", ")", "return", "load", "(", "fp", ",", "object_pairs_...
Parse the contents of the string ``s`` as a simple line-oriented ``.properties`` file and return a `dict` of the key-value pairs. ``s`` may be either a text string or bytes string. If it is a bytes string, its contents are decoded as Latin-1. By default, the key-value pairs extracted from ``s`` are c...
[ "Parse", "the", "contents", "of", "the", "string", "s", "as", "a", "simple", "line", "-", "oriented", ".", "properties", "file", "and", "return", "a", "dict", "of", "the", "key", "-", "value", "pairs", "." ]
python
train
obulpathi/cdn-fastly-python
fastly/__init__.py
https://github.com/obulpathi/cdn-fastly-python/blob/db2564b047e8af4bce72c3b88d6c27d3d0291425/fastly/__init__.py#L965-L968
def deactivate_version(self, service_id, version_number): """Deactivate the current version.""" content = self._fetch("/service/%s/version/%d/deactivate" % (service_id, version_number), method="PUT") return FastlyVersion(self, content)
[ "def", "deactivate_version", "(", "self", ",", "service_id", ",", "version_number", ")", ":", "content", "=", "self", ".", "_fetch", "(", "\"/service/%s/version/%d/deactivate\"", "%", "(", "service_id", ",", "version_number", ")", ",", "method", "=", "\"PUT\"", ...
Deactivate the current version.
[ "Deactivate", "the", "current", "version", "." ]
python
train
AltSchool/dynamic-rest
dynamic_rest/viewsets.py
https://github.com/AltSchool/dynamic-rest/blob/5b0338c3dd8bc638d60c3bb92645857c5b89c920/dynamic_rest/viewsets.py#L94-L144
def initialize_request(self, request, *args, **kargs): """ Override DRF initialize_request() method to swap request.GET (which is aliased by request.query_params) with a mutable instance of QueryParams, and to convert request MergeDict to a subclass of dict for consistency (Merge...
[ "def", "initialize_request", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "def", "handle_encodings", "(", "request", ")", ":", "\"\"\"\n WSGIRequest does not support Unicode values in the query string.\n WSGIRequest ...
Override DRF initialize_request() method to swap request.GET (which is aliased by request.query_params) with a mutable instance of QueryParams, and to convert request MergeDict to a subclass of dict for consistency (MergeDict is not a subclass of dict)
[ "Override", "DRF", "initialize_request", "()", "method", "to", "swap", "request", ".", "GET", "(", "which", "is", "aliased", "by", "request", ".", "query_params", ")", "with", "a", "mutable", "instance", "of", "QueryParams", "and", "to", "convert", "request", ...
python
train
inspirehep/harvesting-kit
harvestingkit/ftp_utils.py
https://github.com/inspirehep/harvesting-kit/blob/33a7f8aa9dade1d863110c6d8b27dfd955cb471f/harvestingkit/ftp_utils.py#L143-L162
def ls(self, folder=''): """ Lists the files and folders of a specific directory default is the current working directory. :param folder: the folder to be listed. :type folder: string :returns: a tuple with the list of files in the folder and the list of subfo...
[ "def", "ls", "(", "self", ",", "folder", "=", "''", ")", ":", "current_folder", "=", "self", ".", "_ftp", ".", "pwd", "(", ")", "self", ".", "cd", "(", "folder", ")", "contents", "=", "[", "]", "self", ".", "_ftp", ".", "retrlines", "(", "'LIST'"...
Lists the files and folders of a specific directory default is the current working directory. :param folder: the folder to be listed. :type folder: string :returns: a tuple with the list of files in the folder and the list of subfolders in the folder.
[ "Lists", "the", "files", "and", "folders", "of", "a", "specific", "directory", "default", "is", "the", "current", "working", "directory", "." ]
python
valid
urinieto/msaf
msaf/base.py
https://github.com/urinieto/msaf/blob/9dbb57d77a1310465a65cc40f1641d083ca74385/msaf/base.py#L112-L140
def estimate_beats(self): """Estimates the beats using librosa. Returns ------- times: np.array Times of estimated beats in seconds. frames: np.array Frame indeces of estimated beats. """ # Compute harmonic-percussive source separation if ...
[ "def", "estimate_beats", "(", "self", ")", ":", "# Compute harmonic-percussive source separation if needed", "if", "self", ".", "_audio_percussive", "is", "None", ":", "self", ".", "_audio_harmonic", ",", "self", ".", "_audio_percussive", "=", "self", ".", "compute_HP...
Estimates the beats using librosa. Returns ------- times: np.array Times of estimated beats in seconds. frames: np.array Frame indeces of estimated beats.
[ "Estimates", "the", "beats", "using", "librosa", "." ]
python
test
astrorafael/twisted-mqtt
examples/subscriber.py
https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/examples/subscriber.py#L72-L87
def connectToBroker(self, protocol): ''' Connect to MQTT broker ''' self.protocol = protocol self.protocol.onPublish = self.onPublish self.protocol.onDisconnection = self.onDisconnection self.protocol.setWindowSize(3) try: ...
[ "def", "connectToBroker", "(", "self", ",", "protocol", ")", ":", "self", ".", "protocol", "=", "protocol", "self", ".", "protocol", ".", "onPublish", "=", "self", ".", "onPublish", "self", ".", "protocol", ".", "onDisconnection", "=", "self", ".", "onDisc...
Connect to MQTT broker
[ "Connect", "to", "MQTT", "broker" ]
python
test
openstack/networking-arista
networking_arista/common/db_lib.py
https://github.com/openstack/networking-arista/blob/07ce6b1fc62ff74308a6eabfc4cc0ee09fb7b0fe/networking_arista/common/db_lib.py#L204-L216
def get_tenants(tenant_id=None): """Returns list of all project/tenant ids that may be relevant on CVX""" if tenant_id == '': return [] session = db.get_reader_session() project_ids = set() with session.begin(): for m in [models_v2.Network, models_v2.Port]: q = session.qu...
[ "def", "get_tenants", "(", "tenant_id", "=", "None", ")", ":", "if", "tenant_id", "==", "''", ":", "return", "[", "]", "session", "=", "db", ".", "get_reader_session", "(", ")", "project_ids", "=", "set", "(", ")", "with", "session", ".", "begin", "(",...
Returns list of all project/tenant ids that may be relevant on CVX
[ "Returns", "list", "of", "all", "project", "/", "tenant", "ids", "that", "may", "be", "relevant", "on", "CVX" ]
python
train
Skype4Py/Skype4Py
Skype4Py/utils.py
https://github.com/Skype4Py/Skype4Py/blob/c48d83f7034109fe46315d45a066126002c6e0d4/Skype4Py/utils.py#L493-L507
def _AddEvents(cls, Class): """Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class. """ def make_e...
[ "def", "_AddEvents", "(", "cls", ",", "Class", ")", ":", "def", "make_event", "(", "event", ")", ":", "return", "property", "(", "lambda", "self", ":", "self", ".", "_GetDefaultEventHandler", "(", "event", ")", ",", "lambda", "self", ",", "Value", ":", ...
Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class.
[ "Adds", "events", "based", "on", "the", "attributes", "of", "the", "given", "...", "Events", "class", ".", ":", "Parameters", ":", "Class", ":", "class", "An", "...", "Events", "class", "whose", "methods", "define", "events", "that", "may", "occur", "in", ...
python
train
jepegit/cellpy
cellpy/utils/batch_tools/engines.py
https://github.com/jepegit/cellpy/blob/9f4a84cdd11f72cfa02cda8c2d7b5174abbb7370/cellpy/utils/batch_tools/engines.py#L87-L131
def simple_db_engine(reader=None, srnos=None): """engine that gets values from the simple excel 'db'""" if reader is None: reader = dbreader.Reader() logger.debug("No reader provided. Creating one myself.") info_dict = dict() info_dict["filenames"] = [reader.get_cell_name(srno) for srn...
[ "def", "simple_db_engine", "(", "reader", "=", "None", ",", "srnos", "=", "None", ")", ":", "if", "reader", "is", "None", ":", "reader", "=", "dbreader", ".", "Reader", "(", ")", "logger", ".", "debug", "(", "\"No reader provided. Creating one myself.\"", ")...
engine that gets values from the simple excel 'db
[ "engine", "that", "gets", "values", "from", "the", "simple", "excel", "db" ]
python
train
django-auth-ldap/django-auth-ldap
django_auth_ldap/backend.py
https://github.com/django-auth-ldap/django-auth-ldap/blob/9ce3c2825527f8faa1793958b041816e63d839af/django_auth_ldap/backend.py#L688-L742
def _normalize_mirror_settings(self): """ Validates the group mirroring settings and converts them as necessary. """ def malformed_mirror_groups_except(): return ImproperlyConfigured( "{} must be a collection of group names".format( self.s...
[ "def", "_normalize_mirror_settings", "(", "self", ")", ":", "def", "malformed_mirror_groups_except", "(", ")", ":", "return", "ImproperlyConfigured", "(", "\"{} must be a collection of group names\"", ".", "format", "(", "self", ".", "settings", ".", "_name", "(", "\"...
Validates the group mirroring settings and converts them as necessary.
[ "Validates", "the", "group", "mirroring", "settings", "and", "converts", "them", "as", "necessary", "." ]
python
train
proycon/pynlpl
pynlpl/formats/sonar.py
https://github.com/proycon/pynlpl/blob/7707f69a91caaa6cde037f0d0379f1d42500a68b/pynlpl/formats/sonar.py#L235-L244
def validate(self, formats_dir="../formats/"): """checks if the document is valid""" #TODO: download XSD from web if self.inline: xmlschema = ElementTree.XMLSchema(ElementTree.parse(StringIO("\n".join(open(formats_dir+"dcoi-dsc.xsd").readlines())))) xmlschema.assertValid(...
[ "def", "validate", "(", "self", ",", "formats_dir", "=", "\"../formats/\"", ")", ":", "#TODO: download XSD from web", "if", "self", ".", "inline", ":", "xmlschema", "=", "ElementTree", ".", "XMLSchema", "(", "ElementTree", ".", "parse", "(", "StringIO", "(", "...
checks if the document is valid
[ "checks", "if", "the", "document", "is", "valid" ]
python
train
faucamp/python-gsmmodem
gsmmodem/modem.py
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/modem.py#L1088-L1112
def deleteMultipleStoredSms(self, delFlag=4, memory=None): """ Deletes all SMS messages that have the specified read status. The messages are read from the memory set by the "memory" parameter. The value of the "delFlag" paramater is the same as the "DelFlag" parameter of the +CMGD comm...
[ "def", "deleteMultipleStoredSms", "(", "self", ",", "delFlag", "=", "4", ",", "memory", "=", "None", ")", ":", "if", "0", "<", "delFlag", "<=", "4", ":", "self", ".", "_setSmsMemory", "(", "readDelete", "=", "memory", ")", "self", ".", "write", "(", ...
Deletes all SMS messages that have the specified read status. The messages are read from the memory set by the "memory" parameter. The value of the "delFlag" paramater is the same as the "DelFlag" parameter of the +CMGD command: 1: Delete All READ messages 2: Delete All READ and...
[ "Deletes", "all", "SMS", "messages", "that", "have", "the", "specified", "read", "status", ".", "The", "messages", "are", "read", "from", "the", "memory", "set", "by", "the", "memory", "parameter", ".", "The", "value", "of", "the", "delFlag", "paramater", ...
python
train
CalebBell/thermo
thermo/viscosity.py
https://github.com/CalebBell/thermo/blob/3857ed023a3e64fd3039a32d53576c24990ef1c3/thermo/viscosity.py#L1503-L1538
def calculate(self, T, method): r'''Method to calculate low-pressure gas viscosity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the ...
[ "def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "if", "method", "==", "GHARAGHEIZI", ":", "mu", "=", "Gharagheizi_gas_viscosity", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "me...
r'''Method to calculate low-pressure gas viscosity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the gas, [K] method : str ...
[ "r", "Method", "to", "calculate", "low", "-", "pressure", "gas", "viscosity", "at", "tempearture", "T", "with", "a", "given", "method", "." ]
python
valid
jasonrbriggs/stomp.py
stomp/transport.py
https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/transport.py#L103-L113
def start(self): """ Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection. """ self.running = True self.attempt_connection() receiver_thread = self....
[ "def", "start", "(", "self", ")", ":", "self", ".", "running", "=", "True", "self", ".", "attempt_connection", "(", ")", "receiver_thread", "=", "self", ".", "create_thread_fc", "(", "self", ".", "__receiver_loop", ")", "receiver_thread", ".", "name", "=", ...
Start the connection. This should be called after all listeners have been registered. If this method is not called, no frames will be received by the connection.
[ "Start", "the", "connection", ".", "This", "should", "be", "called", "after", "all", "listeners", "have", "been", "registered", ".", "If", "this", "method", "is", "not", "called", "no", "frames", "will", "be", "received", "by", "the", "connection", "." ]
python
train
divio/django-filer
filer/admin/folderadmin.py
https://github.com/divio/django-filer/blob/946629087943d41eff290f07bfdf240b8853dd88/filer/admin/folderadmin.py#L504-L581
def response_action(self, request, files_queryset, folders_queryset): """ Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise. """ # There can be multiple action forms o...
[ "def", "response_action", "(", "self", ",", "request", ",", "files_queryset", ",", "folders_queryset", ")", ":", "# There can be multiple action forms on the page (at the top", "# and bottom of the change list, for example). Get the action", "# whose button was pushed.", "try", ":", ...
Handle an admin action. This is called if a request is POSTed to the changelist; it returns an HttpResponse if the action was handled, and None otherwise.
[ "Handle", "an", "admin", "action", ".", "This", "is", "called", "if", "a", "request", "is", "POSTed", "to", "the", "changelist", ";", "it", "returns", "an", "HttpResponse", "if", "the", "action", "was", "handled", "and", "None", "otherwise", "." ]
python
train
materialsproject/pymatgen
pymatgen/analysis/fragmenter.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/fragmenter.py#L90-L126
def _fragment_one_level(self, mol_graphs): """ Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If ...
[ "def", "_fragment_one_level", "(", "self", ",", "mol_graphs", ")", ":", "unique_fragments_on_this_level", "=", "[", "]", "for", "mol_graph", "in", "mol_graphs", ":", "for", "edge", "in", "mol_graph", ".", "graph", ".", "edges", ":", "bond", "=", "[", "(", ...
Perform one step of iterative fragmentation on a list of molecule graphs. Loop through the graphs, then loop through each graph's edges and attempt to remove that edge in order to obtain two disconnected subgraphs, aka two new fragments. If successful, check to see if the new fragments are alrea...
[ "Perform", "one", "step", "of", "iterative", "fragmentation", "on", "a", "list", "of", "molecule", "graphs", ".", "Loop", "through", "the", "graphs", "then", "loop", "through", "each", "graph", "s", "edges", "and", "attempt", "to", "remove", "that", "edge", ...
python
train
awslabs/sockeye
sockeye/image_captioning/inference.py
https://github.com/awslabs/sockeye/blob/5d64a1ee1ef3cbba17c6d1d94bc061020c43f6ab/sockeye/image_captioning/inference.py#L102-L130
def translate(self, trans_inputs: List[TranslatorInput]) -> List[TranslatorOutput]: """ Batch-translates a list of TranslatorInputs, returns a list of TranslatorOutputs. Splits oversized sentences to sentence chunks of size less than max_input_length. :param trans_inputs: List of Transl...
[ "def", "translate", "(", "self", ",", "trans_inputs", ":", "List", "[", "TranslatorInput", "]", ")", "->", "List", "[", "TranslatorOutput", "]", ":", "batch_size", "=", "self", ".", "max_batch_size", "# translate in batch-sized blocks over input chunks", "translations...
Batch-translates a list of TranslatorInputs, returns a list of TranslatorOutputs. Splits oversized sentences to sentence chunks of size less than max_input_length. :param trans_inputs: List of TranslatorInputs as returned by make_input(). :return: List of translation results.
[ "Batch", "-", "translates", "a", "list", "of", "TranslatorInputs", "returns", "a", "list", "of", "TranslatorOutputs", ".", "Splits", "oversized", "sentences", "to", "sentence", "chunks", "of", "size", "less", "than", "max_input_length", "." ]
python
train
ivanyu/idx2numpy
idx2numpy/converters.py
https://github.com/ivanyu/idx2numpy/blob/9b88698314973226212181d1747dfad6c6974e51/idx2numpy/converters.py#L49-L59
def convert_from_file(file): """ Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name. """ if isinstance(file, six_string_types): with open(file, 'rb') as f: return _internal_con...
[ "def", "convert_from_file", "(", "file", ")", ":", "if", "isinstance", "(", "file", ",", "six_string_types", ")", ":", "with", "open", "(", "file", ",", "'rb'", ")", "as", "f", ":", "return", "_internal_convert", "(", "f", ")", "else", ":", "return", "...
Reads the content of file in IDX format, converts it into numpy.ndarray and returns it. file is a file-like object (with read() method) or a file name.
[ "Reads", "the", "content", "of", "file", "in", "IDX", "format", "converts", "it", "into", "numpy", ".", "ndarray", "and", "returns", "it", ".", "file", "is", "a", "file", "-", "like", "object", "(", "with", "read", "()", "method", ")", "or", "a", "fi...
python
train
armstrong/armstrong.dev
armstrong/dev/tasks.py
https://github.com/armstrong/armstrong.dev/blob/6fd8b863038d9e5ebfd52dfe5ce6c85fb441c267/armstrong/dev/tasks.py#L64-L74
def replaced_by_django_migrations(func, *args, **kwargs): """Decorator to preempt South requirement""" DjangoSettings() # trigger helpful messages if Django is missing import django if django.VERSION >= (1, 7): print("Django 1.7+ has its own migrations system.") print("Use this instea...
[ "def", "replaced_by_django_migrations", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "DjangoSettings", "(", ")", "# trigger helpful messages if Django is missing", "import", "django", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "7",...
Decorator to preempt South requirement
[ "Decorator", "to", "preempt", "South", "requirement" ]
python
train
mozillazg/python-pinyin
pypinyin/core.py
https://github.com/mozillazg/python-pinyin/blob/b44756c852e0d2f50f251e3098cbbfef51774979/pypinyin/core.py#L251-L283
def slug(hans, style=Style.NORMAL, heteronym=False, separator='-', errors='default', strict=True): """生成 slug 字符串. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~pypinyin.Style` :param heteronym...
[ "def", "slug", "(", "hans", ",", "style", "=", "Style", ".", "NORMAL", ",", "heteronym", "=", "False", ",", "separator", "=", "'-'", ",", "errors", "=", "'default'", ",", "strict", "=", "True", ")", ":", "return", "separator", ".", "join", "(", "chai...
生成 slug 字符串. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 :py:attr:`~pypinyin.Style.NORMAL` 风格。 更多拼音风格详见 :class:`~pypinyin.Style` :param heteronym: 是否启用多音字 :param separstor: 两个拼音间的分隔符/连接符 :param errors: 指定如何处理没有拼音的字符,详情请参考 :py:func:`~...
[ "生成", "slug", "字符串", "." ]
python
train
NASA-AMMOS/AIT-Core
ait/core/server/stream.py
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/server/stream.py#L54-L68
def process(self, input_data, topic=None): """ Invokes each handler in sequence. Publishes final output data. Params: input_data: message received by stream topic: name of plugin or stream message received from, if applicable ...
[ "def", "process", "(", "self", ",", "input_data", ",", "topic", "=", "None", ")", ":", "for", "handler", "in", "self", ".", "handlers", ":", "output", "=", "handler", ".", "handle", "(", "input_data", ")", "input_data", "=", "output", "self", ".", "pub...
Invokes each handler in sequence. Publishes final output data. Params: input_data: message received by stream topic: name of plugin or stream message received from, if applicable
[ "Invokes", "each", "handler", "in", "sequence", ".", "Publishes", "final", "output", "data", "." ]
python
train
libtcod/python-tcod
tcod/libtcodpy.py
https://github.com/libtcod/python-tcod/blob/8ba10c5cfb813eaf3e834de971ba2d6acb7838e4/tcod/libtcodpy.py#L762-L780
def color_lerp( c1: Tuple[int, int, int], c2: Tuple[int, int, int], a: float ) -> Color: """Return the linear interpolation between two colors. ``a`` is the interpolation value, with 0 returing ``c1``, 1 returning ``c2``, and 0.5 returing a color halfway between both. Args: c1 (Union[Tuple...
[ "def", "color_lerp", "(", "c1", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ",", "c2", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ",", "a", ":", "float", ")", "->", "Color", ":", "return", "Color", ".", "_new_from_cdata", ...
Return the linear interpolation between two colors. ``a`` is the interpolation value, with 0 returing ``c1``, 1 returning ``c2``, and 0.5 returing a color halfway between both. Args: c1 (Union[Tuple[int, int, int], Sequence[int]]): The first color. At a=0. c2 (Union[Tuple[int,...
[ "Return", "the", "linear", "interpolation", "between", "two", "colors", "." ]
python
train
pypa/pipenv
pipenv/patched/notpip/_internal/cli/cmdoptions.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_internal/cli/cmdoptions.py#L623-L643
def no_use_pep517_callback(option, opt, value, parser): """ Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option. """ # Since --no-use-pep517 doesn't accept arguments, the value argument # will be None if --no-use-pep517 is pa...
[ "def", "no_use_pep517_callback", "(", "option", ",", "opt", ",", "value", ",", "parser", ")", ":", "# Since --no-use-pep517 doesn't accept arguments, the value argument", "# will be None if --no-use-pep517 is passed via the command-line.", "# However, the value can be non-None if the opt...
Process a value provided for the --no-use-pep517 option. This is an optparse.Option callback for the no_use_pep517 option.
[ "Process", "a", "value", "provided", "for", "the", "--", "no", "-", "use", "-", "pep517", "option", "." ]
python
train
saltstack/salt
salt/modules/state.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/state.py#L527-L576
def template(tem, queue=False, **kwargs): ''' Execute the information stored in a template file on the minion. This function does not ask a master for a SLS file to render but instead directly processes the file at the provided path on the minion. CLI Example: .. code-block:: bash sa...
[ "def", "template", "(", "tem", ",", "queue", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "'env'", "in", "kwargs", ":", "# \"env\" is not supported; Use \"saltenv\".", "kwargs", ".", "pop", "(", "'env'", ")", "conflict", "=", "_check_queue", "(", ...
Execute the information stored in a template file on the minion. This function does not ask a master for a SLS file to render but instead directly processes the file at the provided path on the minion. CLI Example: .. code-block:: bash salt '*' state.template '<Path to template on the minion...
[ "Execute", "the", "information", "stored", "in", "a", "template", "file", "on", "the", "minion", "." ]
python
train
tensorflow/probability
tensorflow_probability/python/distributions/mixture_same_family.py
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture_same_family.py#L566-L583
def _prevent_2nd_derivative(x): """Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that rai...
[ "def", "_prevent_2nd_derivative", "(", "x", ")", ":", "def", "grad", "(", "dy", ")", ":", "return", "array_ops", ".", "prevent_gradient", "(", "dy", ",", "message", "=", "\"Second derivative is not implemented.\"", ")", "return", "tf", ".", "identity", "(", "x...
Disables computation of the second derivatives for a tensor. NB: you need to apply a non-identity function to the output tensor for the exception to be raised. Arguments: x: A tensor. Returns: A tensor with the same value and the same derivative as x, but that raises LookupError when trying to co...
[ "Disables", "computation", "of", "the", "second", "derivatives", "for", "a", "tensor", "." ]
python
test
python-rope/rope
rope/base/oi/type_hinting/utils.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/oi/type_hinting/utils.py#L77-L95
def resolve_type(type_name, pyobject): """ :type type_name: str :type pyobject: rope.base.pyobjects.PyDefinedObject | rope.base.pyobjects.PyObject :rtype: rope.base.pyobjects.PyDefinedObject | rope.base.pyobjects.PyObject or None """ if '.' not in type_name: try: return pyobj...
[ "def", "resolve_type", "(", "type_name", ",", "pyobject", ")", ":", "if", "'.'", "not", "in", "type_name", ":", "try", ":", "return", "pyobject", ".", "get_module", "(", ")", ".", "get_scope", "(", ")", ".", "get_name", "(", "type_name", ")", ".", "get...
:type type_name: str :type pyobject: rope.base.pyobjects.PyDefinedObject | rope.base.pyobjects.PyObject :rtype: rope.base.pyobjects.PyDefinedObject | rope.base.pyobjects.PyObject or None
[ ":", "type", "type_name", ":", "str", ":", "type", "pyobject", ":", "rope", ".", "base", ".", "pyobjects", ".", "PyDefinedObject", "|", "rope", ".", "base", ".", "pyobjects", ".", "PyObject", ":", "rtype", ":", "rope", ".", "base", ".", "pyobjects", "....
python
train
PythonCharmers/python-future
src/future/backports/http/server.py
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/http/server.py#L688-L727
def send_head(self): """Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all cir...
[ "def", "send_head", "(", "self", ")", ":", "path", "=", "self", ".", "translate_path", "(", "self", ".", "path", ")", "f", "=", "None", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "not", "self", ".", "path", ".", "endswith...
Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in...
[ "Common", "code", "for", "GET", "and", "HEAD", "commands", "." ]
python
train
amadeus4dev/amadeus-python
amadeus/shopping/_hotel_offer.py
https://github.com/amadeus4dev/amadeus-python/blob/afb93667d2cd486ddc7f4a7f29f222f04453a44a/amadeus/shopping/_hotel_offer.py#L9-L21
def get(self, **params): ''' Returns details for a specific offer. .. code-block:: python amadeus.shopping.hotel_offer('XXX').get :rtype: amadeus.Response :raises amadeus.ResponseError: if the request could not be completed ''' return self.client.ge...
[ "def", "get", "(", "self", ",", "*", "*", "params", ")", ":", "return", "self", ".", "client", ".", "get", "(", "'/v2/shopping/hotel-offers/{0}'", ".", "format", "(", "self", ".", "offer_id", ")", ",", "*", "*", "params", ")" ]
Returns details for a specific offer. .. code-block:: python amadeus.shopping.hotel_offer('XXX').get :rtype: amadeus.Response :raises amadeus.ResponseError: if the request could not be completed
[ "Returns", "details", "for", "a", "specific", "offer", "." ]
python
train
alex-sherman/unsync
examples/mixing_methods.py
https://github.com/alex-sherman/unsync/blob/a52a0b04980dcaf6dc2fd734aa9d7be9d8960bbe/examples/mixing_methods.py#L25-L32
async def result_processor(tasks): """An async result aggregator that combines all the results This gets executed in unsync.loop and unsync.thread""" output = {} for task in tasks: num, res = await task output[num] = res return output
[ "async", "def", "result_processor", "(", "tasks", ")", ":", "output", "=", "{", "}", "for", "task", "in", "tasks", ":", "num", ",", "res", "=", "await", "task", "output", "[", "num", "]", "=", "res", "return", "output" ]
An async result aggregator that combines all the results This gets executed in unsync.loop and unsync.thread
[ "An", "async", "result", "aggregator", "that", "combines", "all", "the", "results", "This", "gets", "executed", "in", "unsync", ".", "loop", "and", "unsync", ".", "thread" ]
python
train
materialsproject/pymatgen
pymatgen/analysis/magnetism/analyzer.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/analysis/magnetism/analyzer.py#L538-L559
def get_exchange_group_info(self, symprec=1e-2, angle_tolerance=5.0): """ Returns the information on the symmetry of the Hamiltonian describing the exchange energy of the system, taking into account relative direction of magnetic moments but not their absolute direction. ...
[ "def", "get_exchange_group_info", "(", "self", ",", "symprec", "=", "1e-2", ",", "angle_tolerance", "=", "5.0", ")", ":", "structure", "=", "self", ".", "get_structure_with_spin", "(", ")", "return", "structure", ".", "get_space_group_info", "(", "symprec", "=",...
Returns the information on the symmetry of the Hamiltonian describing the exchange energy of the system, taking into account relative direction of magnetic moments but not their absolute direction. This is not strictly accurate (e.g. some/many atoms will have zero magnetic momen...
[ "Returns", "the", "information", "on", "the", "symmetry", "of", "the", "Hamiltonian", "describing", "the", "exchange", "energy", "of", "the", "system", "taking", "into", "account", "relative", "direction", "of", "magnetic", "moments", "but", "not", "their", "abs...
python
train
pantsbuild/pants
contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py
https://github.com/pantsbuild/pants/blob/b72e650da0df685824ffdcc71988b8c282d0962d/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py#L400-L405
def build_file_lines(self): """Like `target_lines`, the entire BUILD file's lines after dependency manipulation.""" build_file_lines = self._build_file_source_lines[:] target_begin, target_end = self._target_interval build_file_lines[target_begin:target_end] = self.target_lines() return build_file_l...
[ "def", "build_file_lines", "(", "self", ")", ":", "build_file_lines", "=", "self", ".", "_build_file_source_lines", "[", ":", "]", "target_begin", ",", "target_end", "=", "self", ".", "_target_interval", "build_file_lines", "[", "target_begin", ":", "target_end", ...
Like `target_lines`, the entire BUILD file's lines after dependency manipulation.
[ "Like", "target_lines", "the", "entire", "BUILD", "file", "s", "lines", "after", "dependency", "manipulation", "." ]
python
train
quantumlib/Cirq
dev_tools/incremental_coverage.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/dev_tools/incremental_coverage.py#L48-L105
def diff_to_new_interesting_lines(unified_diff_lines: List[str] ) -> Dict[int, str]: """ Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-l...
[ "def", "diff_to_new_interesting_lines", "(", "unified_diff_lines", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "int", ",", "str", "]", ":", "interesting_lines", "=", "dict", "(", ")", "for", "diff_line", "in", "unified_diff_lines", ":", "# Parse the ...
Extracts a set of 'interesting' lines out of a GNU unified diff format. Format: gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html @@ from-line-numbers to-line-numbers @@ line-from-either-file ... @@ start,count start,count @@ line-from-either-file ...
[ "Extracts", "a", "set", "of", "interesting", "lines", "out", "of", "a", "GNU", "unified", "diff", "format", "." ]
python
train
ThreatConnect-Inc/tcex
tcex/tcex_data_filter.py
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_data_filter.py#L28-L57
def _build_indexes(self): """Build indexes from data for fast filtering of data. Building indexes of data when possible. This is only supported when dealing with a List of Dictionaries with String values. """ if isinstance(self._data, list): for d in self._data: ...
[ "def", "_build_indexes", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "_data", ",", "list", ")", ":", "for", "d", "in", "self", ".", "_data", ":", "if", "not", "isinstance", "(", "d", ",", "dict", ")", ":", "err", "=", "u'Cannot bui...
Build indexes from data for fast filtering of data. Building indexes of data when possible. This is only supported when dealing with a List of Dictionaries with String values.
[ "Build", "indexes", "from", "data", "for", "fast", "filtering", "of", "data", "." ]
python
train
saltstack/salt
salt/runners/ddns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/ddns.py#L187-L229
def add_host(zone, name, ttl, ip, keyname, keyfile, nameserver, timeout, port=53, keyalgorithm='hmac-md5'): ''' Create both A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/sal...
[ "def", "add_host", "(", "zone", ",", "name", ",", "ttl", ",", "ip", ",", "keyname", ",", "keyfile", ",", "nameserver", ",", "timeout", ",", "port", "=", "53", ",", "keyalgorithm", "=", "'hmac-md5'", ")", ":", "res", "=", "[", "]", "if", "zone", "in...
Create both A and PTR (reverse) records for a host. CLI Example: .. code-block:: bash salt-run ddns.add_host domain.com my-test-vm 3600 10.20.30.40 my-tsig-key /etc/salt/tsig.keyring 10.0.0.1 5
[ "Create", "both", "A", "and", "PTR", "(", "reverse", ")", "records", "for", "a", "host", "." ]
python
train
sosy-lab/benchexec
benchexec/tablegenerator/columns.py
https://github.com/sosy-lab/benchexec/blob/44428f67f41384c03aea13e7e25f884764653617/benchexec/tablegenerator/columns.py#L348-L364
def get_column_type(column, column_values): """ Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the ...
[ "def", "get_column_type", "(", "column", ",", "column_values", ")", ":", "try", ":", "return", "_get_column_type_heur", "(", "column", ",", "column_values", ")", "except", "util", ".", "TableDefinitionError", "as", "e", ":", "logging", ".", "error", "(", "\"Co...
Returns the type of the given column based on its row values on the given RunSetResult. @param column: the column to return the correct ColumnType for @param column_values: the column values to consider @return: a tuple of a type object describing the column - the concrete ColumnType is stored in the attrib...
[ "Returns", "the", "type", "of", "the", "given", "column", "based", "on", "its", "row", "values", "on", "the", "given", "RunSetResult", "." ]
python
train
Microsoft/LightGBM
python-package/lightgbm/basic.py
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L234-L252
def c_int_array(data): """Get pointer of int numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.int32: ptr_data = data...
[ "def", "c_int_array", "(", "data", ")", ":", "if", "is_1d_list", "(", "data", ")", ":", "data", "=", "np", ".", "array", "(", "data", ",", "copy", "=", "False", ")", "if", "is_numpy_1d_array", "(", "data", ")", ":", "data", "=", "convert_from_sliced_ob...
Get pointer of int numpy array / list.
[ "Get", "pointer", "of", "int", "numpy", "array", "/", "list", "." ]
python
train
datajoint/datajoint-python
datajoint/declare.py
https://github.com/datajoint/datajoint-python/blob/4f29bb154a7ed2b8b64b4d3a9c8be4c16b39621c/datajoint/declare.py#L255-L325
def compile_attribute(line, in_key, foreign_key_sql): """ Convert attribute definition from DataJoint format to SQL :param line: attribution line :param in_key: set to True if attribute is in primary key set :param foreign_key_sql: :returns: (name, sql, is_external) -- attribute name and sql co...
[ "def", "compile_attribute", "(", "line", ",", "in_key", ",", "foreign_key_sql", ")", ":", "try", ":", "match", "=", "attribute_parser", ".", "parseString", "(", "line", "+", "'#'", ",", "parseAll", "=", "True", ")", "except", "pp", ".", "ParseException", "...
Convert attribute definition from DataJoint format to SQL :param line: attribution line :param in_key: set to True if attribute is in primary key set :param foreign_key_sql: :returns: (name, sql, is_external) -- attribute name and sql code for its declaration
[ "Convert", "attribute", "definition", "from", "DataJoint", "format", "to", "SQL" ]
python
train
bloomberg/bqplot
bqplot/pyplot.py
https://github.com/bloomberg/bqplot/blob/8eb8b163abe9ee6306f6918067e2f36c1caef2ef/bqplot/pyplot.py#L871-L897
def bin(sample, options={}, **kwargs): """Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' ...
[ "def", "bin", "(", "sample", ",", "options", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'sample'", "]", "=", "sample", "scales", "=", "kwargs", ".", "pop", "(", "'scales'", ",", "{", "}", ")", "for", "xy", "in", "[", "'x'...
Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' is required for that mark, options['x'] c...
[ "Draw", "a", "histogram", "in", "the", "current", "context", "figure", ".", "Parameters", "----------", "sample", ":", "numpy", ".", "ndarray", "1d", "The", "sample", "for", "which", "the", "histogram", "must", "be", "generated", ".", "options", ":", "dict",...
python
train
ska-sa/katcp-python
katcp/fake_clients.py
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/fake_clients.py#L16-L59
def fake_KATCP_client_resource_factory( KATCPClientResourceClass, fake_options, resource_spec, *args, **kwargs): """Create a fake KATCPClientResource-like class and a fake-manager Parameters ---------- KATCPClientResourceClass : class Subclass of :class:`katcp.resource_client.KATCPClien...
[ "def", "fake_KATCP_client_resource_factory", "(", "KATCPClientResourceClass", ",", "fake_options", ",", "resource_spec", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO Implement allow_any_request functionality. When True, any unknown request (even", "# if there is n...
Create a fake KATCPClientResource-like class and a fake-manager Parameters ---------- KATCPClientResourceClass : class Subclass of :class:`katcp.resource_client.KATCPClientResource` fake_options : dict Options for the faking process. Keys: allow_any_request : bool, default F...
[ "Create", "a", "fake", "KATCPClientResource", "-", "like", "class", "and", "a", "fake", "-", "manager" ]
python
train
linkedin/luminol
src/luminol/correlator.py
https://github.com/linkedin/luminol/blob/42e4ab969b774ff98f902d064cb041556017f635/src/luminol/correlator.py#L72-L90
def _get_algorithm_and_params(self, algorithm_name, algorithm_params): """ Get the specific algorithm and merge the algorithm params. :param str algorithm: name of the algorithm to use. :param dict algorithm_params: additional params for the specific algorithm. """ algori...
[ "def", "_get_algorithm_and_params", "(", "self", ",", "algorithm_name", ",", "algorithm_params", ")", ":", "algorithm_name", "=", "algorithm_name", "or", "CORRELATOR_ALGORITHM", "try", ":", "self", ".", "algorithm", "=", "correlator_algorithms", "[", "algorithm_name", ...
Get the specific algorithm and merge the algorithm params. :param str algorithm: name of the algorithm to use. :param dict algorithm_params: additional params for the specific algorithm.
[ "Get", "the", "specific", "algorithm", "and", "merge", "the", "algorithm", "params", ".", ":", "param", "str", "algorithm", ":", "name", "of", "the", "algorithm", "to", "use", ".", ":", "param", "dict", "algorithm_params", ":", "additional", "params", "for",...
python
train
summa-tx/riemann
riemann/encoding/base58.py
https://github.com/summa-tx/riemann/blob/04ae336dfd4007ceaed748daadc91cc32fa278ec/riemann/encoding/base58.py#L42-L55
def decode(s, checksum=True): """Convert base58 to binary using BASE58_ALPHABET.""" v, prefix = to_long( BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8")) data = from_long(v, prefix, 256, lambda x: x) if checksum: data, the_hash = data[:-4], data[-4:] if utils.hash256(...
[ "def", "decode", "(", "s", ",", "checksum", "=", "True", ")", ":", "v", ",", "prefix", "=", "to_long", "(", "BASE58_BASE", ",", "lambda", "c", ":", "BASE58_LOOKUP", "[", "c", "]", ",", "s", ".", "encode", "(", "\"utf8\"", ")", ")", "data", "=", "...
Convert base58 to binary using BASE58_ALPHABET.
[ "Convert", "base58", "to", "binary", "using", "BASE58_ALPHABET", "." ]
python
train
ANTsX/ANTsPy
ants/learn/decomposition.py
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/learn/decomposition.py#L19-L248
def sparse_decom2(inmatrix, inmask=(None, None), sparseness=(0.01, 0.01), nvecs=3, its=20, cthresh=(0,0), statdir=None, perms=0, uselong=0, ...
[ "def", "sparse_decom2", "(", "inmatrix", ",", "inmask", "=", "(", "None", ",", "None", ")", ",", "sparseness", "=", "(", "0.01", ",", "0.01", ")", ",", "nvecs", "=", "3", ",", "its", "=", "20", ",", "cthresh", "=", "(", "0", ",", "0", ")", ",",...
Decomposes two matrices into paired sparse eigenevectors to maximize canonical correlation - aka Sparse CCA. Note: we do not scale the matrices internally. We leave scaling choices to the user. ANTsR function: `sparseDecom2` Arguments --------- inmatrix : 2-tuple of ndarrays input ...
[ "Decomposes", "two", "matrices", "into", "paired", "sparse", "eigenevectors", "to", "maximize", "canonical", "correlation", "-", "aka", "Sparse", "CCA", ".", "Note", ":", "we", "do", "not", "scale", "the", "matrices", "internally", ".", "We", "leave", "scaling...
python
train
adrn/gala
gala/potential/frame/builtin/transformations.py
https://github.com/adrn/gala/blob/ea95575a0df1581bb4b0986aebd6eea8438ab7eb/gala/potential/frame/builtin/transformations.py#L10-L29
def rodrigues_axis_angle_rotate(x, vec, theta): """ Rotated the input vector or set of vectors `x` around the axis `vec` by the angle `theta`. Parameters ---------- x : array_like The vector or array of vectors to transform. Must have shape """ x = np.array(x).T vec = np.a...
[ "def", "rodrigues_axis_angle_rotate", "(", "x", ",", "vec", ",", "theta", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", ".", "T", "vec", "=", "np", ".", "array", "(", "vec", ")", ".", "T", "theta", "=", "np", ".", "array", "(", "theta"...
Rotated the input vector or set of vectors `x` around the axis `vec` by the angle `theta`. Parameters ---------- x : array_like The vector or array of vectors to transform. Must have shape
[ "Rotated", "the", "input", "vector", "or", "set", "of", "vectors", "x", "around", "the", "axis", "vec", "by", "the", "angle", "theta", "." ]
python
train
fboender/ansible-cmdb
lib/mako/_ast_util.py
https://github.com/fboender/ansible-cmdb/blob/ebd960ac10684e8c9ec2b12751bba2c4c9504ab7/lib/mako/_ast_util.py#L107-L122
def dump(node): """ A very verbose representation of the node passed. This is useful for debugging purposes. """ def _format(node): if isinstance(node, AST): return '%s(%s)' % (node.__class__.__name__, ', '.join('%s=%s' % (a, _format(b)) ...
[ "def", "dump", "(", "node", ")", ":", "def", "_format", "(", "node", ")", ":", "if", "isinstance", "(", "node", ",", "AST", ")", ":", "return", "'%s(%s)'", "%", "(", "node", ".", "__class__", ".", "__name__", ",", "', '", ".", "join", "(", "'%s=%s'...
A very verbose representation of the node passed. This is useful for debugging purposes.
[ "A", "very", "verbose", "representation", "of", "the", "node", "passed", ".", "This", "is", "useful", "for", "debugging", "purposes", "." ]
python
train
scanny/python-pptx
pptx/chart/axis.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/chart/axis.py#L164-L172
def minor_tick_mark(self): """ Read/write :ref:`XlTickMark` value specifying the type of minor tick mark for this axis. """ minorTickMark = self._element.minorTickMark if minorTickMark is None: return XL_TICK_MARK.CROSS return minorTickMark.val
[ "def", "minor_tick_mark", "(", "self", ")", ":", "minorTickMark", "=", "self", ".", "_element", ".", "minorTickMark", "if", "minorTickMark", "is", "None", ":", "return", "XL_TICK_MARK", ".", "CROSS", "return", "minorTickMark", ".", "val" ]
Read/write :ref:`XlTickMark` value specifying the type of minor tick mark for this axis.
[ "Read", "/", "write", ":", "ref", ":", "XlTickMark", "value", "specifying", "the", "type", "of", "minor", "tick", "mark", "for", "this", "axis", "." ]
python
train
EwilDawe/typy
typy/mouse.py
https://github.com/EwilDawe/typy/blob/0349e7176567a4dbef318e75d9b3d6868950a1a9/typy/mouse.py#L43-L69
def move_arc(x, y, r, speed = 1, orientation = True): # WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions """ Moves the cursor in an arc of radius r to (x, y) at a certain speed :param x: target x-ordinate :param y: target y-ordinate :par...
[ "def", "move_arc", "(", "x", ",", "y", ",", "r", ",", "speed", "=", "1", ",", "orientation", "=", "True", ")", ":", "# WARNING: This function currently contains inaccuracy likely due to the rounding of trigonometric functions", "_x", ",", "_y", "=", "win32api", ".", ...
Moves the cursor in an arc of radius r to (x, y) at a certain speed :param x: target x-ordinate :param y: target y-ordinate :param r: radius :param speed: pixel traversal rate :param orientation: direction of arc :return: None
[ "Moves", "the", "cursor", "in", "an", "arc", "of", "radius", "r", "to", "(", "x", "y", ")", "at", "a", "certain", "speed" ]
python
train
mblayman/httpony
httpony/application.py
https://github.com/mblayman/httpony/blob/5af404d647a8dac8a043b64ea09882589b3b5247/httpony/application.py#L15-L55
def make_app(): """Make a WSGI app that has all the HTTPie pieces baked in.""" env = Environment() # STDIN is ignored because HTTPony runs a server that doesn't care. # Additionally, it is needed or else pytest blows up. args = parser.parse_args(args=['/', '--ignore-stdin'], env=env) args.output...
[ "def", "make_app", "(", ")", ":", "env", "=", "Environment", "(", ")", "# STDIN is ignored because HTTPony runs a server that doesn't care.", "# Additionally, it is needed or else pytest blows up.", "args", "=", "parser", ".", "parse_args", "(", "args", "=", "[", "'/'", "...
Make a WSGI app that has all the HTTPie pieces baked in.
[ "Make", "a", "WSGI", "app", "that", "has", "all", "the", "HTTPie", "pieces", "baked", "in", "." ]
python
test
merll/docker-fabric
dockerfabric/apiclient.py
https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/apiclient.py#L147-L156
def build(self, tag, **kwargs): """ Identical to :meth:`dockermap.client.base.DockerClientWrapper.build` with additional logging. """ self.push_log("Building image '{0}'.".format(tag)) set_raise_on_error(kwargs) try: return super(DockerFabricClient, self).buil...
[ "def", "build", "(", "self", ",", "tag", ",", "*", "*", "kwargs", ")", ":", "self", ".", "push_log", "(", "\"Building image '{0}'.\"", ".", "format", "(", "tag", ")", ")", "set_raise_on_error", "(", "kwargs", ")", "try", ":", "return", "super", "(", "D...
Identical to :meth:`dockermap.client.base.DockerClientWrapper.build` with additional logging.
[ "Identical", "to", ":", "meth", ":", "dockermap", ".", "client", ".", "base", ".", "DockerClientWrapper", ".", "build", "with", "additional", "logging", "." ]
python
train
plivo/plivohelper-python
plivohelper.py
https://github.com/plivo/plivohelper-python/blob/a2f706d69e2138fbb973f792041341f662072d26/plivohelper.py#L244-L249
def schedule_play(self, call_params): """REST Schedule playing something on a call Helper """ path = '/' + self.api_version + '/SchedulePlay/' method = 'POST' return self.request(path, method, call_params)
[ "def", "schedule_play", "(", "self", ",", "call_params", ")", ":", "path", "=", "'/'", "+", "self", ".", "api_version", "+", "'/SchedulePlay/'", "method", "=", "'POST'", "return", "self", ".", "request", "(", "path", ",", "method", ",", "call_params", ")" ...
REST Schedule playing something on a call Helper
[ "REST", "Schedule", "playing", "something", "on", "a", "call", "Helper" ]
python
valid
gem/oq-engine
openquake/hazardlib/gsim/boore_1997.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/hazardlib/gsim/boore_1997.py#L121-L141
def _compute_style_of_faulting_term(self, rup, C): """ Computes the coefficient to scale for reverse or strike-slip events Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to ...
[ "def", "_compute_style_of_faulting_term", "(", "self", ",", "rup", ",", "C", ")", ":", "if", "np", ".", "abs", "(", "rup", ".", "rake", ")", "<=", "30.0", "or", "(", "180.0", "-", "np", ".", "abs", "(", "rup", ".", "rake", ")", ")", "<=", "30.0",...
Computes the coefficient to scale for reverse or strike-slip events Fault type (Strike-slip, Normal, Thrust/reverse) is derived from rake angle. Rakes angles within 30 of horizontal are strike-slip, angles from 30 to 150 are reverse, and angles from -30 to -150 are normal. See pa...
[ "Computes", "the", "coefficient", "to", "scale", "for", "reverse", "or", "strike", "-", "slip", "events", "Fault", "type", "(", "Strike", "-", "slip", "Normal", "Thrust", "/", "reverse", ")", "is", "derived", "from", "rake", "angle", ".", "Rakes", "angles"...
python
train
Infinidat/infi.clickhouse_orm
src/infi/clickhouse_orm/models.py
https://github.com/Infinidat/infi.clickhouse_orm/blob/595f2023e334e3925a5c3fbfdd6083a5992a7169/src/infi/clickhouse_orm/models.py#L207-L228
def from_tsv(cls, line, field_names, timezone_in_use=pytz.utc, database=None): ''' Create a model instance from a tab-separated line. The line may or may not include a newline. The `field_names` list must match the fields defined in the model, but does not have to include all of them. -...
[ "def", "from_tsv", "(", "cls", ",", "line", ",", "field_names", ",", "timezone_in_use", "=", "pytz", ".", "utc", ",", "database", "=", "None", ")", ":", "from", "six", "import", "next", "values", "=", "iter", "(", "parse_tsv", "(", "line", ")", ")", ...
Create a model instance from a tab-separated line. The line may or may not include a newline. The `field_names` list must match the fields defined in the model, but does not have to include all of them. - `line`: the TSV-formatted data. - `field_names`: names of the model fields in the data. ...
[ "Create", "a", "model", "instance", "from", "a", "tab", "-", "separated", "line", ".", "The", "line", "may", "or", "may", "not", "include", "a", "newline", ".", "The", "field_names", "list", "must", "match", "the", "fields", "defined", "in", "the", "mode...
python
train
brutasse/rache
rache/__init__.py
https://github.com/brutasse/rache/blob/fa9cf073376a8c731a13924b84fb8422a771a4ab/rache/__init__.py#L48-L87
def schedule_job(job_id, schedule_in, connection=None, **kwargs): """Schedules a job. :param job_id: unique identifier for this job :param schedule_in: number of seconds from now in which to schedule the job or timedelta object. :param **kwargs: parameters to attach to the job, key-value structure...
[ "def", "schedule_job", "(", "job_id", ",", "schedule_in", ",", "connection", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "schedule_in", ",", "int", ")", ":", "# assumed to be a timedelta", "schedule_in", "=", "schedule_in", ...
Schedules a job. :param job_id: unique identifier for this job :param schedule_in: number of seconds from now in which to schedule the job or timedelta object. :param **kwargs: parameters to attach to the job, key-value structure. >>> schedule_job('http://example.com/test', schedule_in=10, num_re...
[ "Schedules", "a", "job", "." ]
python
train
UCBerkeleySETI/blimpy
blimpy/file_wrapper.py
https://github.com/UCBerkeleySETI/blimpy/blob/b8822d3e3e911944370d84371a91fa0c29e9772e/blimpy/file_wrapper.py#L147-L158
def _calc_selection_shape(self): """Calculate shape of data of interest. """ #Check how many integrations requested n_ints = int(self.t_stop - self.t_start) #Check how many frequency channels requested n_chan = int(np.round((self.f_stop - self.f_start) / abs(self.header[...
[ "def", "_calc_selection_shape", "(", "self", ")", ":", "#Check how many integrations requested", "n_ints", "=", "int", "(", "self", ".", "t_stop", "-", "self", ".", "t_start", ")", "#Check how many frequency channels requested", "n_chan", "=", "int", "(", "np", ".",...
Calculate shape of data of interest.
[ "Calculate", "shape", "of", "data", "of", "interest", "." ]
python
test
rodluger/everest
everest/missions/k2/utils.py
https://github.com/rodluger/everest/blob/6779591f9f8b3556847e2fbf761bdfac7520eaea/everest/missions/k2/utils.py#L545-L615
def GetHiResImage(ID): ''' Queries the Palomar Observatory Sky Survey II catalog to obtain a higher resolution optical image of the star with EPIC number :py:obj:`ID`. ''' # Get the TPF info client = kplr.API() star = client.k2_star(ID) k2ra = star.k2_ra k2dec = star.k2_dec ...
[ "def", "GetHiResImage", "(", "ID", ")", ":", "# Get the TPF info", "client", "=", "kplr", ".", "API", "(", ")", "star", "=", "client", ".", "k2_star", "(", "ID", ")", "k2ra", "=", "star", ".", "k2_ra", "k2dec", "=", "star", ".", "k2_dec", "tpf", "=",...
Queries the Palomar Observatory Sky Survey II catalog to obtain a higher resolution optical image of the star with EPIC number :py:obj:`ID`.
[ "Queries", "the", "Palomar", "Observatory", "Sky", "Survey", "II", "catalog", "to", "obtain", "a", "higher", "resolution", "optical", "image", "of", "the", "star", "with", "EPIC", "number", ":", "py", ":", "obj", ":", "ID", "." ]
python
train
OpenHydrology/floodestimation
floodestimation/analysis.py
https://github.com/OpenHydrology/floodestimation/blob/782da7c5abd1348923129efe89fb70003ebb088c/floodestimation/analysis.py#L973-L981
def _solve_location_param(self): """ We're lazy here and simply iterate to find the location parameter such that growth_curve(0.5)=1. """ params = copy.copy(self.params) del params['loc'] f = lambda location: self.distr_f.ppf(0.5, loc=location, **params) - 1 retu...
[ "def", "_solve_location_param", "(", "self", ")", ":", "params", "=", "copy", ".", "copy", "(", "self", ".", "params", ")", "del", "params", "[", "'loc'", "]", "f", "=", "lambda", "location", ":", "self", ".", "distr_f", ".", "ppf", "(", "0.5", ",", ...
We're lazy here and simply iterate to find the location parameter such that growth_curve(0.5)=1.
[ "We", "re", "lazy", "here", "and", "simply", "iterate", "to", "find", "the", "location", "parameter", "such", "that", "growth_curve", "(", "0", ".", "5", ")", "=", "1", "." ]
python
train
awslabs/serverless-application-model
samtranslator/sdk/parameter.py
https://github.com/awslabs/serverless-application-model/blob/cccb0c96b5c91e53355ebc07e542467303a5eedd/samtranslator/sdk/parameter.py#L19-L59
def add_default_parameter_values(self, sam_template): """ Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String ...
[ "def", "add_default_parameter_values", "(", "self", ",", "sam_template", ")", ":", "parameter_definition", "=", "sam_template", ".", "get", "(", "\"Parameters\"", ",", "None", ")", "if", "not", "parameter_definition", "or", "not", "isinstance", "(", "parameter_defin...
Method to read default values for template parameters and merge with user supplied values. Example: If the template contains the following parameters defined Parameters: Param1: Type: String Default: default_value Param2: ...
[ "Method", "to", "read", "default", "values", "for", "template", "parameters", "and", "merge", "with", "user", "supplied", "values", "." ]
python
train
tensorflow/cleverhans
cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/model_zoo/deep_k_nearest_neighbors/dknn.py#L170-L190
def nonconformity(self, knns_labels): """ Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label. """ nb_data = knns_labels[self.layers[0]].shape[0] ...
[ "def", "nonconformity", "(", "self", ",", "knns_labels", ")", ":", "nb_data", "=", "knns_labels", "[", "self", ".", "layers", "[", "0", "]", "]", ".", "shape", "[", "0", "]", "knns_not_in_class", "=", "np", ".", "zeros", "(", "(", "nb_data", ",", "se...
Given an dictionary of nb_data x nb_classes dimension, compute the nonconformity of each candidate label for each data point: i.e. the number of knns whose label is different from the candidate label.
[ "Given", "an", "dictionary", "of", "nb_data", "x", "nb_classes", "dimension", "compute", "the", "nonconformity", "of", "each", "candidate", "label", "for", "each", "data", "point", ":", "i", ".", "e", ".", "the", "number", "of", "knns", "whose", "label", "...
python
train
Rediker-Software/doac
doac/contrib/rest_framework/authentication.py
https://github.com/Rediker-Software/doac/blob/398fdd64452e4ff8662297b0381926addd77505a/doac/contrib/rest_framework/authentication.py#L6-L25
def authenticate(self, request): """ Send the request through the authentication middleware that is provided with DOAC and grab the user and token from it. """ from doac.middleware import AuthenticationMiddleware try: response = AuthenticationMiddleware().pr...
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "from", "doac", ".", "middleware", "import", "AuthenticationMiddleware", "try", ":", "response", "=", "AuthenticationMiddleware", "(", ")", ".", "process_request", "(", "request", ")", "except", ":", ...
Send the request through the authentication middleware that is provided with DOAC and grab the user and token from it.
[ "Send", "the", "request", "through", "the", "authentication", "middleware", "that", "is", "provided", "with", "DOAC", "and", "grab", "the", "user", "and", "token", "from", "it", "." ]
python
train