nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
cvlab-epfl/LIFT
30414a61e97c33ae941b903a220952eecde1ba26
python-code/Utils/networks/eccv_base.py
python
ECCVNetworkBase.runTest4Image
(self, image, deterministic=True, model_epoch="", verbose=True, network_weights=None)
WRITE ME The test loop
WRITE ME
[ "WRITE", "ME" ]
def runTest4Image(self, image, deterministic=True, model_epoch="", verbose=True, network_weights=None): '''WRITE ME The test loop ''' save_dir = self.config.save_dir # --------------------------------------------------------------------- # Testing Loop if verbose: print('testing...') # --------------------------------------------------------------------- # Load the model if network_weights is None: if os.path.exists(save_dir + model_epoch): # for each layer of the model for idxSiam in six.moves.xrange(self.config.num_siamese): save_file_name = save_dir + model_epoch + "model" loadNetwork(self.layers[idxSiam], save_file_name) else: print(("PATH:", save_dir + model_epoch)) raise NotImplementedError( "I DON'T HAVE THE LEARNED MODEL READY!") else: # for each layer of the model for idxSiam in six.moves.xrange(self.config.num_siamese): # save_file_name = save_dir + model_epoch + "model" save_file_name = network_weights loadNetwork(self.layers[idxSiam], save_file_name) # Copy test data to share memory (test memory), we don't care about the # labels here val = image.reshape([1, 1, image.shape[0], image.shape[1]]) if self.config.bNormalizeInput: val = (val - self.config.mean_x) / self.config.std_x else: val /= np.cast[floatX](255.0) self.test_x[0].set_value(val) # for idxSiam in six.moves.xrange(num_siamese): # self.test_x[idxSiam].set_value(image) if deterministic: # print("running KP") return self.test_scoremap_deterministic()[-1] else: # print("running KP") return self.test_scoremap_stochastic()[-1]
[ "def", "runTest4Image", "(", "self", ",", "image", ",", "deterministic", "=", "True", ",", "model_epoch", "=", "\"\"", ",", "verbose", "=", "True", ",", "network_weights", "=", "None", ")", ":", "save_dir", "=", "self", ".", "config", ".", "save_dir", "#...
https://github.com/cvlab-epfl/LIFT/blob/30414a61e97c33ae941b903a220952eecde1ba26/python-code/Utils/networks/eccv_base.py#L239-L295
chengzhengxin/groupsoftmax-simpledet
3f63a00998c57fee25241cf43a2e8600893ea462
models/NASFPN/builder.py
python
reluconvbn
(data, num_filter, init, norm, name, prefix)
return data
:param data: data :param num_filter: number of convolution filter :param init: init method of conv weight :param norm: normalizer :param name: name :return: relu-3x3conv-bn
:param data: data :param num_filter: number of convolution filter :param init: init method of conv weight :param norm: normalizer :param name: name :return: relu-3x3conv-bn
[ ":", "param", "data", ":", "data", ":", "param", "num_filter", ":", "number", "of", "convolution", "filter", ":", "param", "init", ":", "init", "method", "of", "conv", "weight", ":", "param", "norm", ":", "normalizer", ":", "param", "name", ":", "name", ...
def reluconvbn(data, num_filter, init, norm, name, prefix): """ :param data: data :param num_filter: number of convolution filter :param init: init method of conv weight :param norm: normalizer :param name: name :return: relu-3x3conv-bn """ data = mx.sym.Activation(data, name=name + '_relu', act_type='relu') weight = mx.sym.var(name=prefix + name + "_weight", init=init) bias = mx.sym.var(name=prefix + name + "_bias") data = mx.sym.Convolution(data, name=prefix + name, weight=weight, bias=bias, num_filter=num_filter, kernel=(3, 3), pad=(1, 1), stride=(1, 1)) data = norm(data, name=name+'_bn') return data
[ "def", "reluconvbn", "(", "data", ",", "num_filter", ",", "init", ",", "norm", ",", "name", ",", "prefix", ")", ":", "data", "=", "mx", ".", "sym", ".", "Activation", "(", "data", ",", "name", "=", "name", "+", "'_relu'", ",", "act_type", "=", "'re...
https://github.com/chengzhengxin/groupsoftmax-simpledet/blob/3f63a00998c57fee25241cf43a2e8600893ea462/models/NASFPN/builder.py#L34-L48
mila-iqia/myia
56774a39579b4ec4123f44843ad4ca688acc859b
myia/compile/transform.py
python
convert_grad
(graph)
return graph
Remove all instances of SymbolicKeyType in the graphs. They will be replaced by globally-unique integers.
Remove all instances of SymbolicKeyType in the graphs.
[ "Remove", "all", "instances", "of", "SymbolicKeyType", "in", "the", "graphs", "." ]
def convert_grad(graph): """Remove all instances of SymbolicKeyType in the graphs. They will be replaced by globally-unique integers. """ mng = graph.manager counter = 0 key_map = {} for node in mng.all_nodes: if node.is_constant(SymbolicKeyInstance): if node.value not in key_map: key_map[node.value] = counter counter += 1 node.value = key_map[node.value] node.abstract = to_abstract(node.value) if node.is_constant(Primitive): if node.value is P.env_setitem: node.abstract = None if node.value is P.env_getitem: node.abstract = None return graph
[ "def", "convert_grad", "(", "graph", ")", ":", "mng", "=", "graph", ".", "manager", "counter", "=", "0", "key_map", "=", "{", "}", "for", "node", "in", "mng", ".", "all_nodes", ":", "if", "node", ".", "is_constant", "(", "SymbolicKeyInstance", ")", ":"...
https://github.com/mila-iqia/myia/blob/56774a39579b4ec4123f44843ad4ca688acc859b/myia/compile/transform.py#L13-L36
microsoft/botbuilder-python
3d410365461dc434df59bdfeaa2f16d28d9df868
libraries/botframework-connector/botframework/connector/token_api/operations/_bot_sign_in_operations.py
python
BotSignInOperations.get_sign_in_url
( self, state, code_challenge=None, emulator_url=None, final_redirect=None, custom_headers=None, raw=False, **operation_config )
return deserialized
:param state: :type state: str :param code_challenge: :type code_challenge: str :param emulator_url: :type emulator_url: str :param final_redirect: :type final_redirect: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: str or ClientRawResponse if raw=true :rtype: str or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
[]
def get_sign_in_url( self, state, code_challenge=None, emulator_url=None, final_redirect=None, custom_headers=None, raw=False, **operation_config ): """ :param state: :type state: str :param code_challenge: :type code_challenge: str :param emulator_url: :type emulator_url: str :param final_redirect: :type final_redirect: str :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: str or ClientRawResponse if raw=true :rtype: str or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>` """ # Construct URL url = self.get_sign_in_url.metadata["url"] # Construct parameters query_parameters = {} query_parameters["state"] = self._serialize.query("state", state, "str") if code_challenge is not None: query_parameters["code_challenge"] = self._serialize.query( "code_challenge", code_challenge, "str" ) if emulator_url is not None: query_parameters["emulatorUrl"] = self._serialize.query( "emulator_url", emulator_url, "str" ) if final_redirect is not None: query_parameters["finalRedirect"] = self._serialize.query( "final_redirect", final_redirect, "str" ) query_parameters["api-version"] = self._serialize.query( "self.api_version", self.api_version, "str" ) # Construct headers header_parameters = {} header_parameters["Accept"] = "application/json" if custom_headers: header_parameters.update(custom_headers) # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise HttpOperationError(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = response.content.decode("utf-8") if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
[ "def", "get_sign_in_url", "(", "self", ",", "state", ",", "code_challenge", "=", "None", ",", "emulator_url", "=", "None", ",", "final_redirect", "=", "None", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "*", "*", "operation_config", ...
https://github.com/microsoft/botbuilder-python/blob/3d410365461dc434df59bdfeaa2f16d28d9df868/libraries/botframework-connector/botframework/connector/token_api/operations/_bot_sign_in_operations.py#L38-L111
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/plat-linux2/IN.py
python
CMSG_FIRSTHDR
(mhdr)
return
[]
def CMSG_FIRSTHDR(mhdr): return
[ "def", "CMSG_FIRSTHDR", "(", "mhdr", ")", ":", "return" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/plat-linux2/IN.py#L433-L433
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/combinatorics/fp_groups.py
python
FpGroup.subgroup
(self, gens, C=None, homomorphism=False)
return g
Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> K, T = f.subgroup(H, homomorphism=True) >>> T(K.generators) [x*y, x**-1*y**2*x**-1]
Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group.
[ "Return", "the", "subgroup", "generated", "by", "gens", "using", "the", "Reidemeister", "-", "Schreier", "algorithm", "homomorphism", "--", "When", "set", "to", "True", "return", "a", "dictionary", "containing", "the", "images", "of", "the", "presentation", "gen...
def subgroup(self, gens, C=None, homomorphism=False): ''' Return the subgroup generated by `gens` using the Reidemeister-Schreier algorithm homomorphism -- When set to True, return a dictionary containing the images of the presentation generators in the original group. Examples ======== >>> from sympy.combinatorics.fp_groups import FpGroup >>> from sympy.combinatorics.free_groups import free_group >>> F, x, y = free_group("x, y") >>> f = FpGroup(F, [x**3, y**5, (x*y)**2]) >>> H = [x*y, x**-1*y**-1*x*y*x] >>> K, T = f.subgroup(H, homomorphism=True) >>> T(K.generators) [x*y, x**-1*y**2*x**-1] ''' if not all(isinstance(g, FreeGroupElement) for g in gens): raise ValueError("Generators must be `FreeGroupElement`s") if not all(g.group == self.free_group for g in gens): raise ValueError("Given generators are not members of the group") if homomorphism: g, rels, _gens = reidemeister_presentation(self, gens, C=C, homomorphism=True) else: g, rels = reidemeister_presentation(self, gens, C=C) if g: g = FpGroup(g[0].group, rels) else: g = FpGroup(free_group('')[0], []) if homomorphism: from sympy.combinatorics.homomorphisms import homomorphism return g, homomorphism(g, self, g.generators, _gens, check=False) return g
[ "def", "subgroup", "(", "self", ",", "gens", ",", "C", "=", "None", ",", "homomorphism", "=", "False", ")", ":", "if", "not", "all", "(", "isinstance", "(", "g", ",", "FreeGroupElement", ")", "for", "g", "in", "gens", ")", ":", "raise", "ValueError",...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/combinatorics/fp_groups.py#L120-L156
ShreyAmbesh/Traffic-Rule-Violation-Detection-System
ae0c327ce014ce6a427da920b5798a0d4bbf001e
metrics/coco_evaluation.py
python
_check_mask_type_and_value
(array_name, masks)
Checks whether mask dtype is uint8 anf the values are either 0 or 1.
Checks whether mask dtype is uint8 anf the values are either 0 or 1.
[ "Checks", "whether", "mask", "dtype", "is", "uint8", "anf", "the", "values", "are", "either", "0", "or", "1", "." ]
def _check_mask_type_and_value(array_name, masks): """Checks whether mask dtype is uint8 anf the values are either 0 or 1.""" if masks.dtype != np.uint8: raise ValueError('{} must be of type np.uint8. Found {}.'.format( array_name, masks.dtype)) if np.any(np.logical_and(masks != 0, masks != 1)): raise ValueError('{} elements can only be either 0 or 1.'.format( array_name))
[ "def", "_check_mask_type_and_value", "(", "array_name", ",", "masks", ")", ":", "if", "masks", ".", "dtype", "!=", "np", ".", "uint8", ":", "raise", "ValueError", "(", "'{} must be of type np.uint8. Found {}.'", ".", "format", "(", "array_name", ",", "masks", "....
https://github.com/ShreyAmbesh/Traffic-Rule-Violation-Detection-System/blob/ae0c327ce014ce6a427da920b5798a0d4bbf001e/metrics/coco_evaluation.py#L287-L294
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/_collections_abc.py
python
Generator.send
(self, value)
Send a value into the generator. Return next yielded value or raise StopIteration.
Send a value into the generator. Return next yielded value or raise StopIteration.
[ "Send", "a", "value", "into", "the", "generator", ".", "Return", "next", "yielded", "value", "or", "raise", "StopIteration", "." ]
def send(self, value): """Send a value into the generator. Return next yielded value or raise StopIteration. """ raise StopIteration
[ "def", "send", "(", "self", ",", "value", ")", ":", "raise", "StopIteration" ]
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/_collections_abc.py#L256-L260
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.py
python
PIDLockFile.acquire
(self, timeout=None)
Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired.
Acquire the lock.
[ "Acquire", "the", "lock", "." ]
def acquire(self, timeout=None): """ Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired. """ timeout = timeout if timeout is not None else self.timeout end_time = time.time() if timeout is not None and timeout > 0: end_time += timeout while True: try: write_pid_to_pidfile(self.path) except OSError as exc: if exc.errno == errno.EEXIST: # The lock creation failed. Maybe sleep a bit. if time.time() > end_time: if timeout is not None and timeout > 0: raise LockTimeout("Timeout waiting to acquire" " lock for %s" % self.path) else: raise AlreadyLocked("%s is already locked" % self.path) time.sleep(timeout is not None and timeout / 10 or 0.1) else: raise LockFailed("failed to create %s" % self.path) else: return
[ "def", "acquire", "(", "self", ",", "timeout", "=", "None", ")", ":", "timeout", "=", "timeout", "if", "timeout", "is", "not", "None", "else", "self", ".", "timeout", "end_time", "=", "time", ".", "time", "(", ")", "if", "timeout", "is", "not", "None...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/site-packages/pip/_vendor/lockfile/pidlockfile.py#L63-L93
bpython/bpython
189da3ecbaa30212b8ba73aeb321b6a6a324348b
bpython/curtsiesfrontend/repl.py
python
BaseRepl.send_session_to_external_editor
(self, filename=None)
Sends entire bpython session to external editor to be edited. Usually bound to F7.
Sends entire bpython session to external editor to be edited. Usually bound to F7.
[ "Sends", "entire", "bpython", "session", "to", "external", "editor", "to", "be", "edited", ".", "Usually", "bound", "to", "F7", "." ]
def send_session_to_external_editor(self, filename=None): """ Sends entire bpython session to external editor to be edited. Usually bound to F7. """ for_editor = EDIT_SESSION_HEADER for_editor += self.get_session_formatted_for_file() text = self.send_to_external_editor(for_editor) if text == for_editor: self.status_bar.message( _("Session not reevaluated because it was not edited") ) return lines = text.split("\n") if len(lines) and not lines[-1].strip(): lines.pop() # strip last line if empty if len(lines) and lines[-1].startswith("### "): current_line = lines[-1][4:] else: current_line = "" from_editor = [ line for line in lines if line[:6] != "# OUT:" and line[:3] != "###" ] if all(not line.strip() for line in from_editor): self.status_bar.message( _("Session not reevaluated because saved file was blank") ) return source = preprocess("\n".join(from_editor), self.interp.compile) lines = source.split("\n") self.history = lines self.reevaluate(new_code=True) self.current_line = current_line self.cursor_offset = len(self.current_line) self.status_bar.message(_("Session edited and reevaluated"))
[ "def", "send_session_to_external_editor", "(", "self", ",", "filename", "=", "None", ")", ":", "for_editor", "=", "EDIT_SESSION_HEADER", "for_editor", "+=", "self", ".", "get_session_formatted_for_file", "(", ")", "text", "=", "self", ".", "send_to_external_editor", ...
https://github.com/bpython/bpython/blob/189da3ecbaa30212b8ba73aeb321b6a6a324348b/bpython/curtsiesfrontend/repl.py#L1092-L1127
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/scrapy/crawler.py
python
_get_spider_loader
(settings)
return loader_cls.from_settings(settings.frozencopy())
Get SpiderLoader instance from settings
Get SpiderLoader instance from settings
[ "Get", "SpiderLoader", "instance", "from", "settings" ]
def _get_spider_loader(settings): """ Get SpiderLoader instance from settings """ cls_path = settings.get('SPIDER_LOADER_CLASS') loader_cls = load_object(cls_path) try: verifyClass(ISpiderLoader, loader_cls) except DoesNotImplement: warnings.warn( 'SPIDER_LOADER_CLASS (previously named SPIDER_MANAGER_CLASS) does ' 'not fully implement scrapy.interfaces.ISpiderLoader interface. ' 'Please add all missing methods to avoid unexpected runtime errors.', category=ScrapyDeprecationWarning, stacklevel=2 ) return loader_cls.from_settings(settings.frozencopy())
[ "def", "_get_spider_loader", "(", "settings", ")", ":", "cls_path", "=", "settings", ".", "get", "(", "'SPIDER_LOADER_CLASS'", ")", "loader_cls", "=", "load_object", "(", "cls_path", ")", "try", ":", "verifyClass", "(", "ISpiderLoader", ",", "loader_cls", ")", ...
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/scrapy/crawler.py#L334-L347
qutebrowser/qutebrowser
3a2aaaacbf97f4bf0c72463f3da94ed2822a5442
qutebrowser/utils/message.py
python
info
(message: str, *, replace: str = None)
Display an info message. Args: message: The message to show. replace: Replace existing messages which are still being shown.
Display an info message.
[ "Display", "an", "info", "message", "." ]
def info(message: str, *, replace: str = None) -> None: """Display an info message. Args: message: The message to show. replace: Replace existing messages which are still being shown. """ log.message.info(message) global_bridge.show(usertypes.MessageLevel.info, message, replace)
[ "def", "info", "(", "message", ":", "str", ",", "*", ",", "replace", ":", "str", "=", "None", ")", "->", "None", ":", "log", ".", "message", ".", "info", "(", "message", ")", "global_bridge", ".", "show", "(", "usertypes", ".", "MessageLevel", ".", ...
https://github.com/qutebrowser/qutebrowser/blob/3a2aaaacbf97f4bf0c72463f3da94ed2822a5442/qutebrowser/utils/message.py#L76-L84
VirtueSecurity/aws-extender
d123b7e1a845847709ba3a481f11996bddc68a1c
BappModules/dateutil/tz/_common.py
python
_validate_fromutc_inputs
(f)
return fromutc
The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``.
The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``.
[ "The", "CPython", "version", "of", "fromutc", "checks", "that", "the", "input", "is", "a", "datetime", "object", "and", "that", "self", "is", "attached", "as", "its", "tzinfo", "." ]
def _validate_fromutc_inputs(f): """ The CPython version of ``fromutc`` checks that the input is a ``datetime`` object and that ``self`` is attached as its ``tzinfo``. """ @wraps(f) def fromutc(self, dt): if not isinstance(dt, datetime): raise TypeError("fromutc() requires a datetime argument") if dt.tzinfo is not self: raise ValueError("dt.tzinfo is not self") return f(self, dt) return fromutc
[ "def", "_validate_fromutc_inputs", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "fromutc", "(", "self", ",", "dt", ")", ":", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "\"fromutc() requires a da...
https://github.com/VirtueSecurity/aws-extender/blob/d123b7e1a845847709ba3a481f11996bddc68a1c/BappModules/dateutil/tz/_common.py#L128-L142
rwightman/pytorch-image-models
ccfeb06936549f19c453b7f1f27e8e632cfbe1c2
timm/models/mobilenetv3.py
python
_gen_mobilenet_v3_rw
(variant, channel_multiplier=1.0, pretrained=False, **kwargs)
return model
Creates a MobileNet-V3 model. Ref impl: ? Paper: https://arxiv.org/abs/1905.02244 Args: channel_multiplier: multiplier to number of channels per layer.
Creates a MobileNet-V3 model.
[ "Creates", "a", "MobileNet", "-", "V3", "model", "." ]
def _gen_mobilenet_v3_rw(variant, channel_multiplier=1.0, pretrained=False, **kwargs): """Creates a MobileNet-V3 model. Ref impl: ? Paper: https://arxiv.org/abs/1905.02244 Args: channel_multiplier: multiplier to number of channels per layer. """ arch_def = [ # stage 0, 112x112 in ['ds_r1_k3_s1_e1_c16_nre_noskip'], # relu # stage 1, 112x112 in ['ir_r1_k3_s2_e4_c24_nre', 'ir_r1_k3_s1_e3_c24_nre'], # relu # stage 2, 56x56 in ['ir_r3_k5_s2_e3_c40_se0.25_nre'], # relu # stage 3, 28x28 in ['ir_r1_k3_s2_e6_c80', 'ir_r1_k3_s1_e2.5_c80', 'ir_r2_k3_s1_e2.3_c80'], # hard-swish # stage 4, 14x14in ['ir_r2_k3_s1_e6_c112_se0.25'], # hard-swish # stage 5, 14x14in ['ir_r3_k5_s2_e6_c160_se0.25'], # hard-swish # stage 6, 7x7 in ['cn_r1_k1_s1_c960'], # hard-swish ] model_kwargs = dict( block_args=decode_arch_def(arch_def), head_bias=False, round_chs_fn=partial(round_channels, multiplier=channel_multiplier), norm_layer=partial(nn.BatchNorm2d, **resolve_bn_args(kwargs)), act_layer=resolve_act_layer(kwargs, 'hard_swish'), se_layer=partial(SqueezeExcite, gate_layer='hard_sigmoid'), **kwargs, ) model = _create_mnv3(variant, pretrained, **model_kwargs) return model
[ "def", "_gen_mobilenet_v3_rw", "(", "variant", ",", "channel_multiplier", "=", "1.0", ",", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "arch_def", "=", "[", "# stage 0, 112x112 in", "[", "'ds_r1_k3_s1_e1_c16_nre_noskip'", "]", ",", "# relu", "...
https://github.com/rwightman/pytorch-image-models/blob/ccfeb06936549f19c453b7f1f27e8e632cfbe1c2/timm/models/mobilenetv3.py#L261-L296
Alexey-T/CudaText
6a8b9a974c5d5029c6c273bde83198c83b3a5fb9
app/cudatext.app/Contents/Resources/py/sys/idna/intranges.py
python
intranges_contain
(int_, ranges)
return False
Determine if `int_` falls into one of the ranges in `ranges`.
Determine if `int_` falls into one of the ranges in `ranges`.
[ "Determine", "if", "int_", "falls", "into", "one", "of", "the", "ranges", "in", "ranges", "." ]
def intranges_contain(int_, ranges): """Determine if `int_` falls into one of the ranges in `ranges`.""" tuple_ = _encode_range(int_, 0) pos = bisect.bisect_left(ranges, tuple_) # we could be immediately ahead of a tuple (start, end) # with start < int_ <= end if pos > 0: left, right = _decode_range(ranges[pos-1]) if left <= int_ < right: return True # or we could be immediately behind a tuple (int_, end) if pos < len(ranges): left, _ = _decode_range(ranges[pos]) if left == int_: return True return False
[ "def", "intranges_contain", "(", "int_", ",", "ranges", ")", ":", "tuple_", "=", "_encode_range", "(", "int_", ",", "0", ")", "pos", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "tuple_", ")", "# we could be immediately ahead of a tuple (start, end)", ...
https://github.com/Alexey-T/CudaText/blob/6a8b9a974c5d5029c6c273bde83198c83b3a5fb9/app/cudatext.app/Contents/Resources/py/sys/idna/intranges.py#L38-L53
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/SilverCity/Python.py
python
EmbeddedHyperTextHTMLGenerator.handle_h_tag
(self, text, **ignored)
[]
def handle_h_tag(self, text, **ignored): self._file.write('<span class="python_h_tag">') self._file.write(self.markup(text)) self._file.write('</span>')
[ "def", "handle_h_tag", "(", "self", ",", "text", ",", "*", "*", "ignored", ")", ":", "self", ".", "_file", ".", "write", "(", "'<span class=\"python_h_tag\">'", ")", "self", ".", "_file", ".", "write", "(", "self", ".", "markup", "(", "text", ")", ")",...
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/SilverCity/Python.py#L69-L72
SiyuanQi/gpnn
b5a37f83c651a79f35766f5d60fd1d98959e7fe4
src/python/datasets/HICO/roi_pooling.py
python
AdaptiveMaxPool2d.forward
(self, input)
return output
[]
def forward(self, input): output = input.new() indices = input.new().long() self.save_for_backward(input) self.indices = indices self._backend = type2backend[type(input)] self._backend.SpatialAdaptiveMaxPooling_updateOutput( self._backend.library_state, input, output, indices, self.out_w, self.out_h) return output
[ "def", "forward", "(", "self", ",", "input", ")", ":", "output", "=", "input", ".", "new", "(", ")", "indices", "=", "input", ".", "new", "(", ")", ".", "long", "(", ")", "self", ".", "save_for_backward", "(", "input", ")", "self", ".", "indices", ...
https://github.com/SiyuanQi/gpnn/blob/b5a37f83c651a79f35766f5d60fd1d98959e7fe4/src/python/datasets/HICO/roi_pooling.py#L16-L25
hzlzh/AlfredWorkflow.com
7055f14f6922c80ea5943839eb0caff11ae57255
Sources/Workflows/Alfred-Time-Keeper/PyAl/Request/requests/packages/urllib3/packages/ordered_dict.py
python
OrderedDict.popitem
(self, last=True)
return key, value
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.
[ "od", ".", "popitem", "()", "-", ">", "(", "k", "v", ")", "return", "and", "remove", "a", "(", "key", "value", ")", "pair", ".", "Pairs", "are", "returned", "in", "LIFO", "order", "if", "last", "is", "true", "or", "FIFO", "order", "if", "false", ...
def popitem(self, last=True): '''od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false. ''' if not self: raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next[0] = root key = link[2] del self.__map[key] value = dict.pop(self, key) return key, value
[ "def", "popitem", "(", "self", ",", "last", "=", "True", ")", ":", "if", "not", "self", ":", "raise", "KeyError", "(", "'dictionary is empty'", ")", "root", "=", "self", ".", "__root", "if", "last", ":", "link", "=", "root", "[", "0", "]", "link_prev...
https://github.com/hzlzh/AlfredWorkflow.com/blob/7055f14f6922c80ea5943839eb0caff11ae57255/Sources/Workflows/Alfred-Time-Keeper/PyAl/Request/requests/packages/urllib3/packages/ordered_dict.py#L92-L113
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/ebooks/lrf/meta.py
python
xml_attr_field.__get__
(self, obj, typ=None)
return ''
Return the data in this field or '' if the field is empty
Return the data in this field or '' if the field is empty
[ "Return", "the", "data", "in", "this", "field", "or", "if", "the", "field", "is", "empty" ]
def __get__(self, obj, typ=None): """ Return the data in this field or '' if the field is empty """ document = obj.info elems = document.getElementsByTagName(self.tag_name) if len(elems): elem = None for candidate in elems: if candidate.parentNode.nodeName == self.parent: elem = candidate if elem and elem.hasAttribute(self.attr): return elem.getAttribute(self.attr) return ''
[ "def", "__get__", "(", "self", ",", "obj", ",", "typ", "=", "None", ")", ":", "document", "=", "obj", ".", "info", "elems", "=", "document", ".", "getElementsByTagName", "(", "self", ".", "tag_name", ")", "if", "len", "(", "elems", ")", ":", "elem", ...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/ebooks/lrf/meta.py#L120-L131
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
kupfer/core/relevance.py
python
score_single
(s, query)
return score
s: text body to score query: A single character This is a single character approximation to `score`. >>> round(score_single('terminal', 't'), 6) 0.973125 >>> round(score_single('terminal', 'e'), 6) 0.903125 >>> round(score_single('terminal', 'a'), 6) 0.903125 >>> round(score_single('t', 't'), 6) 0.995
s: text body to score query: A single character
[ "s", ":", "text", "body", "to", "score", "query", ":", "A", "single", "character" ]
def score_single(s, query): """ s: text body to score query: A single character This is a single character approximation to `score`. >>> round(score_single('terminal', 't'), 6) 0.973125 >>> round(score_single('terminal', 'e'), 6) 0.903125 >>> round(score_single('terminal', 'a'), 6) 0.903125 >>> round(score_single('t', 't'), 6) 0.995 """ ls = s.lower() # Find the shortest possible substring that matches the query # and get the ration of their lengths for a base score first = ls.find(query) if first == -1: return .0 score = 0.9 + .025 / len(s) if first == 0: score += 0.07 return score
[ "def", "score_single", "(", "s", ",", "query", ")", ":", "ls", "=", "s", ".", "lower", "(", ")", "# Find the shortest possible substring that matches the query", "# and get the ration of their lengths for a base score", "first", "=", "ls", ".", "find", "(", "query", "...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/kupfer/core/relevance.py#L92-L120
yianjiajia/django_web_ansible
1103343082a65abf9d37310f5048514d74930753
devops/apps/ansible/elfinder/widgets.py
python
ElfinderWidget._media
(self)
return forms.Media(css={'screen': screen_css}, js=js)
Set the widget's javascript and css
Set the widget's javascript and css
[ "Set", "the", "widget", "s", "javascript", "and", "css" ]
def _media(self): """ Set the widget's javascript and css """ js = [ls.ELFINDER_JS_URLS[x] for x in sorted(ls.ELFINDER_JS_URLS)] + [ls.ELFINDER_WIDGET_JS_URL] screen_css = [ls.ELFINDER_CSS_URLS[x] for x in sorted(ls.ELFINDER_CSS_URLS)] + [ls.ELFINDER_WIDGET_CSS_URL] # add language file to javascript media if not self.current_locale.startswith('en') and self.current_locale in ls.ELFINDER_LANGUAGES: js.append('%selfinder.%s.js' % (ls.ELFINDER_LANGUAGES_ROOT_URL, self.current_locale)) return forms.Media(css={'screen': screen_css}, js=js)
[ "def", "_media", "(", "self", ")", ":", "js", "=", "[", "ls", ".", "ELFINDER_JS_URLS", "[", "x", "]", "for", "x", "in", "sorted", "(", "ls", ".", "ELFINDER_JS_URLS", ")", "]", "+", "[", "ls", ".", "ELFINDER_WIDGET_JS_URL", "]", "screen_css", "=", "["...
https://github.com/yianjiajia/django_web_ansible/blob/1103343082a65abf9d37310f5048514d74930753/devops/apps/ansible/elfinder/widgets.py#L32-L43
youngyangyang04/NoSQLAttack
a5b0329c21543e955d2d9e1890fea58dbcdf8840
globalVar.py
python
get_vulnAddrs
()
return GlobalVar.vulnAddrs
[]
def get_vulnAddrs(): return GlobalVar.vulnAddrs
[ "def", "get_vulnAddrs", "(", ")", ":", "return", "GlobalVar", ".", "vulnAddrs" ]
https://github.com/youngyangyang04/NoSQLAttack/blob/a5b0329c21543e955d2d9e1890fea58dbcdf8840/globalVar.py#L20-L21
Theano/Theano
8fd9203edfeecebced9344b0c70193be292a9ade
theano/tensor/basic.py
python
stacklists
(arg)
Recursively stack lists of tensors to maintain similar structure. This function can create a tensor from a shaped list of scalars: Examples -------- >>> from theano.tensor import stacklists, scalars, matrices >>> from theano import function >>> a, b, c, d = scalars('abcd') >>> X = stacklists([[a, b], [c, d]]) >>> f = function([a, b, c, d], X) >>> f(1, 2, 3, 4) array([[ 1., 2.], [ 3., 4.]], dtype=float32) We can also stack arbitrarily shaped tensors. Here we stack matrices into a 2 by 2 grid: >>> from numpy import ones >>> a, b, c, d = matrices('abcd') >>> X = stacklists([[a, b], [c, d]]) >>> f = function([a, b, c, d], X) >>> x = ones((4, 4), 'float32') >>> f(x, x, x, x).shape (2, 2, 4, 4)
Recursively stack lists of tensors to maintain similar structure.
[ "Recursively", "stack", "lists", "of", "tensors", "to", "maintain", "similar", "structure", "." ]
def stacklists(arg): """ Recursively stack lists of tensors to maintain similar structure. This function can create a tensor from a shaped list of scalars: Examples -------- >>> from theano.tensor import stacklists, scalars, matrices >>> from theano import function >>> a, b, c, d = scalars('abcd') >>> X = stacklists([[a, b], [c, d]]) >>> f = function([a, b, c, d], X) >>> f(1, 2, 3, 4) array([[ 1., 2.], [ 3., 4.]], dtype=float32) We can also stack arbitrarily shaped tensors. Here we stack matrices into a 2 by 2 grid: >>> from numpy import ones >>> a, b, c, d = matrices('abcd') >>> X = stacklists([[a, b], [c, d]]) >>> f = function([a, b, c, d], X) >>> x = ones((4, 4), 'float32') >>> f(x, x, x, x).shape (2, 2, 4, 4) """ if isinstance(arg, (tuple, list)): return stack(list(map(stacklists, arg))) else: return arg
[ "def", "stacklists", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "stack", "(", "list", "(", "map", "(", "stacklists", ",", "arg", ")", ")", ")", "else", ":", "return", "arg" ]
https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/tensor/basic.py#L6687-L6719
theislab/anndata
664e32b0aa6625fe593370d37174384c05abfd4e
anndata/_core/anndata.py
python
AnnData.__eq__
(self, other)
Equality testing
Equality testing
[ "Equality", "testing" ]
def __eq__(self, other): """Equality testing""" raise NotImplementedError( "Equality comparisons are not supported for AnnData objects, " "instead compare the desired attributes." )
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "raise", "NotImplementedError", "(", "\"Equality comparisons are not supported for AnnData objects, \"", "\"instead compare the desired attributes.\"", ")" ]
https://github.com/theislab/anndata/blob/664e32b0aa6625fe593370d37174384c05abfd4e/anndata/_core/anndata.py#L581-L586
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/polys/polyclasses.py
python
DMP.primitive
(f)
return cont, f.per(F)
Returns content and a primitive form of ``f``.
Returns content and a primitive form of ``f``.
[ "Returns", "content", "and", "a", "primitive", "form", "of", "f", "." ]
def primitive(f): """Returns content and a primitive form of ``f``. """ cont, F = dmp_ground_primitive(f.rep, f.lev, f.dom) return cont, f.per(F)
[ "def", "primitive", "(", "f", ")", ":", "cont", ",", "F", "=", "dmp_ground_primitive", "(", "f", ".", "rep", ",", "f", ".", "lev", ",", "f", ".", "dom", ")", "return", "cont", ",", "f", ".", "per", "(", "F", ")" ]
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/polys/polyclasses.py#L716-L719
openstack/python-novaclient
63d368168c87bc0b9a9b7928b42553c609e46089
novaclient/v2/migrations.py
python
MigrationManager.list
(self, host=None, status=None, instance_uuid=None, migration_type=None, source_compute=None)
return self._list_base(host=host, status=status, instance_uuid=instance_uuid, migration_type=migration_type, source_compute=source_compute)
Get a list of migrations. :param host: filter migrations by host name (optional). :param status: filter migrations by status (optional). :param instance_uuid: filter migrations by instance uuid (optional). :param migration_type: Filter migrations by type. Valid values are: evacuation, live-migration, migration (cold), resize :param source_compute: Filter migrations by source compute host name.
Get a list of migrations. :param host: filter migrations by host name (optional). :param status: filter migrations by status (optional). :param instance_uuid: filter migrations by instance uuid (optional). :param migration_type: Filter migrations by type. Valid values are: evacuation, live-migration, migration (cold), resize :param source_compute: Filter migrations by source compute host name.
[ "Get", "a", "list", "of", "migrations", ".", ":", "param", "host", ":", "filter", "migrations", "by", "host", "name", "(", "optional", ")", ".", ":", "param", "status", ":", "filter", "migrations", "by", "status", "(", "optional", ")", ".", ":", "param...
def list(self, host=None, status=None, instance_uuid=None, migration_type=None, source_compute=None): """ Get a list of migrations. :param host: filter migrations by host name (optional). :param status: filter migrations by status (optional). :param instance_uuid: filter migrations by instance uuid (optional). :param migration_type: Filter migrations by type. Valid values are: evacuation, live-migration, migration (cold), resize :param source_compute: Filter migrations by source compute host name. """ return self._list_base(host=host, status=status, instance_uuid=instance_uuid, migration_type=migration_type, source_compute=source_compute)
[ "def", "list", "(", "self", ",", "host", "=", "None", ",", "status", "=", "None", ",", "instance_uuid", "=", "None", ",", "migration_type", "=", "None", ",", "source_compute", "=", "None", ")", ":", "return", "self", ".", "_list_base", "(", "host", "="...
https://github.com/openstack/python-novaclient/blob/63d368168c87bc0b9a9b7928b42553c609e46089/novaclient/v2/migrations.py#L60-L74
haoctopus/molohub
7699ef2b8b92bfddd2726b966b927648aa44395f
molohub/molo_hub_client.py
python
MoloHubClient.handle_connect
(self)
When connected, this method will be call.
When connected, this method will be call.
[ "When", "connected", "this", "method", "will", "be", "call", "." ]
def handle_connect(self): """When connected, this method will be call.""" LOGGER.debug("server connected") self.append_connect = False domain = MOLO_CONFIGS.get_config_object().get('domain', '') self.send_dict_pack( MoloSocketHelper.molo_auth(CLIENT_VERSION, MOLO_CLIENT_APP.hass_context, __short_version__, domain),)
[ "def", "handle_connect", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "\"server connected\"", ")", "self", ".", "append_connect", "=", "False", "domain", "=", "MOLO_CONFIGS", ".", "get_config_object", "(", ")", ".", "get", "(", "'domain'", ",", "''", ...
https://github.com/haoctopus/molohub/blob/7699ef2b8b92bfddd2726b966b927648aa44395f/molohub/molo_hub_client.py#L49-L57
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.3/django/db/models/query.py
python
QuerySet.create
(self, **kwargs)
return obj
Creates a new object with the given kwargs, saving it to the database and returning the created object.
Creates a new object with the given kwargs, saving it to the database and returning the created object.
[ "Creates", "a", "new", "object", "with", "the", "given", "kwargs", "saving", "it", "to", "the", "database", "and", "returning", "the", "created", "object", "." ]
def create(self, **kwargs): """ Creates a new object with the given kwargs, saving it to the database and returning the created object. """ obj = self.model(**kwargs) self._for_write = True obj.save(force_insert=True, using=self.db) return obj
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "self", ".", "model", "(", "*", "*", "kwargs", ")", "self", ".", "_for_write", "=", "True", "obj", ".", "save", "(", "force_insert", "=", "True", ",", "using", "=", "sel...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.3/django/db/models/query.py#L353-L361
rucio/rucio
6d0d358e04f5431f0b9a98ae40f31af0ddff4833
lib/rucio/db/sqla/migrate_repo/versions/4a7182d9578b_added_bytes_length_accessed_at_columns.py
python
downgrade
()
Downgrade the database to the previous revision
Downgrade the database to the previous revision
[ "Downgrade", "the", "database", "to", "the", "previous", "revision" ]
def downgrade(): ''' Downgrade the database to the previous revision ''' if context.get_context().dialect.name in ['oracle', 'mysql', 'postgresql']: schema = context.get_context().version_table_schema if context.get_context().version_table_schema else '' drop_column('dataset_locks', 'length', schema=schema) drop_column('dataset_locks', 'bytes', schema=schema) drop_column('dataset_locks', 'accessed_at', schema=schema) drop_column('dids', 'accessed_at', schema=schema)
[ "def", "downgrade", "(", ")", ":", "if", "context", ".", "get_context", "(", ")", ".", "dialect", ".", "name", "in", "[", "'oracle'", ",", "'mysql'", ",", "'postgresql'", "]", ":", "schema", "=", "context", ".", "get_context", "(", ")", ".", "version_t...
https://github.com/rucio/rucio/blob/6d0d358e04f5431f0b9a98ae40f31af0ddff4833/lib/rucio/db/sqla/migrate_repo/versions/4a7182d9578b_added_bytes_length_accessed_at_columns.py#L45-L55
JBakamovic/cxxd
142c19649b036bd6f6bdcd4684de735ea11a6c94
parser/ast_node_identifier.py
python
ASTNodeId.getUsingDeclarationId
()
return "using_declaration"
[]
def getUsingDeclarationId(): return "using_declaration"
[ "def", "getUsingDeclarationId", "(", ")", ":", "return", "\"using_declaration\"" ]
https://github.com/JBakamovic/cxxd/blob/142c19649b036bd6f6bdcd4684de735ea11a6c94/parser/ast_node_identifier.py#L79-L80
thiagopena/djangoSIGE
e32186b27bfd8acf21b0fa400e699cb5c73e5433
djangosige/apps/estoque/models/movimento.py
python
SaidaEstoque.get_tipo
(self)
return 'Saída'
[]
def get_tipo(self): return 'Saída'
[ "def", "get_tipo", "(", "self", ")", ":", "return", "'Saída'" ]
https://github.com/thiagopena/djangoSIGE/blob/e32186b27bfd8acf21b0fa400e699cb5c73e5433/djangosige/apps/estoque/models/movimento.py#L132-L133
debian-calibre/calibre
020fc81d3936a64b2ac51459ecb796666ab6a051
src/calibre/gui2/dnd.py
python
dnd_get_image
(md, image_exts=None)
return None, None
Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found
Get the image in the QMimeData object md.
[ "Get", "the", "image", "in", "the", "QMimeData", "object", "md", "." ]
def dnd_get_image(md, image_exts=None): ''' Get the image in the QMimeData object md. :return: None, None if no image is found QPixmap, None if an image is found, the pixmap is guaranteed not null url, filename if a URL that points to an image is found ''' if image_exts is None: image_exts = image_extensions() pmap, data = dnd_get_local_image_and_pixmap(md, image_exts) if pmap is not None: return pmap, None # Look for a remote image urls = urls_from_md(md) # First, see if this is from Firefox rurl, fname = get_firefox_rurl(md, image_exts) if rurl and fname: return rurl, fname # Look through all remaining URLs for remote_url, filename in remote_urls_from_qurl(urls, image_exts): return remote_url, filename return None, None
[ "def", "dnd_get_image", "(", "md", ",", "image_exts", "=", "None", ")", ":", "if", "image_exts", "is", "None", ":", "image_exts", "=", "image_extensions", "(", ")", "pmap", ",", "data", "=", "dnd_get_local_image_and_pixmap", "(", "md", ",", "image_exts", ")"...
https://github.com/debian-calibre/calibre/blob/020fc81d3936a64b2ac51459ecb796666ab6a051/src/calibre/gui2/dnd.py#L260-L284
DxCx/plugin.video.9anime
34358c2f701e5ddf19d3276926374a16f63f7b6a
resources/lib/ui/js2py/es6/babel.py
python
PyJs_anonymous_3672_
(require, module, exports, this, arguments, var=var)
[]
def PyJs_anonymous_3672_(require, module, exports, this, arguments, var=var): var = Scope({u'this':this, u'require':require, u'exports':exports, u'module':module, u'arguments':arguments}, var) var.registers([u'exports', u'hashGet', u'nativeCreate', u'HASH_UNDEFINED', u'require', u'module', u'hasOwnProperty', u'objectProto']) @Js def PyJsHoisted_hashGet_(key, this, arguments, var=var): var = Scope({u'this':this, u'arguments':arguments, u'key':key}, var) var.registers([u'data', u'result', u'key']) var.put(u'data', var.get(u"this").get(u'__data__')) if var.get(u'nativeCreate'): var.put(u'result', var.get(u'data').get(var.get(u'key'))) return (var.get(u'undefined') if PyJsStrictEq(var.get(u'result'),var.get(u'HASH_UNDEFINED')) else var.get(u'result')) return (var.get(u'data').get(var.get(u'key')) if var.get(u'hasOwnProperty').callprop(u'call', var.get(u'data'), var.get(u'key')) else var.get(u'undefined')) PyJsHoisted_hashGet_.func_name = u'hashGet' var.put(u'hashGet', PyJsHoisted_hashGet_) var.put(u'nativeCreate', var.get(u'require')(Js(u'./_nativeCreate'))) var.put(u'HASH_UNDEFINED', Js(u'__lodash_hash_undefined__')) var.put(u'objectProto', var.get(u'Object').get(u'prototype')) var.put(u'hasOwnProperty', var.get(u'objectProto').get(u'hasOwnProperty')) pass var.get(u'module').put(u'exports', var.get(u'hashGet'))
[ "def", "PyJs_anonymous_3672_", "(", "require", ",", "module", ",", "exports", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'this'", ":", "this", ",", "u'require'", ":", "require", ",", "u'exports'", ...
https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/es6/babel.py#L41546-L41565
spack/spack
675210bd8bd1c5d32ad1cc83d898fb43b569ed74
lib/spack/spack/util/parallel.py
python
num_processes
(max_processes=None)
return min(cpus_available(), max_processes)
Return the number of processes in a pool. Currently the function return the minimum between the maximum number of processes and the cpus available. When a maximum number of processes is not specified return the cpus available. Args: max_processes (int or None): maximum number of processes allowed
Return the number of processes in a pool.
[ "Return", "the", "number", "of", "processes", "in", "a", "pool", "." ]
def num_processes(max_processes=None): """Return the number of processes in a pool. Currently the function return the minimum between the maximum number of processes and the cpus available. When a maximum number of processes is not specified return the cpus available. Args: max_processes (int or None): maximum number of processes allowed """ max_processes or cpus_available() return min(cpus_available(), max_processes)
[ "def", "num_processes", "(", "max_processes", "=", "None", ")", ":", "max_processes", "or", "cpus_available", "(", ")", "return", "min", "(", "cpus_available", "(", ")", ",", "max_processes", ")" ]
https://github.com/spack/spack/blob/675210bd8bd1c5d32ad1cc83d898fb43b569ed74/lib/spack/spack/util/parallel.py#L101-L113
quora/asynq
67c611c5afb00794a95a3126ef9fdbf8604174aa
asynq/debug.py
python
extract_tb
(tb, limit=None)
return tb_list
This implementation is stolen from traceback module but respects __traceback_hide__.
This implementation is stolen from traceback module but respects __traceback_hide__.
[ "This", "implementation", "is", "stolen", "from", "traceback", "module", "but", "respects", "__traceback_hide__", "." ]
def extract_tb(tb, limit=None): """This implementation is stolen from traceback module but respects __traceback_hide__.""" if limit is None: if hasattr(sys, "tracebacklimit"): limit = sys.tracebacklimit tb_list = [] n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame if not _should_skip_frame(f): lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) if line: line = line.strip() else: line = None tb_list.append((filename, lineno, name, line)) tb = tb.tb_next n = n + 1 return tb_list
[ "def", "extract_tb", "(", "tb", ",", "limit", "=", "None", ")", ":", "if", "limit", "is", "None", ":", "if", "hasattr", "(", "sys", ",", "\"tracebacklimit\"", ")", ":", "limit", "=", "sys", ".", "tracebacklimit", "tb_list", "=", "[", "]", "n", "=", ...
https://github.com/quora/asynq/blob/67c611c5afb00794a95a3126ef9fdbf8604174aa/asynq/debug.py#L165-L188
pdoc3/pdoc
4aa70de2221a34a3003a7e5f52a9b91965f0e359
pdoc/html_helpers.py
python
minify_css
(css: str, _whitespace=partial(re.compile(r'\s*([,{:;}])\s*').sub, r'\1'), _comments=partial(re.compile(r'/\*.*?\*/', flags=re.DOTALL).sub, ''), _trailing_semicolon=partial(re.compile(r';\s*}').sub, '}'))
return _trailing_semicolon(_whitespace(_comments(css))).strip()
Minify CSS by removing extraneous whitespace, comments, and trailing semicolons.
Minify CSS by removing extraneous whitespace, comments, and trailing semicolons.
[ "Minify", "CSS", "by", "removing", "extraneous", "whitespace", "comments", "and", "trailing", "semicolons", "." ]
def minify_css(css: str, _whitespace=partial(re.compile(r'\s*([,{:;}])\s*').sub, r'\1'), _comments=partial(re.compile(r'/\*.*?\*/', flags=re.DOTALL).sub, ''), _trailing_semicolon=partial(re.compile(r';\s*}').sub, '}')): """ Minify CSS by removing extraneous whitespace, comments, and trailing semicolons. """ return _trailing_semicolon(_whitespace(_comments(css))).strip()
[ "def", "minify_css", "(", "css", ":", "str", ",", "_whitespace", "=", "partial", "(", "re", ".", "compile", "(", "r'\\s*([,{:;}])\\s*'", ")", ".", "sub", ",", "r'\\1'", ")", ",", "_comments", "=", "partial", "(", "re", ".", "compile", "(", "r'/\\*.*?\\*/...
https://github.com/pdoc3/pdoc/blob/4aa70de2221a34a3003a7e5f52a9b91965f0e359/pdoc/html_helpers.py#L24-L31
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/motech/dhis2/management/commands/populate_sqldatasetmap.py
python
Command.update_or_create_sql_object
(self, doc)
return (model, created)
[]
def update_or_create_sql_object(self, doc): model, created = self.sql_class().objects.update_or_create( domain=doc['domain'], couch_id=doc['_id'], defaults={ 'connection_settings': get_connection_settings( doc['domain'], doc.get('connection_settings_id'), ), 'ucr_id': doc['ucr_id'], 'description': doc['description'], 'frequency': doc['frequency'], 'day_to_send': doc['day_to_send'], 'data_set_id': doc.get('data_set_id'), 'org_unit_id': doc.get('org_unit_id'), 'org_unit_column': doc.get('org_unit_column'), 'period': doc.get('period'), 'period_column': doc.get('period_column'), 'attribute_option_combo_id': doc.get('attribute_option_combo_id'), 'complete_date': as_date_or_none(doc['complete_date']) } ) if created: for datavalue_map in doc['datavalue_maps']: model.datavalue_maps.create( column=datavalue_map['column'], data_element_id=datavalue_map['data_element_id'], category_option_combo_id=datavalue_map['category_option_combo_id'], comment=datavalue_map.get('comment'), ) return (model, created)
[ "def", "update_or_create_sql_object", "(", "self", ",", "doc", ")", ":", "model", ",", "created", "=", "self", ".", "sql_class", "(", ")", ".", "objects", ".", "update_or_create", "(", "domain", "=", "doc", "[", "'domain'", "]", ",", "couch_id", "=", "do...
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/motech/dhis2/management/commands/populate_sqldatasetmap.py#L19-L48
fake-name/ReadableWebProxy
ed5c7abe38706acc2684a1e6cd80242a03c5f010
WebMirror/management/rss_parser_funcs/feed_parse_extractSchweitzertranslationsBlogspotCom.py
python
extractSchweitzertranslationsBlogspotCom
(item)
return False
Parser for 'schweitzertranslations.blogspot.com'
Parser for 'schweitzertranslations.blogspot.com'
[ "Parser", "for", "schweitzertranslations", ".", "blogspot", ".", "com" ]
def extractSchweitzertranslationsBlogspotCom(item): ''' Parser for 'schweitzertranslations.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
[ "def", "extractSchweitzertranslationsBlogspotCom", "(", "item", ")", ":", "vol", ",", "chp", ",", "frag", ",", "postfix", "=", "extractVolChapterFragmentPostfix", "(", "item", "[", "'title'", "]", ")", "if", "not", "(", "chp", "or", "vol", ")", "or", "\"prev...
https://github.com/fake-name/ReadableWebProxy/blob/ed5c7abe38706acc2684a1e6cd80242a03c5f010/WebMirror/management/rss_parser_funcs/feed_parse_extractSchweitzertranslationsBlogspotCom.py#L2-L21
princewen/leetcode_python
79e6e760e4d81824c96903e6c996630c24d01932
sort_by_leetcode/linked_list/easy/237. Delete Node in a Linked List.py
python
Solution.deleteNode
(self, node)
:type node: ListNode :rtype: void Do not return anything, modify node in-place instead.
:type node: ListNode :rtype: void Do not return anything, modify node in-place instead.
[ ":", "type", "node", ":", "ListNode", ":", "rtype", ":", "void", "Do", "not", "return", "anything", "modify", "node", "in", "-", "place", "instead", "." ]
def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next
[ "def", "deleteNode", "(", "self", ",", "node", ")", ":", "node", ".", "val", "=", "node", ".", "next", ".", "val", "node", ".", "next", "=", "node", ".", "next", ".", "next" ]
https://github.com/princewen/leetcode_python/blob/79e6e760e4d81824c96903e6c996630c24d01932/sort_by_leetcode/linked_list/easy/237. Delete Node in a Linked List.py#L19-L25
rdevooght/sequence-based-recommendations
0dfefeda9d7d5395b9b9bd2a4aa6a4fabfe3ca96
helpers/evaluation.py
python
Evaluator.get_correct_predictions
(self)
return correct_predictions
Return a concatenation of the correct predictions of each instances
Return a concatenation of the correct predictions of each instances
[ "Return", "a", "concatenation", "of", "the", "correct", "predictions", "of", "each", "instances" ]
def get_correct_predictions(self): '''Return a concatenation of the correct predictions of each instances ''' correct_predictions = [] for goal, prediction in self.instances: correct_predictions.extend(list(set(goal) & set(prediction[:min(len(prediction), self.k)]))) return correct_predictions
[ "def", "get_correct_predictions", "(", "self", ")", ":", "correct_predictions", "=", "[", "]", "for", "goal", ",", "prediction", "in", "self", ".", "instances", ":", "correct_predictions", ".", "extend", "(", "list", "(", "set", "(", "goal", ")", "&", "set...
https://github.com/rdevooght/sequence-based-recommendations/blob/0dfefeda9d7d5395b9b9bd2a4aa6a4fabfe3ca96/helpers/evaluation.py#L179-L185
friends-of-freeswitch/switchio
dee6e9addcf881b2b411ec1dbb397b0acfbb78cf
switchio/api.py
python
Client.set_orig_cmd
(self, *args, **kwargs)
Build and cache an originate cmd string for later use as the default input for calls to `originate`
Build and cache an originate cmd string for later use as the default input for calls to `originate`
[ "Build", "and", "cache", "an", "originate", "cmd", "string", "for", "later", "use", "as", "the", "default", "input", "for", "calls", "to", "originate" ]
def set_orig_cmd(self, *args, **kwargs): '''Build and cache an originate cmd string for later use as the default input for calls to `originate` ''' # by default this inserts a couple placeholders which can be replaced # at run time by a format(uuid_str='blah', app_id='foo') call xhs = {} if self.listener: xhs[self.call_tracking_header] = '{uuid_str}' xhs.update(kwargs.pop('xheaders', {})) # overrides from caller origparams = {self.app_id_header: '{app_id}'} if 'uuid_str' in kwargs: raise ConfigurationError( "passing 'uuid_str' here is improper usage") origparams.update(kwargs) # build a reusable command string self._orig_cmd = build_originate_cmd( *args, xheaders=xhs, **origparams )
[ "def", "set_orig_cmd", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# by default this inserts a couple placeholders which can be replaced", "# at run time by a format(uuid_str='blah', app_id='foo') call", "xhs", "=", "{", "}", "if", "self", ".", "lis...
https://github.com/friends-of-freeswitch/switchio/blob/dee6e9addcf881b2b411ec1dbb397b0acfbb78cf/switchio/api.py#L399-L421
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/idlelib/pathbrowser.py
python
PathBrowserTreeItem.GetText
(self)
return "sys.path"
[]
def GetText(self): return "sys.path"
[ "def", "GetText", "(", "self", ")", ":", "return", "\"sys.path\"" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/idlelib/pathbrowser.py#L31-L32
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/contrib/gis/gdal/srs.py
python
SpatialReference.__del__
(self)
Destroys this spatial reference.
Destroys this spatial reference.
[ "Destroys", "this", "spatial", "reference", "." ]
def __del__(self): "Destroys this spatial reference." if self._ptr: capi.release_srs(self._ptr)
[ "def", "__del__", "(", "self", ")", ":", "if", "self", ".", "_ptr", ":", "capi", ".", "release_srs", "(", "self", ".", "_ptr", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/contrib/gis/gdal/srs.py#L95-L97
packetloop/packetpig
6e101090224df219123ff5f6ab4c37524637571f
lib/scripts/impacket/impacket/dot11.py
python
Dot11WPA.set_TSC4
(self, value)
Set the \'WPA TSC4\' field
Set the \'WPA TSC4\' field
[ "Set", "the", "\\", "WPA", "TSC4", "\\", "field" ]
def set_TSC4(self, value): 'Set the \'WPA TSC4\' field' # set the bits nb = (value & 0xFF) self.header.set_byte(6, nb)
[ "def", "set_TSC4", "(", "self", ",", "value", ")", ":", "# set the bits", "nb", "=", "(", "value", "&", "0xFF", ")", "self", ".", "header", ".", "set_byte", "(", "6", ",", "nb", ")" ]
https://github.com/packetloop/packetpig/blob/6e101090224df219123ff5f6ab4c37524637571f/lib/scripts/impacket/impacket/dot11.py#L1247-L1251
python/mypy
17850b3bd77ae9efb5d21f656c4e4e05ac48d894
mypyc/irbuild/expression.py
python
translate_method_call
(builder: IRBuilder, expr: CallExpr, callee: MemberExpr)
Generate IR for an arbitrary call of form e.m(...). This can also deal with calls to module-level functions.
Generate IR for an arbitrary call of form e.m(...).
[ "Generate", "IR", "for", "an", "arbitrary", "call", "of", "form", "e", ".", "m", "(", "...", ")", "." ]
def translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr) -> Value: """Generate IR for an arbitrary call of form e.m(...). This can also deal with calls to module-level functions. """ if builder.is_native_ref_expr(callee): # Call to module-level native function or such return translate_call(builder, expr, callee) elif ( isinstance(callee.expr, RefExpr) and isinstance(callee.expr.node, TypeInfo) and callee.expr.node in builder.mapper.type_to_ir and builder.mapper.type_to_ir[callee.expr.node].has_method(callee.name) ): # Call a method via the *class* assert isinstance(callee.expr.node, TypeInfo) ir = builder.mapper.type_to_ir[callee.expr.node] decl = ir.method_decl(callee.name) args = [] arg_kinds, arg_names = expr.arg_kinds[:], expr.arg_names[:] # Add the class argument for class methods in extension classes if decl.kind == FUNC_CLASSMETHOD and ir.is_ext_class: args.append(builder.load_native_type_object(callee.expr.node.fullname)) arg_kinds.insert(0, ARG_POS) arg_names.insert(0, None) args += [builder.accept(arg) for arg in expr.args] if ir.is_ext_class: return builder.builder.call(decl, args, arg_kinds, arg_names, expr.line) else: obj = builder.accept(callee.expr) return builder.gen_method_call(obj, callee.name, args, builder.node_type(expr), expr.line, expr.arg_kinds, expr.arg_names) elif builder.is_module_member_expr(callee): # Fall back to a PyCall for non-native module calls function = builder.accept(callee) args = [builder.accept(arg) for arg in expr.args] return builder.py_call(function, args, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names) else: receiver_typ = builder.node_type(callee.expr) # If there is a specializer for this method name/type, try calling it. # We would return the first successful one. val = apply_method_specialization(builder, expr, callee, receiver_typ) if val is not None: return val obj = builder.accept(callee.expr) args = [builder.accept(arg) for arg in expr.args] return builder.gen_method_call(obj, callee.name, args, builder.node_type(expr), expr.line, expr.arg_kinds, expr.arg_names)
[ "def", "translate_method_call", "(", "builder", ":", "IRBuilder", ",", "expr", ":", "CallExpr", ",", "callee", ":", "MemberExpr", ")", "->", "Value", ":", "if", "builder", ".", "is_native_ref_expr", "(", "callee", ")", ":", "# Call to module-level native function ...
https://github.com/python/mypy/blob/17850b3bd77ae9efb5d21f656c4e4e05ac48d894/mypyc/irbuild/expression.py#L240-L302
DamnWidget/anaconda
a9998fb362320f907d5ccbc6fcf5b62baca677c0
anaconda_lib/parso/utils.py
python
version_info
()
return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)])
Returns a namedtuple of parso's version, similar to Python's ``sys.version_info``.
Returns a namedtuple of parso's version, similar to Python's ``sys.version_info``.
[ "Returns", "a", "namedtuple", "of", "parso", "s", "version", "similar", "to", "Python", "s", "sys", ".", "version_info", "." ]
def version_info(): """ Returns a namedtuple of parso's version, similar to Python's ``sys.version_info``. """ from parso import __version__ tupl = re.findall(r'[a-z]+|\d+', __version__) return Version(*[x if i == 3 else int(x) for i, x in enumerate(tupl)])
[ "def", "version_info", "(", ")", ":", "from", "parso", "import", "__version__", "tupl", "=", "re", ".", "findall", "(", "r'[a-z]+|\\d+'", ",", "__version__", ")", "return", "Version", "(", "*", "[", "x", "if", "i", "==", "3", "else", "int", "(", "x", ...
https://github.com/DamnWidget/anaconda/blob/a9998fb362320f907d5ccbc6fcf5b62baca677c0/anaconda_lib/parso/utils.py#L112-L119
google/macops
8442745359c0c941cd4e4e7d243e43bd16b40dec
gmacpyutil/gmacpyutil/cocoadialog.py
python
Standard_InputBox.SetNoCancel
(self, cancel=True)
[]
def SetNoCancel(self, cancel=True): self._no_cancel = cancel
[ "def", "SetNoCancel", "(", "self", ",", "cancel", "=", "True", ")", ":", "self", ".", "_no_cancel", "=", "cancel" ]
https://github.com/google/macops/blob/8442745359c0c941cd4e4e7d243e43bd16b40dec/gmacpyutil/gmacpyutil/cocoadialog.py#L421-L422
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py
python
_emit_update_statements
(base_mapper, uowtransaction, cached_connections, mapper, table, update, bookkeeping=True)
Emit UPDATE statements corresponding to value lists collected by _collect_update_commands().
Emit UPDATE statements corresponding to value lists collected by _collect_update_commands().
[ "Emit", "UPDATE", "statements", "corresponding", "to", "value", "lists", "collected", "by", "_collect_update_commands", "()", "." ]
def _emit_update_statements(base_mapper, uowtransaction, cached_connections, mapper, table, update, bookkeeping=True): """Emit UPDATE statements corresponding to value lists collected by _collect_update_commands().""" needs_version_id = mapper.version_id_col is not None and \ mapper.version_id_col in mapper._cols_by_table[table] def update_stmt(): clause = sql.and_() for col in mapper._pks_by_table[table]: clause.clauses.append(col == sql.bindparam(col._label, type_=col.type)) if needs_version_id: clause.clauses.append( mapper.version_id_col == sql.bindparam( mapper.version_id_col._label, type_=mapper.version_id_col.type)) stmt = table.update(clause) return stmt cached_stmt = base_mapper._memo(('update', table), update_stmt) for (connection, paramkeys, hasvalue, has_all_defaults, has_all_pks), \ records in groupby( update, lambda rec: ( rec[4], # connection set(rec[2]), # set of parameter keys bool(rec[5]), # whether or not we have "value" parameters rec[6], # has_all_defaults rec[7] # has all pks ) ): rows = 0 records = list(records) statement = cached_stmt # TODO: would be super-nice to not have to determine this boolean # inside the loop here, in the 99.9999% of the time there's only # one connection in use assert_singlerow = connection.dialect.supports_sane_rowcount assert_multirow = assert_singlerow and \ connection.dialect.supports_sane_multi_rowcount allow_multirow = has_all_defaults and not needs_version_id if not has_all_pks: statement = statement.return_defaults() elif bookkeeping and not has_all_defaults and \ mapper.base_mapper.eager_defaults: statement = statement.return_defaults() elif mapper.version_id_col is not None: statement = statement.return_defaults(mapper.version_id_col) if hasvalue: for state, state_dict, params, mapper, \ connection, value_params, \ has_all_defaults, has_all_pks in records: c = connection.execute( statement.values(value_params), params) if bookkeeping: _postfetch( mapper, uowtransaction, table, state, state_dict, c, c.context.compiled_parameters[0], value_params) rows += c.rowcount check_rowcount = True else: if not allow_multirow: check_rowcount = assert_singlerow for state, state_dict, params, mapper, \ connection, value_params, has_all_defaults, \ has_all_pks in records: c = cached_connections[connection].\ execute(statement, params) # TODO: why with bookkeeping=False? if bookkeeping: _postfetch( mapper, uowtransaction, table, state, state_dict, c, c.context.compiled_parameters[0], value_params) rows += c.rowcount else: multiparams = [rec[2] for rec in records] check_rowcount = assert_multirow or ( assert_singlerow and len(multiparams) == 1 ) c = cached_connections[connection].\ execute(statement, multiparams) rows += c.rowcount for state, state_dict, params, mapper, \ connection, value_params, \ has_all_defaults, has_all_pks in records: if bookkeeping: _postfetch( mapper, uowtransaction, table, state, state_dict, c, c.context.compiled_parameters[0], value_params) if check_rowcount: if rows != len(records): raise orm_exc.StaleDataError( "UPDATE statement on table '%s' expected to " "update %d row(s); %d were matched." % (table.description, len(records), rows)) elif needs_version_id: util.warn("Dialect %s does not support updated rowcount " "- versioning cannot be verified." % c.dialect.dialect_description)
[ "def", "_emit_update_statements", "(", "base_mapper", ",", "uowtransaction", ",", "cached_connections", ",", "mapper", ",", "table", ",", "update", ",", "bookkeeping", "=", "True", ")", ":", "needs_version_id", "=", "mapper", ".", "version_id_col", "is", "not", ...
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py#L618-L754
Pyomo/pyomo
dbd4faee151084f343b893cc2b0c04cf2b76fd92
pyomo/core/kernel/block.py
python
IBlock.child
(self, key)
Get the child object associated with a given storage key for this container. Raises: KeyError: if the argument is not a storage key for any children of this container
Get the child object associated with a given storage key for this container.
[ "Get", "the", "child", "object", "associated", "with", "a", "given", "storage", "key", "for", "this", "container", "." ]
def child(self, key): """Get the child object associated with a given storage key for this container. Raises: KeyError: if the argument is not a storage key for any children of this container """ try: return getattr(self, key) except AttributeError: raise KeyError(str(key))
[ "def", "child", "(", "self", ",", "key", ")", ":", "try", ":", "return", "getattr", "(", "self", ",", "key", ")", "except", "AttributeError", ":", "raise", "KeyError", "(", "str", "(", "key", ")", ")" ]
https://github.com/Pyomo/pyomo/blob/dbd4faee151084f343b893cc2b0c04cf2b76fd92/pyomo/core/kernel/block.py#L52-L63
Chaffelson/nipyapi
d3b186fd701ce308c2812746d98af9120955e810
nipyapi/nifi/models/connection_statistics_dto.py
python
ConnectionStatisticsDTO.node_snapshots
(self)
return self._node_snapshots
Gets the node_snapshots of this ConnectionStatisticsDTO. A list of status snapshots for each node :return: The node_snapshots of this ConnectionStatisticsDTO. :rtype: list[NodeConnectionStatisticsSnapshotDTO]
Gets the node_snapshots of this ConnectionStatisticsDTO. A list of status snapshots for each node
[ "Gets", "the", "node_snapshots", "of", "this", "ConnectionStatisticsDTO", ".", "A", "list", "of", "status", "snapshots", "for", "each", "node" ]
def node_snapshots(self): """ Gets the node_snapshots of this ConnectionStatisticsDTO. A list of status snapshots for each node :return: The node_snapshots of this ConnectionStatisticsDTO. :rtype: list[NodeConnectionStatisticsSnapshotDTO] """ return self._node_snapshots
[ "def", "node_snapshots", "(", "self", ")", ":", "return", "self", ".", "_node_snapshots" ]
https://github.com/Chaffelson/nipyapi/blob/d3b186fd701ce308c2812746d98af9120955e810/nipyapi/nifi/models/connection_statistics_dto.py#L136-L144
alephdata/aleph
6d4e944e87f66e9c412e4b6fc807ebd4e57370e0
aleph/logic/permissions.py
python
update_permission
(role, collection, read, write, editor_id=None)
return post
Update a roles permission to access a given collection.
Update a roles permission to access a given collection.
[ "Update", "a", "roles", "permission", "to", "access", "a", "given", "collection", "." ]
def update_permission(role, collection, read, write, editor_id=None): """Update a roles permission to access a given collection.""" pre = Permission.by_collection_role(collection, role) post = Permission.grant(collection, role, read, write) db.session.flush() refresh_role(role) if post is None: return params = {"role": role, "collection": collection} if pre is None or not pre.read: if role.foreign_id == Role.SYSTEM_GUEST: publish( Events.PUBLISH_COLLECTION, actor_id=editor_id, params=params, channels=[GLOBAL], ) else: publish( Events.GRANT_COLLECTION, actor_id=editor_id, params=params, channels=[role], ) return post
[ "def", "update_permission", "(", "role", ",", "collection", ",", "read", ",", "write", ",", "editor_id", "=", "None", ")", ":", "pre", "=", "Permission", ".", "by_collection_role", "(", "collection", ",", "role", ")", "post", "=", "Permission", ".", "grant...
https://github.com/alephdata/aleph/blob/6d4e944e87f66e9c412e4b6fc807ebd4e57370e0/aleph/logic/permissions.py#L11-L35
ethereum/lahja
f51c0b738a7dfd8b2b08a021cb31849792422625
lahja/base.py
python
EndpointAPI.serve
(cls, config: ConnectionConfig)
Context manager API for running and endpoint server. .. code-block:: python async with EndpointClass.serve(config): ... # server running within context ... # server stopped
Context manager API for running and endpoint server.
[ "Context", "manager", "API", "for", "running", "and", "endpoint", "server", "." ]
def serve(cls, config: ConnectionConfig) -> AsyncContextManager["EndpointAPI"]: """ Context manager API for running and endpoint server. .. code-block:: python async with EndpointClass.serve(config): ... # server running within context ... # server stopped """ ...
[ "def", "serve", "(", "cls", ",", "config", ":", "ConnectionConfig", ")", "->", "AsyncContextManager", "[", "\"EndpointAPI\"", "]", ":", "..." ]
https://github.com/ethereum/lahja/blob/f51c0b738a7dfd8b2b08a021cb31849792422625/lahja/base.py#L378-L389
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/idlelib/configHandler.py
python
IdleConf.GetSectionList
(self, configSet, configType)
return cfgParser.sections()
Return sections for configSet configType configuration. configSet must be either 'user' or 'default' configType must be in self.config_types.
Return sections for configSet configType configuration.
[ "Return", "sections", "for", "configSet", "configType", "configuration", "." ]
def GetSectionList(self, configSet, configType): """Return sections for configSet configType configuration. configSet must be either 'user' or 'default' configType must be in self.config_types. """ if not (configType in self.config_types): raise InvalidConfigType('Invalid configType specified') if configSet == 'user': cfgParser = self.userCfg[configType] elif configSet == 'default': cfgParser=self.defaultCfg[configType] else: raise InvalidConfigSet('Invalid configSet specified') return cfgParser.sections()
[ "def", "GetSectionList", "(", "self", ",", "configSet", ",", "configType", ")", ":", "if", "not", "(", "configType", "in", "self", ".", "config_types", ")", ":", "raise", "InvalidConfigType", "(", "'Invalid configType specified'", ")", "if", "configSet", "==", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/idlelib/configHandler.py#L264-L278
LinOTP/LinOTP
bb3940bbaccea99550e6c063ff824f258dd6d6d7
linotp/provider/__init__.py
python
setProvider
(params)
return True, {}
save the provider info in linotp config :param params: generic parameter dictionary to support later more complex provider definitions in the dictionary currently required keys are :param type: push,sms or email :param name: the provider name :param config: the provider config :param timeout: the provider timeout :param: default: boolean :return: success - boolean
save the provider info in linotp config
[ "save", "the", "provider", "info", "in", "linotp", "config" ]
def setProvider(params): """ save the provider info in linotp config :param params: generic parameter dictionary to support later more complex provider definitions in the dictionary currently required keys are :param type: push,sms or email :param name: the provider name :param config: the provider config :param timeout: the provider timeout :param: default: boolean :return: success - boolean """ provider_type = params["type"] provider_name = params["name"] if provider_name == Legacy_Provider_Name: save_legacy_provider(provider_type, params) else: save_new_provider(provider_type, provider_name, params) if "default" in params: default_provider_key = Default_Provider_Key[provider_type] if params["default"] is True or params["default"].lower() == "true": storeConfig(key=default_provider_key, val=provider_name) # uncomment this if you want to get provider config as ini file: # from linotp.provider.create_provider_ini import create_provider_config # create_provider_config() return True, {}
[ "def", "setProvider", "(", "params", ")", ":", "provider_type", "=", "params", "[", "\"type\"", "]", "provider_name", "=", "params", "[", "\"name\"", "]", "if", "provider_name", "==", "Legacy_Provider_Name", ":", "save_legacy_provider", "(", "provider_type", ",", ...
https://github.com/LinOTP/LinOTP/blob/bb3940bbaccea99550e6c063ff824f258dd6d6d7/linotp/provider/__init__.py#L517-L550
UDST/urbansim
0db75668ada0005352b7c7e0a405265f78ccadd7
urbansim/models/regression.py
python
RegressionModel.report_fit
(self)
Print a report of the fit results.
Print a report of the fit results.
[ "Print", "a", "report", "of", "the", "fit", "results", "." ]
def report_fit(self): """ Print a report of the fit results. """ if not self.fitted: print('Model not yet fit.') return print('R-Squared: {0:.3f}'.format(self.model_fit.rsquared)) print('Adj. R-Squared: {0:.3f}'.format(self.model_fit.rsquared_adj)) print('') tbl = PrettyTable( ['Component', ]) tbl = PrettyTable() tbl.add_column('Component', self.fit_parameters.index.values) for col in ('Coefficient', 'Std. Error', 'T-Score'): tbl.add_column(col, self.fit_parameters[col].values) tbl.align['Component'] = 'l' tbl.float_format = '.3' print(tbl)
[ "def", "report_fit", "(", "self", ")", ":", "if", "not", "self", ".", "fitted", ":", "print", "(", "'Model not yet fit.'", ")", "return", "print", "(", "'R-Squared: {0:.3f}'", ".", "format", "(", "self", ".", "model_fit", ".", "rsquared", ")", ")", "print"...
https://github.com/UDST/urbansim/blob/0db75668ada0005352b7c7e0a405265f78ccadd7/urbansim/models/regression.py#L364-L388
aneisch/home-assistant-config
86e381fde9609cb8871c439c433c12989e4e225d
custom_components/localtuya/fan.py
python
flow_schema
(dps)
return { vol.Optional(CONF_FAN_SPEED_CONTROL): vol.In(dps), vol.Optional(CONF_FAN_OSCILLATING_CONTROL): vol.In(dps), vol.Optional(CONF_FAN_SPEED_LOW, default=SPEED_LOW): vol.In( [SPEED_LOW, "1", "2", "small"] ), vol.Optional(CONF_FAN_SPEED_MEDIUM, default=SPEED_MEDIUM): vol.In( [SPEED_MEDIUM, "mid", "2", "3"] ), vol.Optional(CONF_FAN_SPEED_HIGH, default=SPEED_HIGH): vol.In( [SPEED_HIGH, "auto", "3", "4", "large", "big"] ), }
Return schema used in config flow.
Return schema used in config flow.
[ "Return", "schema", "used", "in", "config", "flow", "." ]
def flow_schema(dps): """Return schema used in config flow.""" return { vol.Optional(CONF_FAN_SPEED_CONTROL): vol.In(dps), vol.Optional(CONF_FAN_OSCILLATING_CONTROL): vol.In(dps), vol.Optional(CONF_FAN_SPEED_LOW, default=SPEED_LOW): vol.In( [SPEED_LOW, "1", "2", "small"] ), vol.Optional(CONF_FAN_SPEED_MEDIUM, default=SPEED_MEDIUM): vol.In( [SPEED_MEDIUM, "mid", "2", "3"] ), vol.Optional(CONF_FAN_SPEED_HIGH, default=SPEED_HIGH): vol.In( [SPEED_HIGH, "auto", "3", "4", "large", "big"] ), }
[ "def", "flow_schema", "(", "dps", ")", ":", "return", "{", "vol", ".", "Optional", "(", "CONF_FAN_SPEED_CONTROL", ")", ":", "vol", ".", "In", "(", "dps", ")", ",", "vol", ".", "Optional", "(", "CONF_FAN_OSCILLATING_CONTROL", ")", ":", "vol", ".", "In", ...
https://github.com/aneisch/home-assistant-config/blob/86e381fde9609cb8871c439c433c12989e4e225d/custom_components/localtuya/fan.py#L29-L43
leancloud/satori
701caccbd4fe45765001ca60435c0cb499477c03
satori-rules/plugin/libs/pymongo/common.py
python
validate_boolean_or_string
(option, value)
return validate_boolean(option, value)
Validates that value is True, False, 'true', or 'false'.
Validates that value is True, False, 'true', or 'false'.
[ "Validates", "that", "value", "is", "True", "False", "true", "or", "false", "." ]
def validate_boolean_or_string(option, value): """Validates that value is True, False, 'true', or 'false'.""" if isinstance(value, string_type): if value not in ('true', 'false'): raise ValueError("The value of %s must be " "'true' or 'false'" % (option,)) return value == 'true' return validate_boolean(option, value)
[ "def", "validate_boolean_or_string", "(", "option", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "string_type", ")", ":", "if", "value", "not", "in", "(", "'true'", ",", "'false'", ")", ":", "raise", "ValueError", "(", "\"The value of %s mu...
https://github.com/leancloud/satori/blob/701caccbd4fe45765001ca60435c0cb499477c03/satori-rules/plugin/libs/pymongo/common.py#L126-L133
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_6.4/Crypto/PublicKey/_slowmath.py
python
_DSAKey.has_private
(self)
return hasattr(self, 'x')
[]
def has_private(self): return hasattr(self, 'x')
[ "def", "has_private", "(", "self", ")", ":", "return", "hasattr", "(", "self", ",", "'x'", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_6.4/Crypto/PublicKey/_slowmath.py#L147-L148
chakki-works/chazutsu
811dedb19e3d670011da3679dc3befe4f1f2c41c
chazutsu/datasets/framework/resource.py
python
Resource.to_batch
(self, kind, columns=())
return X, y
[]
def to_batch(self, kind, columns=()): df = self._get_data(kind, split_target=False) y = None Xs = [] _columns = columns if len(columns) > 0 else self.columns for c in _columns: if c not in df.columns: raise Exception("{} is not exist.".format(c)) s = self._to_array(c, df[c]) if c == self.target: y = s else: Xs.append(s) if len(Xs) == 1: X = Xs[0] else: X = np.hstack(Xs) return X, y
[ "def", "to_batch", "(", "self", ",", "kind", ",", "columns", "=", "(", ")", ")", ":", "df", "=", "self", ".", "_get_data", "(", "kind", ",", "split_target", "=", "False", ")", "y", "=", "None", "Xs", "=", "[", "]", "_columns", "=", "columns", "if...
https://github.com/chakki-works/chazutsu/blob/811dedb19e3d670011da3679dc3befe4f1f2c41c/chazutsu/datasets/framework/resource.py#L180-L198
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py-rest/applications/admin/controllers/default.py
python
remove_compiled_app
()
Remove the compiled application
Remove the compiled application
[ "Remove", "the", "compiled", "application" ]
def remove_compiled_app(): """ Remove the compiled application """ app = get_app() remove_compiled_application(apath(app, r=request)) session.flash = T('compiled application removed') redirect(URL('site'))
[ "def", "remove_compiled_app", "(", ")", ":", "app", "=", "get_app", "(", ")", "remove_compiled_application", "(", "apath", "(", "app", ",", "r", "=", "request", ")", ")", "session", ".", "flash", "=", "T", "(", "'compiled application removed'", ")", "redirec...
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py-rest/applications/admin/controllers/default.py#L513-L518
securityclippy/elasticintel
aa08d3e9f5ab1c000128e95161139ce97ff0e334
intelbot/requests/models.py
python
Response.__iter__
(self)
return self.iter_content(128)
Allows you to use a response as an iterator.
Allows you to use a response as an iterator.
[ "Allows", "you", "to", "use", "a", "response", "as", "an", "iterator", "." ]
def __iter__(self): """Allows you to use a response as an iterator.""" return self.iter_content(128)
[ "def", "__iter__", "(", "self", ")", ":", "return", "self", ".", "iter_content", "(", "128", ")" ]
https://github.com/securityclippy/elasticintel/blob/aa08d3e9f5ab1c000128e95161139ce97ff0e334/intelbot/requests/models.py#L614-L616
SCSSoftware/BlenderTools
96f323d3bdf2d8cb8ed7f882dcdf036277a802dd
addon/io_scs_tools/imp/pim.py
python
get_global
(pim_container)
return vertex_count, face_count, edge_count, material_count, piece_count, part_count, bone_count, locator_count, skeleton, piece_skin_count
Receives PIM container and returns all its Global properties in its own variables. For any item that fails to be found, it returns None.
Receives PIM container and returns all its Global properties in its own variables. For any item that fails to be found, it returns None.
[ "Receives", "PIM", "container", "and", "returns", "all", "its", "Global", "properties", "in", "its", "own", "variables", ".", "For", "any", "item", "that", "fails", "to", "be", "found", "it", "returns", "None", "." ]
def get_global(pim_container): """Receives PIM container and returns all its Global properties in its own variables. For any item that fails to be found, it returns None.""" vertex_count = face_count = edge_count = material_count = piece_count = part_count = bone_count = locator_count = piece_skin_count = 0 skeleton = None for section in pim_container: if section.type == "Global": for prop in section.props: if prop[0] in ("", "#"): pass elif prop[0] == "VertexCount": vertex_count = prop[1] elif prop[0] in ("TriangleCount", "FaceCount"): face_count = prop[1] elif prop[0] == "EdgeCount": edge_count = prop[1] elif prop[0] == "MaterialCount": material_count = prop[1] elif prop[0] == "PieceCount": piece_count = prop[1] elif prop[0] == "PartCount": part_count = prop[1] elif prop[0] == "BoneCount": bone_count = prop[1] elif prop[0] == "LocatorCount": locator_count = prop[1] elif prop[0] == "Skeleton": skeleton = prop[1] elif prop[0] == "PieceSkinCount": piece_skin_count = prop[1] else: lprint('\nW Unknown property in "Global" data: "%s"!', prop[0]) return vertex_count, face_count, edge_count, material_count, piece_count, part_count, bone_count, locator_count, skeleton, piece_skin_count
[ "def", "get_global", "(", "pim_container", ")", ":", "vertex_count", "=", "face_count", "=", "edge_count", "=", "material_count", "=", "piece_count", "=", "part_count", "=", "bone_count", "=", "locator_count", "=", "piece_skin_count", "=", "0", "skeleton", "=", ...
https://github.com/SCSSoftware/BlenderTools/blob/96f323d3bdf2d8cb8ed7f882dcdf036277a802dd/addon/io_scs_tools/imp/pim.py#L64-L96
livid/v2ex-gae
32be3a77d535e7c9df85a333e01ab8834d0e8581
mapreduce/handlers.py
python
MapperWorkerCallbackHandler.worker_parameters
(mapreduce_spec, shard_id, slice_id, input_reader)
return {"mapreduce_spec": mapreduce_spec.to_json_str(), "shard_id": shard_id, "slice_id": str(slice_id), "input_reader_state": input_reader.to_json_str()}
Fill in mapper worker task parameters. Returned parameters map is to be used as task payload, and it contains all the data, required by mapper worker to perform its function. Args: mapreduce_spec: specification of the mapreduce. shard_id: id of the shard (part of the whole dataset). slice_id: id of the slice (part of the shard). input_reader: InputReader containing the remaining inputs for this shard. Returns: string->string map of parameters to be used as task payload.
Fill in mapper worker task parameters.
[ "Fill", "in", "mapper", "worker", "task", "parameters", "." ]
def worker_parameters(mapreduce_spec, shard_id, slice_id, input_reader): """Fill in mapper worker task parameters. Returned parameters map is to be used as task payload, and it contains all the data, required by mapper worker to perform its function. Args: mapreduce_spec: specification of the mapreduce. shard_id: id of the shard (part of the whole dataset). slice_id: id of the slice (part of the shard). input_reader: InputReader containing the remaining inputs for this shard. Returns: string->string map of parameters to be used as task payload. """ return {"mapreduce_spec": mapreduce_spec.to_json_str(), "shard_id": shard_id, "slice_id": str(slice_id), "input_reader_state": input_reader.to_json_str()}
[ "def", "worker_parameters", "(", "mapreduce_spec", ",", "shard_id", ",", "slice_id", ",", "input_reader", ")", ":", "return", "{", "\"mapreduce_spec\"", ":", "mapreduce_spec", ".", "to_json_str", "(", ")", ",", "\"shard_id\"", ":", "shard_id", ",", "\"slice_id\"",...
https://github.com/livid/v2ex-gae/blob/32be3a77d535e7c9df85a333e01ab8834d0e8581/mapreduce/handlers.py#L248-L270
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/sympy/liealgebras/type_a.py
python
TypeA.highest_root
(self)
return self.basic_root(0, self.n)
Returns the highest weight root for A_n
Returns the highest weight root for A_n
[ "Returns", "the", "highest", "weight", "root", "for", "A_n" ]
def highest_root(self): """ Returns the highest weight root for A_n """ return self.basic_root(0, self.n)
[ "def", "highest_root", "(", "self", ")", ":", "return", "self", ".", "basic_root", "(", "0", ",", "self", ".", "n", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/sympy/liealgebras/type_a.py#L104-L109
TencentCloud/tencentcloud-sdk-python
3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2
tencentcloud/tcb/v20180608/models.py
python
DescribeCloudBaseRunServerResponse.__init__
(self)
r""" :param TotalCount: 个数 注意:此字段可能返回 null,表示取不到有效值。 :type TotalCount: int :param VersionItems: 版本列表 注意:此字段可能返回 null,表示取不到有效值。 :type VersionItems: list of CloudBaseRunServerVersionItem :param ServerName: 服务名称 注意:此字段可能返回 null,表示取不到有效值。 :type ServerName: str :param IsPublic: 是否对于外网开放 注意:此字段可能返回 null,表示取不到有效值。 :type IsPublic: bool :param ImageRepo: 镜像仓库 注意:此字段可能返回 null,表示取不到有效值。 :type ImageRepo: str :param TrafficType: 流量配置的类型(FLOW,URL_PARAMS) 注意:此字段可能返回 null,表示取不到有效值。 :type TrafficType: str :param SourceType: 服务创建类型,默认为空,一键部署为oneclick 注意:此字段可能返回 null,表示取不到有效值。 :type SourceType: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
r""" :param TotalCount: 个数 注意:此字段可能返回 null,表示取不到有效值。 :type TotalCount: int :param VersionItems: 版本列表 注意:此字段可能返回 null,表示取不到有效值。 :type VersionItems: list of CloudBaseRunServerVersionItem :param ServerName: 服务名称 注意:此字段可能返回 null,表示取不到有效值。 :type ServerName: str :param IsPublic: 是否对于外网开放 注意:此字段可能返回 null,表示取不到有效值。 :type IsPublic: bool :param ImageRepo: 镜像仓库 注意:此字段可能返回 null,表示取不到有效值。 :type ImageRepo: str :param TrafficType: 流量配置的类型(FLOW,URL_PARAMS) 注意:此字段可能返回 null,表示取不到有效值。 :type TrafficType: str :param SourceType: 服务创建类型,默认为空,一键部署为oneclick 注意:此字段可能返回 null,表示取不到有效值。 :type SourceType: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str
[ "r", ":", "param", "TotalCount", ":", "个数", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "TotalCount", ":", "int", ":", "param", "VersionItems", ":", "版本列表", "注意:此字段可能返回", "null,表示取不到有效值。", ":", "type", "VersionItems", ":", "list", "of", "CloudBaseRunServerVersion...
def __init__(self): r""" :param TotalCount: 个数 注意:此字段可能返回 null,表示取不到有效值。 :type TotalCount: int :param VersionItems: 版本列表 注意:此字段可能返回 null,表示取不到有效值。 :type VersionItems: list of CloudBaseRunServerVersionItem :param ServerName: 服务名称 注意:此字段可能返回 null,表示取不到有效值。 :type ServerName: str :param IsPublic: 是否对于外网开放 注意:此字段可能返回 null,表示取不到有效值。 :type IsPublic: bool :param ImageRepo: 镜像仓库 注意:此字段可能返回 null,表示取不到有效值。 :type ImageRepo: str :param TrafficType: 流量配置的类型(FLOW,URL_PARAMS) 注意:此字段可能返回 null,表示取不到有效值。 :type TrafficType: str :param SourceType: 服务创建类型,默认为空,一键部署为oneclick 注意:此字段可能返回 null,表示取不到有效值。 :type SourceType: str :param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.TotalCount = None self.VersionItems = None self.ServerName = None self.IsPublic = None self.ImageRepo = None self.TrafficType = None self.SourceType = None self.RequestId = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "TotalCount", "=", "None", "self", ".", "VersionItems", "=", "None", "self", ".", "ServerName", "=", "None", "self", ".", "IsPublic", "=", "None", "self", ".", "ImageRepo", "=", "None", "self", "."...
https://github.com/TencentCloud/tencentcloud-sdk-python/blob/3677fd1cdc8c5fd626ce001c13fd3b59d1f279d2/tencentcloud/tcb/v20180608/models.py#L3700-L3733
mylar3/mylar3
fce4771c5b627f8de6868dd4ab6bc53f7b22d303
lib/rtorrent/common.py
python
cmd_exists
(cmds_list, cmd)
return(cmd in cmds_list)
Check if given command is in list of available commands @param cmds_list: see L{RTorrent._rpc_methods} @type cmds_list: list @param cmd: name of command to be checked @type cmd: str @return: bool
Check if given command is in list of available commands
[ "Check", "if", "given", "command", "is", "in", "list", "of", "available", "commands" ]
def cmd_exists(cmds_list, cmd): """Check if given command is in list of available commands @param cmds_list: see L{RTorrent._rpc_methods} @type cmds_list: list @param cmd: name of command to be checked @type cmd: str @return: bool """ return(cmd in cmds_list)
[ "def", "cmd_exists", "(", "cmds_list", ",", "cmd", ")", ":", "return", "(", "cmd", "in", "cmds_list", ")" ]
https://github.com/mylar3/mylar3/blob/fce4771c5b627f8de6868dd4ab6bc53f7b22d303/lib/rtorrent/common.py#L34-L46
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/python-openid/openid/store/sqlstore.py
python
SQLStore.blobDecode
(self, blob)
return blob
Convert a blob as returned by the SQL engine into a str object. str -> str
Convert a blob as returned by the SQL engine into a str object.
[ "Convert", "a", "blob", "as", "returned", "by", "the", "SQL", "engine", "into", "a", "str", "object", "." ]
def blobDecode(self, blob): """Convert a blob as returned by the SQL engine into a str object. str -> str""" return blob
[ "def", "blobDecode", "(", "self", ",", "blob", ")", ":", "return", "blob" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/python-openid/openid/store/sqlstore.py#L115-L119
NVIDIA/PyProf
218dcc183bf7fdf97dbfc648878a3d09aea3b199
pyprof/parse/kernel.py
python
demangle
(name)
return result
Demangle a C++ string
Demangle a C++ string
[ "Demangle", "a", "C", "++", "string" ]
def demangle(name): """ Demangle a C++ string """ result = name try: result = cxxfilt.demangle(name) except: pass return result
[ "def", "demangle", "(", "name", ")", ":", "result", "=", "name", "try", ":", "result", "=", "cxxfilt", ".", "demangle", "(", "name", ")", "except", ":", "pass", "return", "result" ]
https://github.com/NVIDIA/PyProf/blob/218dcc183bf7fdf97dbfc648878a3d09aea3b199/pyprof/parse/kernel.py#L23-L32
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/_trie/py.py
python
Trie.__contains__
(self, key)
return key in self._data
[]
def __contains__(self, key): return key in self._data
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "return", "key", "in", "self", ".", "_data" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pip/_vendor/html5lib/_trie/py.py#L19-L20
amymcgovern/pyparrot
bf4775ec1199b282e4edde1e4a8e018dcc8725e0
pyparrot/utils/vlc.py
python
Instance.media_list_new
(self, mrls=None)
return l
Create a new MediaList instance. @param mrls: optional list of MRL strings
Create a new MediaList instance.
[ "Create", "a", "new", "MediaList", "instance", "." ]
def media_list_new(self, mrls=None): """Create a new MediaList instance. @param mrls: optional list of MRL strings """ l = libvlc_media_list_new(self) # We should take the lock, but since we did not leak the # reference, nobody else can access it. if mrls: for m in mrls: l.add_media(m) l._instance = self return l
[ "def", "media_list_new", "(", "self", ",", "mrls", "=", "None", ")", ":", "l", "=", "libvlc_media_list_new", "(", "self", ")", "# We should take the lock, but since we did not leak the", "# reference, nobody else can access it.", "if", "mrls", ":", "for", "m", "in", "...
https://github.com/amymcgovern/pyparrot/blob/bf4775ec1199b282e4edde1e4a8e018dcc8725e0/pyparrot/utils/vlc.py#L1781-L1792
IronLanguages/ironpython3
7a7bb2a872eeab0d1009fc8a6e24dca43f65b693
Src/StdLib/Lib/gzip.py
python
_PaddedFile.unused
(self)
return self._buffer[self._read:]
[]
def unused(self): if self._read is None: return b'' return self._buffer[self._read:]
[ "def", "unused", "(", "self", ")", ":", "if", "self", ".", "_read", "is", "None", ":", "return", "b''", "return", "self", ".", "_buffer", "[", "self", ".", "_read", ":", "]" ]
https://github.com/IronLanguages/ironpython3/blob/7a7bb2a872eeab0d1009fc8a6e24dca43f65b693/Src/StdLib/Lib/gzip.py#L103-L106
allianceauth/allianceauth
6585b07e96571a99a4d6dc03cc03f9b8c8f690ca
allianceauth/authentication/admin.py
python
make_service_hooks_update_groups_action
(service)
return update_service_groups
Make a admin action for the given service :param service: services.hooks.ServicesHook :return: fn to update services groups for the selected users
Make a admin action for the given service :param service: services.hooks.ServicesHook :return: fn to update services groups for the selected users
[ "Make", "a", "admin", "action", "for", "the", "given", "service", ":", "param", "service", ":", "services", ".", "hooks", ".", "ServicesHook", ":", "return", ":", "fn", "to", "update", "services", "groups", "for", "the", "selected", "users" ]
def make_service_hooks_update_groups_action(service): """ Make a admin action for the given service :param service: services.hooks.ServicesHook :return: fn to update services groups for the selected users """ def update_service_groups(modeladmin, request, queryset): for user in queryset: # queryset filtering doesn't work here? service.update_groups(user) update_service_groups.__name__ = str('update_{}_groups'.format(slugify(service.name))) update_service_groups.short_description = "Sync groups for selected {} accounts".format(service.title) return update_service_groups
[ "def", "make_service_hooks_update_groups_action", "(", "service", ")", ":", "def", "update_service_groups", "(", "modeladmin", ",", "request", ",", "queryset", ")", ":", "for", "user", "in", "queryset", ":", "# queryset filtering doesn't work here?", "service", ".", "...
https://github.com/allianceauth/allianceauth/blob/6585b07e96571a99a4d6dc03cc03f9b8c8f690ca/allianceauth/authentication/admin.py#L15-L27
VisionLearningGroup/DA_Detection
730eaca8528d22ed3aa6b4dbc1965828a697cf9a
lib/model/faster_rcnn/resnet_dafrcnn.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "...
https://github.com/VisionLearningGroup/DA_Detection/blob/730eaca8528d22ed3aa6b4dbc1965828a697cf9a/lib/model/faster_rcnn/resnet_dafrcnn.py#L28-L31
googlefonts/fontbakery
cb8196c3a636b63654f8370636cb3f438b60d5b1
Lib/fontbakery/profiles/kern.py
python
com_google_fonts_check_kern_table
(ttFont)
Is there a usable "kern" table declared in the font?
Is there a usable "kern" table declared in the font?
[ "Is", "there", "a", "usable", "kern", "table", "declared", "in", "the", "font?" ]
def com_google_fonts_check_kern_table(ttFont): """Is there a usable "kern" table declared in the font?""" kern = ttFont.get("kern") if kern: cmap = set(ttFont.getBestCmap().values()) nonCharacterGlyphs = set() for kernTable in kern.kernTables: if kernTable.format == 0: for leftGlyph, rightGlyph in kernTable.kernTable.keys(): if leftGlyph not in cmap: nonCharacterGlyphs.add(leftGlyph) if rightGlyph not in cmap: nonCharacterGlyphs.add(rightGlyph) if all(kernTable.format != 0 for kernTable in kern.kernTables): yield WARN,\ Message("kern-unknown-format", 'The "kern" table does not have any format-0 subtable ' 'and will not work in a few programs that may require ' 'the table.') elif nonCharacterGlyphs: yield FAIL,\ Message("kern-non-character-glyphs", 'The following glyphs should not be used in the "kern" ' 'table because they are not in the "cmap" table: %s' % ', '.join(sorted(nonCharacterGlyphs))) else: yield INFO,\ Message("kern-found", 'Only a few programs may require the kerning' ' info that this font provides on its "kern" table.') else: yield PASS, 'Font does not declare an optional "kern" table.'
[ "def", "com_google_fonts_check_kern_table", "(", "ttFont", ")", ":", "kern", "=", "ttFont", ".", "get", "(", "\"kern\"", ")", "if", "kern", ":", "cmap", "=", "set", "(", "ttFont", ".", "getBestCmap", "(", ")", ".", "values", "(", ")", ")", "nonCharacterG...
https://github.com/googlefonts/fontbakery/blob/cb8196c3a636b63654f8370636cb3f438b60d5b1/Lib/fontbakery/profiles/kern.py#L24-L56
coin-or/pulp
0cf902579b8ca52cca09d66df5619095f8062f99
pulp/pulp.py
python
LpProblem.toJson
(self, filename, *args, **kwargs)
Creates a json file from the LpProblem information :param str filename: filename to write json :param args: additional arguments for json function :param kwargs: additional keyword arguments for json function :return: None
Creates a json file from the LpProblem information
[ "Creates", "a", "json", "file", "from", "the", "LpProblem", "information" ]
def toJson(self, filename, *args, **kwargs): """ Creates a json file from the LpProblem information :param str filename: filename to write json :param args: additional arguments for json function :param kwargs: additional keyword arguments for json function :return: None """ with open(filename, "w") as f: json.dump(self.toDict(), f, *args, **kwargs)
[ "def", "toJson", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "open", "(", "filename", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "self", ".", "toDict", "(", ")", ",", "f", ",", ...
https://github.com/coin-or/pulp/blob/0cf902579b8ca52cca09d66df5619095f8062f99/pulp/pulp.py#L1510-L1520
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/quantum_info/synthesis/one_qubit_decompose.py
python
OneQubitEulerDecomposer._params_xyx
(mat)
return theta, newphi, newlam, phase + (newphi + newlam - phi - lam) / 2
Return the Euler angles and phase for the XYX basis.
Return the Euler angles and phase for the XYX basis.
[ "Return", "the", "Euler", "angles", "and", "phase", "for", "the", "XYX", "basis", "." ]
def _params_xyx(mat): """Return the Euler angles and phase for the XYX basis.""" # We use the fact that # Rx(a).Ry(b).Rx(c) = H.Rz(a).Ry(-b).Rz(c).H mat_zyz = 0.5 * np.array( [ [ mat[0, 0] + mat[0, 1] + mat[1, 0] + mat[1, 1], mat[0, 0] - mat[0, 1] + mat[1, 0] - mat[1, 1], ], [ mat[0, 0] + mat[0, 1] - mat[1, 0] - mat[1, 1], mat[0, 0] - mat[0, 1] - mat[1, 0] + mat[1, 1], ], ], dtype=complex, ) theta, phi, lam, phase = OneQubitEulerDecomposer._params_zyz(mat_zyz) newphi, newlam = _mod_2pi(phi + np.pi), _mod_2pi(lam + np.pi) return theta, newphi, newlam, phase + (newphi + newlam - phi - lam) / 2
[ "def", "_params_xyx", "(", "mat", ")", ":", "# We use the fact that", "# Rx(a).Ry(b).Rx(c) = H.Rz(a).Ry(-b).Rz(c).H", "mat_zyz", "=", "0.5", "*", "np", ".", "array", "(", "[", "[", "mat", "[", "0", ",", "0", "]", "+", "mat", "[", "0", ",", "1", "]", "+",...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/quantum_info/synthesis/one_qubit_decompose.py#L248-L267
openstack/python-neutronclient
517bef2c5454dde2eba5cc2194ee857be6be7164
neutronclient/neutron/client.py
python
make_client
(instance)
return client
Returns an neutron client.
Returns an neutron client.
[ "Returns", "an", "neutron", "client", "." ]
def make_client(instance): """Returns an neutron client.""" neutron_client = utils.get_client_class( API_NAME, instance._api_version, API_VERSIONS, ) instance.initialize() url = instance._url url = url.rstrip("/") client = neutron_client(username=instance._username, project_name=instance._project_name, password=instance._password, region_name=instance._region_name, auth_url=instance._auth_url, endpoint_url=url, endpoint_type=instance._endpoint_type, token=instance._token, auth_strategy=instance._auth_strategy, insecure=instance._insecure, ca_cert=instance._ca_cert, retries=instance._retries, raise_errors=instance._raise_errors, session=instance._session, auth=instance._auth) return client
[ "def", "make_client", "(", "instance", ")", ":", "neutron_client", "=", "utils", ".", "get_client_class", "(", "API_NAME", ",", "instance", ".", "_api_version", ",", "API_VERSIONS", ",", ")", "instance", ".", "initialize", "(", ")", "url", "=", "instance", "...
https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/neutron/client.py#L27-L52
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/v6_0/client_factory.py
python
ClientFactoryV6_0.get_test_plan_client
(self)
return self._connection.get_client('azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient')
get_test_plan_client. Gets the 6.0 version of the TestPlanClient :rtype: :class:`<TestPlanClient> <azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient>`
get_test_plan_client. Gets the 6.0 version of the TestPlanClient :rtype: :class:`<TestPlanClient> <azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient>`
[ "get_test_plan_client", ".", "Gets", "the", "6", ".", "0", "version", "of", "the", "TestPlanClient", ":", "rtype", ":", ":", "class", ":", "<TestPlanClient", ">", "<azure", ".", "devops", ".", "v6_0", ".", "test_plan", ".", "test_plan_client", ".", "TestPlan...
def get_test_plan_client(self): """get_test_plan_client. Gets the 6.0 version of the TestPlanClient :rtype: :class:`<TestPlanClient> <azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient>` """ return self._connection.get_client('azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient')
[ "def", "get_test_plan_client", "(", "self", ")", ":", "return", "self", ".", "_connection", ".", "get_client", "(", "'azure.devops.v6_0.test_plan.test_plan_client.TestPlanClient'", ")" ]
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/v6_0/client_factory.py#L333-L338
poppy-project/pypot
c5d384fe23eef9f6ec98467f6f76626cdf20afb9
pypot/dynamixel/protocol/v2.py
python
DxlStatusPacket.from_string
(cls, data)
return cls(header.id, packet[8], tuple(packet[9:-2]))
[]
def from_string(cls, data): packet = bytearray(data) header = DxlPacketHeader.from_string(packet[:DxlPacketHeader.length]) if (len(packet) != DxlPacketHeader.length + header.packet_length or cls._checksum(packet) != packet[-2:]): raise ValueError('try to parse corrupted data ({})'.format(packet)) return cls(header.id, packet[8], tuple(packet[9:-2]))
[ "def", "from_string", "(", "cls", ",", "data", ")", ":", "packet", "=", "bytearray", "(", "data", ")", "header", "=", "DxlPacketHeader", ".", "from_string", "(", "packet", "[", ":", "DxlPacketHeader", ".", "length", "]", ")", "if", "(", "len", "(", "pa...
https://github.com/poppy-project/pypot/blob/c5d384fe23eef9f6ec98467f6f76626cdf20afb9/pypot/dynamixel/protocol/v2.py#L176-L185
plasticityai/magnitude
7ac0baeaf181263b661c3ae00643d21e3fd90216
pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py
python
GrammarState.is_finished
(self)
return not self._nonterminal_stack
u""" Have we finished producing our logical form? We have finished producing the logical form if and only if there are no more non-terminals on the stack.
u""" Have we finished producing our logical form? We have finished producing the logical form if and only if there are no more non-terminals on the stack.
[ "u", "Have", "we", "finished", "producing", "our", "logical", "form?", "We", "have", "finished", "producing", "the", "logical", "form", "if", "and", "only", "if", "there", "are", "no", "more", "non", "-", "terminals", "on", "the", "stack", "." ]
def is_finished(self) : u""" Have we finished producing our logical form? We have finished producing the logical form if and only if there are no more non-terminals on the stack. """ return not self._nonterminal_stack
[ "def", "is_finished", "(", "self", ")", ":", "return", "not", "self", ".", "_nonterminal_stack" ]
https://github.com/plasticityai/magnitude/blob/7ac0baeaf181263b661c3ae00643d21e3fd90216/pymagnitude/third_party/allennlp/nn/decoding/grammar_state.py#L68-L73
open-research/sumatra
2ff2a359e11712a7d17cf9346a0b676ab33e2074
sumatra/records.py
python
Record.command_line
(self)
return self.launch_mode.generate_command(self.executable, self.main_file, self.script_arguments)
Return the command-line string for the computation captured by this record.
Return the command-line string for the computation captured by this record.
[ "Return", "the", "command", "-", "line", "string", "for", "the", "computation", "captured", "by", "this", "record", "." ]
def command_line(self): """ Return the command-line string for the computation captured by this record. """ return self.launch_mode.generate_command(self.executable, self.main_file, self.script_arguments)
[ "def", "command_line", "(", "self", ")", ":", "return", "self", ".", "launch_mode", ".", "generate_command", "(", "self", ".", "executable", ",", "self", ".", "main_file", ",", "self", ".", "script_arguments", ")" ]
https://github.com/open-research/sumatra/blob/2ff2a359e11712a7d17cf9346a0b676ab33e2074/sumatra/records.py#L265-L270
qibinlou/SinaWeibo-Emotion-Classification
f336fc104abd68b0ec4180fe2ed80fafe49cb790
nltk/featstruct.py
python
_apply_forwards
(fstruct, forward, fs_class, visited)
return fstruct
Replace any feature structure that has a forward pointer with the target of its forward pointer (to preserve reentrancy).
Replace any feature structure that has a forward pointer with the target of its forward pointer (to preserve reentrancy).
[ "Replace", "any", "feature", "structure", "that", "has", "a", "forward", "pointer", "with", "the", "target", "of", "its", "forward", "pointer", "(", "to", "preserve", "reentrancy", ")", "." ]
def _apply_forwards(fstruct, forward, fs_class, visited): """ Replace any feature structure that has a forward pointer with the target of its forward pointer (to preserve reentrancy). """ # Follow our own forwards pointers (if any) while id(fstruct) in forward: fstruct = forward[id(fstruct)] # Visit each node only once: if id(fstruct) in visited: return visited.add(id(fstruct)) if _is_mapping(fstruct): items = fstruct.items() elif _is_sequence(fstruct): items = enumerate(fstruct) else: raise ValueError('Expected mapping or sequence') for fname, fval in items: if isinstance(fval, fs_class): # Replace w/ forwarded value. while id(fval) in forward: fval = forward[id(fval)] fstruct[fname] = fval # Recurse to child. _apply_forwards(fval, forward, fs_class, visited) return fstruct
[ "def", "_apply_forwards", "(", "fstruct", ",", "forward", ",", "fs_class", ",", "visited", ")", ":", "# Follow our own forwards pointers (if any)", "while", "id", "(", "fstruct", ")", "in", "forward", ":", "fstruct", "=", "forward", "[", "id", "(", "fstruct", ...
https://github.com/qibinlou/SinaWeibo-Emotion-Classification/blob/f336fc104abd68b0ec4180fe2ed80fafe49cb790/nltk/featstruct.py#L1549-L1573
kbandla/ImmunityDebugger
2abc03fb15c8f3ed0914e1175c4d8933977c73e3
1.84/Libs/libstackanalyze.py
python
FunctionBranches.getBranches
(self)
return self.branches
Get the function branches processed by the TraverseTree function. @rtype: LIST @return: a list of branches, each one is a list of Basic Block start address
Get the function branches processed by the TraverseTree function.
[ "Get", "the", "function", "branches", "processed", "by", "the", "TraverseTree", "function", "." ]
def getBranches(self): """ Get the function branches processed by the TraverseTree function. @rtype: LIST @return: a list of branches, each one is a list of Basic Block start address """ return self.branches
[ "def", "getBranches", "(", "self", ")", ":", "return", "self", ".", "branches" ]
https://github.com/kbandla/ImmunityDebugger/blob/2abc03fb15c8f3ed0914e1175c4d8933977c73e3/1.84/Libs/libstackanalyze.py#L510-L517
HazyResearch/fonduer
c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd
src/fonduer/candidates/models/implicit_span_mention.py
python
TemporaryImplicitSpanMention.__len__
(self)
return sum(map(len, self.words))
Get the length of the mention.
Get the length of the mention.
[ "Get", "the", "length", "of", "the", "mention", "." ]
def __len__(self) -> int: """Get the length of the mention.""" return sum(map(len, self.words))
[ "def", "__len__", "(", "self", ")", "->", "int", ":", "return", "sum", "(", "map", "(", "len", ",", "self", ".", "words", ")", ")" ]
https://github.com/HazyResearch/fonduer/blob/c9fd6b91998cd708ab95aeee3dfaf47b9e549ffd/src/fonduer/candidates/models/implicit_span_mention.py#L57-L59
django-haystack/django-haystack
b6dd72e6b5c97b782f5436b7bb4e8227ba6e3b06
haystack/query.py
python
SearchQuerySet.__getstate__
(self)
return obj_dict
For pickling.
For pickling.
[ "For", "pickling", "." ]
def __getstate__(self): """ For pickling. """ len(self) obj_dict = self.__dict__.copy() obj_dict["_iter"] = None obj_dict["log"] = None return obj_dict
[ "def", "__getstate__", "(", "self", ")", ":", "len", "(", "self", ")", "obj_dict", "=", "self", ".", "__dict__", ".", "copy", "(", ")", "obj_dict", "[", "\"_iter\"", "]", "=", "None", "obj_dict", "[", "\"log\"", "]", "=", "None", "return", "obj_dict" ]
https://github.com/django-haystack/django-haystack/blob/b6dd72e6b5c97b782f5436b7bb4e8227ba6e3b06/haystack/query.py#L60-L68
HuobiRDCenter/huobi_Python
c75a7fa8b31e99ffc1c173d74dcfcad83682e943
huobi/client/margin.py
python
MarginClient.post_cross_margin_create_loan_orders
(self, currency: 'str', amount: 'float')
return PostCrossMarginCreateLoanOrdersService(params).request(**self.__kwargs)
create cross margin loan orders :param currency: currency name (mandatory) :param amount: transfer amount (mandatory) :return: return order id.
create cross margin loan orders
[ "create", "cross", "margin", "loan", "orders" ]
def post_cross_margin_create_loan_orders(self, currency: 'str', amount: 'float') -> int: """ create cross margin loan orders :param currency: currency name (mandatory) :param amount: transfer amount (mandatory) :return: return order id. """ check_should_not_none(currency, "currency") check_should_not_none(amount, "amount") params = { "amount": amount, "currency": currency } from huobi.service.margin.post_cross_margin_create_loan_orders import PostCrossMarginCreateLoanOrdersService return PostCrossMarginCreateLoanOrdersService(params).request(**self.__kwargs)
[ "def", "post_cross_margin_create_loan_orders", "(", "self", ",", "currency", ":", "'str'", ",", "amount", ":", "'float'", ")", "->", "int", ":", "check_should_not_none", "(", "currency", ",", "\"currency\"", ")", "check_should_not_none", "(", "amount", ",", "\"amo...
https://github.com/HuobiRDCenter/huobi_Python/blob/c75a7fa8b31e99ffc1c173d74dcfcad83682e943/huobi/client/margin.py#L216-L234
sqlfluff/sqlfluff
c2278f41f270a29ef5ffc6b179236abf32dc18e1
src/sqlfluff/core/string_helpers.py
python
findall
(substr: str, in_str: str)
Yields all the positions sbstr within in_str. https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring
Yields all the positions sbstr within in_str.
[ "Yields", "all", "the", "positions", "sbstr", "within", "in_str", "." ]
def findall(substr: str, in_str: str) -> Iterator[int]: """Yields all the positions sbstr within in_str. https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring """ # Return nothing if one of the inputs is trivial if not substr or not in_str: return idx = in_str.find(substr) while idx != -1: yield idx idx = in_str.find(substr, idx + 1)
[ "def", "findall", "(", "substr", ":", "str", ",", "in_str", ":", "str", ")", "->", "Iterator", "[", "int", "]", ":", "# Return nothing if one of the inputs is trivial", "if", "not", "substr", "or", "not", "in_str", ":", "return", "idx", "=", "in_str", ".", ...
https://github.com/sqlfluff/sqlfluff/blob/c2278f41f270a29ef5ffc6b179236abf32dc18e1/src/sqlfluff/core/string_helpers.py#L19-L30
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/cmd.py
python
Cmd.default
(self, line)
Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns.
Called on an input line when the command prefix is not recognized.
[ "Called", "on", "an", "input", "line", "when", "the", "command", "prefix", "is", "not", "recognized", "." ]
def default(self, line): """Called on an input line when the command prefix is not recognized. If this method is not overridden, it prints an error message and returns. """ self.stdout.write('*** Unknown syntax: %s\n'%line)
[ "def", "default", "(", "self", ",", "line", ")", ":", "self", ".", "stdout", ".", "write", "(", "'*** Unknown syntax: %s\\n'", "%", "line", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/cmd.py#L231-L238
facebookresearch/ParlAI
e4d59c30eef44f1f67105961b82a83fd28d7d78b
parlai/core/dict.py
python
DictionaryAgent.__getitem__
(self, key)
Lookup the word or ID. If key is an int, returns the corresponding token. If it does not exist, return the unknown token. If key is a str, return the token's index. If the token is not in the dictionary, return the index of the unknown token. If there is no unknown token, return ``None``.
Lookup the word or ID.
[ "Lookup", "the", "word", "or", "ID", "." ]
def __getitem__(self, key): """ Lookup the word or ID. If key is an int, returns the corresponding token. If it does not exist, return the unknown token. If key is a str, return the token's index. If the token is not in the dictionary, return the index of the unknown token. If there is no unknown token, return ``None``. """ if type(key) == str: return self._word_lookup(key) if type(key) == int: return self._index_lookup(key)
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "if", "type", "(", "key", ")", "==", "str", ":", "return", "self", ".", "_word_lookup", "(", "key", ")", "if", "type", "(", "key", ")", "==", "int", ":", "return", "self", ".", "_index_lookup...
https://github.com/facebookresearch/ParlAI/blob/e4d59c30eef44f1f67105961b82a83fd28d7d78b/parlai/core/dict.py#L406-L418
accel-brain/accel-brain-code
86f489dc9be001a3bae6d053f48d6b57c0bedb95
Accel-Brain-Base/accelbrainbase/controllablemodel/_mxnet/transforming_auto_encoder_controller.py
python
TransformingAutoEncoderController.set_init_deferred_flag
(self, value)
setter for `bool` that means initialization in this class will be deferred or not.
setter for `bool` that means initialization in this class will be deferred or not.
[ "setter", "for", "bool", "that", "means", "initialization", "in", "this", "class", "will", "be", "deferred", "or", "not", "." ]
def set_init_deferred_flag(self, value): ''' setter for `bool` that means initialization in this class will be deferred or not.''' self.__init_deferred_flag = value
[ "def", "set_init_deferred_flag", "(", "self", ",", "value", ")", ":", "self", ".", "__init_deferred_flag", "=", "value" ]
https://github.com/accel-brain/accel-brain-code/blob/86f489dc9be001a3bae6d053f48d6b57c0bedb95/Accel-Brain-Base/accelbrainbase/controllablemodel/_mxnet/transforming_auto_encoder_controller.py#L555-L557
google/grr
8ad8a4d2c5a93c92729206b7771af19d92d4f915
grr/server/grr_response_server/gui/api_call_router_without_checks.py
python
ApiCallRouterWithoutChecks.GetVfsFileContentUpdateState
(self, args, context=None)
return api_vfs.ApiGetVfsFileContentUpdateStateHandler()
[]
def GetVfsFileContentUpdateState(self, args, context=None): return api_vfs.ApiGetVfsFileContentUpdateStateHandler()
[ "def", "GetVfsFileContentUpdateState", "(", "self", ",", "args", ",", "context", "=", "None", ")", ":", "return", "api_vfs", ".", "ApiGetVfsFileContentUpdateStateHandler", "(", ")" ]
https://github.com/google/grr/blob/8ad8a4d2c5a93c92729206b7771af19d92d4f915/grr/server/grr_response_server/gui/api_call_router_without_checks.py#L151-L152
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/lib-tk/ttk.py
python
Notebook.add
(self, child, **kw)
Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position.
Adds a new tab to the notebook.
[ "Adds", "a", "new", "tab", "to", "the", "notebook", "." ]
def add(self, child, **kw): """Adds a new tab to the notebook. If window is currently managed by the notebook but hidden, it is restored to its previous position.""" self.tk.call(self._w, "add", child, *(_format_optdict(kw)))
[ "def", "add", "(", "self", ",", "child", ",", "*", "*", "kw", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"add\"", ",", "child", ",", "*", "(", "_format_optdict", "(", "kw", ")", ")", ")" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/lib-tk/ttk.py#L860-L865
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/provisioningserver/rpc/osystems.py
python
get_os_release_title
(osystem, release)
Get the title for the operating systems release. :raises NoSuchOperatingSystem: If ``osystem`` is not found.
Get the title for the operating systems release.
[ "Get", "the", "title", "for", "the", "operating", "systems", "release", "." ]
def get_os_release_title(osystem, release): """Get the title for the operating systems release. :raises NoSuchOperatingSystem: If ``osystem`` is not found. """ try: osystem = OperatingSystemRegistry[osystem] except KeyError: raise exceptions.NoSuchOperatingSystem(osystem) else: title = osystem.get_release_title(release) if title is None: return "" return title
[ "def", "get_os_release_title", "(", "osystem", ",", "release", ")", ":", "try", ":", "osystem", "=", "OperatingSystemRegistry", "[", "osystem", "]", "except", "KeyError", ":", "raise", "exceptions", ".", "NoSuchOperatingSystem", "(", "osystem", ")", "else", ":",...
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/rpc/osystems.py#L57-L70
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/OrangeCanvas/canvas/items/nodeitem.py
python
NodeItem.inputAnchors
(self)
return self.inputAnchorItem.anchorPoints()
Return a list of all input anchor points.
Return a list of all input anchor points.
[ "Return", "a", "list", "of", "all", "input", "anchor", "points", "." ]
def inputAnchors(self): """ Return a list of all input anchor points. """ return self.inputAnchorItem.anchorPoints()
[ "def", "inputAnchors", "(", "self", ")", ":", "return", "self", ".", "inputAnchorItem", ".", "anchorPoints", "(", ")" ]
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/OrangeCanvas/canvas/items/nodeitem.py#L1162-L1166
mpenning/ciscoconfparse
a6a176e6ceac7c5f3e974272fa70273476ba84a3
ciscoconfparse/models_nxos.py
python
NXOSRouteLine.tag
(self)
return self.route_info["tag"] or ""
[]
def tag(self): return self.route_info["tag"] or ""
[ "def", "tag", "(", "self", ")", ":", "return", "self", ".", "route_info", "[", "\"tag\"", "]", "or", "\"\"" ]
https://github.com/mpenning/ciscoconfparse/blob/a6a176e6ceac7c5f3e974272fa70273476ba84a3/ciscoconfparse/models_nxos.py#L2234-L2235
openedx/ecommerce
db6c774e239e5aa65e5a6151995073d364e8c896
ecommerce/courses/management/commands/create_enrollment_codes.py
python
Command._generate_enrollment_codes_from_db
(self, batch_limit)
return total_courses, failed_courses
Generate enrollment codes for the course. Arguments: batch_limit (int): How many courses to fetch from db to process in each batch. Returns: (total_course, failed_course): a tuple containing count of course processed and a list containing ids of courses whose enrollment codes could not be generated.
Generate enrollment codes for the course.
[ "Generate", "enrollment", "codes", "for", "the", "course", "." ]
def _generate_enrollment_codes_from_db(self, batch_limit): """ Generate enrollment codes for the course. Arguments: batch_limit (int): How many courses to fetch from db to process in each batch. Returns: (total_course, failed_course): a tuple containing count of course processed and a list containing ids of courses whose enrollment codes could not be generated. """ failed_courses = [] total_courses = 0 courses = Course.objects.all()[0:batch_limit] while courses: total_courses += len(courses) logger.info('Creating enrollment code for %d courses.', courses.count()) for course in courses: try: self._generate_enrollment_code(course) except CourseInfoError as error: logger.error( 'Enrollment code generation failed for "%s" course. Because %s', course.id, str(error), ) failed_courses.append(course.id) courses = Course.objects.all()[total_courses:total_courses + batch_limit] return total_courses, failed_courses
[ "def", "_generate_enrollment_codes_from_db", "(", "self", ",", "batch_limit", ")", ":", "failed_courses", "=", "[", "]", "total_courses", "=", "0", "courses", "=", "Course", ".", "objects", ".", "all", "(", ")", "[", "0", ":", "batch_limit", "]", "while", ...
https://github.com/openedx/ecommerce/blob/db6c774e239e5aa65e5a6151995073d364e8c896/ecommerce/courses/management/commands/create_enrollment_codes.py#L66-L97
cgre-aachen/gempy
6ad16c46fc6616c9f452fba85d31ce32decd8b10
gempy/plot/vista.py
python
GemPyToVista.set_scalar_data
(self, regular_grid, data: Union[dict, gp.Solution, str] = 'Default', scalar_field='all', series='', cmap='viridis')
return regular_grid, cmap
Args: regular_grid: data: dictionary or solution scalar_field: if data is a gp.Solutions object, name of the grid that you want to plot. series: cmap:
Args: regular_grid: data: dictionary or solution scalar_field: if data is a gp.Solutions object, name of the grid that you want to plot. series: cmap:
[ "Args", ":", "regular_grid", ":", "data", ":", "dictionary", "or", "solution", "scalar_field", ":", "if", "data", "is", "a", "gp", ".", "Solutions", "object", "name", "of", "the", "grid", "that", "you", "want", "to", "plot", ".", "series", ":", "cmap", ...
def set_scalar_data(self, regular_grid, data: Union[dict, gp.Solution, str] = 'Default', scalar_field='all', series='', cmap='viridis'): """ Args: regular_grid: data: dictionary or solution scalar_field: if data is a gp.Solutions object, name of the grid that you want to plot. series: cmap: """ if data == 'Default': data = self.model.solutions if isinstance(data, gp.Solution): if scalar_field == 'lith' or scalar_field == 'all': regular_grid['id'] = data.lith_block hex_colors = list(self._get_color_lot(is_faults=True, is_basement=True)) cmap = mcolors.ListedColormap(hex_colors) if scalar_field == 'scalar' or scalar_field == 'all' or 'sf_' in scalar_field: scalar_field_ = 'sf_' for e, series in enumerate(self.model._stack.df.groupby('isActive').groups[True]): regular_grid[scalar_field_ + series] = data.scalar_field_matrix[e] if (scalar_field == 'values' or scalar_field == 'all' or 'values_' in scalar_field) and\ data.values_matrix.shape[0] \ != 0: scalar_field_ = 'values_' for e, lith_property in enumerate(self.model._surfaces.df.columns[self.model._surfaces._n_properties:]): regular_grid[scalar_field_ + lith_property] = data.values_matrix[e] if type(data) == dict: for key in data: regular_grid[key] = data[key] if scalar_field == 'all' or scalar_field == 'lith': scalar_field_ = 'lith' series = '' # else: # scalar_field_ = regular_grid.scalar_names[-1] # series = '' self.set_active_scalar_fields(scalar_field_ + series, regular_grid, update_cmap=False) return regular_grid, cmap
[ "def", "set_scalar_data", "(", "self", ",", "regular_grid", ",", "data", ":", "Union", "[", "dict", ",", "gp", ".", "Solution", ",", "str", "]", "=", "'Default'", ",", "scalar_field", "=", "'all'", ",", "series", "=", "''", ",", "cmap", "=", "'viridis'...
https://github.com/cgre-aachen/gempy/blob/6ad16c46fc6616c9f452fba85d31ce32decd8b10/gempy/plot/vista.py#L702-L746
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/Scale.py
python
_log2
(num)
return math.log(num) / math.log(2)
[]
def _log2(num): return math.log(num) / math.log(2)
[ "def", "_log2", "(", "num", ")", ":", "return", "math", ".", "log", "(", "num", ")", "/", "math", ".", "log", "(", "2", ")" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/Scale.py#L15-L16
Trusted-AI/adversarial-robustness-toolbox
9fabffdbb92947efa1ecc5d825d634d30dfbaf29
art/metrics/verification_decisions_trees.py
python
Box.__init__
(self, intervals: Optional[Dict[int, Interval]] = None)
A box of intervals. :param intervals: A dictionary of intervals with features as keys.
A box of intervals.
[ "A", "box", "of", "intervals", "." ]
def __init__(self, intervals: Optional[Dict[int, Interval]] = None) -> None: """ A box of intervals. :param intervals: A dictionary of intervals with features as keys. """ if intervals is None: self.intervals = dict() else: self.intervals = intervals
[ "def", "__init__", "(", "self", ",", "intervals", ":", "Optional", "[", "Dict", "[", "int", ",", "Interval", "]", "]", "=", "None", ")", "->", "None", ":", "if", "intervals", "is", "None", ":", "self", ".", "intervals", "=", "dict", "(", ")", "else...
https://github.com/Trusted-AI/adversarial-robustness-toolbox/blob/9fabffdbb92947efa1ecc5d825d634d30dfbaf29/art/metrics/verification_decisions_trees.py#L56-L65
nopernik/mpDNS
b17dc39e7068406df82cb3431b3042e74e520cf9
circuits/net/sockets.py
python
UDPServer._create_socket
(self)
return sock
[]
def _create_socket(self): sock = socket(self.socket_family, SOCK_DGRAM) sock.bind(self._bind) sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.setblocking(False) return sock
[ "def", "_create_socket", "(", "self", ")", ":", "sock", "=", "socket", "(", "self", ".", "socket_family", ",", "SOCK_DGRAM", ")", "sock", ".", "bind", "(", "self", ".", "_bind", ")", "sock", ".", "setsockopt", "(", "SOL_SOCKET", ",", "SO_BROADCAST", ",",...
https://github.com/nopernik/mpDNS/blob/b17dc39e7068406df82cb3431b3042e74e520cf9/circuits/net/sockets.py#L725-L735