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
dfunckt/django-rules
rules/contrib/views.py
https://github.com/dfunckt/django-rules/blob/fcf3711122243c0c0c8124e9bb9bbb829f42ce1b/rules/contrib/views.py#L79-L145
def permission_required(perm, fn=None, login_url=None, raise_exception=False, redirect_field_name=REDIRECT_FIELD_NAME): """ View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules....
[ "def", "permission_required", "(", "perm", ",", "fn", "=", "None", ",", "login_url", "=", "None", ",", "raise_exception", "=", "False", ",", "redirect_field_name", "=", "REDIRECT_FIELD_NAME", ")", ":", "def", "decorator", "(", "view_func", ")", ":", "@", "wr...
View decorator that checks for the given permissions before allowing the view to execute. Use it like this:: from django.shortcuts import get_object_or_404 from rules.contrib.views import permission_required from posts.models import Post def get_post_by_pk(request, post_id): ...
[ "View", "decorator", "that", "checks", "for", "the", "given", "permissions", "before", "allowing", "the", "view", "to", "execute", ".", "Use", "it", "like", "this", "::" ]
python
train
cloudtools/troposphere
troposphere/rds.py
https://github.com/cloudtools/troposphere/blob/f7ea5591a7c287a843adc9c184d2f56064cfc632/troposphere/rds.py#L26-L34
def validate_iops(iops): """DBInstance Iops validation rules.""" iops = integer(iops) if int(iops) == 0: return iops if int(iops) < 1000: raise ValueError("DBInstance Iops, if set, must be greater than 1000.") return iops
[ "def", "validate_iops", "(", "iops", ")", ":", "iops", "=", "integer", "(", "iops", ")", "if", "int", "(", "iops", ")", "==", "0", ":", "return", "iops", "if", "int", "(", "iops", ")", "<", "1000", ":", "raise", "ValueError", "(", "\"DBInstance Iops,...
DBInstance Iops validation rules.
[ "DBInstance", "Iops", "validation", "rules", "." ]
python
train
pycontribs/pyrax
pyrax/object_storage.py
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/object_storage.py#L1927-L1945
def _store_object(self, obj_name, content, etag=None, chunked=False, chunk_size=None, headers=None): """ Handles the low-level creation of a storage object and the uploading of the contents of that object. """ head_etag = headers.pop("ETag", "") if chunked: ...
[ "def", "_store_object", "(", "self", ",", "obj_name", ",", "content", ",", "etag", "=", "None", ",", "chunked", "=", "False", ",", "chunk_size", "=", "None", ",", "headers", "=", "None", ")", ":", "head_etag", "=", "headers", ".", "pop", "(", "\"ETag\"...
Handles the low-level creation of a storage object and the uploading of the contents of that object.
[ "Handles", "the", "low", "-", "level", "creation", "of", "a", "storage", "object", "and", "the", "uploading", "of", "the", "contents", "of", "that", "object", "." ]
python
train
orbingol/NURBS-Python
geomdl/helpers.py
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L217-L304
def basis_function_ders(degree, knot_vector, span, knot, order): """ Computes derivatives of the basis functions for a single parameter. Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math...
[ "def", "basis_function_ders", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ",", "order", ")", ":", "# Initialize variables", "left", "=", "[", "1.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "right", "=", "[", "1.0"...
Computes derivatives of the basis functions for a single parameter. Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math...
[ "Computes", "derivatives", "of", "the", "basis", "functions", "for", "a", "single", "parameter", "." ]
python
train
apple/turicreate
src/unity/python/turicreate/data_structures/sarray.py
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/sarray.py#L4146-L4221
def rolling_count(self, window_start, window_end): """ Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window...
[ "def", "rolling_count", "(", "self", ",", "window_start", ",", "window_end", ")", ":", "agg_op", "=", "'__builtin__nonnull__count__'", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "builtin_rolling_apply", "(", "agg_op", ",", "window_start...
Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window_start` and `window_end`. For a better understanding of this, s...
[ "Count", "the", "number", "of", "non", "-", "NULL", "values", "of", "different", "subsets", "over", "this", "SArray", "." ]
python
train
odlgroup/odl
odl/set/domain.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/set/domain.py#L444-L493
def dist(self, point, exponent=2.0): """Return the distance of ``point`` to this set. Parameters ---------- point : `array-like` or float Point whose distance to calculate. Its length must be equal to the set's dimension. Can be a float in the 1d case. ex...
[ "def", "dist", "(", "self", ",", "point", ",", "exponent", "=", "2.0", ")", ":", "point", "=", "np", ".", "atleast_1d", "(", "point", ")", "if", "len", "(", "point", ")", "!=", "self", ".", "ndim", ":", "raise", "ValueError", "(", "'`point` must have...
Return the distance of ``point`` to this set. Parameters ---------- point : `array-like` or float Point whose distance to calculate. Its length must be equal to the set's dimension. Can be a float in the 1d case. exponent : non-zero float or ``float('inf')``, opt...
[ "Return", "the", "distance", "of", "point", "to", "this", "set", "." ]
python
train
cloud9ers/gurumate
environment/share/doc/ipython/examples/parallel/interengine/interengine.py
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/interengine/interengine.py#L30-L39
def send(client, sender, targets, msg_name, dest_name=None, block=None): """send a message from one to one-or-more engines.""" dest_name = msg_name if dest_name is None else dest_name def _send(targets, m_name): msg = globals()[m_name] return com.send(targets, msg) client[sender...
[ "def", "send", "(", "client", ",", "sender", ",", "targets", ",", "msg_name", ",", "dest_name", "=", "None", ",", "block", "=", "None", ")", ":", "dest_name", "=", "msg_name", "if", "dest_name", "is", "None", "else", "dest_name", "def", "_send", "(", "...
send a message from one to one-or-more engines.
[ "send", "a", "message", "from", "one", "to", "one", "-", "or", "-", "more", "engines", "." ]
python
test
openstack/pyghmi
pyghmi/ipmi/command.py
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/command.py#L740-L769
def _fetch_lancfg_param(self, channel, param, prefixlen=False): """Internal helper for fetching lan cfg parameters If the parameter revison != 0x11, bail. Further, if 4 bytes, return string with ipv4. If 6 bytes, colon delimited hex (mac address). If one byte, return the int value ...
[ "def", "_fetch_lancfg_param", "(", "self", ",", "channel", ",", "param", ",", "prefixlen", "=", "False", ")", ":", "fetchcmd", "=", "bytearray", "(", "(", "channel", ",", "param", ",", "0", ",", "0", ")", ")", "fetched", "=", "self", ".", "xraw_command...
Internal helper for fetching lan cfg parameters If the parameter revison != 0x11, bail. Further, if 4 bytes, return string with ipv4. If 6 bytes, colon delimited hex (mac address). If one byte, return the int value
[ "Internal", "helper", "for", "fetching", "lan", "cfg", "parameters" ]
python
train
sdispater/orator
orator/orm/relations/has_one.py
https://github.com/sdispater/orator/blob/bd90bf198ee897751848f9a92e49d18e60a74136/orator/orm/relations/has_one.py#L26-L34
def match(self, models, results, relation): """ Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str """ return self.match_one(models, results, relation)
[ "def", "match", "(", "self", ",", "models", ",", "results", ",", "relation", ")", ":", "return", "self", ".", "match_one", "(", "models", ",", "results", ",", "relation", ")" ]
Match the eagerly loaded results to their parents. :type models: list :type results: Collection :type relation: str
[ "Match", "the", "eagerly", "loaded", "results", "to", "their", "parents", "." ]
python
train
brainiak/brainiak
brainiak/utils/fmrisim.py
https://github.com/brainiak/brainiak/blob/408f12dec2ff56559a26873a848a09e4c8facfeb/brainiak/utils/fmrisim.py#L2597-L2800
def generate_noise(dimensions, stimfunction_tr, tr_duration, template, mask=None, noise_dict=None, temporal_proportion=0.5, iterations=None, fit_thresh=0.05, ...
[ "def", "generate_noise", "(", "dimensions", ",", "stimfunction_tr", ",", "tr_duration", ",", "template", ",", "mask", "=", "None", ",", "noise_dict", "=", "None", ",", "temporal_proportion", "=", "0.5", ",", "iterations", "=", "None", ",", "fit_thresh", "=", ...
Generate the noise to be added to the signal. Default noise parameters will create a noise volume with a standard deviation of 0.1 (where the signal defaults to a value of 1). This has built into estimates of how different types of noise mix. All noise values can be set by the user or estimated with cal...
[ "Generate", "the", "noise", "to", "be", "added", "to", "the", "signal", ".", "Default", "noise", "parameters", "will", "create", "a", "noise", "volume", "with", "a", "standard", "deviation", "of", "0", ".", "1", "(", "where", "the", "signal", "defaults", ...
python
train
randomir/plucky
plucky/structural.py
https://github.com/randomir/plucky/blob/16b7b59aa19d619d8e619dc15dc7eeffc9fe078a/plucky/structural.py#L134-L178
def _extract_from_object(self, selector): """Extracts all values from `self.obj` object addressed with a `selector`. Selector can be a ``slice``, or a singular value extractor in form of a valid dictionary key (hashable object). Object (operated on) can be anything with an itemg...
[ "def", "_extract_from_object", "(", "self", ",", "selector", ")", ":", "if", "isinstance", "(", "selector", ",", "slice", ")", ":", "# we must expand the slice manually, in order to be able to apply to", "# for example, to mapping types, or general objects", "# (e.g. slice `4::2`...
Extracts all values from `self.obj` object addressed with a `selector`. Selector can be a ``slice``, or a singular value extractor in form of a valid dictionary key (hashable object). Object (operated on) can be anything with an itemgetter or attrgetter, including, but limited t...
[ "Extracts", "all", "values", "from", "self", ".", "obj", "object", "addressed", "with", "a", "selector", ".", "Selector", "can", "be", "a", "slice", "or", "a", "singular", "value", "extractor", "in", "form", "of", "a", "valid", "dictionary", "key", "(", ...
python
train
CityOfZion/neo-python
neo/Wallets/Wallet.py
https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Wallet.py#L507-L523
def GetUnavailableBonus(self): """ Gets the total claimable amount of Gas in the wallet that is not available to claim because it has not yet been spent. Returns: Fixed8: the amount of Gas unavailable to claim. """ height = Blockchain.Default().Height + 1 ...
[ "def", "GetUnavailableBonus", "(", "self", ")", ":", "height", "=", "Blockchain", ".", "Default", "(", ")", ".", "Height", "+", "1", "unspents", "=", "self", ".", "FindUnspentCoinsByAsset", "(", "Blockchain", ".", "SystemShare", "(", ")", ".", "Hash", ")",...
Gets the total claimable amount of Gas in the wallet that is not available to claim because it has not yet been spent. Returns: Fixed8: the amount of Gas unavailable to claim.
[ "Gets", "the", "total", "claimable", "amount", "of", "Gas", "in", "the", "wallet", "that", "is", "not", "available", "to", "claim", "because", "it", "has", "not", "yet", "been", "spent", "." ]
python
train
diamondman/proteusisc
proteusisc/drivers/digilentdriver.py
https://github.com/diamondman/proteusisc/blob/7622b7b04e63f9dc0f5a04429ff78d9a490c9c5c/proteusisc/drivers/digilentdriver.py#L334-L367
def write_tdi_bits(self, buff, return_tdo=False, TMS=True): """ Command controller to write TDI data (with constant TMS bit) to the physical scan chain. Optionally return TDO bits sent back from scan the chain. Args: data - bits to send over TDI line of scan chain (b...
[ "def", "write_tdi_bits", "(", "self", ",", "buff", ",", "return_tdo", "=", "False", ",", "TMS", "=", "True", ")", ":", "self", ".", "_check_jtag", "(", ")", "tms_bits", "=", "bitarray", "(", "[", "TMS", "]", "*", "len", "(", "buff", ")", ")", "self...
Command controller to write TDI data (with constant TMS bit) to the physical scan chain. Optionally return TDO bits sent back from scan the chain. Args: data - bits to send over TDI line of scan chain (bitarray) return_tdo (bool) - return the devices bitarray response ...
[ "Command", "controller", "to", "write", "TDI", "data", "(", "with", "constant", "TMS", "bit", ")", "to", "the", "physical", "scan", "chain", ".", "Optionally", "return", "TDO", "bits", "sent", "back", "from", "scan", "the", "chain", "." ]
python
train
sontek/bulby
bulby/color.py
https://github.com/sontek/bulby/blob/a2e741f843ee8e361b50a6079601108bfbe52526/bulby/color.py#L18-L27
def in_lamp_reach(p): ''' Check if the provided XYPoint can be recreated by a Hue lamp. ''' v1 = XYPoint(Lime.x - Red.x, Lime.y - Red.y) v2 = XYPoint(Blue.x - Red.x, Blue.y - Red.y) q = XYPoint(p.x - Red.x, p.y - Red.y) s = cross_product(q, v2) / cross_product(v1, v2) t = cross_product(v1, q) /...
[ "def", "in_lamp_reach", "(", "p", ")", ":", "v1", "=", "XYPoint", "(", "Lime", ".", "x", "-", "Red", ".", "x", ",", "Lime", ".", "y", "-", "Red", ".", "y", ")", "v2", "=", "XYPoint", "(", "Blue", ".", "x", "-", "Red", ".", "x", ",", "Blue",...
Check if the provided XYPoint can be recreated by a Hue lamp.
[ "Check", "if", "the", "provided", "XYPoint", "can", "be", "recreated", "by", "a", "Hue", "lamp", "." ]
python
train
gregreen/dustmaps
dustmaps/unstructured_map.py
https://github.com/gregreen/dustmaps/blob/c8f571a71da0d951bf8ea865621bee14492bdfd9/dustmaps/unstructured_map.py#L105-L121
def _coords2idx(self, coords): """ Converts from sky coordinates to pixel indices. Args: coords (:obj:`astropy.coordinates.SkyCoord`): Sky coordinates. Returns: Pixel indices of the coordinates, with the same shape as the input coordinates. Pixels wh...
[ "def", "_coords2idx", "(", "self", ",", "coords", ")", ":", "x", "=", "self", ".", "_coords2vec", "(", "coords", ")", "idx", "=", "self", ".", "_kd", ".", "query", "(", "x", ",", "p", "=", "self", ".", "_metric_p", ",", "distance_upper_bound", "=", ...
Converts from sky coordinates to pixel indices. Args: coords (:obj:`astropy.coordinates.SkyCoord`): Sky coordinates. Returns: Pixel indices of the coordinates, with the same shape as the input coordinates. Pixels which are outside the map are given an index ...
[ "Converts", "from", "sky", "coordinates", "to", "pixel", "indices", "." ]
python
train
greenbender/pynntp
nntp/nntp.py
https://github.com/greenbender/pynntp/blob/991a76331cdf5d8f9dbf5b18f6e29adc80749a2f/nntp/nntp.py#L860-L881
def list_overview_fmt_gen(self): """Generator for the LIST OVERVIEW.FMT See list_overview_fmt() for more information. Yields: An element in the list returned by list_overview_fmt(). """ code, message = self.command("LIST OVERVIEW.FMT") if code != 215: ...
[ "def", "list_overview_fmt_gen", "(", "self", ")", ":", "code", ",", "message", "=", "self", ".", "command", "(", "\"LIST OVERVIEW.FMT\"", ")", "if", "code", "!=", "215", ":", "raise", "NNTPReplyError", "(", "code", ",", "message", ")", "for", "line", "in",...
Generator for the LIST OVERVIEW.FMT See list_overview_fmt() for more information. Yields: An element in the list returned by list_overview_fmt().
[ "Generator", "for", "the", "LIST", "OVERVIEW", ".", "FMT" ]
python
test
jbasko/autoboto
botogen/indentist/blocks.py
https://github.com/jbasko/autoboto/blob/0329afd4730d3d78bd021116857b10e6956dffb1/botogen/indentist/blocks.py#L239-L262
def to_code(self, context: Context =None): """ Generate the code and return it as a string. """ # Do not override this method! context = context or Context() for imp in self.imports: if imp not in context.imports: context.imports.append(imp) ...
[ "def", "to_code", "(", "self", ",", "context", ":", "Context", "=", "None", ")", ":", "# Do not override this method!", "context", "=", "context", "or", "Context", "(", ")", "for", "imp", "in", "self", ".", "imports", ":", "if", "imp", "not", "in", "cont...
Generate the code and return it as a string.
[ "Generate", "the", "code", "and", "return", "it", "as", "a", "string", "." ]
python
train
jrief/django-angular
djng/forms/fields.py
https://github.com/jrief/django-angular/blob/9f2f8247027173e3b3ad3b245ca299a9c9f31b40/djng/forms/fields.py#L266-L275
def get_multiple_choices_required(self): """ Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked". """ errors = [] if self.required: msg = _("A...
[ "def", "get_multiple_choices_required", "(", "self", ")", ":", "errors", "=", "[", "]", "if", "self", ".", "required", ":", "msg", "=", "_", "(", "\"At least one checkbox has to be selected.\"", ")", "errors", ".", "append", "(", "(", "'$error.multifield'", ",",...
Add only the required message, but no 'ng-required' attribute to the input fields, otherwise all Checkboxes of a MultipleChoiceField would require the property "checked".
[ "Add", "only", "the", "required", "message", "but", "no", "ng", "-", "required", "attribute", "to", "the", "input", "fields", "otherwise", "all", "Checkboxes", "of", "a", "MultipleChoiceField", "would", "require", "the", "property", "checked", "." ]
python
train
ziwenxie/netease-dl
netease/weapi.py
https://github.com/ziwenxie/netease-dl/blob/84b226fc07b10f7f66580f0fc69f10356f66b5c3/netease/weapi.py#L378-L405
def login(self): """Login entrance.""" username = click.prompt('Please enter your email or phone number') password = click.prompt('Please enter your password', hide_input=True) pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$') if pattern.match(username): # use phone nu...
[ "def", "login", "(", "self", ")", ":", "username", "=", "click", ".", "prompt", "(", "'Please enter your email or phone number'", ")", "password", "=", "click", ".", "prompt", "(", "'Please enter your password'", ",", "hide_input", "=", "True", ")", "pattern", "...
Login entrance.
[ "Login", "entrance", "." ]
python
train
openvax/pepdata
pepdata/pmbec.py
https://github.com/openvax/pepdata/blob/2f1bad79f8084545227f4a7f895bbf08a6fb6fdc/pepdata/pmbec.py#L22-L84
def read_pmbec_coefficients( key_type='row', verbose=True, filename=join(MATRIX_DIR, 'pmbec.mat')): """ Parameters ------------ filename : str Location of PMBEC coefficient matrix key_type : str 'row' : every key is a single amino acid, which maps...
[ "def", "read_pmbec_coefficients", "(", "key_type", "=", "'row'", ",", "verbose", "=", "True", ",", "filename", "=", "join", "(", "MATRIX_DIR", ",", "'pmbec.mat'", ")", ")", ":", "d", "=", "{", "}", "if", "key_type", "==", "'row'", ":", "def", "add_pair",...
Parameters ------------ filename : str Location of PMBEC coefficient matrix key_type : str 'row' : every key is a single amino acid, which maps to a dictionary for that row 'pair' : every key is a tuple of amino acids 'pair_string' : every key is a string of two ...
[ "Parameters", "------------" ]
python
train
hhromic/python-oslom-runner
oslom/runner.py
https://github.com/hhromic/python-oslom-runner/blob/f5991bd5014c65d0a9852641d51cbc344407d6a2/oslom/runner.py#L155-L208
def run(args): """Main OSLOM runner function.""" # Create an OSLOM runner with a temporary working directory oslom_runner = OslomRunner(tempfile.mkdtemp()) # (Re-)create OSLOM output directory shutil.rmtree(args.oslom_output, ignore_errors=True) os.makedirs(args.oslom_output) # Read edges ...
[ "def", "run", "(", "args", ")", ":", "# Create an OSLOM runner with a temporary working directory", "oslom_runner", "=", "OslomRunner", "(", "tempfile", ".", "mkdtemp", "(", ")", ")", "# (Re-)create OSLOM output directory", "shutil", ".", "rmtree", "(", "args", ".", "...
Main OSLOM runner function.
[ "Main", "OSLOM", "runner", "function", "." ]
python
train
horazont/aioxmpp
aioxmpp/bookmarks/service.py
https://github.com/horazont/aioxmpp/blob/22a68e5e1d23f2a4dee470092adbd4672f9ef061/aioxmpp/bookmarks/service.py#L268-L278
def get_bookmarks(self): """ Get the stored bookmarks from the server. Causes signals to be fired to reflect the changes. :returns: a list of bookmarks """ with (yield from self._lock): bookmarks = yield from self._get_bookmarks() self._diff_emit_...
[ "def", "get_bookmarks", "(", "self", ")", ":", "with", "(", "yield", "from", "self", ".", "_lock", ")", ":", "bookmarks", "=", "yield", "from", "self", ".", "_get_bookmarks", "(", ")", "self", ".", "_diff_emit_update", "(", "bookmarks", ")", "return", "b...
Get the stored bookmarks from the server. Causes signals to be fired to reflect the changes. :returns: a list of bookmarks
[ "Get", "the", "stored", "bookmarks", "from", "the", "server", ".", "Causes", "signals", "to", "be", "fired", "to", "reflect", "the", "changes", "." ]
python
train
DeepHorizons/iarm
iarm/arm_instructions/conditional_branch.py
https://github.com/DeepHorizons/iarm/blob/b913c9fd577b793a6bbced78b78a5d8d7cd88de4/iarm/arm_instructions/conditional_branch.py#L243-L258
def BVC(self, params): """ BVC label Branch to the instruction at label if the V flag is not set """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BVC label def BVC_func(): if not se...
[ "def", "BVC", "(", "self", ",", "params", ")", ":", "label", "=", "self", ".", "get_one_parameter", "(", "self", ".", "ONE_PARAMETER", ",", "params", ")", "self", ".", "check_arguments", "(", "label_exists", "=", "(", "label", ",", ")", ")", "# BVC label...
BVC label Branch to the instruction at label if the V flag is not set
[ "BVC", "label" ]
python
train
atztogo/phonopy
phonopy/api_phonopy.py
https://github.com/atztogo/phonopy/blob/869cc2ba9e7d495d5f4cf6942415ab3fc9e2a10f/phonopy/api_phonopy.py#L1252-L1277
def set_iter_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False): """Create an IterMesh instancer Attr...
[ "def", "set_iter_mesh", "(", "self", ",", "mesh", ",", "shift", "=", "None", ",", "is_time_reversal", "=", "True", ",", "is_mesh_symmetry", "=", "True", ",", "is_eigenvectors", "=", "False", ",", "is_gamma_center", "=", "False", ")", ":", "warnings", ".", ...
Create an IterMesh instancer Attributes ---------- See set_mesh method.
[ "Create", "an", "IterMesh", "instancer" ]
python
train
wavefrontHQ/python-client
wavefront_api_client/api/search_api.py
https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/api/search_api.py#L3750-L3770
def search_registered_query_for_facets(self, **kwargs): # noqa: E501 """Lists the values of one or more facets over the customer's non-deleted derived metric definition # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP re...
[ "def", "search_registered_query_for_facets", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "search_r...
Lists the values of one or more facets over the customer's non-deleted derived metric definition # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.search_registered_quer...
[ "Lists", "the", "values", "of", "one", "or", "more", "facets", "over", "the", "customer", "s", "non", "-", "deleted", "derived", "metric", "definition", "#", "noqa", ":", "E501" ]
python
train
angr/angr
angr/misc/hookset.py
https://github.com/angr/angr/blob/4e2f97d56af5419ee73bdb30482c8dd8ff5f3e40/angr/misc/hookset.py#L29-L46
def remove_hooks(target, **hooks): """ Remove the given hooks from the given target. :param target: The object from which to remove hooks. If all hooks are removed from a given method, the HookedMethod object will be removed and replaced with the original function. ...
[ "def", "remove_hooks", "(", "target", ",", "*", "*", "hooks", ")", ":", "for", "name", ",", "hook", "in", "hooks", ".", "items", "(", ")", ":", "hooked", "=", "getattr", "(", "target", ",", "name", ")", "if", "hook", "in", "hooked", ".", "pending",...
Remove the given hooks from the given target. :param target: The object from which to remove hooks. If all hooks are removed from a given method, the HookedMethod object will be removed and replaced with the original function. :param hooks: Any keywords will be interpreted as...
[ "Remove", "the", "given", "hooks", "from", "the", "given", "target", "." ]
python
train
apache/incubator-mxnet
python/mxnet/ndarray/sparse.py
https://github.com/apache/incubator-mxnet/blob/1af29e9c060a4c7d60eeaacba32afdb9a7775ba7/python/mxnet/ndarray/sparse.py#L808-L818
def _prepare_default_dtype(src_array, dtype): """Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise.""" if dtype is None: if isinstance(src_array, (NDArray, np.ndarray)): ...
[ "def", "_prepare_default_dtype", "(", "src_array", ",", "dtype", ")", ":", "if", "dtype", "is", "None", ":", "if", "isinstance", "(", "src_array", ",", "(", "NDArray", ",", "np", ".", "ndarray", ")", ")", ":", "dtype", "=", "src_array", ".", "dtype", "...
Prepare the value of dtype if `dtype` is None. If `src_array` is an NDArray, numpy.ndarray or scipy.sparse.csr.csr_matrix, return src_array.dtype. float32 is returned otherwise.
[ "Prepare", "the", "value", "of", "dtype", "if", "dtype", "is", "None", ".", "If", "src_array", "is", "an", "NDArray", "numpy", ".", "ndarray", "or", "scipy", ".", "sparse", ".", "csr", ".", "csr_matrix", "return", "src_array", ".", "dtype", ".", "float32...
python
train
numba/llvmlite
llvmlite/binding/module.py
https://github.com/numba/llvmlite/blob/fcadf8af11947f3fd041c5d6526c5bf231564883/llvmlite/binding/module.py#L130-L137
def data_layout(self): """ This module's data layout specification, as a string. """ # LLVMGetDataLayout() points inside a std::string managed by LLVM. with ffi.OutputString(owned=False) as outmsg: ffi.lib.LLVMPY_GetDataLayout(self, outmsg) return str(outm...
[ "def", "data_layout", "(", "self", ")", ":", "# LLVMGetDataLayout() points inside a std::string managed by LLVM.", "with", "ffi", ".", "OutputString", "(", "owned", "=", "False", ")", "as", "outmsg", ":", "ffi", ".", "lib", ".", "LLVMPY_GetDataLayout", "(", "self", ...
This module's data layout specification, as a string.
[ "This", "module", "s", "data", "layout", "specification", "as", "a", "string", "." ]
python
train
nschloe/orthopy
orthopy/e1r/orth.py
https://github.com/nschloe/orthopy/blob/64713d0533b0af042810a7535fff411b8e0aea9e/orthopy/e1r/orth.py#L20-L53
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
[ "def", "recurrence_coefficients", "(", "n", ",", "alpha", ",", "standardization", "=", "\"normal\"", ",", "symbolic", "=", "False", ")", ":", "S", "=", "sympy", ".", "S", "if", "symbolic", "else", "lambda", "x", ":", "x", "sqrt", "=", "sympy", ".", "sq...
Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k
[ "Recurrence", "coefficients", "for", "generalized", "Laguerre", "polynomials", "." ]
python
train
nanoporetech/ont_fast5_api
ont_fast5_api/fast5_file.py
https://github.com/nanoporetech/ont_fast5_api/blob/352b3903155fcf4f19234c4f429dcefaa6d6bc4a/ont_fast5_api/fast5_file.py#L504-L516
def add_analysis_attributes(self, group_name, attrs, clear=False): """ Add attributes on the group or dataset specified. :param group_name: The name of the group (or dataset). :param attrs: A dictionary representing the attributes to add. :param clear: If set, any existing attri...
[ "def", "add_analysis_attributes", "(", "self", ",", "group_name", ",", "attrs", ",", "clear", "=", "False", ")", ":", "self", ".", "assert_writeable", "(", ")", "group", "=", "'Analyses/{}'", ".", "format", "(", "group_name", ")", "self", ".", "_add_attribut...
Add attributes on the group or dataset specified. :param group_name: The name of the group (or dataset). :param attrs: A dictionary representing the attributes to add. :param clear: If set, any existing attributes will be cleared. The specified group name can be any exi...
[ "Add", "attributes", "on", "the", "group", "or", "dataset", "specified", ".", ":", "param", "group_name", ":", "The", "name", "of", "the", "group", "(", "or", "dataset", ")", ".", ":", "param", "attrs", ":", "A", "dictionary", "representing", "the", "att...
python
train
NuGrid/NuGridPy
nugridpy/nugridse.py
https://github.com/NuGrid/NuGridPy/blob/eee8047446e398be77362d82c1d8b3310054fab0/nugridpy/nugridse.py#L867-L875
def plot4_nolog(self, num): """ Plots the abundances of H-1, He-4, C-12 and O-16. """ self.plot_prof_2(num,'H-1',0.,5.) self.plot_prof_2(num,'He-4',0.,5.) self.plot_prof_2(num,'C-12',0.,5.) self.plot_prof_2(num,'O-16',0.,5.) pyl.legend(loc=3)
[ "def", "plot4_nolog", "(", "self", ",", "num", ")", ":", "self", ".", "plot_prof_2", "(", "num", ",", "'H-1'", ",", "0.", ",", "5.", ")", "self", ".", "plot_prof_2", "(", "num", ",", "'He-4'", ",", "0.", ",", "5.", ")", "self", ".", "plot_prof_2", ...
Plots the abundances of H-1, He-4, C-12 and O-16.
[ "Plots", "the", "abundances", "of", "H", "-", "1", "He", "-", "4", "C", "-", "12", "and", "O", "-", "16", "." ]
python
train
dahlia/wikidata
wikidata/commonsmedia.py
https://github.com/dahlia/wikidata/blob/b07c9f8fffc59b088ec9dd428d0ec4d989c82db4/wikidata/commonsmedia.py#L58-L68
def image_resolution(self) -> Optional[Tuple[int, int]]: r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`, :class:`int`]]) The (width, height) pair of the image. It may be :const:`None` if it's not an image. """ images = self.attributes.get('imageinfo', [])...
[ "def", "image_resolution", "(", "self", ")", "->", "Optional", "[", "Tuple", "[", "int", ",", "int", "]", "]", ":", "images", "=", "self", ".", "attributes", ".", "get", "(", "'imageinfo'", ",", "[", "]", ")", "if", "images", "and", "isinstance", "("...
r"""(:class:`~typing.Optional`\ [:class:`~typing.Tuple`\ [:class:`int`, :class:`int`]]) The (width, height) pair of the image. It may be :const:`None` if it's not an image.
[ "r", "(", ":", "class", ":", "~typing", ".", "Optional", "\\", "[", ":", "class", ":", "~typing", ".", "Tuple", "\\", "[", ":", "class", ":", "int", ":", "class", ":", "int", "]]", ")", "The", "(", "width", "height", ")", "pair", "of", "the", "...
python
train
inveniosoftware/invenio-search
invenio_search/ext.py
https://github.com/inveniosoftware/invenio-search/blob/19c073d608d4c811f1c5aecb6622402d39715228/invenio_search/ext.py#L206-L212
def _client_builder(self): """Build Elasticsearch client.""" client_config = self.app.config.get('SEARCH_CLIENT_CONFIG') or {} client_config.setdefault( 'hosts', self.app.config.get('SEARCH_ELASTIC_HOSTS')) client_config.setdefault('connection_class', RequestsHttpConnection) ...
[ "def", "_client_builder", "(", "self", ")", ":", "client_config", "=", "self", ".", "app", ".", "config", ".", "get", "(", "'SEARCH_CLIENT_CONFIG'", ")", "or", "{", "}", "client_config", ".", "setdefault", "(", "'hosts'", ",", "self", ".", "app", ".", "c...
Build Elasticsearch client.
[ "Build", "Elasticsearch", "client", "." ]
python
train
PmagPy/PmagPy
SPD/lib/lib_arai_plot_statistics.py
https://github.com/PmagPy/PmagPy/blob/c7984f8809bf40fe112e53dcc311a33293b62d0b/SPD/lib/lib_arai_plot_statistics.py#L10-L68
def York_Regression(x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai): """ input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept, x_intercept, x_prime, y_prime, delta_x_prime, delta_...
[ "def", "York_Regression", "(", "x_segment", ",", "y_segment", ",", "x_mean", ",", "y_mean", ",", "n", ",", "lab_dc_field", ",", "steps_Arai", ")", ":", "x_err", "=", "x_segment", "-", "x_mean", "y_err", "=", "y_segment", "-", "y_mean", "york_b", "=", "-", ...
input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept, x_intercept, x_prime, y_prime, delta_x_prime, delta_y_prime, f_Coe, g_Coe, g_lim, specimen_q, specimen_w, count_IZ, count_ZI, B_lab, B_anc, ...
[ "input", ":", "x_segment", "y_segment", "x_mean", "y_mean", "n", "lab_dc_field", "steps_Arai", "output", ":", "x_err", "y_err", "x_tag", "y_tag", "b", "b_sigma", "specimen_b_beta", "y_intercept", "x_intercept", "x_prime", "y_prime", "delta_x_prime", "delta_y_prime", "...
python
train
pzs741/TEDT
TEDT/candidate_corpus.py
https://github.com/pzs741/TEDT/blob/6b6663227b755005fe1a1e3e807a05bdb521e066/TEDT/candidate_corpus.py#L174-L250
def get_corpus(self): """获取语料库 Return: corpus -- 语料库,str类型 """ # 正向判定 corpus = [] cd = 0 tag = None for i in range(0, self.init_corpus[0][0]): init_unit = self.unit_raw[self.init_corpus[0][0] - i] cdm = CDM(i...
[ "def", "get_corpus", "(", "self", ")", ":", "# 正向判定", "corpus", "=", "[", "]", "cd", "=", "0", "tag", "=", "None", "for", "i", "in", "range", "(", "0", ",", "self", ".", "init_corpus", "[", "0", "]", "[", "0", "]", ")", ":", "init_unit", "=", ...
获取语料库 Return: corpus -- 语料库,str类型
[ "获取语料库" ]
python
train
PatrikValkovic/grammpy
grammpy/parsers/CYK/Field.py
https://github.com/PatrikValkovic/grammpy/blob/879ce0ef794ac2823acc19314fcd7a8aba53e50f/grammpy/parsers/CYK/Field.py#L78-L86
def put(self, x, y, rules): # type: (int, int, List[PlaceItem]) -> None """ Set possible rules at specific position. :param x: X coordinate. :param y: Y coordinate. :param rules: Value to set. """ self._field[y][x] = rules
[ "def", "put", "(", "self", ",", "x", ",", "y", ",", "rules", ")", ":", "# type: (int, int, List[PlaceItem]) -> None", "self", ".", "_field", "[", "y", "]", "[", "x", "]", "=", "rules" ]
Set possible rules at specific position. :param x: X coordinate. :param y: Y coordinate. :param rules: Value to set.
[ "Set", "possible", "rules", "at", "specific", "position", ".", ":", "param", "x", ":", "X", "coordinate", ".", ":", "param", "y", ":", "Y", "coordinate", ".", ":", "param", "rules", ":", "Value", "to", "set", "." ]
python
train
gagneurlab/concise
concise/effects/gradient.py
https://github.com/gagneurlab/concise/blob/d15262eb1e590008bc96ba31e93bfbdbfa1a9fd4/concise/effects/gradient.py#L230-L319
def gradient_pred(model, ref, ref_rc, alt, alt_rc, mutation_positions, out_annotation_all_outputs, output_filter_mask=None, out_annotation=None): """Gradient-based (saliency) variant effect prediction Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based...
[ "def", "gradient_pred", "(", "model", ",", "ref", ",", "ref_rc", ",", "alt", ",", "alt_rc", ",", "mutation_positions", ",", "out_annotation_all_outputs", ",", "output_filter_mask", "=", "None", ",", "out_annotation", "=", "None", ")", ":", "seqs", "=", "{", ...
Gradient-based (saliency) variant effect prediction Based on the idea of [saliency maps](https://arxiv.org/pdf/1312.6034.pdf) the gradient-based prediction of variant effects uses the `gradient` function of the Keras backend to estimate the importance of a variant for a given output. This value is then mul...
[ "Gradient", "-", "based", "(", "saliency", ")", "variant", "effect", "prediction" ]
python
train
open511/open511
open511/utils/schedule.py
https://github.com/open511/open511/blob/3d573f59d7efa06ff1b5419ea5ff4d90a90b3cf8/open511/utils/schedule.py#L274-L279
def weekdays(self): """A set of integers representing the weekdays the schedule recurs on, with Monday = 0 and Sunday = 6.""" if not self.root.xpath('days'): return set(range(7)) return set(int(d) - 1 for d in self.root.xpath('days/day/text()'))
[ "def", "weekdays", "(", "self", ")", ":", "if", "not", "self", ".", "root", ".", "xpath", "(", "'days'", ")", ":", "return", "set", "(", "range", "(", "7", ")", ")", "return", "set", "(", "int", "(", "d", ")", "-", "1", "for", "d", "in", "sel...
A set of integers representing the weekdays the schedule recurs on, with Monday = 0 and Sunday = 6.
[ "A", "set", "of", "integers", "representing", "the", "weekdays", "the", "schedule", "recurs", "on", "with", "Monday", "=", "0", "and", "Sunday", "=", "6", "." ]
python
valid
django-leonardo/django-leonardo
leonardo/views/defaults.py
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/views/defaults.py#L11-L38
def render_in_page(request, template): """return rendered template in standalone mode or ``False`` """ from leonardo.module.web.models import Page page = request.leonardo_page if hasattr( request, 'leonardo_page') else Page.objects.filter(parent=None).first() if page: try: ...
[ "def", "render_in_page", "(", "request", ",", "template", ")", ":", "from", "leonardo", ".", "module", ".", "web", ".", "models", "import", "Page", "page", "=", "request", ".", "leonardo_page", "if", "hasattr", "(", "request", ",", "'leonardo_page'", ")", ...
return rendered template in standalone mode or ``False``
[ "return", "rendered", "template", "in", "standalone", "mode", "or", "False" ]
python
train
census-instrumentation/opencensus-python
contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py
https://github.com/census-instrumentation/opencensus-python/blob/992b223f7e34c5dcb65922b7d5c827e7a1351e7d/contrib/opencensus-ext-stackdriver/opencensus/ext/stackdriver/stats_exporter/__init__.py#L287-L299
def register_metric_descriptor(self, oc_md): """Register a metric descriptor with stackdriver.""" metric_type = self.get_metric_type(oc_md) with self._md_lock: if metric_type in self._md_cache: return self._md_cache[metric_type] descriptor = self.get_metric_d...
[ "def", "register_metric_descriptor", "(", "self", ",", "oc_md", ")", ":", "metric_type", "=", "self", ".", "get_metric_type", "(", "oc_md", ")", "with", "self", ".", "_md_lock", ":", "if", "metric_type", "in", "self", ".", "_md_cache", ":", "return", "self",...
Register a metric descriptor with stackdriver.
[ "Register", "a", "metric", "descriptor", "with", "stackdriver", "." ]
python
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L570-L579
def set_pointer0d(subseqs): """Set_pointer function for 0-dimensional link sequences.""" print(' . set_pointer0d') lines = Lines() lines.add(1, 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):') for seq in subseqs: ...
[ "def", "set_pointer0d", "(", "subseqs", ")", ":", "print", "(", "' . set_pointer0d'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline set_pointer0d'", "'(self, str name, pointerutils.PDouble value):'", ")", "for", ...
Set_pointer function for 0-dimensional link sequences.
[ "Set_pointer", "function", "for", "0", "-", "dimensional", "link", "sequences", "." ]
python
train
nkgilley/python-ecobee-api
pyecobee/__init__.py
https://github.com/nkgilley/python-ecobee-api/blob/cc8d90d20abcb9ef5b66ec9cb035bae2f06ba174/pyecobee/__init__.py#L259-L269
def set_climate_hold(self, index, climate, hold_type="nextTransition"): ''' Set a climate hold - ie away, home, sleep ''' body = {"selection": { "selectionType": "thermostats", "selectionMatch": self.thermostats[index]['identifier']}, "functions": ...
[ "def", "set_climate_hold", "(", "self", ",", "index", ",", "climate", ",", "hold_type", "=", "\"nextTransition\"", ")", ":", "body", "=", "{", "\"selection\"", ":", "{", "\"selectionType\"", ":", "\"thermostats\"", ",", "\"selectionMatch\"", ":", "self", ".", ...
Set a climate hold - ie away, home, sleep
[ "Set", "a", "climate", "hold", "-", "ie", "away", "home", "sleep" ]
python
test
MrYsLab/PyMata
PyMata/pymata.py
https://github.com/MrYsLab/PyMata/blob/7e0ec34670b5a0d3d6b74bcbe4f3808c845cc429/PyMata/pymata.py#L933-L940
def stepper_request_library_version(self): """ Request the stepper library version from the Arduino. To retrieve the version after this command is called, call get_stepper_version """ data = [self.STEPPER_LIBRARY_VERSION] self._command_handler.send_sysex(self._com...
[ "def", "stepper_request_library_version", "(", "self", ")", ":", "data", "=", "[", "self", ".", "STEPPER_LIBRARY_VERSION", "]", "self", ".", "_command_handler", ".", "send_sysex", "(", "self", ".", "_command_handler", ".", "STEPPER_DATA", ",", "data", ")" ]
Request the stepper library version from the Arduino. To retrieve the version after this command is called, call get_stepper_version
[ "Request", "the", "stepper", "library", "version", "from", "the", "Arduino", ".", "To", "retrieve", "the", "version", "after", "this", "command", "is", "called", "call", "get_stepper_version" ]
python
valid
bcbio/bcbio-nextgen
bcbio/upload/irods.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/upload/irods.py#L25-L31
def update_file(finfo, sample_info, config): """ Update the file to an iRODS repository. """ ffinal = filesystem.update_file(finfo, sample_info, config, pass_uptodate=True) _upload_dir_icommands_cli(config.get("dir"), config.get("folder"), config)
[ "def", "update_file", "(", "finfo", ",", "sample_info", ",", "config", ")", ":", "ffinal", "=", "filesystem", ".", "update_file", "(", "finfo", ",", "sample_info", ",", "config", ",", "pass_uptodate", "=", "True", ")", "_upload_dir_icommands_cli", "(", "config...
Update the file to an iRODS repository.
[ "Update", "the", "file", "to", "an", "iRODS", "repository", "." ]
python
train
lk-geimfari/mimesis
mimesis/providers/text.py
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/text.py#L102-L111
def swear_word(self) -> str: """Get a random swear word. :return: Swear word. :Example: Damn. """ bad_words = self._data['words'].get('bad') return self.random.choice(bad_words)
[ "def", "swear_word", "(", "self", ")", "->", "str", ":", "bad_words", "=", "self", ".", "_data", "[", "'words'", "]", ".", "get", "(", "'bad'", ")", "return", "self", ".", "random", ".", "choice", "(", "bad_words", ")" ]
Get a random swear word. :return: Swear word. :Example: Damn.
[ "Get", "a", "random", "swear", "word", "." ]
python
train
todddeluca/fabvenv
fabvenv.py
https://github.com/todddeluca/fabvenv/blob/ba0121412a7f47b3732d45b6cee42ac2b8737159/fabvenv.py#L70-L77
def install(self): ''' Use pip to install the requirements file. ''' remote_path = os.path.join(self.venv, 'requirements.txt') put(self.requirements, remote_path) run('{pip} install -r {requirements}'.format( pip=self.pip(), requirements=remote_path))
[ "def", "install", "(", "self", ")", ":", "remote_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "venv", ",", "'requirements.txt'", ")", "put", "(", "self", ".", "requirements", ",", "remote_path", ")", "run", "(", "'{pip} install -r {require...
Use pip to install the requirements file.
[ "Use", "pip", "to", "install", "the", "requirements", "file", "." ]
python
train
computational-metabolomics/msp2db
msp2db/parse.py
https://github.com/computational-metabolomics/msp2db/blob/f86f01efca26fd2745547c9993f97337c6bef123/msp2db/parse.py#L409-L431
def _parse_spectra(self, line): """Parse and store the spectral details """ if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']: self.start_spectra = False self.current_id_meta += 1 self.collect_meta = True return splist = line.split() ...
[ "def", "_parse_spectra", "(", "self", ",", "line", ")", ":", "if", "line", "in", "[", "'\\n'", ",", "'\\r\\n'", ",", "'//\\n'", ",", "'//\\r\\n'", ",", "''", ",", "'//'", "]", ":", "self", ".", "start_spectra", "=", "False", "self", ".", "current_id_me...
Parse and store the spectral details
[ "Parse", "and", "store", "the", "spectral", "details" ]
python
train
PyCQA/pylint
pylint/checkers/variables.py
https://github.com/PyCQA/pylint/blob/2bf5c61a3ff6ae90613b81679de42c0f19aea600/pylint/checkers/variables.py#L1609-L1627
def visit_importfrom(self, node): """check modules attribute accesses""" if not self._analyse_fallback_blocks and utils.is_from_fallback_block(node): # No need to verify this, since ImportError is already # handled by the client code. return name_parts = node...
[ "def", "visit_importfrom", "(", "self", ",", "node", ")", ":", "if", "not", "self", ".", "_analyse_fallback_blocks", "and", "utils", ".", "is_from_fallback_block", "(", "node", ")", ":", "# No need to verify this, since ImportError is already", "# handled by the client co...
check modules attribute accesses
[ "check", "modules", "attribute", "accesses" ]
python
test
saltstack/salt
salt/modules/libcloud_dns.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/libcloud_dns.py#L354-L376
def extra(method, profile, **libcloud_kwargs): ''' Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method ...
[ "def", "extra", "(", "method", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "_sanitize_kwargs", "(", "libcloud_kwargs", ")", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "connection_method", "=", "getattr", "(", "conn", ","...
Call an extended method on the driver :param method: Driver's method name :type method: ``str`` :param profile: The profile key :type profile: ``str`` :param libcloud_kwargs: Extra arguments for the driver's delete_container method :type libcloud_kwargs: ``dict`` CLI Example: .. ...
[ "Call", "an", "extended", "method", "on", "the", "driver" ]
python
train
delfick/harpoon
harpoon/formatter.py
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/formatter.py#L51-L65
def get_string(self, key): """Get a string from all_options""" if key not in self.all_options: kwargs = {} if len(self.chain) > 1: kwargs['source'] = Meta(self.all_options, self.chain[-2]).source raise BadOptionFormat("Can't find key in options", key=k...
[ "def", "get_string", "(", "self", ",", "key", ")", ":", "if", "key", "not", "in", "self", ".", "all_options", ":", "kwargs", "=", "{", "}", "if", "len", "(", "self", ".", "chain", ")", ">", "1", ":", "kwargs", "[", "'source'", "]", "=", "Meta", ...
Get a string from all_options
[ "Get", "a", "string", "from", "all_options" ]
python
train
DataDog/integrations-core
datadog_checks_base/datadog_checks/base/checks/win/wmi/__init__.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/datadog_checks_base/datadog_checks/base/checks/win/wmi/__init__.py#L50-L73
def _format_tag_query(self, sampler, wmi_obj, tag_query): """ Format `tag_query` or raise on incorrect parameters. """ try: link_source_property = int(wmi_obj[tag_query[0]]) target_class = tag_query[1] link_target_class_property = tag_query[2] ...
[ "def", "_format_tag_query", "(", "self", ",", "sampler", ",", "wmi_obj", ",", "tag_query", ")", ":", "try", ":", "link_source_property", "=", "int", "(", "wmi_obj", "[", "tag_query", "[", "0", "]", "]", ")", "target_class", "=", "tag_query", "[", "1", "]...
Format `tag_query` or raise on incorrect parameters.
[ "Format", "tag_query", "or", "raise", "on", "incorrect", "parameters", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/vasp/inputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/inputs.py#L1620-L1632
def element(self): """ Attempt to return the atomic symbol based on the VRHFIN keyword. """ element = self.keywords["VRHFIN"].split(":")[0].strip() try: return Element(element).symbol except ValueError: # VASP incorrectly gives the element symbol f...
[ "def", "element", "(", "self", ")", ":", "element", "=", "self", ".", "keywords", "[", "\"VRHFIN\"", "]", ".", "split", "(", "\":\"", ")", "[", "0", "]", ".", "strip", "(", ")", "try", ":", "return", "Element", "(", "element", ")", ".", "symbol", ...
Attempt to return the atomic symbol based on the VRHFIN keyword.
[ "Attempt", "to", "return", "the", "atomic", "symbol", "based", "on", "the", "VRHFIN", "keyword", "." ]
python
train
DLR-RM/RAFCON
source/rafcon/core/states/state.py
https://github.com/DLR-RM/RAFCON/blob/24942ef1a904531f49ab8830a1dbb604441be498/source/rafcon/core/states/state.py#L1110-L1147
def output_data_ports(self, output_data_ports): """ Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.OutputDataP...
[ "def", "output_data_ports", "(", "self", ",", "output_data_ports", ")", ":", "if", "not", "isinstance", "(", "output_data_ports", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"output_data_ports must be of type dict\"", ")", "if", "[", "port_id", "for", "por...
Setter for _output_data_ports field See property :param dict output_data_ports: Dictionary that maps :class:`int` data_port_ids onto values of type :class:`rafcon.core.state_elements.data_port.OutputDataPort` :raises exceptions.TypeError: if the output_dat...
[ "Setter", "for", "_output_data_ports", "field" ]
python
train
Spinmob/spinmob
_spline.py
https://github.com/Spinmob/spinmob/blob/f037f5df07f194bcd4a01f4d9916e57b9e8fb45a/_spline.py#L343-L365
def copy_spline_array(a): """ This returns an instance of a new spline_array with all the fixins, and the data from a. """ b = spline_array() b.x_splines = a.x_splines b.y_splines = a.y_splines b.max_y_splines = a.max_y_splines b.xmin = a.xmin b.xmax = a.xmax b.ymin = a.ym...
[ "def", "copy_spline_array", "(", "a", ")", ":", "b", "=", "spline_array", "(", ")", "b", ".", "x_splines", "=", "a", ".", "x_splines", "b", ".", "y_splines", "=", "a", ".", "y_splines", "b", ".", "max_y_splines", "=", "a", ".", "max_y_splines", "b", ...
This returns an instance of a new spline_array with all the fixins, and the data from a.
[ "This", "returns", "an", "instance", "of", "a", "new", "spline_array", "with", "all", "the", "fixins", "and", "the", "data", "from", "a", "." ]
python
train
JukeboxPipeline/jukebox-core
src/jukeboxcore/gui/widgets/reftrackwin.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/gui/widgets/reftrackwin.py#L291-L314
def create_shot_model(self, ): """Return a treemodel with the levels: project, sequence, shot and reftrack type :returns: a treemodel :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = tre...
[ "def", "create_shot_model", "(", "self", ",", ")", ":", "rootdata", "=", "treemodel", ".", "ListItemData", "(", "[", "'Name'", "]", ")", "rootitem", "=", "treemodel", ".", "TreeItem", "(", "rootdata", ")", "prjs", "=", "djadapter", ".", "projects", ".", ...
Return a treemodel with the levels: project, sequence, shot and reftrack type :returns: a treemodel :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None
[ "Return", "a", "treemodel", "with", "the", "levels", ":", "project", "sequence", "shot", "and", "reftrack", "type" ]
python
train
xtream1101/web-wrapper
web_wrapper/driver_selenium_chrome.py
https://github.com/xtream1101/web-wrapper/blob/2bfc63caa7d316564088951f01a490db493ea240/web_wrapper/driver_selenium_chrome.py#L175-L279
def _header_extension(self, remove_headers=[], add_or_modify_headers={}): """Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modif...
[ "def", "_header_extension", "(", "self", ",", "remove_headers", "=", "[", "]", ",", "add_or_modify_headers", "=", "{", "}", ")", ":", "import", "string", "import", "zipfile", "plugin_file", "=", "'custom_headers_plugin.zip'", "if", "remove_headers", "is", "None", ...
Create modheaders extension Source: https://vimmaniac.com/blog/bangal/modify-and-add-custom-headers-in-selenium-chrome-driver/ kwargs: remove_headers (list): headers name to remove add_or_modify_headers (dict): ie. {"Header-Name": "Header Value"} return str -> plugin p...
[ "Create", "modheaders", "extension" ]
python
train
LionelR/pyair
pyair/xair.py
https://github.com/LionelR/pyair/blob/467e8a843ca9f882f8bb2958805b7293591996ad/pyair/xair.py#L44-L70
def to_date(date, dayfirst=False, format=None): """ Transforme un champ date vers un objet python datetime Paramètres: date: - si None, renvoie la date du jour - si de type str, renvoie un objet python datetime - si de type datetime, le retourne sans modification dayfirst: Si...
[ "def", "to_date", "(", "date", ",", "dayfirst", "=", "False", ",", "format", "=", "None", ")", ":", "## TODO: voir si pd.tseries.api ne peut pas remplacer tout ca", "if", "not", "date", ":", "return", "dt", ".", "datetime", ".", "fromordinal", "(", "dt", ".", ...
Transforme un champ date vers un objet python datetime Paramètres: date: - si None, renvoie la date du jour - si de type str, renvoie un objet python datetime - si de type datetime, le retourne sans modification dayfirst: Si True, aide l'analyse du champ date de type str en informant...
[ "Transforme", "un", "champ", "date", "vers", "un", "objet", "python", "datetime", "Paramètres", ":", "date", ":", "-", "si", "None", "renvoie", "la", "date", "du", "jour", "-", "si", "de", "type", "str", "renvoie", "un", "objet", "python", "datetime", "-...
python
valid
project-ncl/pnc-cli
pnc_cli/buildrecords.py
https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/buildrecords.py#L33-L39
def list_records_for_build_configuration(id=None, name=None, page_size=200, page_index=0, sort="", q=""): """ List all BuildRecords for a given BuildConfiguration """ data = list_records_for_build_configuration_raw(id, name, page_size, page_index, sort, q) if data: return utils.format_json_l...
[ "def", "list_records_for_build_configuration", "(", "id", "=", "None", ",", "name", "=", "None", ",", "page_size", "=", "200", ",", "page_index", "=", "0", ",", "sort", "=", "\"\"", ",", "q", "=", "\"\"", ")", ":", "data", "=", "list_records_for_build_conf...
List all BuildRecords for a given BuildConfiguration
[ "List", "all", "BuildRecords", "for", "a", "given", "BuildConfiguration" ]
python
train
Capitains/MyCapytain
MyCapytain/common/metadata.py
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/metadata.py#L139-L145
def remove(self, predicate=None, obj=None): """ Remove triple matching the predicate or the object :param predicate: Predicate to match, None to match all :param obj: Object to match, None to match all """ self.graph.remove((self.asNode(), predicate, obj))
[ "def", "remove", "(", "self", ",", "predicate", "=", "None", ",", "obj", "=", "None", ")", ":", "self", ".", "graph", ".", "remove", "(", "(", "self", ".", "asNode", "(", ")", ",", "predicate", ",", "obj", ")", ")" ]
Remove triple matching the predicate or the object :param predicate: Predicate to match, None to match all :param obj: Object to match, None to match all
[ "Remove", "triple", "matching", "the", "predicate", "or", "the", "object" ]
python
train
gem/oq-engine
openquake/engine/tools/make_html_report.py
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/engine/tools/make_html_report.py#L34-L39
def html(header_rows): """ Convert a list of tuples describing a table into a HTML string """ name = 'table%d' % next(tablecounter) return HtmlTable([map(str, row) for row in header_rows], name).render()
[ "def", "html", "(", "header_rows", ")", ":", "name", "=", "'table%d'", "%", "next", "(", "tablecounter", ")", "return", "HtmlTable", "(", "[", "map", "(", "str", ",", "row", ")", "for", "row", "in", "header_rows", "]", ",", "name", ")", ".", "render"...
Convert a list of tuples describing a table into a HTML string
[ "Convert", "a", "list", "of", "tuples", "describing", "a", "table", "into", "a", "HTML", "string" ]
python
train
googleapis/google-cloud-python
monitoring/google/cloud/monitoring_v3/query.py
https://github.com/googleapis/google-cloud-python/blob/85e80125a59cb10f8cb105f25ecc099e4b940b50/monitoring/google/cloud/monitoring_v3/query.py#L407-L441
def iter(self, headers_only=False, page_size=None): """Yield all time series objects selected by the query. The generator returned iterates over :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects containing points ordered from oldest to newest. Note that the :class:`...
[ "def", "iter", "(", "self", ",", "headers_only", "=", "False", ",", "page_size", "=", "None", ")", ":", "if", "self", ".", "_end_time", "is", "None", ":", "raise", "ValueError", "(", "\"Query time interval not specified.\"", ")", "params", "=", "self", ".", ...
Yield all time series objects selected by the query. The generator returned iterates over :class:`~google.cloud.monitoring_v3.types.TimeSeries` objects containing points ordered from oldest to newest. Note that the :class:`Query` object itself is an iterable, such that the foll...
[ "Yield", "all", "time", "series", "objects", "selected", "by", "the", "query", "." ]
python
train
CivicSpleen/ambry
ambry/bundle/bundle.py
https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L962-L1001
def field_row(self, fields): """ Return a list of values to match the fields values. This is used when listing bundles to produce a table of information about the bundle. :param fields: A list of names of data items. :return: A list of values, in the same order as the fields inp...
[ "def", "field_row", "(", "self", ",", "fields", ")", ":", "row", "=", "self", ".", "dataset", ".", "row", "(", "fields", ")", "# Modify for special fields", "for", "i", ",", "f", "in", "enumerate", "(", "fields", ")", ":", "if", "f", "==", "'bstate'", ...
Return a list of values to match the fields values. This is used when listing bundles to produce a table of information about the bundle. :param fields: A list of names of data items. :return: A list of values, in the same order as the fields input The names in the fields llist can be:...
[ "Return", "a", "list", "of", "values", "to", "match", "the", "fields", "values", ".", "This", "is", "used", "when", "listing", "bundles", "to", "produce", "a", "table", "of", "information", "about", "the", "bundle", "." ]
python
train
pydata/xarray
xarray/core/dataset.py
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/dataset.py#L412-L421
def load_store(cls, store, decoder=None): """Create a new dataset from the contents of a backends.*DataStore object """ variables, attributes = store.load() if decoder: variables, attributes = decoder(variables, attributes) obj = cls(variables, attrs=attribute...
[ "def", "load_store", "(", "cls", ",", "store", ",", "decoder", "=", "None", ")", ":", "variables", ",", "attributes", "=", "store", ".", "load", "(", ")", "if", "decoder", ":", "variables", ",", "attributes", "=", "decoder", "(", "variables", ",", "att...
Create a new dataset from the contents of a backends.*DataStore object
[ "Create", "a", "new", "dataset", "from", "the", "contents", "of", "a", "backends", ".", "*", "DataStore", "object" ]
python
train
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L81-L107
def _transform_constant_sequence(self, seq): """ Transform a frozenset or tuple. """ should_transform = is_a(self.types) if not any(filter(should_transform, flatten(seq))): # Tuple doesn't contain any transformable strings. Ignore. yield LOAD_CONST(seq) ...
[ "def", "_transform_constant_sequence", "(", "self", ",", "seq", ")", ":", "should_transform", "=", "is_a", "(", "self", ".", "types", ")", "if", "not", "any", "(", "filter", "(", "should_transform", ",", "flatten", "(", "seq", ")", ")", ")", ":", "# Tupl...
Transform a frozenset or tuple.
[ "Transform", "a", "frozenset", "or", "tuple", "." ]
python
train
watson-developer-cloud/python-sdk
ibm_watson/natural_language_understanding_v1.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/natural_language_understanding_v1.py#L1364-L1377
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'limit') and self.limit is not None: _dict['limit'] = self.limit if hasattr(self, 'mentions') and self.mentions is not None: _dict['mentions'] = self.mentions ...
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'limit'", ")", "and", "self", ".", "limit", "is", "not", "None", ":", "_dict", "[", "'limit'", "]", "=", "self", ".", "limit", "if", "hasattr", ...
Return a json dictionary representing this model.
[ "Return", "a", "json", "dictionary", "representing", "this", "model", "." ]
python
train
tensorpack/tensorpack
tensorpack/models/pool.py
https://github.com/tensorpack/tensorpack/blob/d7a13cb74c9066bc791d7aafc3b744b60ee79a9f/tensorpack/models/pool.py#L91-L140
def FixedUnPooling(x, shape, unpool_mat=None, data_format='channels_last'): """ Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. ...
[ "def", "FixedUnPooling", "(", "x", ",", "shape", ",", "unpool_mat", "=", "None", ",", "data_format", "=", "'channels_last'", ")", ":", "data_format", "=", "get_data_format", "(", "data_format", ",", "keras_mode", "=", "False", ")", "shape", "=", "shape2d", "...
Unpool the input with a fixed matrix to perform kronecker product with. Args: x (tf.Tensor): a 4D image tensor shape: int or (h, w) tuple unpool_mat: a tf.Tensor or np.ndarray 2D matrix with size=shape. If is None, will use a matrix with 1 at top-left corner. Returns: ...
[ "Unpool", "the", "input", "with", "a", "fixed", "matrix", "to", "perform", "kronecker", "product", "with", "." ]
python
train
SUSE-Enceladus/ipa
ipa/ipa_cloud.py
https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_cloud.py#L437-L443
def _update_history(self): """Save the current test information to history json.""" ipa_utils.update_history_log( self.history_log, description=self.description, test_log=self.log_file )
[ "def", "_update_history", "(", "self", ")", ":", "ipa_utils", ".", "update_history_log", "(", "self", ".", "history_log", ",", "description", "=", "self", ".", "description", ",", "test_log", "=", "self", ".", "log_file", ")" ]
Save the current test information to history json.
[ "Save", "the", "current", "test", "information", "to", "history", "json", "." ]
python
train
inasafe/inasafe
safe/metadata/base_metadata.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/metadata/base_metadata.py#L330-L344
def _read_json_file(self): """ read metadata from a json file. :return: the parsed json dict :rtype: dict """ with open(self.json_uri) as metadata_file: try: metadata = json.load(metadata_file) return metadata excep...
[ "def", "_read_json_file", "(", "self", ")", ":", "with", "open", "(", "self", ".", "json_uri", ")", "as", "metadata_file", ":", "try", ":", "metadata", "=", "json", ".", "load", "(", "metadata_file", ")", "return", "metadata", "except", "ValueError", ":", ...
read metadata from a json file. :return: the parsed json dict :rtype: dict
[ "read", "metadata", "from", "a", "json", "file", "." ]
python
train
trehn/hnmp
hnmp.py
https://github.com/trehn/hnmp/blob/a21f9e73c96a35bff2354894031c4788ad4ed2f0/hnmp.py#L65-L90
def _convert_value_to_native(value): """ Converts pysnmp objects into native Python objects. """ if isinstance(value, Counter32): return int(value.prettyPrint()) if isinstance(value, Counter64): return int(value.prettyPrint()) if isinstance(value, Gauge32): return int(val...
[ "def", "_convert_value_to_native", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Counter32", ")", ":", "return", "int", "(", "value", ".", "prettyPrint", "(", ")", ")", "if", "isinstance", "(", "value", ",", "Counter64", ")", ":", "retu...
Converts pysnmp objects into native Python objects.
[ "Converts", "pysnmp", "objects", "into", "native", "Python", "objects", "." ]
python
train
decryptus/httpdis
httpdis/httpdis.py
https://github.com/decryptus/httpdis/blob/5d198cdc5558f416634602689b3df2c8aeb34984/httpdis/httpdis.py#L540-L550
def send_exception(self, code, exc_info=None, headers=None): "send an error response including a backtrace to the client" if headers is None: headers = {} if not exc_info: exc_info = sys.exc_info() self.send_error_msg(code, traceback....
[ "def", "send_exception", "(", "self", ",", "code", ",", "exc_info", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "{", "}", "if", "not", "exc_info", ":", "exc_info", "=", "sys", ".", "exc_info...
send an error response including a backtrace to the client
[ "send", "an", "error", "response", "including", "a", "backtrace", "to", "the", "client" ]
python
train
dmlc/gluon-nlp
src/gluonnlp/model/attention_cell.py
https://github.com/dmlc/gluon-nlp/blob/4b83eb6bcc8881e5f1081a3675adaa19fac5c0ba/src/gluonnlp/model/attention_cell.py#L99-L120
def _read_by_weight(self, F, att_weights, value): """Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (b...
[ "def", "_read_by_weight", "(", "self", ",", "F", ",", "att_weights", ",", "value", ")", ":", "output", "=", "F", ".", "batch_dot", "(", "att_weights", ",", "value", ")", "return", "output" ]
Read from the value matrix given the attention weights. Parameters ---------- F : symbol or ndarray att_weights : Symbol or NDArray Attention weights. For single-head attention, Shape (batch_size, query_length, memory_length). For mult...
[ "Read", "from", "the", "value", "matrix", "given", "the", "attention", "weights", "." ]
python
train
SuryaSankar/flask-sqlalchemy-booster
flask_sqlalchemy_booster/model_booster/dictizable_mixin.py
https://github.com/SuryaSankar/flask-sqlalchemy-booster/blob/444048d167ab7718f758e943665ef32d101423a5/flask_sqlalchemy_booster/model_booster/dictizable_mixin.py#L321-L368
def todict_using_struct(self, dict_struct=None, dict_post_processors=None): """ dict_struct: { 'attrs': ['id', 'created_at'], 'rels': { 'merchandise': { 'attrs': ['id', 'label'] } ...
[ "def", "todict_using_struct", "(", "self", ",", "dict_struct", "=", "None", ",", "dict_post_processors", "=", "None", ")", ":", "# It is important to assign the passed kwarg to a differently named variable.", "# A dict is passed by reference and using the same kwarg here results in it"...
dict_struct: { 'attrs': ['id', 'created_at'], 'rels': { 'merchandise': { 'attrs': ['id', 'label'] } } }
[ "dict_struct", ":", "{", "attrs", ":", "[", "id", "created_at", "]", "rels", ":", "{", "merchandise", ":", "{", "attrs", ":", "[", "id", "label", "]", "}", "}", "}" ]
python
train
rodynnz/xccdf
src/xccdf/models/html_element.py
https://github.com/rodynnz/xccdf/blob/1b9dc2f06b5cce8db2a54c5f95a8f6bcf5cb6981/src/xccdf/models/html_element.py#L68-L99
def get_html_content(self): """ Parses the element and subelements and parses any HTML enabled text to its original HTML form for rendering. :returns: Parsed HTML enabled text content. :rtype: str """ # Extract full element node content (including subelements) ...
[ "def", "get_html_content", "(", "self", ")", ":", "# Extract full element node content (including subelements)", "html_content", "=", "''", "if", "hasattr", "(", "self", ",", "'xml_element'", ")", ":", "xml", "=", "self", ".", "xml_element", "content_list", "=", "["...
Parses the element and subelements and parses any HTML enabled text to its original HTML form for rendering. :returns: Parsed HTML enabled text content. :rtype: str
[ "Parses", "the", "element", "and", "subelements", "and", "parses", "any", "HTML", "enabled", "text", "to", "its", "original", "HTML", "form", "for", "rendering", "." ]
python
train
splitkeycoffee/pyhottop
pyhottop/cli/config.py
https://github.com/splitkeycoffee/pyhottop/blob/2986bbb2d848f7e41fa3ece5ebb1b33c8882219c/pyhottop/cli/config.py#L23-L42
def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('test') setup_parser.add_argument('--interface', default=None, help='Manually pass in the USB connection.') args = parser.parse_args() ...
[ "def", "main", "(", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "subs", "=", "parser", ".", "add_subparsers", "(", "dest", "=", "'cmd'", ")", "setup_parser", "=", "subs", ".", "add_parser", "(", "'test'", ")", "setup_parser", ".", "add_argument", ...
Run the core.
[ "Run", "the", "core", "." ]
python
train
Cue/scales
src/greplin/scales/formats.py
https://github.com/Cue/scales/blob/0aced26eb050ceb98ee9d5d6cdca8db448666986/src/greplin/scales/formats.py#L38-L60
def runQuery(statDict, query): """Filters for the given query.""" parts = [x.strip() for x in OPERATOR.split(query)] assert len(parts) in (1, 3) queryKey = parts[0] result = {} for key, value in six.iteritems(statDict): if key == queryKey: if len(parts) == 3: op = OPERATORS[parts[1]] ...
[ "def", "runQuery", "(", "statDict", ",", "query", ")", ":", "parts", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "OPERATOR", ".", "split", "(", "query", ")", "]", "assert", "len", "(", "parts", ")", "in", "(", "1", ",", "3", ")", ...
Filters for the given query.
[ "Filters", "for", "the", "given", "query", "." ]
python
train
saltstack/salt
salt/cloud/clouds/gce.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/gce.py#L159-L169
def get_dependencies(): ''' Warn if dependencies aren't met. ''' if LIBCLOUD_IMPORT_ERROR: log.error("Failure when importing LibCloud: ", exc_info=LIBCLOUD_IMPORT_ERROR) log.error("Note: The libcloud dependency is called 'apache-libcloud' on PyPi/pip.") return config.check_driver_dep...
[ "def", "get_dependencies", "(", ")", ":", "if", "LIBCLOUD_IMPORT_ERROR", ":", "log", ".", "error", "(", "\"Failure when importing LibCloud: \"", ",", "exc_info", "=", "LIBCLOUD_IMPORT_ERROR", ")", "log", ".", "error", "(", "\"Note: The libcloud dependency is called 'apach...
Warn if dependencies aren't met.
[ "Warn", "if", "dependencies", "aren", "t", "met", "." ]
python
train
materialsproject/pymatgen
pymatgen/io/vasp/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L625-L643
def hubbards(self): """ Hubbard U values used if a vasprun is a GGA+U run. {} otherwise. """ symbols = [s.split()[1] for s in self.potcar_symbols] symbols = [re.split(r"_", s)[0] for s in symbols] if not self.incar.get("LDAU", False): return {} us = se...
[ "def", "hubbards", "(", "self", ")", ":", "symbols", "=", "[", "s", ".", "split", "(", ")", "[", "1", "]", "for", "s", "in", "self", ".", "potcar_symbols", "]", "symbols", "=", "[", "re", ".", "split", "(", "r\"_\"", ",", "s", ")", "[", "0", ...
Hubbard U values used if a vasprun is a GGA+U run. {} otherwise.
[ "Hubbard", "U", "values", "used", "if", "a", "vasprun", "is", "a", "GGA", "+", "U", "run", ".", "{}", "otherwise", "." ]
python
train
fumitoh/modelx
modelx/core/api.py
https://github.com/fumitoh/modelx/blob/0180da34d052c44fb94dab9e115e218bbebfc9c3/modelx/core/api.py#L206-L216
def _get_node(name: str, args: str): """Get node from object name and arg string Not Used. Left for future reference purpose. """ obj = get_object(name) args = ast.literal_eval(args) if not isinstance(args, tuple): args = (args,) return obj.node(*args)
[ "def", "_get_node", "(", "name", ":", "str", ",", "args", ":", "str", ")", ":", "obj", "=", "get_object", "(", "name", ")", "args", "=", "ast", ".", "literal_eval", "(", "args", ")", "if", "not", "isinstance", "(", "args", ",", "tuple", ")", ":", ...
Get node from object name and arg string Not Used. Left for future reference purpose.
[ "Get", "node", "from", "object", "name", "and", "arg", "string" ]
python
valid
rackerlabs/simpl
simpl/middleware/context.py
https://github.com/rackerlabs/simpl/blob/60ed3336a931cd6a7a7246e60f26165d9dc7c99c/simpl/middleware/context.py#L97-L104
def start_response_callback(start_response, transaction_id): """Intercept upstream start_response and adds our headers.""" def callback(status, headers, exc_info=None): """Add our headers to response using a closure.""" headers.append(('X-Transaction-Id', transaction_id)) ...
[ "def", "start_response_callback", "(", "start_response", ",", "transaction_id", ")", ":", "def", "callback", "(", "status", ",", "headers", ",", "exc_info", "=", "None", ")", ":", "\"\"\"Add our headers to response using a closure.\"\"\"", "headers", ".", "append", "(...
Intercept upstream start_response and adds our headers.
[ "Intercept", "upstream", "start_response", "and", "adds", "our", "headers", "." ]
python
train
scanny/python-pptx
pptx/shapes/shapetree.py
https://github.com/scanny/python-pptx/blob/d6ab8234f8b03953d2f831ff9394b1852db34130/pptx/shapes/shapetree.py#L465-L492
def add_movie(self, movie_file, left, top, width, height, poster_frame_image=None, mime_type=CT.VIDEO): """Return newly added movie shape displaying video in *movie_file*. **EXPERIMENTAL.** This method has important limitations: * The size must be specified; no auto-scaling s...
[ "def", "add_movie", "(", "self", ",", "movie_file", ",", "left", ",", "top", ",", "width", ",", "height", ",", "poster_frame_image", "=", "None", ",", "mime_type", "=", "CT", ".", "VIDEO", ")", ":", "movie_pic", "=", "_MoviePicElementCreator", ".", "new_mo...
Return newly added movie shape displaying video in *movie_file*. **EXPERIMENTAL.** This method has important limitations: * The size must be specified; no auto-scaling such as that provided by :meth:`add_picture` is performed. * The MIME type of the video file should be specified, e....
[ "Return", "newly", "added", "movie", "shape", "displaying", "video", "in", "*", "movie_file", "*", "." ]
python
train
qacafe/cdrouter.py
cdrouter/system.py
https://github.com/qacafe/cdrouter.py/blob/aacf2c6ab0b987250f7b1892f4bba14bb2b7dbe5/cdrouter/system.py#L379-L391
def manual_update_license(self, fd, filename='cdrouter.lic'): """Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. ...
[ "def", "manual_update_license", "(", "self", ",", "fd", ",", "filename", "=", "'cdrouter.lic'", ")", ":", "schema", "=", "UpgradeSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "'license/'", ",", "files...
Update the license on your CDRouter system manually by uploading a .lic license from the CDRouter Support Lounge. :param fd: File-like object to upload. :param filename: (optional) Filename to use for license as string. :return: :class:`system.Upgrade <system.Upgrade>` object :r...
[ "Update", "the", "license", "on", "your", "CDRouter", "system", "manually", "by", "uploading", "a", ".", "lic", "license", "from", "the", "CDRouter", "Support", "Lounge", "." ]
python
train
knipknap/SpiffWorkflow
SpiffWorkflow/bpmn/parser/TaskParser.py
https://github.com/knipknap/SpiffWorkflow/blob/f0af7f59a332e0619e4f3c00a7d4a3d230760e00/SpiffWorkflow/bpmn/parser/TaskParser.py#L149-L156
def create_task(self): """ Create an instance of the task appropriately. A subclass can override this method to get extra information from the node. """ return self.spec_class(self.spec, self.get_task_spec_name(), lane=self.get_lane(), ...
[ "def", "create_task", "(", "self", ")", ":", "return", "self", ".", "spec_class", "(", "self", ".", "spec", ",", "self", ".", "get_task_spec_name", "(", ")", ",", "lane", "=", "self", ".", "get_lane", "(", ")", ",", "description", "=", "self", ".", "...
Create an instance of the task appropriately. A subclass can override this method to get extra information from the node.
[ "Create", "an", "instance", "of", "the", "task", "appropriately", ".", "A", "subclass", "can", "override", "this", "method", "to", "get", "extra", "information", "from", "the", "node", "." ]
python
valid
mdickinson/bigfloat
bigfloat/core.py
https://github.com/mdickinson/bigfloat/blob/e5fdd1048615191ed32a2b7460e14b3b3ff24662/bigfloat/core.py#L2471-L2492
def remainder(x, y, context=None): """ Return x reduced modulo y. Returns the value of x - n * y, where n is the integer quotient of x divided by y, rounded to the nearest integer (ties rounded to even). Special values are handled as described in Section F.9.7.1 of the ISO C99 standard: If x i...
[ "def", "remainder", "(", "x", ",", "y", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_remainder", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", "BigFloat"...
Return x reduced modulo y. Returns the value of x - n * y, where n is the integer quotient of x divided by y, rounded to the nearest integer (ties rounded to even). Special values are handled as described in Section F.9.7.1 of the ISO C99 standard: If x is infinite or y is zero, the result is NaN. If ...
[ "Return", "x", "reduced", "modulo", "y", "." ]
python
train
outini/python-pylls
pylls/cachet.py
https://github.com/outini/python-pylls/blob/f9fa220594bc1974469097d9bad690a42d0d0f0f/pylls/cachet.py#L366-L381
def get(self, metric_id=None, **kwargs): """Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https:/...
[ "def", "get", "(", "self", ",", "metric_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'metrics'", "if", "metric_id", "is", "not", "None", ":", "path", "+=", "'/%s'", "%", "metric_id", "return", "self", ".", "paginate_get", "(", "...
Get metrics :param int metric_id: Metric ID :return: Metrics data (:class:`dict`) Additional named arguments may be passed and are directly transmitted to API. It is useful to use the API search features. .. seealso:: https://docs.cachethq.io/reference#get-metrics .. s...
[ "Get", "metrics" ]
python
train
google/apitools
apitools/base/py/transfer.py
https://github.com/google/apitools/blob/f3745a7ea535aa0e88b0650c16479b696d6fd446/apitools/base/py/transfer.py#L1041-L1064
def __SendMediaBody(self, start, additional_headers=None): """Send the entire media stream in a single request.""" self.EnsureInitialized() if self.total_size is None: raise exceptions.TransferInvalidError( 'Total size must be known for SendMediaBody') body_st...
[ "def", "__SendMediaBody", "(", "self", ",", "start", ",", "additional_headers", "=", "None", ")", ":", "self", ".", "EnsureInitialized", "(", ")", "if", "self", ".", "total_size", "is", "None", ":", "raise", "exceptions", ".", "TransferInvalidError", "(", "'...
Send the entire media stream in a single request.
[ "Send", "the", "entire", "media", "stream", "in", "a", "single", "request", "." ]
python
train
DataDog/integrations-core
haproxy/datadog_checks/haproxy/haproxy.py
https://github.com/DataDog/integrations-core/blob/ebd41c873cf9f97a8c51bf9459bc6a7536af8acd/haproxy/datadog_checks/haproxy/haproxy.py#L428-L439
def _should_process(self, data_dict, collect_aggregates_only): """ if collect_aggregates_only, we process only the aggregates else we process all except Services.BACKEND """ if collect_aggregates_only: if self._is_aggregate(data_dict): return T...
[ "def", "_should_process", "(", "self", ",", "data_dict", ",", "collect_aggregates_only", ")", ":", "if", "collect_aggregates_only", ":", "if", "self", ".", "_is_aggregate", "(", "data_dict", ")", ":", "return", "True", "return", "False", "elif", "data_dict", "["...
if collect_aggregates_only, we process only the aggregates else we process all except Services.BACKEND
[ "if", "collect_aggregates_only", "we", "process", "only", "the", "aggregates", "else", "we", "process", "all", "except", "Services", ".", "BACKEND" ]
python
train
spyder-ide/spyder
spyder/plugins/editor/panels/manager.py
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/plugins/editor/panels/manager.py#L58-L81
def register(self, panel, position=Panel.Position.LEFT): """ Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel """ assert panel is not None pos_to_strin...
[ "def", "register", "(", "self", ",", "panel", ",", "position", "=", "Panel", ".", "Position", ".", "LEFT", ")", ":", "assert", "panel", "is", "not", "None", "pos_to_string", "=", "{", "Panel", ".", "Position", ".", "BOTTOM", ":", "'bottom'", ",", "Pane...
Installs a panel on the editor. :param panel: Panel to install :param position: Position where the panel must be installed. :return: The installed panel
[ "Installs", "a", "panel", "on", "the", "editor", "." ]
python
train
saltstack/salt
salt/utils/decorators/__init__.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/decorators/__init__.py#L561-L578
def _is_used_deprecated(self): ''' Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return: ''' func_path = "{m_name}.{f_name}".format( m_name=self._globals.get(self.MODULE_NAME, '') or self._g...
[ "def", "_is_used_deprecated", "(", "self", ")", ":", "func_path", "=", "\"{m_name}.{f_name}\"", ".", "format", "(", "m_name", "=", "self", ".", "_globals", ".", "get", "(", "self", ".", "MODULE_NAME", ",", "''", ")", "or", "self", ".", "_globals", "[", "...
Returns True, if a component configuration explicitly is asking to use an old version of the deprecated function. :return:
[ "Returns", "True", "if", "a", "component", "configuration", "explicitly", "is", "asking", "to", "use", "an", "old", "version", "of", "the", "deprecated", "function", "." ]
python
train
Azure/azure-sdk-for-python
azure-servicemanagement-legacy/azure/servicemanagement/_serialization.py
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/_serialization.py#L233-L240
def _parse_response_body_from_xml_node(node, return_type): ''' parse the xml and fill all the data into a class of return_type ''' return_obj = return_type() _MinidomXmlToObject._fill_data_to_return_object(node, return_obj) return return_obj
[ "def", "_parse_response_body_from_xml_node", "(", "node", ",", "return_type", ")", ":", "return_obj", "=", "return_type", "(", ")", "_MinidomXmlToObject", ".", "_fill_data_to_return_object", "(", "node", ",", "return_obj", ")", "return", "return_obj" ]
parse the xml and fill all the data into a class of return_type
[ "parse", "the", "xml", "and", "fill", "all", "the", "data", "into", "a", "class", "of", "return_type" ]
python
test
macbre/sql-metadata
sql_metadata.py
https://github.com/macbre/sql-metadata/blob/4b7b4ae0a961d568075aefe78535cf5aee74583c/sql_metadata.py#L69-L128
def get_query_columns(query): """ :type query str :rtype: list[str] """ columns = [] last_keyword = None last_token = None # print(preprocess_query(query)) # these keywords should not change the state of a parser # and not "reset" previously found SELECT keyword keywords_ig...
[ "def", "get_query_columns", "(", "query", ")", ":", "columns", "=", "[", "]", "last_keyword", "=", "None", "last_token", "=", "None", "# print(preprocess_query(query))", "# these keywords should not change the state of a parser", "# and not \"reset\" previously found SELECT keywo...
:type query str :rtype: list[str]
[ ":", "type", "query", "str", ":", "rtype", ":", "list", "[", "str", "]" ]
python
train
aerogear/digger-build-cli
digger/helpers/android.py
https://github.com/aerogear/digger-build-cli/blob/8b88a31063526ec7222dbea6a87309686ad21320/digger/helpers/android.py#L84-L101
def get_highest_build_tool(sdk_version=None): """ Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found) """ ...
[ "def", "get_highest_build_tool", "(", "sdk_version", "=", "None", ")", ":", "if", "sdk_version", "is", "None", ":", "sdk_version", "=", "config", ".", "sdk_version", "android_home", "=", "os", ".", "environ", ".", "get", "(", "'AG_MOBILE_SDK'", ",", "os", "....
Gets the highest build tool version based on major version sdk version. :param sdk_version(int) - sdk version to be used as the marjor build tool version context. Returns: A string containg the build tool version (default is 23.0.2 if none is found)
[ "Gets", "the", "highest", "build", "tool", "version", "based", "on", "major", "version", "sdk", "version", "." ]
python
train
Fizzadar/pyinfra
pyinfra/api/facts.py
https://github.com/Fizzadar/pyinfra/blob/006f751f7db2e07d32522c0285160783de2feb79/pyinfra/api/facts.py#L104-L246
def get_facts(state, name, args=None, ensure_hosts=None): ''' Get a single fact for all hosts in the state. ''' # Create an instance of the fact fact = FACTS[name]() if isinstance(fact, ShortFactBase): return get_short_facts(state, fact, args=args, ensure_hosts=ensure_hosts) logge...
[ "def", "get_facts", "(", "state", ",", "name", ",", "args", "=", "None", ",", "ensure_hosts", "=", "None", ")", ":", "# Create an instance of the fact", "fact", "=", "FACTS", "[", "name", "]", "(", ")", "if", "isinstance", "(", "fact", ",", "ShortFactBase"...
Get a single fact for all hosts in the state.
[ "Get", "a", "single", "fact", "for", "all", "hosts", "in", "the", "state", "." ]
python
train
pwaller/__autoversion__
__autoversion__.py
https://github.com/pwaller/__autoversion__/blob/caaaff2c5a758388cdd6117fed0847fb4cd103f5/__autoversion__.py#L89-L101
def getversion(package): """ Obtain the ``__version__`` for ``package``, looking at the egg information or the source repository's version control if necessary. """ distribution = get_distribution(package) if distribution is None: raise RuntimeError("Can't find distribution {0}".format(p...
[ "def", "getversion", "(", "package", ")", ":", "distribution", "=", "get_distribution", "(", "package", ")", "if", "distribution", "is", "None", ":", "raise", "RuntimeError", "(", "\"Can't find distribution {0}\"", ".", "format", "(", "package", ")", ")", "repo_...
Obtain the ``__version__`` for ``package``, looking at the egg information or the source repository's version control if necessary.
[ "Obtain", "the", "__version__", "for", "package", "looking", "at", "the", "egg", "information", "or", "the", "source", "repository", "s", "version", "control", "if", "necessary", "." ]
python
train
Erotemic/utool
utool/util_cplat.py
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_cplat.py#L1450-L1486
def unload_module(modname): """ WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK References: http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module CommandLine: python -m utool.util_cplat --test-unload_module Example: >>> # DISABLE_DOCTEST >...
[ "def", "unload_module", "(", "modname", ")", ":", "import", "sys", "import", "gc", "if", "modname", "in", "sys", ".", "modules", ":", "referrer_list", "=", "gc", ".", "get_referrers", "(", "sys", ".", "modules", "[", "modname", "]", ")", "#module = sys.mod...
WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK References: http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module CommandLine: python -m utool.util_cplat --test-unload_module Example: >>> # DISABLE_DOCTEST >>> import sys, gc # NOQA >>> im...
[ "WARNING", "POTENTIALLY", "DANGEROUS", "AND", "MAY", "NOT", "WORK" ]
python
train
gawel/irc3
irc3/plugins/core.py
https://github.com/gawel/irc3/blob/cd27840a5809a1f803dc620860fe75d83d2a2ec8/irc3/plugins/core.py#L88-L91
def ping(self, data): """PING reply""" self.bot.send('PONG :' + data) self.pong(event='PING', data=data)
[ "def", "ping", "(", "self", ",", "data", ")", ":", "self", ".", "bot", ".", "send", "(", "'PONG :'", "+", "data", ")", "self", ".", "pong", "(", "event", "=", "'PING'", ",", "data", "=", "data", ")" ]
PING reply
[ "PING", "reply" ]
python
train
yougov/openpack
openpack/editor.py
https://github.com/yougov/openpack/blob/1412ec34c1bab6ba6c8ae5490c2205d696f13717/openpack/editor.py#L151-L176
def find_file(path): """ Given a path to a part in a zip file, return a path to the file and the path to the part. Assuming /foo.zipx exists as a file, >>> find_file('/foo.zipx/dir/part') # doctest: +SKIP ('/foo.zipx', '/dir/part') >>> find_file('/foo.zipx') # doctest: +SKIP ('/foo.zipx', '') """ path_comp...
[ "def", "find_file", "(", "path", ")", ":", "path_components", "=", "split_all", "(", "path", ")", "def", "get_assemblies", "(", ")", ":", "\"\"\"\n\t\tEnumerate the various combinations of file paths and part paths\n\t\t\"\"\"", "for", "n", "in", "range", "(", "len", ...
Given a path to a part in a zip file, return a path to the file and the path to the part. Assuming /foo.zipx exists as a file, >>> find_file('/foo.zipx/dir/part') # doctest: +SKIP ('/foo.zipx', '/dir/part') >>> find_file('/foo.zipx') # doctest: +SKIP ('/foo.zipx', '')
[ "Given", "a", "path", "to", "a", "part", "in", "a", "zip", "file", "return", "a", "path", "to", "the", "file", "and", "the", "path", "to", "the", "part", "." ]
python
test
pandas-dev/pandas
pandas/plotting/_timeseries.py
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/plotting/_timeseries.py#L173-L194
def _get_ax_freq(ax): """ Get the freq attribute of the ax object if set. Also checks shared axes (eg when using secondary yaxis, sharex=True or twinx) """ ax_freq = getattr(ax, 'freq', None) if ax_freq is None: # check for left/right ax in case of secondary yaxis if hasattr(...
[ "def", "_get_ax_freq", "(", "ax", ")", ":", "ax_freq", "=", "getattr", "(", "ax", ",", "'freq'", ",", "None", ")", "if", "ax_freq", "is", "None", ":", "# check for left/right ax in case of secondary yaxis", "if", "hasattr", "(", "ax", ",", "'left_ax'", ")", ...
Get the freq attribute of the ax object if set. Also checks shared axes (eg when using secondary yaxis, sharex=True or twinx)
[ "Get", "the", "freq", "attribute", "of", "the", "ax", "object", "if", "set", ".", "Also", "checks", "shared", "axes", "(", "eg", "when", "using", "secondary", "yaxis", "sharex", "=", "True", "or", "twinx", ")" ]
python
train
materialsproject/pymatgen
pymatgen/io/vasp/outputs.py
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/vasp/outputs.py#L1305-L1365
def as_dict(self): """ Json-serializable dict representation. """ d = {"vasp_version": self.vasp_version, "has_vasp_completed": True, "nsites": len(self.final_structure)} comp = self.final_structure.composition d["unit_cell_formula"] = comp.as_di...
[ "def", "as_dict", "(", "self", ")", ":", "d", "=", "{", "\"vasp_version\"", ":", "self", ".", "vasp_version", ",", "\"has_vasp_completed\"", ":", "True", ",", "\"nsites\"", ":", "len", "(", "self", ".", "final_structure", ")", "}", "comp", "=", "self", "...
Json-serializable dict representation.
[ "Json", "-", "serializable", "dict", "representation", "." ]
python
train
mouradmourafiq/pandas2sklearn
pandas_sklearn/__init__.py
https://github.com/mouradmourafiq/pandas2sklearn/blob/dbaf5180a893f4612852c1c217551b161fd519d4/pandas_sklearn/__init__.py#L181-L206
def _get_columns(self, X, cols): """ Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the se...
[ "def", "_get_columns", "(", "self", ",", "X", ",", "cols", ")", ":", "if", "isinstance", "(", "X", ",", "DataSet", ")", ":", "X", "=", "X", "[", "cols", "]", "return_vector", "=", "False", "if", "isinstance", "(", "cols", ",", "basestring", ")", ":...
Get a subset of columns from the given table X. X a Pandas dataframe; the table to select columns from cols a string or list of strings representing the columns to select Returns a numpy array with the data from the selected columns
[ "Get", "a", "subset", "of", "columns", "from", "the", "given", "table", "X", ".", "X", "a", "Pandas", "dataframe", ";", "the", "table", "to", "select", "columns", "from", "cols", "a", "string", "or", "list", "of", "strings", "representing", "the", "colum...
python
train
DistrictDataLabs/yellowbrick
yellowbrick/cluster/silhouette.py
https://github.com/DistrictDataLabs/yellowbrick/blob/59b67236a3862c73363e8edad7cd86da5b69e3b2/yellowbrick/cluster/silhouette.py#L184-L217
def finalize(self): """ Prepare the figure for rendering by setting the title and adjusting the limits on the axes, adding labels and a legend. """ # Set the title self.set_title(( "Silhouette Plot of {} Clustering for {} Samples in {} Centers" ).form...
[ "def", "finalize", "(", "self", ")", ":", "# Set the title", "self", ".", "set_title", "(", "(", "\"Silhouette Plot of {} Clustering for {} Samples in {} Centers\"", ")", ".", "format", "(", "self", ".", "name", ",", "self", ".", "n_samples_", ",", "self", ".", ...
Prepare the figure for rendering by setting the title and adjusting the limits on the axes, adding labels and a legend.
[ "Prepare", "the", "figure", "for", "rendering", "by", "setting", "the", "title", "and", "adjusting", "the", "limits", "on", "the", "axes", "adding", "labels", "and", "a", "legend", "." ]
python
train