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
pywren/pywren
d898af6418a2d915c3984152de07d95e32c9789a
pywren/storage/s3_backend.py
python
S3Backend.put_object
(self, key, data)
Put an object in S3. Override the object if the key already exists. :param key: key of the object. :param data: data of the object :type data: str/bytes :return: None
Put an object in S3. Override the object if the key already exists. :param key: key of the object. :param data: data of the object :type data: str/bytes :return: None
[ "Put", "an", "object", "in", "S3", ".", "Override", "the", "object", "if", "the", "key", "already", "exists", ".", ":", "param", "key", ":", "key", "of", "the", "object", ".", ":", "param", "data", ":", "data", "of", "the", "object", ":", "type", "...
def put_object(self, key, data): """ Put an object in S3. Override the object if the key already exists. :param key: key of the object. :param data: data of the object :type data: str/bytes :return: None """ self.s3client.put_object(Bucket=self.s3_bucket, Key=key, Body=data)
[ "def", "put_object", "(", "self", ",", "key", ",", "data", ")", ":", "self", ".", "s3client", ".", "put_object", "(", "Bucket", "=", "self", ".", "s3_bucket", ",", "Key", "=", "key", ",", "Body", "=", "data", ")" ]
https://github.com/pywren/pywren/blob/d898af6418a2d915c3984152de07d95e32c9789a/pywren/storage/s3_backend.py#L33-L41
shamangary/FSA-Net
4361d0e48103bb215d15734220c9d17e6812bb48
lib/FSANET_model.py
python
BaseFSANet.ssr_S_model_build
(self, num_primcaps, m_dim)
return Model(inputs=[input_s1_preS, input_s2_preS, input_s3_preS],outputs=primcaps, name='ssr_S_model')
[]
def ssr_S_model_build(self, num_primcaps, m_dim): input_s1_preS = Input((self.map_xy_size,self.map_xy_size,64)) input_s2_preS = Input((self.map_xy_size,self.map_xy_size,64)) input_s3_preS = Input((self.map_xy_size,self.map_xy_size,64)) feat_S_model = self.ssr_feat_S_model_build(m_dim) SR_matrix_s1,feat_s1_preS = feat_S_model(input_s1_preS) SR_matrix_s2,feat_s2_preS = feat_S_model(input_s2_preS) SR_matrix_s3,feat_s3_preS = feat_S_model(input_s3_preS) feat_pre_concat = Concatenate()([feat_s1_preS,feat_s2_preS,feat_s3_preS]) SL_matrix = Dense(int(num_primcaps/3)*m_dim,activation='sigmoid')(feat_pre_concat) SL_matrix = Reshape((int(num_primcaps/3),m_dim))(SL_matrix) S_matrix_s1 = MatrixMultiplyLayer(name="S_matrix_s1")([SL_matrix,SR_matrix_s1]) S_matrix_s2 = MatrixMultiplyLayer(name='S_matrix_s2')([SL_matrix,SR_matrix_s2]) S_matrix_s3 = MatrixMultiplyLayer(name='S_matrix_s3')([SL_matrix,SR_matrix_s3]) # Very important!!! Without this training won't converge. # norm_S_s1 = Lambda(lambda x: K.tile(K.sum(x,axis=-1,keepdims=True),(1,1,64)))(S_matrix_s1) norm_S_s1 = MatrixNormLayer(tile_count=64)(S_matrix_s1) norm_S_s2 = MatrixNormLayer(tile_count=64)(S_matrix_s2) norm_S_s3 = MatrixNormLayer(tile_count=64)(S_matrix_s3) feat_s1_pre = Reshape((self.map_xy_size*self.map_xy_size,64))(input_s1_preS) feat_s2_pre = Reshape((self.map_xy_size*self.map_xy_size,64))(input_s2_preS) feat_s3_pre = Reshape((self.map_xy_size*self.map_xy_size,64))(input_s3_preS) feat_pre_concat = Concatenate(axis=1)([feat_s1_pre, feat_s2_pre, feat_s3_pre]) # Warining: don't use keras's 'K.dot'. It is very weird when high dimension is used. # https://github.com/keras-team/keras/issues/9779 # Make sure 'tf.matmul' is used # primcaps = Lambda(lambda x: tf.matmul(x[0],x[1])/x[2])([S_matrix,feat_pre_concat, norm_S]) primcaps_s1 = PrimCapsLayer()([S_matrix_s1,feat_pre_concat, norm_S_s1]) primcaps_s2 = PrimCapsLayer()([S_matrix_s2,feat_pre_concat, norm_S_s2]) primcaps_s3 = PrimCapsLayer()([S_matrix_s3,feat_pre_concat, norm_S_s3]) primcaps = Concatenate(axis=1)([primcaps_s1,primcaps_s2,primcaps_s3]) return Model(inputs=[input_s1_preS, input_s2_preS, input_s3_preS],outputs=primcaps, name='ssr_S_model')
[ "def", "ssr_S_model_build", "(", "self", ",", "num_primcaps", ",", "m_dim", ")", ":", "input_s1_preS", "=", "Input", "(", "(", "self", ".", "map_xy_size", ",", "self", ".", "map_xy_size", ",", "64", ")", ")", "input_s2_preS", "=", "Input", "(", "(", "sel...
https://github.com/shamangary/FSA-Net/blob/4361d0e48103bb215d15734220c9d17e6812bb48/lib/FSANET_model.py#L365-L406
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/tsa/ardl/model.py
python
UECM.from_ardl
( cls, ardl: ARDL, missing: Literal["none", "drop", "raise"] = "none" )
return cls( ardl.data.orig_endog, ar_lags, ardl.data.orig_exog, uecm_lags, trend=ardl.trend, fixed=ardl.fixed, seasonal=ardl.seasonal, hold_back=ardl.hold_back, period=ardl.period, causal=ardl.causal, missing=missing, deterministic=ardl.deterministic, )
Construct a UECM from an ARDL model Parameters ---------- ardl : ARDL The ARDL model instance missing : {"none", "drop", "raise"}, default "none" How to treat missing observations. Returns ------- UECM The UECM model instance Notes ----- The lag requirements for a UECM are stricter than for an ARDL. Any variable that is included in the UECM must have a lag length of at least 1. Additionally, the included lags must be contiguous starting at 0 if non-causal or 1 if causal.
Construct a UECM from an ARDL model
[ "Construct", "a", "UECM", "from", "an", "ARDL", "model" ]
def from_ardl( cls, ardl: ARDL, missing: Literal["none", "drop", "raise"] = "none" ): """ Construct a UECM from an ARDL model Parameters ---------- ardl : ARDL The ARDL model instance missing : {"none", "drop", "raise"}, default "none" How to treat missing observations. Returns ------- UECM The UECM model instance Notes ----- The lag requirements for a UECM are stricter than for an ARDL. Any variable that is included in the UECM must have a lag length of at least 1. Additionally, the included lags must be contiguous starting at 0 if non-causal or 1 if causal. """ err = ( "UECM can only be created from ARDL models that include all " "{var_typ} lags up to the maximum lag in the model." ) uecm_lags = {} dl_lags = ardl.dl_lags for key, val in dl_lags.items(): max_val = max(val) if len(dl_lags[key]) < (max_val + int(not ardl.causal)): raise ValueError(err.format(var_typ="exogenous")) uecm_lags[key] = max_val if ardl.ar_lags is None: ar_lags = None else: max_val = max(ardl.ar_lags) if len(ardl.ar_lags) != max_val: raise ValueError(err.format(var_typ="endogenous")) ar_lags = max_val return cls( ardl.data.orig_endog, ar_lags, ardl.data.orig_exog, uecm_lags, trend=ardl.trend, fixed=ardl.fixed, seasonal=ardl.seasonal, hold_back=ardl.hold_back, period=ardl.period, causal=ardl.causal, missing=missing, deterministic=ardl.deterministic, )
[ "def", "from_ardl", "(", "cls", ",", "ardl", ":", "ARDL", ",", "missing", ":", "Literal", "[", "\"none\"", ",", "\"drop\"", ",", "\"raise\"", "]", "=", "\"none\"", ")", ":", "err", "=", "(", "\"UECM can only be created from ARDL models that include all \"", "\"{...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/tsa/ardl/model.py#L1929-L1986
rizar/attention-lvcsr
1ae52cafdd8419874846f9544a299eef9c758f3b
libs/Theano/theano/tensor/opt.py
python
local_useless_inc_subtensor
(node)
Remove IncSubtensor, when we overwrite the full inputs with the new value.
Remove IncSubtensor, when we overwrite the full inputs with the new value.
[ "Remove", "IncSubtensor", "when", "we", "overwrite", "the", "full", "inputs", "with", "the", "new", "value", "." ]
def local_useless_inc_subtensor(node): """ Remove IncSubtensor, when we overwrite the full inputs with the new value. """ if not isinstance(node.op, IncSubtensor): return if node.op.set_instead_of_inc is False: # This is an IncSubtensor, so the init value must be zeros try: c = get_scalar_constant_value(node.inputs[0]) if c != 0: return except NotScalarConstantError: return if (node.inputs[0].ndim != node.inputs[1].ndim or node.inputs[0].broadcastable != node.inputs[1].broadcastable): # FB: I didn't check if this case can happen, but this opt # don't support it. return # We have a SetSubtensor or an IncSubtensor on zeros # If is this IncSubtensor useful? # Check that we keep all the original data. # Put the constant inputs in the slice. idx_cst = get_idx_list(node.inputs[1:], node.op.idx_list) if all(isinstance(e, slice) and e.start is None and e.stop is None and (e.step is None or T.extract_constant(e.step) == -1) for e in idx_cst): # IncSubtensor broadcast node.inputs[1] on node.inputs[0] # based on run time shapes, so we must check they are the same. if not hasattr(node.fgraph, 'shape_feature'): return if not node.fgraph.shape_feature.same_shape(node.inputs[0], node.inputs[1]): return # There is no reverse, so we don't need a replacement. if all(e.step is None for e in node.op.idx_list): # They are the same shape, so we can remore this IncSubtensor return [node.inputs[1]] ret = Subtensor(node.op.idx_list)(*node.inputs[1:]) # Copy over previous output stacktrace copy_stack_trace(node.outputs, ret) return [ret]
[ "def", "local_useless_inc_subtensor", "(", "node", ")", ":", "if", "not", "isinstance", "(", "node", ".", "op", ",", "IncSubtensor", ")", ":", "return", "if", "node", ".", "op", ".", "set_instead_of_inc", "is", "False", ":", "# This is an IncSubtensor, so the in...
https://github.com/rizar/attention-lvcsr/blob/1ae52cafdd8419874846f9544a299eef9c758f3b/libs/Theano/theano/tensor/opt.py#L2304-L2349
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Tools/scripts/patchcheck.py
python
normalize_c_whitespace
(file_paths)
return fixed
Report if any C files
Report if any C files
[ "Report", "if", "any", "C", "files" ]
def normalize_c_whitespace(file_paths): """Report if any C files """ fixed = [] for path in file_paths: abspath = os.path.join(SRCDIR, path) with open(abspath, 'r') as f: if '\t' not in f.read(): continue untabify.process(abspath, 8, verbose=False) fixed.append(path) return fixed
[ "def", "normalize_c_whitespace", "(", "file_paths", ")", ":", "fixed", "=", "[", "]", "for", "path", "in", "file_paths", ":", "abspath", "=", "os", ".", "path", ".", "join", "(", "SRCDIR", ",", "path", ")", "with", "open", "(", "abspath", ",", "'r'", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Tools/scripts/patchcheck.py#L104-L114
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/swift/swift/common/middleware/recon.py
python
ReconMiddleware.get_socket_info
(self, openr=open)
return sockstat
get info from /proc/net/sockstat and sockstat6 Note: The mem value is actually kernel pages, but we return bytes allocated based on the systems page size.
get info from /proc/net/sockstat and sockstat6
[ "get", "info", "from", "/", "proc", "/", "net", "/", "sockstat", "and", "sockstat6" ]
def get_socket_info(self, openr=open): """ get info from /proc/net/sockstat and sockstat6 Note: The mem value is actually kernel pages, but we return bytes allocated based on the systems page size. """ sockstat = {} try: with openr('/proc/net/sockstat', 'r') as proc_sockstat: for entry in proc_sockstat: if entry.startswith("TCP: inuse"): tcpstats = entry.split() sockstat['tcp_in_use'] = int(tcpstats[2]) sockstat['orphan'] = int(tcpstats[4]) sockstat['time_wait'] = int(tcpstats[6]) sockstat['tcp_mem_allocated_bytes'] = \ int(tcpstats[10]) * getpagesize() except IOError as e: if e.errno != errno.ENOENT: raise try: with openr('/proc/net/sockstat6', 'r') as proc_sockstat6: for entry in proc_sockstat6: if entry.startswith("TCP6: inuse"): sockstat['tcp6_in_use'] = int(entry.split()[2]) except IOError as e: if e.errno != errno.ENOENT: raise return sockstat
[ "def", "get_socket_info", "(", "self", ",", "openr", "=", "open", ")", ":", "sockstat", "=", "{", "}", "try", ":", "with", "openr", "(", "'/proc/net/sockstat'", ",", "'r'", ")", "as", "proc_sockstat", ":", "for", "entry", "in", "proc_sockstat", ":", "if"...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/swift/swift/common/middleware/recon.py#L243-L272
asterisk/ari-py
1647d79176d9ac0dacf4655ca6cb07bd70351f62
ari/model.py
python
Channel.__init__
(self, client, channel_json)
[]
def __init__(self, client, channel_json): super(Channel, self).__init__( client, client.swagger.channels, channel_json, client.on_channel_event)
[ "def", "__init__", "(", "self", ",", "client", ",", "channel_json", ")", ":", "super", "(", "Channel", ",", "self", ")", ".", "__init__", "(", "client", ",", "client", ".", "swagger", ".", "channels", ",", "channel_json", ",", "client", ".", "on_channel_...
https://github.com/asterisk/ari-py/blob/1647d79176d9ac0dacf4655ca6cb07bd70351f62/ari/model.py#L200-L203
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/manifolds/differentiable/de_rham_cohomology.py
python
DeRhamCohomologyRing._element_constructor_
(self, x)
return self.element_class(self, x)
r""" Construct an element of ``self``. TESTS:: sage: M = Manifold(2, 'M') sage: X.<x,y> = M.chart() sage: C = M.de_rham_complex() sage: H = C.cohomology() sage: H._element_constructor_(C.one()) [one] Non-cycle element:: sage: omega = M.diff_form(1, name='omega') sage: omega[0] = y sage: omega.display() omega = y dx sage: H(omega) Traceback (most recent call last): ... ValueError: Mixed differential form omega on the 2-dimensional differentiable manifold M must be a closed form
r""" Construct an element of ``self``.
[ "r", "Construct", "an", "element", "of", "self", "." ]
def _element_constructor_(self, x): r""" Construct an element of ``self``. TESTS:: sage: M = Manifold(2, 'M') sage: X.<x,y> = M.chart() sage: C = M.de_rham_complex() sage: H = C.cohomology() sage: H._element_constructor_(C.one()) [one] Non-cycle element:: sage: omega = M.diff_form(1, name='omega') sage: omega[0] = y sage: omega.display() omega = y dx sage: H(omega) Traceback (most recent call last): ... ValueError: Mixed differential form omega on the 2-dimensional differentiable manifold M must be a closed form """ if isinstance(x, CharacteristicCohomologyClassRingElement): x = x.representative() elif x not in self._module: raise TypeError(f"{x} must be an element of {self._module}") x = self._module(x) if x.derivative() != 0: raise ValueError(f"{x} must be a closed form") return self.element_class(self, x)
[ "def", "_element_constructor_", "(", "self", ",", "x", ")", ":", "if", "isinstance", "(", "x", ",", "CharacteristicCohomologyClassRingElement", ")", ":", "x", "=", "x", ".", "representative", "(", ")", "elif", "x", "not", "in", "self", ".", "_module", ":",...
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/manifolds/differentiable/de_rham_cohomology.py#L391-L424
deanishe/alfred-vpn-manager
f5d0dd1433ea69b1517d4866a12b1118097057b9
src/vpn.py
python
timed
(name=None)
Context manager that logs execution time.
Context manager that logs execution time.
[ "Context", "manager", "that", "logs", "execution", "time", "." ]
def timed(name=None): """Context manager that logs execution time.""" name = name or '' start_time = time() yield log.debug('[%0.2fs] %s', time() - start_time, name)
[ "def", "timed", "(", "name", "=", "None", ")", ":", "name", "=", "name", "or", "''", "start_time", "=", "time", "(", ")", "yield", "log", ".", "debug", "(", "'[%0.2fs] %s'", ",", "time", "(", ")", "-", "start_time", ",", "name", ")" ]
https://github.com/deanishe/alfred-vpn-manager/blob/f5d0dd1433ea69b1517d4866a12b1118097057b9/src/vpn.py#L80-L85
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.2/django/utils/translation/trans_real.py
python
to_locale
(language, to_lower=False)
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us).
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us).
[ "Turns", "a", "language", "name", "(", "en", "-", "us", ")", "into", "a", "locale", "name", "(", "en_US", ")", ".", "If", "to_lower", "is", "True", "the", "last", "component", "is", "lower", "-", "cased", "(", "en_us", ")", "." ]
def to_locale(language, to_lower=False): """ Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is True, the last component is lower-cased (en_us). """ p = language.find('-') if p >= 0: if to_lower: return language[:p].lower()+'_'+language[p+1:].lower() else: # Get correct locale for sr-latn if len(language[p+1:]) > 2: return language[:p].lower()+'_'+language[p+1].upper()+language[p+2:].lower() return language[:p].lower()+'_'+language[p+1:].upper() else: return language.lower()
[ "def", "to_locale", "(", "language", ",", "to_lower", "=", "False", ")", ":", "p", "=", "language", ".", "find", "(", "'-'", ")", "if", "p", ">=", "0", ":", "if", "to_lower", ":", "return", "language", "[", ":", "p", "]", ".", "lower", "(", ")", ...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.2/django/utils/translation/trans_real.py#L34-L49
dump247/aws-mock-metadata
ec85bc8c6f41afa8fa624898d6ba1ee5315ebcc2
metadata/bottle.py
python
BaseRequest.json
(self)
return None
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion.
[ "If", "the", "Content", "-", "Type", "header", "is", "application", "/", "json", "this", "property", "holds", "the", "parsed", "content", "of", "the", "request", "body", ".", "Only", "requests", "smaller", "than", ":", "attr", ":", "MEMFILE_MAX", "are", "p...
def json(self): ''' If the ``Content-Type`` header is ``application/json``, this property holds the parsed content of the request body. Only requests smaller than :attr:`MEMFILE_MAX` are processed to avoid memory exhaustion. ''' if 'application/json' in self.environ.get('CONTENT_TYPE', ''): return json_loads(self._get_body_string()) return None
[ "def", "json", "(", "self", ")", ":", "if", "'application/json'", "in", "self", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "''", ")", ":", "return", "json_loads", "(", "self", ".", "_get_body_string", "(", ")", ")", "return", "None" ]
https://github.com/dump247/aws-mock-metadata/blob/ec85bc8c6f41afa8fa624898d6ba1ee5315ebcc2/metadata/bottle.py#L1108-L1115
digidotcom/xbee-python
0757f4be0017530c205175fbee8f9f61be9614d1
digi/xbee/filesystem.py
python
LocalXBeeFileSystemManager._is_function_supported
(self, function)
return function.cmd_name in self._supported_functions
Returns whether the specified file system function is supported or not. Args: function (:class:`._FilesystemFunction`): The file system function to check. Returns: Boolean: `True` if the specified file system function is supported, `False` otherwise.
Returns whether the specified file system function is supported or not.
[ "Returns", "whether", "the", "specified", "file", "system", "function", "is", "supported", "or", "not", "." ]
def _is_function_supported(self, function): """ Returns whether the specified file system function is supported or not. Args: function (:class:`._FilesystemFunction`): The file system function to check. Returns: Boolean: `True` if the specified file system function is supported, `False` otherwise. """ if not isinstance(function, _FilesystemFunction): return False return function.cmd_name in self._supported_functions
[ "def", "_is_function_supported", "(", "self", ",", "function", ")", ":", "if", "not", "isinstance", "(", "function", ",", "_FilesystemFunction", ")", ":", "return", "False", "return", "function", ".", "cmd_name", "in", "self", ".", "_supported_functions" ]
https://github.com/digidotcom/xbee-python/blob/0757f4be0017530c205175fbee8f9f61be9614d1/digi/xbee/filesystem.py#L2674-L2689
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v2alpha1_cron_job_spec.py
python
V2alpha1CronJobSpec.suspend
(self, suspend)
Sets the suspend of this V2alpha1CronJobSpec. This flag tells the controller to suspend subsequent executions, it does not apply to already started executions. Defaults to false. # noqa: E501 :param suspend: The suspend of this V2alpha1CronJobSpec. # noqa: E501 :type: bool
Sets the suspend of this V2alpha1CronJobSpec.
[ "Sets", "the", "suspend", "of", "this", "V2alpha1CronJobSpec", "." ]
def suspend(self, suspend): """Sets the suspend of this V2alpha1CronJobSpec. This flag tells the controller to suspend subsequent executions, it does not apply to already started executions. Defaults to false. # noqa: E501 :param suspend: The suspend of this V2alpha1CronJobSpec. # noqa: E501 :type: bool """ self._suspend = suspend
[ "def", "suspend", "(", "self", ",", "suspend", ")", ":", "self", ".", "_suspend", "=", "suspend" ]
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v2alpha1_cron_job_spec.py#L235-L244
orbingol/NURBS-Python
8ae8b127eb0b130a25a6c81e98e90f319733bca0
geomdl/compatibility.py
python
generate_ctrlpts_weights
(ctrlpts)
return new_ctrlpts
Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list
Generates unweighted control points from weighted ones in 1-D.
[ "Generates", "unweighted", "control", "points", "from", "weighted", "ones", "in", "1", "-", "D", "." ]
def generate_ctrlpts_weights(ctrlpts): """ Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Divide control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt / cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
[ "def", "generate_ctrlpts_weights", "(", "ctrlpts", ")", ":", "# Divide control points by weight", "new_ctrlpts", "=", "[", "]", "for", "cpt", "in", "ctrlpts", ":", "temp", "=", "[", "float", "(", "pt", "/", "cpt", "[", "-", "1", "]", ")", "for", "pt", "i...
https://github.com/orbingol/NURBS-Python/blob/8ae8b127eb0b130a25a6c81e98e90f319733bca0/geomdl/compatibility.py#L139-L160
django/django
0a17666045de6739ae1c2ac695041823d5f827f7
django/template/base.py
python
DebugLexer.tokenize
(self)
return result
Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True.
Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True.
[ "Split", "a", "template", "string", "into", "tokens", "and", "annotates", "each", "token", "with", "its", "start", "and", "end", "position", "in", "the", "source", ".", "This", "is", "slower", "than", "the", "default", "lexer", "so", "only", "use", "it", ...
def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ # For maintainability, it is helpful if the implementation below can # continue to closely parallel Lexer.tokenize()'s implementation. in_tag = False lineno = 1 result = [] for token_string, position in self._tag_re_split(): if token_string: result.append(self.create_token(token_string, position, lineno, in_tag)) lineno += token_string.count('\n') in_tag = not in_tag return result
[ "def", "tokenize", "(", "self", ")", ":", "# For maintainability, it is helpful if the implementation below can", "# continue to closely parallel Lexer.tokenize()'s implementation.", "in_tag", "=", "False", "lineno", "=", "1", "result", "=", "[", "]", "for", "token_string", "...
https://github.com/django/django/blob/0a17666045de6739ae1c2ac695041823d5f827f7/django/template/base.py#L414-L430
AutodeskRoboticsLab/Mimic
85447f0d346be66988303a6a054473d92f1ed6f4
mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/widgets/SpinBox.py
python
SpinBox.setRange
(self, r0, r1)
Set the upper and lower limits for values in the spinbox.
Set the upper and lower limits for values in the spinbox.
[ "Set", "the", "upper", "and", "lower", "limits", "for", "values", "in", "the", "spinbox", "." ]
def setRange(self, r0, r1): """Set the upper and lower limits for values in the spinbox. """ self.setOpts(bounds = [r0,r1])
[ "def", "setRange", "(", "self", ",", "r0", ",", "r1", ")", ":", "self", ".", "setOpts", "(", "bounds", "=", "[", "r0", ",", "r1", "]", ")" ]
https://github.com/AutodeskRoboticsLab/Mimic/blob/85447f0d346be66988303a6a054473d92f1ed6f4/mimic/scripts/extern/pyqtgraph_0_11_0_dev0/pyqtgraph/widgets/SpinBox.py#L262-L265
pulp/pulp
a0a28d804f997b6f81c391378aff2e4c90183df9
nodes/common/pulp_node/error.py
python
ErrorList.update
(self, **details)
Update the details of all contained errors. :param details: A details dictionary. :type details: dict
Update the details of all contained errors. :param details: A details dictionary. :type details: dict
[ "Update", "the", "details", "of", "all", "contained", "errors", ".", ":", "param", "details", ":", "A", "details", "dictionary", ".", ":", "type", "details", ":", "dict" ]
def update(self, **details): """ Update the details of all contained errors. :param details: A details dictionary. :type details: dict """ for e in self: e.details.update(details)
[ "def", "update", "(", "self", ",", "*", "*", "details", ")", ":", "for", "e", "in", "self", ":", "e", ".", "details", ".", "update", "(", "details", ")" ]
https://github.com/pulp/pulp/blob/a0a28d804f997b6f81c391378aff2e4c90183df9/nodes/common/pulp_node/error.py#L223-L230
giantbranch/python-hacker-code
addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d
我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/malware/apihooks.py
python
Hook._module_name
(self, module)
return str(module.BaseDllName or '') or str(module.FullDllName or '') or '<unknown>'
Return a sanitized module name
Return a sanitized module name
[ "Return", "a", "sanitized", "module", "name" ]
def _module_name(self, module): """Return a sanitized module name""" # The module can't be identified if not module: return '<unknown>' # The module is a string name like "ntdll.dll" if isinstance(module, basic.String) or isinstance(module, str): return str(module) # The module is a _LDR_DATA_TABLE_ENTRY return str(module.BaseDllName or '') or str(module.FullDllName or '') or '<unknown>'
[ "def", "_module_name", "(", "self", ",", "module", ")", ":", "# The module can't be identified ", "if", "not", "module", ":", "return", "'<unknown>'", "# The module is a string name like \"ntdll.dll\"", "if", "isinstance", "(", "module", ",", "basic", ".", "String", "...
https://github.com/giantbranch/python-hacker-code/blob/addbc8c73e7e6fb9e4fcadcec022fa1d3da4b96d/我手敲的代码(中文注释)/chapter11/volatility-2.3/build/lib/volatility/plugins/malware/apihooks.py#L205-L217
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/pyinotify-0.9.4-py2.7.egg/pyinotify.py
python
command_line
()
By default the watched path is '/tmp' and all types of events are monitored. Events monitoring serves forever, type c^c to stop it.
By default the watched path is '/tmp' and all types of events are monitored. Events monitoring serves forever, type c^c to stop it.
[ "By", "default", "the", "watched", "path", "is", "/", "tmp", "and", "all", "types", "of", "events", "are", "monitored", ".", "Events", "monitoring", "serves", "forever", "type", "c^c", "to", "stop", "it", "." ]
def command_line(): """ By default the watched path is '/tmp' and all types of events are monitored. Events monitoring serves forever, type c^c to stop it. """ from optparse import OptionParser usage = "usage: %prog [options] [path1] [path2] [pathn]" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Verbose mode") parser.add_option("-r", "--recursive", action="store_true", dest="recursive", help="Add watches recursively on paths") parser.add_option("-a", "--auto_add", action="store_true", dest="auto_add", help="Automatically add watches on new directories") parser.add_option("-g", "--glob", action="store_true", dest="glob", help="Treat paths as globs") parser.add_option("-e", "--events-list", metavar="EVENT[,...]", dest="events_list", help=("A comma-separated list of events to watch for - " "see the documentation for valid options (defaults" " to everything)")) parser.add_option("-s", "--stats", action="store_true", dest="stats", help="Display dummy statistics") parser.add_option("-V", "--version", action="store_true", dest="version", help="Pyinotify version") parser.add_option("-f", "--raw-format", action="store_true", dest="raw_format", help="Disable enhanced output format.") parser.add_option("-c", "--command", action="store", dest="command", help="Shell command to run upon event") (options, args) = parser.parse_args() if options.verbose: log.setLevel(10) if options.version: print(__version__) if not options.raw_format: global output_format output_format = ColoredOutputFormat() if len(args) < 1: path = '/tmp' # default watched path else: path = args # watch manager instance wm = WatchManager() # notifier instance and init if options.stats: notifier = Notifier(wm, default_proc_fun=Stats(), read_freq=5) else: notifier = Notifier(wm, default_proc_fun=PrintAllEvents()) # What mask to apply mask = 0 if options.events_list: events_list = options.events_list.split(',') for ev in events_list: evcode = EventsCodes.ALL_FLAGS.get(ev, 0) if evcode: mask |= evcode else: parser.error("The event '%s' specified with option -e" " is not valid" % ev) else: mask = ALL_EVENTS # stats cb_fun = None if options.stats: def cb(s): sys.stdout.write(repr(s.proc_fun())) sys.stdout.write('\n') sys.stdout.write(str(s.proc_fun())) sys.stdout.write('\n') sys.stdout.flush() cb_fun = cb # External command if options.command: def cb(s): subprocess.Popen(options.command, shell=True) cb_fun = cb log.debug('Start monitoring %s, (press c^c to halt pyinotify)' % path) wm.add_watch(path, mask, rec=options.recursive, auto_add=options.auto_add, do_glob=options.glob) # Loop forever (until sigint signal get caught) notifier.loop(callback=cb_fun)
[ "def", "command_line", "(", ")", ":", "from", "optparse", "import", "OptionParser", "usage", "=", "\"usage: %prog [options] [path1] [path2] [pathn]\"", "parser", "=", "OptionParser", "(", "usage", "=", "usage", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", ...
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/pyinotify-0.9.4-py2.7.egg/pyinotify.py#L2275-L2373
abcminiuser/python-elgato-streamdeck
681c7e9c084981e9286a41abb05d85713cd16317
src/StreamDeck/Devices/StreamDeckXL.py
python
StreamDeckXL._reset_key_stream
(self)
Sends a blank key report to the StreamDeck, resetting the key image streamer in the device. This prevents previously started partial key writes that were not completed from corrupting images sent from this application.
Sends a blank key report to the StreamDeck, resetting the key image streamer in the device. This prevents previously started partial key writes that were not completed from corrupting images sent from this application.
[ "Sends", "a", "blank", "key", "report", "to", "the", "StreamDeck", "resetting", "the", "key", "image", "streamer", "in", "the", "device", ".", "This", "prevents", "previously", "started", "partial", "key", "writes", "that", "were", "not", "completed", "from", ...
def _reset_key_stream(self): """ Sends a blank key report to the StreamDeck, resetting the key image streamer in the device. This prevents previously started partial key writes that were not completed from corrupting images sent from this application. """ payload = bytearray(self.IMAGE_REPORT_LENGTH) payload[0] = 0x02 self.device.write(payload)
[ "def", "_reset_key_stream", "(", "self", ")", ":", "payload", "=", "bytearray", "(", "self", ".", "IMAGE_REPORT_LENGTH", ")", "payload", "[", "0", "]", "=", "0x02", "self", ".", "device", ".", "write", "(", "payload", ")" ]
https://github.com/abcminiuser/python-elgato-streamdeck/blob/681c7e9c084981e9286a41abb05d85713cd16317/src/StreamDeck/Devices/StreamDeckXL.py#L93-L103
skarra/ASynK
e908a1ad670a2d79f791a6a7539392e078a64add
asynk/contact_ex.py
python
EXContact._add_email_helper
(self, ews_con, emails, n, key_start)
return i
From the list of emails, add at most n emails to ews_con. Return actual added count. n is the max number of emails from the list that can be added
From the list of emails, add at most n emails to ews_con. Return actual added count.
[ "From", "the", "list", "of", "emails", "add", "at", "most", "n", "emails", "to", "ews_con", ".", "Return", "actual", "added", "count", "." ]
def _add_email_helper (self, ews_con, emails, n, key_start): """From the list of emails, add at most n emails to ews_con. Return actual added count. n is the max number of emails from the list that can be added""" i = 0 for email in emails: if i >= n: ## FIXME: we are effetively losing teh remaining ## addresses. These should be put into a custom field break ews_con.emails.add('EmailAddress%d' % (key_start+i), email) i += 1 return i
[ "def", "_add_email_helper", "(", "self", ",", "ews_con", ",", "emails", ",", "n", ",", "key_start", ")", ":", "i", "=", "0", "for", "email", "in", "emails", ":", "if", "i", ">=", "n", ":", "## FIXME: we are effetively losing teh remaining", "## addresses. Thes...
https://github.com/skarra/ASynK/blob/e908a1ad670a2d79f791a6a7539392e078a64add/asynk/contact_ex.py#L369-L385
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
plexpy/webserve.py
python
WebInterface.get_server_pref
(self, pref=None, **kwargs)
Get a specified PMS server preference. ``` Required parameters: pref (str): Name of preference Returns: string: Value of preference ```
Get a specified PMS server preference.
[ "Get", "a", "specified", "PMS", "server", "preference", "." ]
def get_server_pref(self, pref=None, **kwargs): """ Get a specified PMS server preference. ``` Required parameters: pref (str): Name of preference Returns: string: Value of preference ``` """ pms_connect = pmsconnect.PmsConnect() result = pms_connect.get_server_pref(pref=pref) if result: return result else: logger.warn("Unable to retrieve data for get_server_pref.") return result
[ "def", "get_server_pref", "(", "self", ",", "pref", "=", "None", ",", "*", "*", "kwargs", ")", ":", "pms_connect", "=", "pmsconnect", ".", "PmsConnect", "(", ")", "result", "=", "pms_connect", ".", "get_server_pref", "(", "pref", "=", "pref", ")", "if", ...
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/plexpy/webserve.py#L4252-L4271
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/ZSI-2.0-py2.7.egg/ZSI/generate/wsdl2dispatch.py
python
ServiceModuleWriter.getClassName
(self, name)
return NCName_to_ClassName(name)
return class name.
return class name.
[ "return", "class", "name", "." ]
def getClassName(self, name): '''return class name. ''' return NCName_to_ClassName(name)
[ "def", "getClassName", "(", "self", ",", "name", ")", ":", "return", "NCName_to_ClassName", "(", "name", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/ZSI-2.0-py2.7.egg/ZSI/generate/wsdl2dispatch.py#L90-L93
nansencenter/DAPPER
406f5a526919286aa73b017add507f5b0cb98233
dapper/mods/Ikeda/__init__.py
python
aux
(x, y)
return s, t, x1, y1
Comps used both by step and its jacobian.
Comps used both by step and its jacobian.
[ "Comps", "used", "both", "by", "step", "and", "its", "jacobian", "." ]
def aux(x, y): """Comps used both by step and its jacobian.""" s = 1 + x**2 + y**2 t = 0.4 - 6 / s # x1= x*cos(t) + y*cos(t) # Colin's mod x1 = x*cos(t) - y*sin(t) y1 = x*sin(t) + y*cos(t) return s, t, x1, y1
[ "def", "aux", "(", "x", ",", "y", ")", ":", "s", "=", "1", "+", "x", "**", "2", "+", "y", "**", "2", "t", "=", "0.4", "-", "6", "/", "s", "# x1= x*cos(t) + y*cos(t) # Colin's mod", "x1", "=", "x", "*", "cos", "(", "t", ")", "-", "y", "*", "...
https://github.com/nansencenter/DAPPER/blob/406f5a526919286aa73b017add507f5b0cb98233/dapper/mods/Ikeda/__init__.py#L28-L35
axcore/tartube
36dd493642923fe8b9190a41db596c30c043ae90
tartube/mainwin.py
python
MainWin.on_video_index_empty_folder
(self, menu_item, media_data_obj)
Called from a callback in self.video_index_popup_menu(). Empties the folder. Args: menu_item (Gtk.MenuItem): The clicked menu item media_data_obj (media.Folder): The clicked media data object
Called from a callback in self.video_index_popup_menu().
[ "Called", "from", "a", "callback", "in", "self", ".", "video_index_popup_menu", "()", "." ]
def on_video_index_empty_folder(self, menu_item, media_data_obj): """Called from a callback in self.video_index_popup_menu(). Empties the folder. Args: menu_item (Gtk.MenuItem): The clicked menu item media_data_obj (media.Folder): The clicked media data object """ if DEBUG_FUNC_FLAG: utils.debug_time('mwn 12148 on_video_index_empty_folder') # The True flag tells the function to empty the container, rather than # delete it self.app_obj.delete_container(media_data_obj, True)
[ "def", "on_video_index_empty_folder", "(", "self", ",", "menu_item", ",", "media_data_obj", ")", ":", "if", "DEBUG_FUNC_FLAG", ":", "utils", ".", "debug_time", "(", "'mwn 12148 on_video_index_empty_folder'", ")", "# The True flag tells the function to empty the container, rathe...
https://github.com/axcore/tartube/blob/36dd493642923fe8b9190a41db596c30c043ae90/tartube/mainwin.py#L13242-L13261
quantumlib/Cirq
89f88b01d69222d3f1ec14d649b7b3a85ed9211f
cirq-web/cirq_web/circuits/symbols.py
python
resolve_operation
(operation: cirq.Operation, resolvers: Iterable[SymbolResolver])
return symbol_info
Builds a SymbolInfo object based off of a designated operation and list of resolvers. The latest resolver takes precendent. Args: operation: the cirq.Operation object to resolve resolvers: a list of SymbolResolvers which provides instructions on how to build SymbolInfo objects. Raises: ValueError: if the operation cannot be resolved into a symbol.
Builds a SymbolInfo object based off of a designated operation and list of resolvers. The latest resolver takes precendent.
[ "Builds", "a", "SymbolInfo", "object", "based", "off", "of", "a", "designated", "operation", "and", "list", "of", "resolvers", ".", "The", "latest", "resolver", "takes", "precendent", "." ]
def resolve_operation(operation: cirq.Operation, resolvers: Iterable[SymbolResolver]) -> SymbolInfo: """Builds a SymbolInfo object based off of a designated operation and list of resolvers. The latest resolver takes precendent. Args: operation: the cirq.Operation object to resolve resolvers: a list of SymbolResolvers which provides instructions on how to build SymbolInfo objects. Raises: ValueError: if the operation cannot be resolved into a symbol. """ symbol_info = None for resolver in resolvers: info = resolver(operation) if info is not None: symbol_info = info if symbol_info is None: raise ValueError(f'Cannot resolve operation: {operation}') return symbol_info
[ "def", "resolve_operation", "(", "operation", ":", "cirq", ".", "Operation", ",", "resolvers", ":", "Iterable", "[", "SymbolResolver", "]", ")", "->", "SymbolInfo", ":", "symbol_info", "=", "None", "for", "resolver", "in", "resolvers", ":", "info", "=", "res...
https://github.com/quantumlib/Cirq/blob/89f88b01d69222d3f1ec14d649b7b3a85ed9211f/cirq-web/cirq_web/circuits/symbols.py#L102-L122
researchmm/tasn
5dba8ccc096cedc63913730eeea14a9647911129
tasn-mxnet/python/mxnet/ndarray/ndarray.py
python
NDArray.arcsin
(self, *args, **kwargs)
return op.arcsin(self, *args, **kwargs)
Convenience fluent method for :py:func:`arcsin`. The arguments are the same as for :py:func:`arcsin`, with this array as data.
Convenience fluent method for :py:func:`arcsin`.
[ "Convenience", "fluent", "method", "for", ":", "py", ":", "func", ":", "arcsin", "." ]
def arcsin(self, *args, **kwargs): """Convenience fluent method for :py:func:`arcsin`. The arguments are the same as for :py:func:`arcsin`, with this array as data. """ return op.arcsin(self, *args, **kwargs)
[ "def", "arcsin", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "op", ".", "arcsin", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/researchmm/tasn/blob/5dba8ccc096cedc63913730eeea14a9647911129/tasn-mxnet/python/mxnet/ndarray/ndarray.py#L1465-L1471
golismero/golismero
7d605b937e241f51c1ca4f47b20f755eeefb9d76
thirdparty_libs/openvas_lib/data.py
python
OpenVASOverride.orphan
(self)
return self.__orphan
:return: indicates if the NVT is orphan :rtype: bool
:return: indicates if the NVT is orphan :rtype: bool
[ ":", "return", ":", "indicates", "if", "the", "NVT", "is", "orphan", ":", "rtype", ":", "bool" ]
def orphan(self): """ :return: indicates if the NVT is orphan :rtype: bool """ return self.__orphan
[ "def", "orphan", "(", "self", ")", ":", "return", "self", ".", "__orphan" ]
https://github.com/golismero/golismero/blob/7d605b937e241f51c1ca4f47b20f755eeefb9d76/thirdparty_libs/openvas_lib/data.py#L618-L623
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/mutagen/_util.py
python
fileobj_name
(fileobj)
return value
Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent.
Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent.
[ "Returns", ":", "text", ":", "A", "potential", "filename", "for", "a", "file", "object", ".", "Always", "a", "valid", "path", "type", "but", "might", "be", "empty", "or", "non", "-", "existent", "." ]
def fileobj_name(fileobj): """ Returns: text: A potential filename for a file object. Always a valid path type, but might be empty or non-existent. """ value = getattr(fileobj, "name", u"") if not isinstance(value, (text_type, bytes)): value = text_type(value) return value
[ "def", "fileobj_name", "(", "fileobj", ")", ":", "value", "=", "getattr", "(", "fileobj", ",", "\"name\"", ",", "u\"\"", ")", "if", "not", "isinstance", "(", "value", ",", "(", "text_type", ",", "bytes", ")", ")", ":", "value", "=", "text_type", "(", ...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/mutagen/_util.py#L83-L93
asyml/texar
a23f021dae289a3d768dc099b220952111da04fd
texar/tf/data/data/mono_text_data.py
python
MonoTextData.dataset
(self)
return self._dataset
The dataset, an instance of :tf_main:`TF dataset <data/TextLineDataset>`.
The dataset, an instance of :tf_main:`TF dataset <data/TextLineDataset>`.
[ "The", "dataset", "an", "instance", "of", ":", "tf_main", ":", "TF", "dataset", "<data", "/", "TextLineDataset", ">", "." ]
def dataset(self): """The dataset, an instance of :tf_main:`TF dataset <data/TextLineDataset>`. """ return self._dataset
[ "def", "dataset", "(", "self", ")", ":", "return", "self", ".", "_dataset" ]
https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/texar/tf/data/data/mono_text_data.py#L543-L547
abhi2610/ohem
1f07dd09b50c8c21716ae36aede92125fe437579
tools/demo.py
python
parse_args
()
return args
Parse input arguments.
Parse input arguments.
[ "Parse", "input", "arguments", "." ]
def parse_args(): """Parse input arguments.""" parser = argparse.ArgumentParser(description='Faster R-CNN demo') parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]', default=0, type=int) parser.add_argument('--cpu', dest='cpu_mode', help='Use CPU mode (overrides --gpu)', action='store_true') parser.add_argument('--net', dest='demo_net', help='Network to use [vgg16]', choices=NETS.keys(), default='vgg16') args = parser.parse_args() return args
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Faster R-CNN demo'", ")", "parser", ".", "add_argument", "(", "'--gpu'", ",", "dest", "=", "'gpu_id'", ",", "help", "=", "'GPU device id to use [0]'"...
https://github.com/abhi2610/ohem/blob/1f07dd09b50c8c21716ae36aede92125fe437579/tools/demo.py#L100-L113
duanhongyi/dwebsocket
8beb7fb5c05fb53eda612cea573692dfc5f0ed69
dwebsocket/backends/default/websocket.py
python
DefaultWebSocket.close
(self, code=None, reason=None)
Forcibly close the websocket.
Forcibly close the websocket.
[ "Forcibly", "close", "the", "websocket", "." ]
def close(self, code=None, reason=None): ''' Forcibly close the websocket. ''' if not self.closed: self.protocol.close(code, reason) self.closed = True
[ "def", "close", "(", "self", ",", "code", "=", "None", ",", "reason", "=", "None", ")", ":", "if", "not", "self", ".", "closed", ":", "self", ".", "protocol", ".", "close", "(", "code", ",", "reason", ")", "self", ".", "closed", "=", "True" ]
https://github.com/duanhongyi/dwebsocket/blob/8beb7fb5c05fb53eda612cea573692dfc5f0ed69/dwebsocket/backends/default/websocket.py#L100-L106
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/click/core.py
python
Parameter.handle_parse_result
(self, ctx, opts, args)
return value, args
[]
def handle_parse_result(self, ctx, opts, args): with augment_usage_errors(ctx, param=self): value = self.consume_value(ctx, opts) try: value = self.full_process_value(ctx, value) except Exception: if not ctx.resilient_parsing: raise value = None if self.callback is not None: try: value = invoke_param_callback( self.callback, ctx, self, value) except Exception: if not ctx.resilient_parsing: raise if self.expose_value: ctx.params[self.name] = value return value, args
[ "def", "handle_parse_result", "(", "self", ",", "ctx", ",", "opts", ",", "args", ")", ":", "with", "augment_usage_errors", "(", "ctx", ",", "param", "=", "self", ")", ":", "value", "=", "self", ".", "consume_value", "(", "ctx", ",", "opts", ")", "try",...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/click/core.py#L1392-L1411
sympy/sympy
d822fcba181155b85ff2b29fe525adbafb22b448
sympy/polys/polyclasses.py
python
DMF.add
(f, g)
return per(num, den)
Add two multivariate fractions ``f`` and ``g``.
Add two multivariate fractions ``f`` and ``g``.
[ "Add", "two", "multivariate", "fractions", "f", "and", "g", "." ]
def add(f, g): """Add two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_add(dmp_mul(F_num, G_den, lev, dom), dmp_mul(F_den, G_num, lev, dom), lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den)
[ "def", "add", "(", "f", ",", "g", ")", ":", "if", "isinstance", "(", "g", ",", "DMP", ")", ":", "lev", ",", "dom", ",", "per", ",", "(", "F_num", ",", "F_den", ")", ",", "G", "=", "f", ".", "poly_unify", "(", "g", ")", "num", ",", "den", ...
https://github.com/sympy/sympy/blob/d822fcba181155b85ff2b29fe525adbafb22b448/sympy/polys/polyclasses.py#L1268-L1281
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/visualization/stretch.py
python
AsinhStretch.inverse
(self)
return SinhStretch(a=1. / np.arcsinh(1. / self.a))
A stretch object that performs the inverse operation.
A stretch object that performs the inverse operation.
[ "A", "stretch", "object", "that", "performs", "the", "inverse", "operation", "." ]
def inverse(self): """A stretch object that performs the inverse operation.""" return SinhStretch(a=1. / np.arcsinh(1. / self.a))
[ "def", "inverse", "(", "self", ")", ":", "return", "SinhStretch", "(", "a", "=", "1.", "/", "np", ".", "arcsinh", "(", "1.", "/", "self", ".", "a", ")", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/astropy-4.0-py3.7-macosx-10.9-x86_64.egg/astropy/visualization/stretch.py#L359-L361
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/api/apps_v1_api.py
python
AppsV1Api.read_namespaced_replica_set_status
(self, name, namespace, **kwargs)
return self.read_namespaced_replica_set_status_with_http_info(name, namespace, **kwargs)
read_namespaced_replica_set_status # noqa: E501 read status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread.
read_namespaced_replica_set_status # noqa: E501
[ "read_namespaced_replica_set_status", "#", "noqa", ":", "E501" ]
def read_namespaced_replica_set_status(self, name, namespace, **kwargs): # noqa: E501 """read_namespaced_replica_set_status # noqa: E501 read status of the specified ReplicaSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_replica_set_status(name, namespace, async_req=True) >>> result = thread.get() :param async_req bool: execute request asynchronously :param str name: name of the ReplicaSet (required) :param str namespace: object name and auth scope, such as for teams and projects (required) :param str pretty: If 'true', then the output is pretty printed. :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: V1ReplicaSet If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True return self.read_namespaced_replica_set_status_with_http_info(name, namespace, **kwargs)
[ "def", "read_namespaced_replica_set_status", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "return", "self", ".", "read_namespaced_replica_set_status_with_htt...
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/api/apps_v1_api.py#L6985-L7010
ifwe/digsby
f5fe00244744aa131e07f09348d10563f3d8fa99
digsby/lib/pyxmpp/interface_micro_impl.py
python
InterfaceClass.implementedBy
(self, cls)
return self in implementedBy(cls)
Do instances of the given class implement the interface?
Do instances of the given class implement the interface?
[ "Do", "instances", "of", "the", "given", "class", "implement", "the", "interface?" ]
def implementedBy(self, cls): """Do instances of the given class implement the interface?""" return self in implementedBy(cls)
[ "def", "implementedBy", "(", "self", ",", "cls", ")", ":", "return", "self", "in", "implementedBy", "(", "cls", ")" ]
https://github.com/ifwe/digsby/blob/f5fe00244744aa131e07f09348d10563f3d8fa99/digsby/lib/pyxmpp/interface_micro_impl.py#L113-L115
fzlee/alipay
0f8eab30fea7adb43284182cc6bcac08f51b2e08
alipay/__init__.py
python
ISVAliPay.api_alipay_open_auth_token_app_query
(self)
return self.verified_sync_response(data, response_type)
[]
def api_alipay_open_auth_token_app_query(self): biz_content = {"app_auth_token": self.app_auth_token} data = self.build_body( "alipay.open.auth.token.app.query", biz_content, ) response_type = "alipay_open_auth_token_app_query_response" return self.verified_sync_response(data, response_type)
[ "def", "api_alipay_open_auth_token_app_query", "(", "self", ")", ":", "biz_content", "=", "{", "\"app_auth_token\"", ":", "self", ".", "app_auth_token", "}", "data", "=", "self", ".", "build_body", "(", "\"alipay.open.auth.token.app.query\"", ",", "biz_content", ",", ...
https://github.com/fzlee/alipay/blob/0f8eab30fea7adb43284182cc6bcac08f51b2e08/alipay/__init__.py#L861-L868
zhanghan1990/zipline-chinese
86904cac4b6e928271f640910aa83675ce945b8b
zipline/finance/performance/position_tracker.py
python
PositionTracker.pay_dividends
(self, dividend_frame)
return net_cash_payment
Given a frame of dividends whose pay_dates are all the next trading day, grant the cash and/or stock payments that were calculated on the given dividends' ex dates.
Given a frame of dividends whose pay_dates are all the next trading day, grant the cash and/or stock payments that were calculated on the given dividends' ex dates.
[ "Given", "a", "frame", "of", "dividends", "whose", "pay_dates", "are", "all", "the", "next", "trading", "day", "grant", "the", "cash", "and", "/", "or", "stock", "payments", "that", "were", "calculated", "on", "the", "given", "dividends", "ex", "dates", "....
def pay_dividends(self, dividend_frame): """ Given a frame of dividends whose pay_dates are all the next trading day, grant the cash and/or stock payments that were calculated on the given dividends' ex dates. """ payments = dividend_frame.apply(self._maybe_pay_dividend, axis=1)\ .dropna(how='all') # Mark these dividends as paid by dropping them from our unpaid # table. self._unpaid_dividends.drop(payments.index) # Add stock for any stock dividends paid. Again, the values here may # be negative in the case of short positions. stock_payments = payments[payments['payment_sid'].notnull()] for _, row in stock_payments.iterrows(): stock = row['payment_sid'] share_count = row['share_count'] # note we create a Position for stock dividend if we don't # already own the asset position = self.positions[stock] position.amount += share_count self._update_asset(stock) # Add cash equal to the net cash payed from all dividends. Note that # "negative cash" is effectively paid if we're short an asset, # representing the fact that we're required to reimburse the owner of # the stock for any dividends paid while borrowing. net_cash_payment = payments['cash_amount'].fillna(0).sum() return net_cash_payment
[ "def", "pay_dividends", "(", "self", ",", "dividend_frame", ")", ":", "payments", "=", "dividend_frame", ".", "apply", "(", "self", ".", "_maybe_pay_dividend", ",", "axis", "=", "1", ")", ".", "dropna", "(", "how", "=", "'all'", ")", "# Mark these dividends ...
https://github.com/zhanghan1990/zipline-chinese/blob/86904cac4b6e928271f640910aa83675ce945b8b/zipline/finance/performance/position_tracker.py#L252-L283
dimagi/commcare-hq
d67ff1d3b4c51fa050c19e60c3253a79d3452a39
corehq/messaging/smsbackends/airtel_tcl/models.py
python
AirtelTCLBackend.get_url
(self)
return 'https://%s/BULK_API/InstantJsonPush' % self.config.host_and_port
[]
def get_url(self): return 'https://%s/BULK_API/InstantJsonPush' % self.config.host_and_port
[ "def", "get_url", "(", "self", ")", ":", "return", "'https://%s/BULK_API/InstantJsonPush'", "%", "self", ".", "config", ".", "host_and_port" ]
https://github.com/dimagi/commcare-hq/blob/d67ff1d3b4c51fa050c19e60c3253a79d3452a39/corehq/messaging/smsbackends/airtel_tcl/models.py#L104-L105
craigmacartney/Wave-U-Net-For-Speech-Enhancement
c8ccbd286cbe73d7539e5703e4407762304e3068
Utils.py
python
crop
(tensor, target_shape, match_feature_dim=True)
return tensor[:,crop_start[1]:-crop_end[1],:]
Crops a 3D tensor [batch_size, width, channels] along the width axes to a target shape. Performs a centre crop. If the dimension difference is uneven, crop last dimensions first. :param tensor: 4D tensor [batch_size, width, height, channels] that should be cropped. :param target_shape: Target shape (4D tensor) that the tensor should be cropped to :return: Cropped tensor
Crops a 3D tensor [batch_size, width, channels] along the width axes to a target shape. Performs a centre crop. If the dimension difference is uneven, crop last dimensions first. :param tensor: 4D tensor [batch_size, width, height, channels] that should be cropped. :param target_shape: Target shape (4D tensor) that the tensor should be cropped to :return: Cropped tensor
[ "Crops", "a", "3D", "tensor", "[", "batch_size", "width", "channels", "]", "along", "the", "width", "axes", "to", "a", "target", "shape", ".", "Performs", "a", "centre", "crop", ".", "If", "the", "dimension", "difference", "is", "uneven", "crop", "last", ...
def crop(tensor, target_shape, match_feature_dim=True): ''' Crops a 3D tensor [batch_size, width, channels] along the width axes to a target shape. Performs a centre crop. If the dimension difference is uneven, crop last dimensions first. :param tensor: 4D tensor [batch_size, width, height, channels] that should be cropped. :param target_shape: Target shape (4D tensor) that the tensor should be cropped to :return: Cropped tensor ''' shape = np.array(tensor.get_shape().as_list()) diff = shape - np.array(target_shape) assert(diff[0] == 0 and (diff[2] == 0 or not match_feature_dim))# Only width axis can differ if (diff[1] % 2 != 0): print("WARNING: Cropping with uneven number of extra entries on one side") assert diff[1] >= 0 # Only positive difference allowed if diff[1] == 0: return tensor crop_start = diff // 2 crop_end = diff - crop_start return tensor[:,crop_start[1]:-crop_end[1],:]
[ "def", "crop", "(", "tensor", ",", "target_shape", ",", "match_feature_dim", "=", "True", ")", ":", "shape", "=", "np", ".", "array", "(", "tensor", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", ")", "diff", "=", "shape", "-", "np", ".", "a...
https://github.com/craigmacartney/Wave-U-Net-For-Speech-Enhancement/blob/c8ccbd286cbe73d7539e5703e4407762304e3068/Utils.py#L121-L140
makerbot/ReplicatorG
d6f2b07785a5a5f1e172fb87cb4303b17c575d5d
skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/bottom.py
python
getCraftedTextFromText
(fileName, svgText, repository=None)
return BottomSkein().getCraftedGcode(fileName, repository, svgText)
Bottom and convert an svgText.
Bottom and convert an svgText.
[ "Bottom", "and", "convert", "an", "svgText", "." ]
def getCraftedTextFromText(fileName, svgText, repository=None): "Bottom and convert an svgText." if gcodec.isProcedureDoneOrFileIsEmpty(svgText, 'bottom'): return svgText if repository == None: repository = settings.getReadRepository(BottomRepository()) if not repository.activateBottom.value: return svgText return BottomSkein().getCraftedGcode(fileName, repository, svgText)
[ "def", "getCraftedTextFromText", "(", "fileName", ",", "svgText", ",", "repository", "=", "None", ")", ":", "if", "gcodec", ".", "isProcedureDoneOrFileIsEmpty", "(", "svgText", ",", "'bottom'", ")", ":", "return", "svgText", "if", "repository", "==", "None", "...
https://github.com/makerbot/ReplicatorG/blob/d6f2b07785a5a5f1e172fb87cb4303b17c575d5d/skein_engines/skeinforge-50/skeinforge_application/skeinforge_plugins/craft_plugins/bottom.py#L75-L83
pika/pika
12dcdf15d0932c388790e0fa990810bfd21b1a32
examples/asynchronous_consumer_example.py
python
ExampleConsumer.acknowledge_message
(self, delivery_tag)
Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame
Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag.
[ "Acknowledge", "the", "message", "delivery", "from", "RabbitMQ", "by", "sending", "a", "Basic", ".", "Ack", "RPC", "method", "for", "the", "delivery", "tag", "." ]
def acknowledge_message(self, delivery_tag): """Acknowledge the message delivery from RabbitMQ by sending a Basic.Ack RPC method for the delivery tag. :param int delivery_tag: The delivery tag from the Basic.Deliver frame """ LOGGER.info('Acknowledging message %s', delivery_tag) self._channel.basic_ack(delivery_tag)
[ "def", "acknowledge_message", "(", "self", ",", "delivery_tag", ")", ":", "LOGGER", ".", "info", "(", "'Acknowledging message %s'", ",", "delivery_tag", ")", "self", ".", "_channel", ".", "basic_ack", "(", "delivery_tag", ")" ]
https://github.com/pika/pika/blob/12dcdf15d0932c388790e0fa990810bfd21b1a32/examples/asynchronous_consumer_example.py#L319-L327
wmliang/pe-afl
4036d2f41da20ff12ecac43a076de5d60ce68bd9
lighthouse/lighthouse/painting/ida_painter.py
python
IDAPainter.clear_nodes
(self, nodes_metadata)
Clear paint from the given graph nodes.
Clear paint from the given graph nodes.
[ "Clear", "paint", "from", "the", "given", "graph", "nodes", "." ]
def clear_nodes(self, nodes_metadata): """ Clear paint from the given graph nodes. """ # create a node info object as our vehicle for resetting the node color node_info = idaapi.node_info_t() node_info.bg_color = idc.DEFCOLOR # NOTE/COMPAT: if disassembler.USING_IDA7API: set_node_info = idaapi.set_node_info else: set_node_info = idaapi.set_node_info2 # # loop through every node that we have metadata data for, clearing # their paint (color) in the IDA graph view as applicable. # for node_metadata in nodes_metadata: # do the *actual* painting of a single node instance set_node_info( node_metadata.function.address, node_metadata.id, node_info, idaapi.NIF_BG_COLOR | idaapi.NIF_FRAME_COLOR ) self._painted_nodes.discard(node_metadata.address)
[ "def", "clear_nodes", "(", "self", ",", "nodes_metadata", ")", ":", "# create a node info object as our vehicle for resetting the node color", "node_info", "=", "idaapi", ".", "node_info_t", "(", ")", "node_info", ".", "bg_color", "=", "idc", ".", "DEFCOLOR", "# NOTE/CO...
https://github.com/wmliang/pe-afl/blob/4036d2f41da20ff12ecac43a076de5d60ce68bd9/lighthouse/lighthouse/painting/ida_painter.py#L253-L283
natea/django-deployer
5ce7d972db2f8500ec53ad89e7eb312d3360d074
django_deployer/tasks.py
python
deploy
(provider=None)
Deploys your project
Deploys your project
[ "Deploys", "your", "project" ]
def deploy(provider=None): """ Deploys your project """ if os.path.exists(DEPLOY_YAML): site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.deploy()
[ "def", "deploy", "(", "provider", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "DEPLOY_YAML", ")", ":", "site", "=", "yaml", ".", "safe_load", "(", "_read_file", "(", "DEPLOY_YAML", ")", ")", "provider_class", "=", "PROVIDERS", "...
https://github.com/natea/django-deployer/blob/5ce7d972db2f8500ec53ad89e7eb312d3360d074/django_deployer/tasks.py#L155-L163
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/rlib/rbigint.py
python
_loghelper
(func, arg)
return func(x) + (e * float(SHIFT) * func(2.0))
A decent logarithm is easy to compute even for huge bigints, but libm can't do that by itself -- loghelper can. func is log or log10. Note that overflow isn't possible: a bigint can contain no more than INT_MAX * SHIFT bits, so has value certainly less than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is small enough to fit in an IEEE single. log and log10 are even smaller.
A decent logarithm is easy to compute even for huge bigints, but libm can't do that by itself -- loghelper can. func is log or log10. Note that overflow isn't possible: a bigint can contain no more than INT_MAX * SHIFT bits, so has value certainly less than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is small enough to fit in an IEEE single. log and log10 are even smaller.
[ "A", "decent", "logarithm", "is", "easy", "to", "compute", "even", "for", "huge", "bigints", "but", "libm", "can", "t", "do", "that", "by", "itself", "--", "loghelper", "can", ".", "func", "is", "log", "or", "log10", ".", "Note", "that", "overflow", "i...
def _loghelper(func, arg): """ A decent logarithm is easy to compute even for huge bigints, but libm can't do that by itself -- loghelper can. func is log or log10. Note that overflow isn't possible: a bigint can contain no more than INT_MAX * SHIFT bits, so has value certainly less than 2**(2**64 * 2**16) == 2**2**80, and log2 of that is 2**80, which is small enough to fit in an IEEE single. log and log10 are even smaller. """ x, e = _AsScaledDouble(arg) if x <= 0.0: raise ValueError # Value is ~= x * 2**(e*SHIFT), so the log ~= # log(x) + log(2) * e * SHIFT. # CAUTION: e*SHIFT may overflow using int arithmetic, # so force use of double. */ return func(x) + (e * float(SHIFT) * func(2.0))
[ "def", "_loghelper", "(", "func", ",", "arg", ")", ":", "x", ",", "e", "=", "_AsScaledDouble", "(", "arg", ")", "if", "x", "<=", "0.0", ":", "raise", "ValueError", "# Value is ~= x * 2**(e*SHIFT), so the log ~=", "# log(x) + log(2) * e * SHIFT.", "# CAUTION: e*SHIF...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/rlib/rbigint.py#L2526-L2542
w3h/isf
6faf0a3df185465ec17369c90ccc16e2a03a1870
lib/thirdparty/bitstring.py
python
BitArray.__irshift__
(self, n)
return self._irshift(n)
Shift bits by n to the right in place. Return self. n -- the number of bits to shift. Must be >= 0.
Shift bits by n to the right in place. Return self.
[ "Shift", "bits", "by", "n", "to", "the", "right", "in", "place", ".", "Return", "self", "." ]
def __irshift__(self, n): """Shift bits by n to the right in place. Return self. n -- the number of bits to shift. Must be >= 0. """ if n < 0: raise ValueError("Cannot shift by a negative amount.") if not self.len: raise ValueError("Cannot shift an empty bitstring.") if not n: return self n = min(n, self.len) return self._irshift(n)
[ "def", "__irshift__", "(", "self", ",", "n", ")", ":", "if", "n", "<", "0", ":", "raise", "ValueError", "(", "\"Cannot shift by a negative amount.\"", ")", "if", "not", "self", ".", "len", ":", "raise", "ValueError", "(", "\"Cannot shift an empty bitstring.\"", ...
https://github.com/w3h/isf/blob/6faf0a3df185465ec17369c90ccc16e2a03a1870/lib/thirdparty/bitstring.py#L3251-L3264
mars-project/mars
6afd7ed86db77f29cc9470485698ef192ecc6d33
mars/lib/version.py
python
parse
(version: str)
Parse the given version string and return either a :class:`Version` object or a :class:`LegacyVersion` object depending on if the given version is a valid PEP 440 version or a legacy version.
Parse the given version string and return either a :class:`Version` object or a :class:`LegacyVersion` object depending on if the given version is a valid PEP 440 version or a legacy version.
[ "Parse", "the", "given", "version", "string", "and", "return", "either", "a", ":", "class", ":", "Version", "object", "or", "a", ":", "class", ":", "LegacyVersion", "object", "depending", "on", "if", "the", "given", "version", "is", "a", "valid", "PEP", ...
def parse(version: str) -> Union["LegacyVersion", "Version"]: """ Parse the given version string and return either a :class:`Version` object or a :class:`LegacyVersion` object depending on if the given version is a valid PEP 440 version or a legacy version. """ try: return Version(version) except InvalidVersion: return LegacyVersion(version)
[ "def", "parse", "(", "version", ":", "str", ")", "->", "Union", "[", "\"LegacyVersion\"", ",", "\"Version\"", "]", ":", "try", ":", "return", "Version", "(", "version", ")", "except", "InvalidVersion", ":", "return", "LegacyVersion", "(", "version", ")" ]
https://github.com/mars-project/mars/blob/6afd7ed86db77f29cc9470485698ef192ecc6d33/mars/lib/version.py#L149-L158
nodejs/node-gyp
a2f298870692022302fa27a1d42363c4a72df407
gyp/pylib/gyp/MSVSSettings.py
python
_MSVSOnly
(tool, name, setting_type)
Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting.
Defines a setting that is only found in MSVS.
[ "Defines", "a", "setting", "that", "is", "only", "found", "in", "MSVS", "." ]
def _MSVSOnly(tool, name, setting_type): """Defines a setting that is only found in MSVS. Args: tool: a dictionary that gives the names of the tool for MSVS and MSBuild. name: the name of the setting. setting_type: the type of this setting. """ def _Translate(unused_value, unused_msbuild_settings): # Since this is for MSVS only settings, no translation will happen. pass _msvs_validators[tool.msvs_name][name] = setting_type.ValidateMSVS _msvs_to_msbuild_converters[tool.msvs_name][name] = _Translate
[ "def", "_MSVSOnly", "(", "tool", ",", "name", ",", "setting_type", ")", ":", "def", "_Translate", "(", "unused_value", ",", "unused_msbuild_settings", ")", ":", "# Since this is for MSVS only settings, no translation will happen.", "pass", "_msvs_validators", "[", "tool",...
https://github.com/nodejs/node-gyp/blob/a2f298870692022302fa27a1d42363c4a72df407/gyp/pylib/gyp/MSVSSettings.py#L293-L307
buke/GreenOdoo
3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df
runtime/python/lib/python2.7/site-packages/psutil-0.6.1-py2.7-linux-x86_64.egg/psutil/_psosx.py
python
get_system_cpu_times
()
return _cputimes_ntuple(user, nice, system, idle)
Return system CPU times as a namedtuple.
Return system CPU times as a namedtuple.
[ "Return", "system", "CPU", "times", "as", "a", "namedtuple", "." ]
def get_system_cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = _psutil_osx.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle)
[ "def", "get_system_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", "=", "_psutil_osx", ".", "get_system_cpu_times", "(", ")", "return", "_cputimes_ntuple", "(", "user", ",", "nice", ",", "system", ",", "idle", ")" ]
https://github.com/buke/GreenOdoo/blob/3d8c55d426fb41fdb3f2f5a1533cfe05983ba1df/runtime/python/lib/python2.7/site-packages/psutil-0.6.1-py2.7-linux-x86_64.egg/psutil/_psosx.py#L58-L61
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/api/v2010/account/short_code.py
python
ShortCodeInstance.api_version
(self)
return self._properties['api_version']
:returns: The API version used to start a new TwiML session :rtype: unicode
:returns: The API version used to start a new TwiML session :rtype: unicode
[ ":", "returns", ":", "The", "API", "version", "used", "to", "start", "a", "new", "TwiML", "session", ":", "rtype", ":", "unicode" ]
def api_version(self): """ :returns: The API version used to start a new TwiML session :rtype: unicode """ return self._properties['api_version']
[ "def", "api_version", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'api_version'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/short_code.py#L340-L345
ales-tsurko/cells
4cf7e395cd433762bea70cdc863a346f3a6fe1d0
packaging/macos/python/lib/python3.7/random.py
python
Random.sample
(self, population, k)
return result
Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60)
Chooses k unique random elements from a population sequence or set.
[ "Chooses", "k", "unique", "random", "elements", "from", "a", "population", "sequence", "or", "set", "." ]
def sample(self, population, k): """Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample. To choose a sample in a range of integers, use range as an argument. This is especially fast and space efficient for sampling from a large population: sample(range(10000000), 60) """ # Sampling without replacement entails tracking either potential # selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the # population, then tracking selections is efficient, requiring # only a small set and an occasional reselection. For # a larger number of selections, the pool tracking method is # preferred since the list takes less space than the # set and it doesn't suffer from frequent reselections. if isinstance(population, _Set): population = tuple(population) if not isinstance(population, _Sequence): raise TypeError("Population must be a sequence or set. For dicts, use list(d).") randbelow = self._randbelow n = len(population) if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") result = [None] * k setsize = 21 # size of a small set minus size of an empty list if k > 5: setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets if n <= setsize: # An n-length list is smaller than a k-length set pool = list(population) for i in range(k): # invariant: non-selected at [0,n-i) j = randbelow(n-i) result[i] = pool[j] pool[j] = pool[n-i-1] # move non-selected item into vacancy else: selected = set() selected_add = selected.add for i in range(k): j = randbelow(n) while j in selected: j = randbelow(n) selected_add(j) result[i] = population[j] return result
[ "def", "sample", "(", "self", ",", "population", ",", "k", ")", ":", "# Sampling without replacement entails tracking either potential", "# selections (the pool) in a list or previous selections in a set.", "# When the number of selections is small compared to the", "# population, then tra...
https://github.com/ales-tsurko/cells/blob/4cf7e395cd433762bea70cdc863a346f3a6fe1d0/packaging/macos/python/lib/python3.7/random.py#L286-L342
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/cherrypy/_cptools.py
python
DeprecatedTool.__init__
(self, point, warnmsg=None)
[]
def __init__(self, point, warnmsg=None): self.point = point if warnmsg is not None: self.warnmsg = warnmsg
[ "def", "__init__", "(", "self", ",", "point", ",", "warnmsg", "=", "None", ")", ":", "self", ".", "point", "=", "point", "if", "warnmsg", "is", "not", "None", ":", "self", ".", "warnmsg", "=", "warnmsg" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/cherrypy/_cptools.py#L469-L472
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/bleach/_vendor/html5lib/filters/base.py
python
Filter.__init__
(self, source)
[]
def __init__(self, source): self.source = source
[ "def", "__init__", "(", "self", ",", "source", ")", ":", "self", ".", "source", "=", "source" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/bleach/_vendor/html5lib/filters/base.py#L5-L6
hudson-and-thames/mlfinlab
79dcc7120ec84110578f75b025a75850eb72fc73
mlfinlab/bet_sizing/ch10_snippets.py
python
limit_price
(target_pos, pos, forecast_price, w_param, max_pos, func)
Derived from SNIPPET 10.4 Calculates the limit price. The 'func' argument allows the user to choose between bet sizing functions. :param target_pos: (int) Target position. :param pos: (int) Current position. :param forecast_price: (float) Forecast price. :param w_param: (float) Coefficient regulating the width of the bet size function. :param max_pos: (int) Maximum absolute position size. :param func: (string) Function to use for dynamic calculation. Valid options are: 'sigmoid', 'power'. :return: (float) Limit price.
Derived from SNIPPET 10.4 Calculates the limit price. The 'func' argument allows the user to choose between bet sizing functions.
[ "Derived", "from", "SNIPPET", "10", ".", "4", "Calculates", "the", "limit", "price", ".", "The", "func", "argument", "allows", "the", "user", "to", "choose", "between", "bet", "sizing", "functions", "." ]
def limit_price(target_pos, pos, forecast_price, w_param, max_pos, func): """ Derived from SNIPPET 10.4 Calculates the limit price. The 'func' argument allows the user to choose between bet sizing functions. :param target_pos: (int) Target position. :param pos: (int) Current position. :param forecast_price: (float) Forecast price. :param w_param: (float) Coefficient regulating the width of the bet size function. :param max_pos: (int) Maximum absolute position size. :param func: (string) Function to use for dynamic calculation. Valid options are: 'sigmoid', 'power'. :return: (float) Limit price. """ pass
[ "def", "limit_price", "(", "target_pos", ",", "pos", ",", "forecast_price", ",", "w_param", ",", "max_pos", ",", "func", ")", ":", "pass" ]
https://github.com/hudson-and-thames/mlfinlab/blob/79dcc7120ec84110578f75b025a75850eb72fc73/mlfinlab/bet_sizing/ch10_snippets.py#L289-L303
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/Pulsedive/Integrations/Pulsedive/Pulsedive.py
python
test_module
(client: Client, api_key)
return 'ok'
Tests API connectivity and authentication
Tests API connectivity and authentication
[ "Tests", "API", "connectivity", "and", "authentication" ]
def test_module(client: Client, api_key) -> str: """Tests API connectivity and authentication""" try: client.test_connect(api_key) except DemistoException: return 'Could not connect to Pulsedive' return 'ok'
[ "def", "test_module", "(", "client", ":", "Client", ",", "api_key", ")", "->", "str", ":", "try", ":", "client", ".", "test_connect", "(", "api_key", ")", "except", "DemistoException", ":", "return", "'Could not connect to Pulsedive'", "return", "'ok'" ]
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/Pulsedive/Integrations/Pulsedive/Pulsedive.py#L113-L120
python-diamond/Diamond
7000e16cfdf4508ed9291fc4b3800592557b2431
src/collectors/elasticsearch/elasticsearch.py
python
ElasticSearchCollector.collect_instance_index_stats
(self, scheme, host, port, metrics)
[]
def collect_instance_index_stats(self, scheme, host, port, metrics): result = self._get(scheme, host, port, '_stats', '_all') if not result: return _all = result['_all'] self._index_metrics(metrics, 'indices._all', _all['primaries']) if 'indices' in _all: indices = _all['indices'] elif 'indices' in result: # elasticsearch >= 0.90RC2 indices = result['indices'] else: return for name, index in indices.iteritems(): self._index_metrics(metrics, 'indices.%s' % name, index['primaries'])
[ "def", "collect_instance_index_stats", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "metrics", ")", ":", "result", "=", "self", ".", "_get", "(", "scheme", ",", "host", ",", "port", ",", "'_stats'", ",", "'_all'", ")", "if", "not", "resul...
https://github.com/python-diamond/Diamond/blob/7000e16cfdf4508ed9291fc4b3800592557b2431/src/collectors/elasticsearch/elasticsearch.py#L224-L241
jiaruncao/Readers
ddef597db761fad90eaf694a7f3ed570d4cf9ce8
Self-MatchingReader/Helper.py
python
merge_two_dicts
(x, y)
return z
Given two dicts, merge them into a new dict as a shallow copy.
Given two dicts, merge them into a new dict as a shallow copy.
[ "Given", "two", "dicts", "merge", "them", "into", "a", "new", "dict", "as", "a", "shallow", "copy", "." ]
def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z
[ "def", "merge_two_dicts", "(", "x", ",", "y", ")", ":", "z", "=", "x", ".", "copy", "(", ")", "z", ".", "update", "(", "y", ")", "return", "z" ]
https://github.com/jiaruncao/Readers/blob/ddef597db761fad90eaf694a7f3ed570d4cf9ce8/Self-MatchingReader/Helper.py#L278-L282
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/pythonwin/pywin/framework/interact.py
python
CreateMDIInteractiveWindow
(makeDoc = None, makeFrame = None)
Create a standard (non-docked) interactive window unconditionally
Create a standard (non-docked) interactive window unconditionally
[ "Create", "a", "standard", "(", "non", "-", "docked", ")", "interactive", "window", "unconditionally" ]
def CreateMDIInteractiveWindow(makeDoc = None, makeFrame = None): """Create a standard (non-docked) interactive window unconditionally """ global edit if makeDoc is None: makeDoc = InteractiveDocument if makeFrame is None: makeFrame = InteractiveFrame edit = CInteractivePython(makeDoc=makeDoc,makeFrame=makeFrame)
[ "def", "CreateMDIInteractiveWindow", "(", "makeDoc", "=", "None", ",", "makeFrame", "=", "None", ")", ":", "global", "edit", "if", "makeDoc", "is", "None", ":", "makeDoc", "=", "InteractiveDocument", "if", "makeFrame", "is", "None", ":", "makeFrame", "=", "I...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/pythonwin/pywin/framework/interact.py#L789-L795
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
plexpy/helpers.py
python
radio
(variable, pos)
[]
def radio(variable, pos): if variable == pos: return 'Checked' else: return ''
[ "def", "radio", "(", "variable", ",", "pos", ")", ":", "if", "variable", "==", "pos", ":", "return", "'Checked'", "else", ":", "return", "''" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/plexpy/helpers.py#L109-L114
apple/ccs-calendarserver
13c706b985fb728b9aab42dc0fef85aae21921c3
twistedcaldav/database.py
python
AbstractADBAPIDatabase.queryList
(self, sql, *query_params)
[]
def queryList(self, sql, *query_params): # Re-try at least once for _ignore in (0, 1): if not self.initialized: yield self.open() try: result = (yield self._db_values_for_sql(sql, *query_params)) except Exception, e: log.error("Error in database queryList: {ex}", ex=e) self.close() else: break returnValue(result)
[ "def", "queryList", "(", "self", ",", "sql", ",", "*", "query_params", ")", ":", "# Re-try at least once", "for", "_ignore", "in", "(", "0", ",", "1", ")", ":", "if", "not", "self", ".", "initialized", ":", "yield", "self", ".", "open", "(", ")", "tr...
https://github.com/apple/ccs-calendarserver/blob/13c706b985fb728b9aab42dc0fef85aae21921c3/twistedcaldav/database.py#L238-L253
daoluan/decode-Django
d46a858b45b56de48b0355f50dd9e45402d04cfd
Django-1.5.1/django/contrib/localflavor/ro/forms.py
python
ROPhoneNumberField.clean
(self, value)
return value
Strips -, (, ) and spaces. Checks the final length.
Strips -, (, ) and spaces. Checks the final length.
[ "Strips", "-", "(", ")", "and", "spaces", ".", "Checks", "the", "final", "length", "." ]
def clean(self, value): """ Strips -, (, ) and spaces. Checks the final length. """ value = super(ROPhoneNumberField, self).clean(value) if value in EMPTY_VALUES: return '' value = value.replace('-', '') value = value.replace('(', '') value = value.replace(')', '') value = value.replace(' ', '') if len(value) != 10: raise ValidationError(self.error_messages['invalid']) return value
[ "def", "clean", "(", "self", ",", "value", ")", ":", "value", "=", "super", "(", "ROPhoneNumberField", ",", "self", ")", ".", "clean", "(", "value", ")", "if", "value", "in", "EMPTY_VALUES", ":", "return", "''", "value", "=", "value", ".", "replace", ...
https://github.com/daoluan/decode-Django/blob/d46a858b45b56de48b0355f50dd9e45402d04cfd/Django-1.5.1/django/contrib/localflavor/ro/forms.py#L182-L195
sensepost/snoopy-ng
eac73f545952583af96c6ae8980e9ffeb8b972bc
includes/wigle_api.py
python
Wigle._haversine
(self, lat1, lon1, lat2, lon2)
return R * c * 1000.0
Calculate distance between points on a sphere
Calculate distance between points on a sphere
[ "Calculate", "distance", "between", "points", "on", "a", "sphere" ]
def _haversine(self, lat1, lon1, lat2, lon2): """Calculate distance between points on a sphere""" R = 6372.8 # In kilometers dLat = math.radians(lat2 - lat1) dLon = math.radians(lon2 - lon1) lat1 = math.radians(lat1) lat2 = math.radians(lat2) a = math.sin(dLat / 2) * math.sin(dLat / 2) + math.sin(dLon / 2) * math.sin(dLon / 2) * math.cos(lat1) * math.cos(lat2) c = 2 * math.asin(math.sqrt(a)) return R * c * 1000.0
[ "def", "_haversine", "(", "self", ",", "lat1", ",", "lon1", ",", "lat2", ",", "lon2", ")", ":", "R", "=", "6372.8", "# In kilometers", "dLat", "=", "math", ".", "radians", "(", "lat2", "-", "lat1", ")", "dLon", "=", "math", ".", "radians", "(", "lo...
https://github.com/sensepost/snoopy-ng/blob/eac73f545952583af96c6ae8980e9ffeb8b972bc/includes/wigle_api.py#L233-L243
apple/coremltools
141a83af482fcbdd5179807c9eaff9a7999c2c49
coremltools/converters/sklearn/_converter_internal.py
python
_convert_sklearn_model
( input_sk_obj, input_features=None, output_feature_names=None, class_labels=None )
return pipeline.spec
Converts a generic sklearn pipeline, transformer, classifier, or regressor into an coreML specification.
Converts a generic sklearn pipeline, transformer, classifier, or regressor into an coreML specification.
[ "Converts", "a", "generic", "sklearn", "pipeline", "transformer", "classifier", "or", "regressor", "into", "an", "coreML", "specification", "." ]
def _convert_sklearn_model( input_sk_obj, input_features=None, output_feature_names=None, class_labels=None ): """ Converts a generic sklearn pipeline, transformer, classifier, or regressor into an coreML specification. """ if not (_HAS_SKLEARN): raise RuntimeError( "scikit-learn not found. scikit-learn conversion API is disabled." ) from sklearn.pipeline import Pipeline as sk_Pipeline if input_features is None: input_features = "input" if isinstance(input_sk_obj, sk_Pipeline): sk_obj_list = input_sk_obj.steps else: sk_obj_list = [("SKObj", input_sk_obj)] if len(sk_obj_list) == 0: raise ValueError("No SKLearn transformers supplied.") # Put the transformers into a pipeline list to hold them so that they can # later be added to a pipeline object. (Hold off adding them to the # pipeline now in case it's a single model at the end, in which case it # gets returned as is.) # # Each member of the pipeline list is a tuple of the proto spec for that # model, the input features, and the output features. pipeline_list = [] # These help us keep track of what's going on a bit easier. Input = _namedtuple("InputTransformer", ["name", "sk_obj", "module"]) Output = _namedtuple( "CoreMLTransformer", ["spec", "input_features", "output_features"] ) # Get a more information rich representation of the list for convenience. # obj_list is a list of tuples of (name, sk_obj, and the converter module for # that step in the list. obj_list = [ Input(sk_obj_name, sk_obj, _get_converter_module(sk_obj)) for sk_obj_name, sk_obj in sk_obj_list ] # Various preprocessing steps. # If the first component of the object list is the sklearn dict vectorizer, # which is unique in that it accepts a list of dictionaries, then we can # get the feature type mapping from that. This then may require the addition # of several OHE steps, so those need to be processed in the first stage. if isinstance(obj_list[0].sk_obj, _dict_vectorizer.sklearn_class): dv_obj = obj_list[0].sk_obj output_dim = len(_dict_vectorizer.get_input_feature_names(dv_obj)) if not isinstance(input_features, str): raise TypeError( "If the first transformer in a pipeline is a " "DictVectorizer, then the input feature must be the name " "of the input dictionary." ) input_features = [(input_features, datatypes.Dictionary(str))] if len(obj_list) > 1: output_feature_name = _PIPELINE_INTERNAL_FEATURE_NAME else: if output_feature_names is None: output_feature_name = "transformed_features" elif isinstance(output_feature_names, str): output_feature_name = output_feature_names else: raise TypeError( "For a transformer pipeline, the " "output_features needs to be None or a string " "for the predicted value." ) output_features = [(output_feature_name, datatypes.Array(output_dim))] spec = _dict_vectorizer.convert(dv_obj, input_features, output_features)._spec pipeline_list.append(Output(spec, input_features, output_features)) # Set up the environment for the rest of the pipeline current_input_features = output_features current_num_dimensions = output_dim # In the corner case that it's only the dict vectorizer here, just return # and exit with that at this point. if len(obj_list) == 1: return spec else: del obj_list[0] else: # First, we need to resolve the input feature types as the sklearn pipeline # expects just an array as input, but what we want to expose to the coreML # user is an interface with named variables. This resolution has to handle # a number of cases. # Can we get the number of features from the model? If so, pass that # information into the feature resolution function. If we can't, then this # function should return None. first_sk_obj = obj_list[0].sk_obj num_dimensions = _get_converter_module(first_sk_obj).get_input_dimension( first_sk_obj ) # Resolve the input features. features = _fm.process_or_validate_features(input_features, num_dimensions) current_num_dimensions = _fm.dimension_of_array_features(features) # Add in a feature vectorizer that consolodates all of the feature inputs # into the form expected by scipy's pipelines. Essentially this is a # translation layer between the coreML form with named arguments and the # scikit learn variable form. if len(features) == 1 and isinstance(features[0][1], datatypes.Array): current_input_features = features else: spec, _output_dimension = create_feature_vectorizer( features, _PIPELINE_INTERNAL_FEATURE_NAME ) assert _output_dimension == current_num_dimensions ft_out_features = [ ( _PIPELINE_INTERNAL_FEATURE_NAME, datatypes.Array(current_num_dimensions), ) ] pipeline_list.append(Output(spec, features, ft_out_features)) current_input_features = ft_out_features # Now, validate the sequence of transformers to make sure we have something # that can work with all of this. for i, (_, _, m) in enumerate(obj_list[:-1]): if m.model_type != "transformer": raise ValueError( "Only a sequence of transformer classes followed by a " "single transformer, regressor, or classifier is currently supported. " "(object in position %d interpreted as %s)" % (i, m.model_type) ) overall_mode = obj_list[-1].module.model_type assert overall_mode in ("transformer", "regressor", "classifier") # Now, go through each transformer in the sequence of transformers and add # it to the pipeline. for _, sk_obj, sk_m in obj_list[:-1]: next_dimension = sk_m.update_dimension(sk_obj, current_num_dimensions) output_features = [ (_PIPELINE_INTERNAL_FEATURE_NAME, datatypes.Array(next_dimension)) ] spec = sk_m.convert(sk_obj, current_input_features, output_features)._spec pipeline_list.append(Output(spec, current_input_features, output_features)) current_input_features = output_features current_num_dimensions = next_dimension # Now, handle the final transformer. This is where we need to have different # behavior depending on whether it's a classifier, transformer, or regressor. _, last_sk_obj, last_sk_m = obj_list[-1] if overall_mode == "classifier": supports_output_scores = last_sk_m.supports_output_scores(last_sk_obj) _internal_output_classes = list(last_sk_m.get_output_classes(last_sk_obj)) if class_labels is None: class_labels = _internal_output_classes output_features = _fm.process_or_validate_classifier_output_features( output_feature_names, class_labels, supports_output_scores ) elif overall_mode == "regressor": if output_feature_names is None: output_features = [("prediction", datatypes.Double())] elif isinstance(output_feature_names, str): output_features = [(output_feature_names, datatypes.Double())] else: raise TypeError( "For a regressor object or regressor pipeline, the " "output_features needs to be None or a string for the predicted value." ) else: # transformer final_output_dimension = last_sk_m.update_dimension( last_sk_obj, current_num_dimensions ) if output_feature_names is None: output_features = [ ("transformed_features", datatypes.Array(final_output_dimension)) ] elif isinstance(output_feature_names, str): output_features = [ (output_feature_names, datatypes.Array(final_output_dimension)) ] else: raise TypeError( "For a transformer object or transformer pipeline, the " "output_features needs to be None or a string for the " "name of the transformed value." ) last_spec = last_sk_m.convert( last_sk_obj, current_input_features, output_features )._spec pipeline_list.append(Output(last_spec, current_input_features, output_features)) # Now, create the pipeline and return the spec for it. # If it's just one element, we can return it. if len(pipeline_list) == 1: return pipeline_list[0].spec original_input_features = pipeline_list[0].input_features if overall_mode == "regressor": pipeline = PipelineRegressor(original_input_features, output_features) elif overall_mode == "classifier": pipeline = PipelineClassifier( original_input_features, class_labels, output_features ) else: pipeline = Pipeline(original_input_features, output_features) # Okay, now we can build the pipeline spec. for spec, input_features, output_features in pipeline_list: pipeline.add_model(spec) return pipeline.spec
[ "def", "_convert_sklearn_model", "(", "input_sk_obj", ",", "input_features", "=", "None", ",", "output_feature_names", "=", "None", ",", "class_labels", "=", "None", ")", ":", "if", "not", "(", "_HAS_SKLEARN", ")", ":", "raise", "RuntimeError", "(", "\"scikit-le...
https://github.com/apple/coremltools/blob/141a83af482fcbdd5179807c9eaff9a7999c2c49/coremltools/converters/sklearn/_converter_internal.py#L120-L364
hubo1016/vlcp
61c4c2595b610675ac0cbc4dbc46f70ec40090d3
vlcp/utils/dataobject.py
python
dump
(obj, attributes = True, _refset = None)
Show full value of a data object
Show full value of a data object
[ "Show", "full", "value", "of", "a", "data", "object" ]
def dump(obj, attributes = True, _refset = None): "Show full value of a data object" if _refset is None: _refset = set() if obj is None: return None elif isinstance(obj, DataObject): if id(obj) in _refset: attributes = False else: _refset.add(id(obj)) cls = type(obj) clsname = getattr(cls, '__module__', '<unknown>') + '.' + getattr(cls, '__name__', '<unknown>') baseresult = {'_type': clsname, '_key': obj.getkey()} if not attributes: return baseresult else: baseresult.update((k,dump(v, attributes, _refset)) for k,v in vars(obj).items() if k[:1] != '_') _refset.remove(id(obj)) return baseresult elif isinstance(obj, ReferenceObject): if obj._ref is not None: return dump(obj._ref, attributes, _refset) else: return {'_ref':obj.getkey()} elif isinstance(obj, WeakReferenceObject): return {'_weakref':obj.getkey()} elif isinstance(obj, DataObjectSet): return dump(list(obj.dataset())) elif isinstance(obj, dict): return dict((k, dump(v, attributes, _refset)) for k,v in obj.items()) elif isinstance(obj, list) or isinstance(obj, tuple) or isinstance(obj, set): return [dump(v, attributes, _refset) for v in obj] else: return obj
[ "def", "dump", "(", "obj", ",", "attributes", "=", "True", ",", "_refset", "=", "None", ")", ":", "if", "_refset", "is", "None", ":", "_refset", "=", "set", "(", ")", "if", "obj", "is", "None", ":", "return", "None", "elif", "isinstance", "(", "obj...
https://github.com/hubo1016/vlcp/blob/61c4c2595b610675ac0cbc4dbc46f70ec40090d3/vlcp/utils/dataobject.py#L583-L617
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/modelcluster/forms.py
python
ClusterForm.is_valid
(self)
return form_is_valid and formsets_are_valid
[]
def is_valid(self): form_is_valid = super(ClusterForm, self).is_valid() formsets_are_valid = all([formset.is_valid() for formset in self.formsets.values()]) return form_is_valid and formsets_are_valid
[ "def", "is_valid", "(", "self", ")", ":", "form_is_valid", "=", "super", "(", "ClusterForm", ",", "self", ")", ".", "is_valid", "(", ")", "formsets_are_valid", "=", "all", "(", "[", "formset", ".", "is_valid", "(", ")", "for", "formset", "in", "self", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/modelcluster/forms.py#L258-L261
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/states/hg.py
python
_update_repo
(ret, name, target, clean, user, identity, rev, opts, update_head)
return ret
Update the repo to a given revision. Using clean passes -C to the hg up
Update the repo to a given revision. Using clean passes -C to the hg up
[ "Update", "the", "repo", "to", "a", "given", "revision", ".", "Using", "clean", "passes", "-", "C", "to", "the", "hg", "up" ]
def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_head): """ Update the repo to a given revision. Using clean passes -C to the hg up """ log.debug('target %s is found, "hg pull && hg up is probably required"', target) current_rev = __salt__["hg.revision"](target, user=user, rev=".") if not current_rev: return _fail(ret, "Seems that {} is not a valid hg repo".format(target)) if __opts__["test"]: return _neutral_test( ret, "Repository {} update is probably required (current revision is {})".format( target, current_rev ), ) try: pull_out = __salt__["hg.pull"]( target, user=user, identity=identity, opts=opts, repository=name ) except CommandExecutionError as err: ret["result"] = False ret["comment"] = err return ret if update_head is False: changes = "no changes found" not in pull_out if changes: ret["comment"] = ( "Update is probably required but update_head=False so we will skip" " updating." ) else: ret[ "comment" ] = "No changes found and update_head=False so will skip updating." return ret if rev: try: __salt__["hg.update"](target, rev, force=clean, user=user) except CommandExecutionError as err: ret["result"] = False ret["comment"] = err return ret else: try: __salt__["hg.update"](target, "tip", force=clean, user=user) except CommandExecutionError as err: ret["result"] = False ret["comment"] = err return ret new_rev = __salt__["hg.revision"](cwd=target, user=user, rev=".") if current_rev != new_rev: revision_text = "{} => {}".format(current_rev, new_rev) log.info("Repository %s updated: %s", target, revision_text) ret["comment"] = "Repository {} updated.".format(target) ret["changes"]["revision"] = revision_text elif "error:" in pull_out: return _fail(ret, "An error was thrown by hg:\n{}".format(pull_out)) return ret
[ "def", "_update_repo", "(", "ret", ",", "name", ",", "target", ",", "clean", ",", "user", ",", "identity", ",", "rev", ",", "opts", ",", "update_head", ")", ":", "log", ".", "debug", "(", "'target %s is found, \"hg pull && hg up is probably required\"'", ",", ...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/states/hg.py#L113-L177
pypa/setuptools_scm
22724eb6c6613ba84f64b399d31f11333dbf3e4a
src/setuptools_scm/_overrides.py
python
_read_pretended_version_for
(config: Configuration)
read a a overridden version from the environment tries ``SETUPTOOLS_SCM_PRETEND_VERSION`` and ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_$UPPERCASE_DIST_NAME``
read a a overridden version from the environment
[ "read", "a", "a", "overridden", "version", "from", "the", "environment" ]
def _read_pretended_version_for(config: Configuration) -> Optional[ScmVersion]: """read a a overridden version from the environment tries ``SETUPTOOLS_SCM_PRETEND_VERSION`` and ``SETUPTOOLS_SCM_PRETEND_VERSION_FOR_$UPPERCASE_DIST_NAME`` """ trace("dist name:", config.dist_name) pretended: Optional[str] if config.dist_name is not None: pretended = os.environ.get( PRETEND_KEY_NAMED.format(name=config.dist_name.upper()) ) else: pretended = None if pretended is None: pretended = os.environ.get(PRETEND_KEY) if pretended is not None: # we use meta here since the pretended version # must adhere to the pep to begin with return meta(tag=pretended, preformatted=True, config=config) else: return None
[ "def", "_read_pretended_version_for", "(", "config", ":", "Configuration", ")", "->", "Optional", "[", "ScmVersion", "]", ":", "trace", "(", "\"dist name:\"", ",", "config", ".", "dist_name", ")", "pretended", ":", "Optional", "[", "str", "]", "if", "config", ...
https://github.com/pypa/setuptools_scm/blob/22724eb6c6613ba84f64b399d31f11333dbf3e4a/src/setuptools_scm/_overrides.py#L14-L37
vektort13/AntiOS
a4632c94e2106370a8cc8c8bd3e29ff0900bfe9b
system_fingerprint.py
python
WinFingerprint.random_ie_service_update
(self)
return self.ie_service_update
Internet Explorer Service Update (SvcKBNumber) :return: String in format "KBNNNNNNN"
Internet Explorer Service Update (SvcKBNumber) :return: String in format "KBNNNNNNN"
[ "Internet", "Explorer", "Service", "Update", "(", "SvcKBNumber", ")", ":", "return", ":", "String", "in", "format", "KBNNNNNNN" ]
def random_ie_service_update(self): """ Internet Explorer Service Update (SvcKBNumber) :return: String in format "KBNNNNNNN" """ return self.ie_service_update
[ "def", "random_ie_service_update", "(", "self", ")", ":", "return", "self", ".", "ie_service_update" ]
https://github.com/vektort13/AntiOS/blob/a4632c94e2106370a8cc8c8bd3e29ff0900bfe9b/system_fingerprint.py#L149-L154
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/util.py
python
cached_property.__get__
(self, obj, cls=None)
return value
[]
def __get__(self, obj, cls=None): if obj is None: return self value = self.func(obj) object.__setattr__(obj, self.func.__name__, value) #obj.__dict__[self.func.__name__] = value = self.func(obj) return value
[ "def", "__get__", "(", "self", ",", "obj", ",", "cls", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "self", "value", "=", "self", ".", "func", "(", "obj", ")", "object", ".", "__setattr__", "(", "obj", ",", "self", ".", "func"...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/distlib/util.py#L443-L449
XanaduAI/strawberryfields
298601e409528f22c6717c2d816ab68ae8bda1fa
strawberryfields/backends/bosonicbackend/backend.py
python
BosonicBackend.gaussian_cptp
(self, modes, X, Y=None)
r"""Transforms the state according to a deterministic Gaussian CPTP map. Args: modes (list): list of modes on which ``(X,Y)`` act X (array): matrix for multiplicative part of transformation Y (array): matrix for additive part of transformation
r"""Transforms the state according to a deterministic Gaussian CPTP map.
[ "r", "Transforms", "the", "state", "according", "to", "a", "deterministic", "Gaussian", "CPTP", "map", "." ]
def gaussian_cptp(self, modes, X, Y=None): r"""Transforms the state according to a deterministic Gaussian CPTP map. Args: modes (list): list of modes on which ``(X,Y)`` act X (array): matrix for multiplicative part of transformation Y (array): matrix for additive part of transformation """ if isinstance(modes, int): modes = [modes] if Y is not None: X2, Y2 = self.circuit.expandXY(modes, X, Y) self.circuit.apply_channel(X2, Y2) else: X2 = self.circuit.expandS(modes, X) self.circuit.apply_channel(X, Y)
[ "def", "gaussian_cptp", "(", "self", ",", "modes", ",", "X", ",", "Y", "=", "None", ")", ":", "if", "isinstance", "(", "modes", ",", "int", ")", ":", "modes", "=", "[", "modes", "]", "if", "Y", "is", "not", "None", ":", "X2", ",", "Y2", "=", ...
https://github.com/XanaduAI/strawberryfields/blob/298601e409528f22c6717c2d816ab68ae8bda1fa/strawberryfields/backends/bosonicbackend/backend.py#L756-L771
google/caliban
56f96e7e05b1d33ebdebc01620dc867f7ec54df3
tutorials/uv-metrics/trainer/train.py
python
local_reporter
(folder: str, job_name: str)
return FSReporter(local_path).stepped()
Returns a reporter implementation that persists metrics on the local filesystem in jsonl format.
Returns a reporter implementation that persists metrics on the local filesystem in jsonl format.
[ "Returns", "a", "reporter", "implementation", "that", "persists", "metrics", "on", "the", "local", "filesystem", "in", "jsonl", "format", "." ]
def local_reporter(folder: str, job_name: str): """Returns a reporter implementation that persists metrics on the local filesystem in jsonl format. """ local_path = fs.path.join(folder, job_name) return FSReporter(local_path).stepped()
[ "def", "local_reporter", "(", "folder", ":", "str", ",", "job_name", ":", "str", ")", ":", "local_path", "=", "fs", ".", "path", ".", "join", "(", "folder", ",", "job_name", ")", "return", "FSReporter", "(", "local_path", ")", ".", "stepped", "(", ")" ...
https://github.com/google/caliban/blob/56f96e7e05b1d33ebdebc01620dc867f7ec54df3/tutorials/uv-metrics/trainer/train.py#L197-L203
yongzhuo/Macropodus
1d7b8f9938cb8b6d7744e9caabc3eb41c8891283
macropodus/network/service/server_streamer.py
python
ServiceNer.streamer_init
(self)
ner初始化 :param model: class, like "ner_model" :param cuda_devices: str, like "processing", "thread" :param stream_type: str, like "0,1" :param batch_size: int, like 32 :param max_latency: float, 0-1, like 0.01 :param worker_num: int, like 2 :return:
ner初始化 :param model: class, like "ner_model" :param cuda_devices: str, like "processing", "thread" :param stream_type: str, like "0,1" :param batch_size: int, like 32 :param max_latency: float, 0-1, like 0.01 :param worker_num: int, like 2 :return:
[ "ner初始化", ":", "param", "model", ":", "class", "like", "ner_model", ":", "param", "cuda_devices", ":", "str", "like", "processing", "thread", ":", "param", "stream_type", ":", "str", "like", "0", "1", ":", "param", "batch_size", ":", "int", "like", "32", ...
def streamer_init(self): """ ner初始化 :param model: class, like "ner_model" :param cuda_devices: str, like "processing", "thread" :param stream_type: str, like "0,1" :param batch_size: int, like 32 :param max_latency: float, 0-1, like 0.01 :param worker_num: int, like 2 :return: """ model = AlbertBilstmPredict(self.path_abs) if self.stream_type == "thread": self.streamer = ThreadedStreamer(model, self.batch_size, self.max_latency) else: self.streamer = Streamer(predict_function_or_model=model, cuda_devices=self.cuda_devices, max_latency=self.max_latency, worker_num=self.worker_num, batch_size=self.batch_size) self.streamer._wait_for_worker_ready()
[ "def", "streamer_init", "(", "self", ")", ":", "model", "=", "AlbertBilstmPredict", "(", "self", ".", "path_abs", ")", "if", "self", ".", "stream_type", "==", "\"thread\"", ":", "self", ".", "streamer", "=", "ThreadedStreamer", "(", "model", ",", "self", "...
https://github.com/yongzhuo/Macropodus/blob/1d7b8f9938cb8b6d7744e9caabc3eb41c8891283/macropodus/network/service/server_streamer.py#L120-L140
tracim/tracim
a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21
backend/tracim_backend/config.py
python
CFG.load_and_check_json_file_path_param
(self, param_name: str, path: str,)
Check if path is valid json file and load it :param param_name: name of parameter to check :param path: path (value of parameter) which is check as a file path :return: json content as dictionnary
Check if path is valid json file and load it :param param_name: name of parameter to check :param path: path (value of parameter) which is check as a file path :return: json content as dictionnary
[ "Check", "if", "path", "is", "valid", "json", "file", "and", "load", "it", ":", "param", "param_name", ":", "name", "of", "parameter", "to", "check", ":", "param", "path", ":", "path", "(", "value", "of", "parameter", ")", "which", "is", "check", "as",...
def load_and_check_json_file_path_param(self, param_name: str, path: str,) -> dict: """ Check if path is valid json file and load it :param param_name: name of parameter to check :param path: path (value of parameter) which is check as a file path :return: json content as dictionnary """ try: with open(path) as json_file: return json.load(json_file) except json.JSONDecodeError as exc: not_a_valid_json_file_msg = ( 'ERROR: "{}" is not a valid json file path, ' 'change "{}" content ' "to a valid json content." ) raise ConfigurationError(not_a_valid_json_file_msg.format(path, param_name)) from exc
[ "def", "load_and_check_json_file_path_param", "(", "self", ",", "param_name", ":", "str", ",", "path", ":", "str", ",", ")", "->", "dict", ":", "try", ":", "with", "open", "(", "path", ")", "as", "json_file", ":", "return", "json", ".", "load", "(", "j...
https://github.com/tracim/tracim/blob/a0e9746fde5a4c45b4e0f0bfa2caf9522b8c4e21/backend/tracim_backend/config.py#L1437-L1453
hyperledger/aries-cloudagent-python
2f36776e99f6053ae92eed8123b5b1b2e891c02a
aries_cloudagent/vc/ld_proofs/purposes/proof_purpose.py
python
ProofPurpose.__eq__
(self, o: object)
return False
Check if object is same as ProofPurpose.
Check if object is same as ProofPurpose.
[ "Check", "if", "object", "is", "same", "as", "ProofPurpose", "." ]
def __eq__(self, o: object) -> bool: """Check if object is same as ProofPurpose.""" if isinstance(o, ProofPurpose): return ( self.date == o.date and self.term == o.term and self.max_timestamp_delta == o.max_timestamp_delta ) return False
[ "def", "__eq__", "(", "self", ",", "o", ":", "object", ")", "->", "bool", ":", "if", "isinstance", "(", "o", ",", "ProofPurpose", ")", ":", "return", "(", "self", ".", "date", "==", "o", ".", "date", "and", "self", ".", "term", "==", "o", ".", ...
https://github.com/hyperledger/aries-cloudagent-python/blob/2f36776e99f6053ae92eed8123b5b1b2e891c02a/aries_cloudagent/vc/ld_proofs/purposes/proof_purpose.py#L62-L71
CPqD/RouteFlow
3f406b9c1a0796f40a86eb1194990cdd2c955f4d
pox/pox/openflow/topology.py
python
OFSyncFlowTable.remove_strict
(self, entries=[])
asynchronously remove entries in the flow table. will raise a FlowTableModification event when the change has been processed by the switch
asynchronously remove entries in the flow table. will raise a FlowTableModification event when the change has been processed by the switch
[ "asynchronously", "remove", "entries", "in", "the", "flow", "table", ".", "will", "raise", "a", "FlowTableModification", "event", "when", "the", "change", "has", "been", "processed", "by", "the", "switch" ]
def remove_strict (self, entries=[]): """ asynchronously remove entries in the flow table. will raise a FlowTableModification event when the change has been processed by the switch """ self._mod(entries, OFSyncFlowTable.REMOVE_STRICT)
[ "def", "remove_strict", "(", "self", ",", "entries", "=", "[", "]", ")", ":", "self", ".", "_mod", "(", "entries", ",", "OFSyncFlowTable", ".", "REMOVE_STRICT", ")" ]
https://github.com/CPqD/RouteFlow/blob/3f406b9c1a0796f40a86eb1194990cdd2c955f4d/pox/pox/openflow/topology.py#L341-L348
pantsbuild/pex
473c6ac732ed4bc338b4b20a9ec930d1d722c9b4
pex/vendor/_vendored/pip/pip/_vendor/cachecontrol/cache.py
python
DictCache.get
(self, key)
return self.data.get(key, None)
[]
def get(self, key): return self.data.get(key, None)
[ "def", "get", "(", "self", ",", "key", ")", ":", "return", "self", ".", "data", ".", "get", "(", "key", ",", "None", ")" ]
https://github.com/pantsbuild/pex/blob/473c6ac732ed4bc338b4b20a9ec930d1d722c9b4/pex/vendor/_vendored/pip/pip/_vendor/cachecontrol/cache.py#L29-L30
tanghaibao/goatools
647e9dd833695f688cd16c2f9ea18f1692e5c6bc
goatools/gosubdag/gosubdag_init.py
python
InitFields.__init__
(self, ini_main, **kws)
[]
def __init__(self, ini_main, **kws): self.go2obj_orig = ini_main.go2obj_orig self.go2obj = ini_main.go2obj self.kws = get_kwargs(kws, self.exp_keys, None) if 'rcntobj' not in kws: self.kws['rcntobj'] = True self.kw_elems = self._init_kwelems() self.relationships = ini_main.relationships self.prt_flds = self._init_prt_flds() self.go2reldepth = self._init_go2reldepth()
[ "def", "__init__", "(", "self", ",", "ini_main", ",", "*", "*", "kws", ")", ":", "self", ".", "go2obj_orig", "=", "ini_main", ".", "go2obj_orig", "self", ".", "go2obj", "=", "ini_main", ".", "go2obj", "self", ".", "kws", "=", "get_kwargs", "(", "kws", ...
https://github.com/tanghaibao/goatools/blob/647e9dd833695f688cd16c2f9ea18f1692e5c6bc/goatools/gosubdag/gosubdag_init.py#L109-L118
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/violin/_box.py
python
Box.width
(self)
return self["width"]
Sets the width of the inner box plots relative to the violins' width. For example, with 1, the inner box plots are as wide as the violins. The 'width' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the width of the inner box plots relative to the violins' width. For example, with 1, the inner box plots are as wide as the violins. The 'width' property is a number and may be specified as: - An int or float in the interval [0, 1]
[ "Sets", "the", "width", "of", "the", "inner", "box", "plots", "relative", "to", "the", "violins", "width", ".", "For", "example", "with", "1", "the", "inner", "box", "plots", "are", "as", "wide", "as", "the", "violins", ".", "The", "width", "property", ...
def width(self): """ Sets the width of the inner box plots relative to the violins' width. For example, with 1, the inner box plots are as wide as the violins. The 'width' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["width"]
[ "def", "width", "(", "self", ")", ":", "return", "self", "[", "\"width\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/violin/_box.py#L124-L137
duo-labs/isthislegit
5d51fd2e0fe070cacd1ee169ca8a371a72e005ef
dashboard/lib/flanker/mime/message/headers/headers.py
python
MimeHeaders.__contains__
(self, key)
return normalize(key) in self._v
[]
def __contains__(self, key): return normalize(key) in self._v
[ "def", "__contains__", "(", "self", ",", "key", ")", ":", "return", "normalize", "(", "key", ")", "in", "self", ".", "_v" ]
https://github.com/duo-labs/isthislegit/blob/5d51fd2e0fe070cacd1ee169ca8a371a72e005ef/dashboard/lib/flanker/mime/message/headers/headers.py#L33-L34
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
cpython/Lib/lib-tk/Tkinter.py
python
PhotoImage.zoom
(self,x,y='')
return destImage
Return a new PhotoImage with the same image as this widget but zoom it with X and Y.
Return a new PhotoImage with the same image as this widget but zoom it with X and Y.
[ "Return", "a", "new", "PhotoImage", "with", "the", "same", "image", "as", "this", "widget", "but", "zoom", "it", "with", "X", "and", "Y", "." ]
def zoom(self,x,y=''): """Return a new PhotoImage with the same image as this widget but zoom it with X and Y.""" destImage = PhotoImage() if y=='': y=x self.tk.call(destImage, 'copy', self.name, '-zoom',x,y) return destImage
[ "def", "zoom", "(", "self", ",", "x", ",", "y", "=", "''", ")", ":", "destImage", "=", "PhotoImage", "(", ")", "if", "y", "==", "''", ":", "y", "=", "x", "self", ".", "tk", ".", "call", "(", "destImage", ",", "'copy'", ",", "self", ".", "name...
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/cpython/Lib/lib-tk/Tkinter.py#L3260-L3266
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/com.oracle.graal.python.benchmarks/python/meso/pathfinder_rodinia.py
python
__benchmark__
(iteration=10)
[]
def __benchmark__(iteration=10): measure(iteration)
[ "def", "__benchmark__", "(", "iteration", "=", "10", ")", ":", "measure", "(", "iteration", ")" ]
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/com.oracle.graal.python.benchmarks/python/meso/pathfinder_rodinia.py#L84-L85
Dash-Industry-Forum/dash-live-source-simulator
23cb15c35656a731d9f6d78a30f2713eff2ec20d
dashlivesim/dashlib/mp4.py
python
tfra_box.__init__
(self, *args)
[]
def __init__(self, *args): super().__init__(*args) self.random_access_time = [] self.random_access_moof_offset = []
[ "def", "__init__", "(", "self", ",", "*", "args", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ")", "self", ".", "random_access_time", "=", "[", "]", "self", ".", "random_access_moof_offset", "=", "[", "]" ]
https://github.com/Dash-Industry-Forum/dash-live-source-simulator/blob/23cb15c35656a731d9f6d78a30f2713eff2ec20d/dashlivesim/dashlib/mp4.py#L1393-L1396
yuxiaokui/Intranet-Penetration
f57678a204840c83cbf3308e3470ae56c5ff514b
proxy/XX-Net/code/default/python27/1.0/lib/noarch/pycparser/c_parser.py
python
CParser.p_specifier_qualifier_list_1
(self, p)
specifier_qualifier_list : type_qualifier specifier_qualifier_list_opt
specifier_qualifier_list : type_qualifier specifier_qualifier_list_opt
[ "specifier_qualifier_list", ":", "type_qualifier", "specifier_qualifier_list_opt" ]
def p_specifier_qualifier_list_1(self, p): """ specifier_qualifier_list : type_qualifier specifier_qualifier_list_opt """ p[0] = self._add_declaration_specifier(p[2], p[1], 'qual')
[ "def", "p_specifier_qualifier_list_1", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "_add_declaration_specifier", "(", "p", "[", "2", "]", ",", "p", "[", "1", "]", ",", "'qual'", ")" ]
https://github.com/yuxiaokui/Intranet-Penetration/blob/f57678a204840c83cbf3308e3470ae56c5ff514b/proxy/XX-Net/code/default/python27/1.0/lib/noarch/pycparser/c_parser.py#L769-L772
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/entities/image.py
python
ImageBase.set_boundary_path
(self, vertices: Iterable["Vertex"])
Set boundary path to `vertices`. Two vertices describe a rectangle (lower left and upper right corner), more than two vertices is a polygon as clipping path.
Set boundary path to `vertices`. Two vertices describe a rectangle (lower left and upper right corner), more than two vertices is a polygon as clipping path.
[ "Set", "boundary", "path", "to", "vertices", ".", "Two", "vertices", "describe", "a", "rectangle", "(", "lower", "left", "and", "upper", "right", "corner", ")", "more", "than", "two", "vertices", "is", "a", "polygon", "as", "clipping", "path", "." ]
def set_boundary_path(self, vertices: Iterable["Vertex"]) -> None: """Set boundary path to `vertices`. Two vertices describe a rectangle (lower left and upper right corner), more than two vertices is a polygon as clipping path. """ _vertices = Vec2.list(vertices) if len(_vertices): if len(_vertices) > 2 and not _vertices[-1].isclose(_vertices[0]): # Close path, otherwise AutoCAD crashes _vertices.append(_vertices[0]) self._boundary_path = _vertices self.set_flag_state(self.USE_CLIPPING_BOUNDARY, state=True) self.dxf.clipping = 1 self.dxf.clipping_boundary_type = 1 if len(_vertices) < 3 else 2 self.dxf.count_boundary_points = len(self._boundary_path) else: self.reset_boundary_path()
[ "def", "set_boundary_path", "(", "self", ",", "vertices", ":", "Iterable", "[", "\"Vertex\"", "]", ")", "->", "None", ":", "_vertices", "=", "Vec2", ".", "list", "(", "vertices", ")", "if", "len", "(", "_vertices", ")", ":", "if", "len", "(", "_vertice...
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/entities/image.py#L144-L161
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/networkx/algorithms/bipartite/basic.py
python
degrees
(B, nodes, weight=None)
return (B.degree(top,weight),B.degree(bottom,weight))
Return the degrees of the two node sets in the bipartite graph B. Parameters ---------- G : NetworkX graph nodes: list or container Nodes in one node set of the bipartite graph. weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. Returns ------- (degX,degY) : tuple of dictionaries The degrees of the two bipartite sets as dictionaries keyed by node. Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.complete_bipartite_graph(3,2) >>> Y=set([3,4]) >>> degX,degY=bipartite.degrees(G,Y) >>> dict(degX) {0: 2, 1: 2, 2: 2} Notes ----- The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid ambiguity in the case of disconnected graphs. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- color, density
Return the degrees of the two node sets in the bipartite graph B.
[ "Return", "the", "degrees", "of", "the", "two", "node", "sets", "in", "the", "bipartite", "graph", "B", "." ]
def degrees(B, nodes, weight=None): """Return the degrees of the two node sets in the bipartite graph B. Parameters ---------- G : NetworkX graph nodes: list or container Nodes in one node set of the bipartite graph. weight : string or None, optional (default=None) The edge attribute that holds the numerical value used as a weight. If None, then each edge has weight 1. The degree is the sum of the edge weights adjacent to the node. Returns ------- (degX,degY) : tuple of dictionaries The degrees of the two bipartite sets as dictionaries keyed by node. Examples -------- >>> from networkx.algorithms import bipartite >>> G = nx.complete_bipartite_graph(3,2) >>> Y=set([3,4]) >>> degX,degY=bipartite.degrees(G,Y) >>> dict(degX) {0: 2, 1: 2, 2: 2} Notes ----- The container of nodes passed as argument must contain all nodes in one of the two bipartite node sets to avoid ambiguity in the case of disconnected graphs. See :mod:`bipartite documentation <networkx.algorithms.bipartite>` for further details on how bipartite graphs are handled in NetworkX. See Also -------- color, density """ bottom=set(nodes) top=set(B)-bottom return (B.degree(top,weight),B.degree(bottom,weight))
[ "def", "degrees", "(", "B", ",", "nodes", ",", "weight", "=", "None", ")", ":", "bottom", "=", "set", "(", "nodes", ")", "top", "=", "set", "(", "B", ")", "-", "bottom", "return", "(", "B", ".", "degree", "(", "top", ",", "weight", ")", ",", ...
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/networkx/algorithms/bipartite/basic.py#L260-L303
aliyun/aliyun-openapi-python-sdk
bda53176cc9cf07605b1cf769f0df444cca626a0
aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/adapters.py
python
HTTPAdapter.send
(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None)
return self.build_response(request, resp)
Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response
Sends PreparedRequest object. Returns Response object.
[ "Sends", "PreparedRequest", "object", ".", "Returns", "Response", "object", "." ]
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple or urllib3 Timeout object :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use :param cert: (optional) Any user-provided SSL certificate to be trusted. :param proxies: (optional) The proxies dictionary to apply to the request. :rtype: requests.Response """ conn = self.get_connection(request.url, proxies) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request) chunked = not (request.body is None or 'Content-Length' in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout timeout = TimeoutSauce(connect=connect, read=read) except ValueError as e: # this may raise a string formatting error. err = ("Invalid timeout {0}. Pass a (connect, read) " "timeout tuple, or a single float to set " "both timeouts to the same value".format(timeout)) raise ValueError(err) elif isinstance(timeout, TimeoutSauce): pass else: timeout = TimeoutSauce(connect=timeout, read=timeout) try: if not chunked: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=timeout ) # Send the request. else: if hasattr(conn, 'proxy_pool'): conn = conn.proxy_pool low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT) try: low_conn.putrequest(request.method, url, skip_accept_encoding=True) for header, value in request.headers.items(): low_conn.putheader(header, value) low_conn.endheaders() for i in request.body: low_conn.send(hex(len(i))[2:].encode('utf-8')) low_conn.send(b'\r\n') low_conn.send(i) low_conn.send(b'\r\n') low_conn.send(b'0\r\n\r\n') # Receive the response from the server try: # For Python 2.7+ versions, use buffering of HTTP # responses r = low_conn.getresponse(buffering=True) except TypeError: # For compatibility with Python 2.6 versions and back r = low_conn.getresponse() resp = HTTPResponse.from_httplib( r, pool=conn, connection=low_conn, preload_content=False, decode_content=False ) except: # If we hit any problems here, clean up the connection. # Then, reraise so that we can handle the actual exception. low_conn.close() raise except (ProtocolError, socket.error) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): # TODO: Remove this in 3.0.0: see #2811 if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): # This branch is for urllib3 v1.22 and later. raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): # This branch is for urllib3 versions earlier than v1.22 raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) else: raise return self.build_response(request, resp)
[ "def", "send", "(", "self", ",", "request", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "conn", "=", "self", ".", "get_connection", "(", "req...
https://github.com/aliyun/aliyun-openapi-python-sdk/blob/bda53176cc9cf07605b1cf769f0df444cca626a0/aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/adapters.py#L388-L525
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/graphics/widgets/GLPane_minimal.py
python
GLPane_minimal.__init__
(self, parent, shareWidget, useStencilBuffer)
return
#doc @note: If shareWidget is specified, useStencilBuffer is ignored: set it in the widget you're sharing with.
#doc
[ "#doc" ]
def __init__(self, parent, shareWidget, useStencilBuffer): """ #doc @note: If shareWidget is specified, useStencilBuffer is ignored: set it in the widget you're sharing with. """ if shareWidget: self.shareWidget = shareWidget #bruce 051212 glformat = shareWidget.format() QGLWidget.__init__(self, glformat, parent, shareWidget) if not self.isSharing(): assert 0, "%r refused to share GL display list namespace " \ "with %r" % (self, shareWidget) return else: glformat = QGLFormat() if (useStencilBuffer): glformat.setStencil(True) # set gl format to request stencil buffer # (needed for mouseover-highlighting of objects of general # shape in BuildAtoms_Graphicsmode.bareMotion) [bruce 050610] if (self.useMultisample): # use full scene anti-aliasing on hardware that supports it # (note: setting this True works around bug 2961 on some systems) glformat.setSampleBuffers(True) QGLWidget.__init__(self, glformat, parent) pass self.glprefs = drawing_globals.glprefs # future: should be ok if this differs for different glpanes, # even between self and self.shareWidget. AFAIK, the refactoring # I'm doing yesterday and today means this would work fine, # or at least it does most of what would be required for that. # [bruce 090304] self._initialize_view_attributes() # Initial value of depth "constant" (changeable by prefs.) self.DEPTH_TWEAK = DEPTH_TWEAK_UNITS * DEPTH_TWEAK_VALUE self.trackball = Trackball(10, 10) self._functions_to_call_when_gl_context_is_current = [] # piotr 080714: Defined this attribute here in case # chunk.py accesses it in ThumbView. self.lastNonReducedDisplayMode = default_display_mode # piotr 080807 # Most recent quaternion to be used in animation timer. self.last_quat = None self.transforms = [] ### TODO: clear this at start of frame, complain if not clear # stack of current transforms (or Nodes that generate them) # [bruce 090220] # Note: this may be revised once we have TransformNode, # e.g. we might push their dt and st separately; # note we might need to push a "slot" for them if they might # change before being popped, or perhaps even if they might # change between the time pushed and the time later used # (by something that collects them from here in association # with a ColorSortedDisplayList). return
[ "def", "__init__", "(", "self", ",", "parent", ",", "shareWidget", ",", "useStencilBuffer", ")", ":", "if", "shareWidget", ":", "self", ".", "shareWidget", "=", "shareWidget", "#bruce 051212", "glformat", "=", "shareWidget", ".", "format", "(", ")", "QGLWidget...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/graphics/widgets/GLPane_minimal.py#L170-L236
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/dagcircuit/dagcircuit.py
python
DAGCircuit.collect_runs
(self, namelist)
return {tuple(x) for x in group_list}
Return a set of non-conditional runs of "op" nodes with the given names. For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .." would produce the tuple of cx nodes as an element of the set returned from a call to collect_runs(["cx"]). If instead the cx nodes were "cx q[0],q[1]; cx q[1],q[0];", the method would still return the pair in a tuple. The namelist can contain names that are not in the circuit's basis. Nodes must have only one successor to continue the run.
Return a set of non-conditional runs of "op" nodes with the given names.
[ "Return", "a", "set", "of", "non", "-", "conditional", "runs", "of", "op", "nodes", "with", "the", "given", "names", "." ]
def collect_runs(self, namelist): """Return a set of non-conditional runs of "op" nodes with the given names. For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .." would produce the tuple of cx nodes as an element of the set returned from a call to collect_runs(["cx"]). If instead the cx nodes were "cx q[0],q[1]; cx q[1],q[0];", the method would still return the pair in a tuple. The namelist can contain names that are not in the circuit's basis. Nodes must have only one successor to continue the run. """ def filter_fn(node): return ( isinstance(node, DAGOpNode) and node.op.name in namelist and node.op.condition is None ) group_list = rx.collect_runs(self._multi_graph, filter_fn) return {tuple(x) for x in group_list}
[ "def", "collect_runs", "(", "self", ",", "namelist", ")", ":", "def", "filter_fn", "(", "node", ")", ":", "return", "(", "isinstance", "(", "node", ",", "DAGOpNode", ")", "and", "node", ".", "op", ".", "name", "in", "namelist", "and", "node", ".", "o...
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/dagcircuit/dagcircuit.py#L1624-L1645
xlcnd/isbntools
e7c85f0f4b3dd023b43b0b5daccbd8f6f62250f9
isbntools/bin/repl.py
python
ISBNRepl.complete_meta
(self, text, line, begidx, endidx)
return self._provandfmts(text)
Autocomplete providers.
Autocomplete providers.
[ "Autocomplete", "providers", "." ]
def complete_meta(self, text, line, begidx, endidx): """Autocomplete providers.""" return self._provandfmts(text)
[ "def", "complete_meta", "(", "self", ",", "text", ",", "line", ",", "begidx", ",", "endidx", ")", ":", "return", "self", ".", "_provandfmts", "(", "text", ")" ]
https://github.com/xlcnd/isbntools/blob/e7c85f0f4b3dd023b43b0b5daccbd8f6f62250f9/isbntools/bin/repl.py#L334-L336
openstack/python-neutronclient
517bef2c5454dde2eba5cc2194ee857be6be7164
neutronclient/v2_0/client.py
python
Client.show_flavor
(self, flavor, **_params)
return self.get(self.flavor_path % (flavor), params=_params)
Fetches information for a certain Neutron service flavor.
Fetches information for a certain Neutron service flavor.
[ "Fetches", "information", "for", "a", "certain", "Neutron", "service", "flavor", "." ]
def show_flavor(self, flavor, **_params): """Fetches information for a certain Neutron service flavor.""" return self.get(self.flavor_path % (flavor), params=_params)
[ "def", "show_flavor", "(", "self", ",", "flavor", ",", "*", "*", "_params", ")", ":", "return", "self", ".", "get", "(", "self", ".", "flavor_path", "%", "(", "flavor", ")", ",", "params", "=", "_params", ")" ]
https://github.com/openstack/python-neutronclient/blob/517bef2c5454dde2eba5cc2194ee857be6be7164/neutronclient/v2_0/client.py#L2066-L2068
jaywink/socialhome
c3178b044936a5c57a502ab6ed2b4f43c8e076ca
socialhome/federate/views.py
python
webfinger_view
(request)
return HttpResponse(webfinger, content_type="application/xrd+xml")
Generate a webfinger document.
Generate a webfinger document.
[ "Generate", "a", "webfinger", "document", "." ]
def webfinger_view(request): """Generate a webfinger document.""" q = request.GET.get("q") if not q: raise Http404() username = q.split("@")[0] if username.startswith("acct:"): username = username.replace("acct:", "", 1) user = get_object_or_404(User, username=username) # Create webfinger document webfinger = generate_legacy_webfinger( "diaspora", handle="{username}@{domain}".format(username=user.username, domain=settings.SOCIALHOME_DOMAIN), host=settings.SOCIALHOME_URL, guid=str(user.profile.uuid), public_key=user.profile.rsa_public_key ) return HttpResponse(webfinger, content_type="application/xrd+xml")
[ "def", "webfinger_view", "(", "request", ")", ":", "q", "=", "request", ".", "GET", ".", "get", "(", "\"q\"", ")", "if", "not", "q", ":", "raise", "Http404", "(", ")", "username", "=", "q", ".", "split", "(", "\"@\"", ")", "[", "0", "]", "if", ...
https://github.com/jaywink/socialhome/blob/c3178b044936a5c57a502ab6ed2b4f43c8e076ca/socialhome/federate/views.py#L37-L54
algorhythms/LeetCode
3fb14aeea62a960442e47dfde9f964c7ffce32be
670 Maximum Swap.py
python
Solution.maximumSwap
(self, num: int)
return int("".join(nums))
stk maintain a increasing stack from right to left
stk maintain a increasing stack from right to left
[ "stk", "maintain", "a", "increasing", "stack", "from", "right", "to", "left" ]
def maximumSwap(self, num: int) -> int: """ stk maintain a increasing stack from right to left """ stk = [] nums = list(str(num)) n = len(nums) for i in range(n-1, -1, -1): if stk and stk[-1][1] >= nums[i]: # only keep the rightmost duplicate continue stk.append((i, nums[i])) for i in range(n): while stk and stk[-1][0] <= i: stk.pop() if stk and stk[-1][1] > nums[i]: j = stk[-1][0] nums[i], nums[j] = nums[j], nums[i] break return int("".join(nums))
[ "def", "maximumSwap", "(", "self", ",", "num", ":", "int", ")", "->", "int", ":", "stk", "=", "[", "]", "nums", "=", "list", "(", "str", "(", "num", ")", ")", "n", "=", "len", "(", "nums", ")", "for", "i", "in", "range", "(", "n", "-", "1",...
https://github.com/algorhythms/LeetCode/blob/3fb14aeea62a960442e47dfde9f964c7ffce32be/670 Maximum Swap.py#L20-L40
hubo1016/vlcp
61c4c2595b610675ac0cbc4dbc46f70ec40090d3
vlcp/event/runnable.py
python
RoutineContainer.wait_for_all
(self, *matchers, eventlist = None, eventdict = None, callback = None)
return eventlist, eventdict
Wait until each matcher matches an event. When this coroutine method returns, `eventlist` is set to the list of events in the arriving order (may not be the same as the matchers); `eventdict` is set to a dictionary `{matcher1: event1, matcher2: event2, ...}` :param eventlist: use external event list, so when an exception occurs (e.g. routine close), you can retrieve the result from the passed-in list :param eventdict: use external event dict :param callback: if not None, the callback should be a callable callback(event, matcher) which is called each time an event is received :return: (eventlist, eventdict)
Wait until each matcher matches an event. When this coroutine method returns, `eventlist` is set to the list of events in the arriving order (may not be the same as the matchers); `eventdict` is set to a dictionary `{matcher1: event1, matcher2: event2, ...}` :param eventlist: use external event list, so when an exception occurs (e.g. routine close), you can retrieve the result from the passed-in list :param eventdict: use external event dict :param callback: if not None, the callback should be a callable callback(event, matcher) which is called each time an event is received :return: (eventlist, eventdict)
[ "Wait", "until", "each", "matcher", "matches", "an", "event", ".", "When", "this", "coroutine", "method", "returns", "eventlist", "is", "set", "to", "the", "list", "of", "events", "in", "the", "arriving", "order", "(", "may", "not", "be", "the", "same", ...
async def wait_for_all(self, *matchers, eventlist = None, eventdict = None, callback = None): """ Wait until each matcher matches an event. When this coroutine method returns, `eventlist` is set to the list of events in the arriving order (may not be the same as the matchers); `eventdict` is set to a dictionary `{matcher1: event1, matcher2: event2, ...}` :param eventlist: use external event list, so when an exception occurs (e.g. routine close), you can retrieve the result from the passed-in list :param eventdict: use external event dict :param callback: if not None, the callback should be a callable callback(event, matcher) which is called each time an event is received :return: (eventlist, eventdict) """ if eventdict is None: eventdict = {} if eventlist is None: eventlist = [] ms = len(matchers) last_matchers = Diff_(matchers) while ms: ev, m = await last_matchers ms -= 1 if callback: callback(ev, m) eventlist.append(ev) eventdict[m] = ev last_matchers = Diff_(last_matchers, remove=(m,)) return eventlist, eventdict
[ "async", "def", "wait_for_all", "(", "self", ",", "*", "matchers", ",", "eventlist", "=", "None", ",", "eventdict", "=", "None", ",", "callback", "=", "None", ")", ":", "if", "eventdict", "is", "None", ":", "eventdict", "=", "{", "}", "if", "eventlist"...
https://github.com/hubo1016/vlcp/blob/61c4c2595b610675ac0cbc4dbc46f70ec40090d3/vlcp/event/runnable.py#L585-L617
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/Django-1.11.29/django/contrib/gis/geos/point.py
python
Point.y
(self, value)
Sets the Y component of the Point.
Sets the Y component of the Point.
[ "Sets", "the", "Y", "component", "of", "the", "Point", "." ]
def y(self, value): "Sets the Y component of the Point." self._cs.setOrdinate(1, 0, value)
[ "def", "y", "(", "self", ",", "value", ")", ":", "self", ".", "_cs", ".", "setOrdinate", "(", "1", ",", "0", ",", "value", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/Django-1.11.29/django/contrib/gis/geos/point.py#L127-L129
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/simulated/sensor.py
python
SimulatedSensor.time_delta
(self)
return dt1 - dt0
Return the time delta.
Return the time delta.
[ "Return", "the", "time", "delta", "." ]
def time_delta(self): """Return the time delta.""" dt0 = self._start_time dt1 = dt_util.utcnow() return dt1 - dt0
[ "def", "time_delta", "(", "self", ")", ":", "dt0", "=", "self", ".", "_start_time", "dt1", "=", "dt_util", ".", "utcnow", "(", ")", "return", "dt1", "-", "dt0" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/simulated/sensor.py#L103-L107
PaddlePaddle/PGL
e48545f2814523c777b8a9a9188bf5a7f00d6e52
apps/Graph4KG/utils.py
python
print_log
(step, interval, log, timer, time_sum)
Print log to logger.
Print log to logger.
[ "Print", "log", "to", "logger", "." ]
def print_log(step, interval, log, timer, time_sum): """Print log to logger. """ logging.info( 'step: %d, loss: %.5f, reg: %.4e, speed: %.2f steps/s, time: %.2f s' % (step, log['loss'] / interval, log['reg'] / interval, interval / time_sum, time_sum)) logging.info('sample: %f, forward: %f, backward: %f, update: %f' % ( timer['sample'], timer['forward'], timer['backward'], timer['update']))
[ "def", "print_log", "(", "step", ",", "interval", ",", "log", ",", "timer", ",", "time_sum", ")", ":", "logging", ".", "info", "(", "'step: %d, loss: %.5f, reg: %.4e, speed: %.2f steps/s, time: %.2f s'", "%", "(", "step", ",", "log", "[", "'loss'", "]", "/", "...
https://github.com/PaddlePaddle/PGL/blob/e48545f2814523c777b8a9a9188bf5a7f00d6e52/apps/Graph4KG/utils.py#L64-L72
brendano/tweetmotif
1b0b1e3a941745cd5a26eba01f554688b7c4b27e
everything_else/djfrontend/django-1.0.2/dispatch/saferef.py
python
BoundNonDescriptorMethodWeakref.__call__
(self)
return None
Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference.
Return a strong reference to the bound method
[ "Return", "a", "strong", "reference", "to", "the", "bound", "method" ]
def __call__(self): """Return a strong reference to the bound method If the target cannot be retrieved, then will return None, otherwise returns a bound instance method for our object and function. Note: You may call this method any number of times, as it does not invalidate the reference. """ target = self.weakSelf() if target is not None: function = self.weakFunc() if function is not None: # Using curry() would be another option, but it erases the # "signature" of the function. That is, after a function is # curried, the inspect module can't be used to determine how # many arguments the function expects, nor what keyword # arguments it supports, and pydispatcher needs this # information. return getattr(target, function.__name__) return None
[ "def", "__call__", "(", "self", ")", ":", "target", "=", "self", ".", "weakSelf", "(", ")", "if", "target", "is", "not", "None", ":", "function", "=", "self", ".", "weakFunc", "(", ")", "if", "function", "is", "not", "None", ":", "# Using curry() would...
https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/dispatch/saferef.py#L218-L240
NaturalHistoryMuseum/inselect
196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6
inselect/gui/main_window.py
python
MainWindow._sync_recent_documents_actions
(self)
Synchronises the 'recent documents' actions
Synchronises the 'recent documents' actions
[ "Synchronises", "the", "recent", "documents", "actions" ]
def _sync_recent_documents_actions(self): "Synchronises the 'recent documents' actions" debug_print('MainWindow._sync_recent_documents_actions') recent = RecentDocuments().read_paths() if not recent: # No recent documents - a single disabled action with placeholder # text self.recent_doc_actions[0].setEnabled(False) self.recent_doc_actions[0].setText('No recent documents') self.recent_doc_actions[0].setVisible(True) hide_actions_after = 1 elif len(recent) > len(self.recent_doc_actions): msg = 'Unexpected number of recent documents [{0}]' raise ValueError(msg.format(len(recent))) else: # Show as many actions as there are recent documents for index, path, action in zip(count(), recent, self.recent_doc_actions): action.setEnabled(True) action.setText(path.stem) action.setToolTip(str(path)) action.setVisible(True) hide_actions_after = 1 + index # Hide all actions after and including 'hide_actions_after' for action in self.recent_doc_actions[hide_actions_after:]: action.setVisible(False) action.setText('')
[ "def", "_sync_recent_documents_actions", "(", "self", ")", ":", "debug_print", "(", "'MainWindow._sync_recent_documents_actions'", ")", "recent", "=", "RecentDocuments", "(", ")", ".", "read_paths", "(", ")", "if", "not", "recent", ":", "# No recent documents - a single...
https://github.com/NaturalHistoryMuseum/inselect/blob/196a3ae2a0ed4e2c7cb667aaba9a6be1bcd90ca6/inselect/gui/main_window.py#L375-L401
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/utils.py
python
fletcher16_checkbytes
(binbuf, offset)
return chb(x) + chb(y)
Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string. Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 the integrity of the buffer on the receiver side. For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501
Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string.
[ "Calculates", "the", "Fletcher", "-", "16", "checkbytes", "returned", "as", "2", "byte", "binary", "-", "string", "." ]
def fletcher16_checkbytes(binbuf, offset): # type: (bytes, int) -> bytes """Calculates the Fletcher-16 checkbytes returned as 2 byte binary-string. Including the bytes into the buffer (at the position marked by offset) the # noqa: E501 global Fletcher-16 checksum of the buffer will be 0. Thus it is easy to verify # noqa: E501 the integrity of the buffer on the receiver side. For details on the algorithm, see RFC 2328 chapter 12.1.7 and RFC 905 Annex B. # noqa: E501 """ # This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501 if len(binbuf) < offset: raise Exception("Packet too short for checkbytes %d" % len(binbuf)) binbuf = binbuf[:offset] + b"\x00\x00" + binbuf[offset + 2:] (c0, c1) = _fletcher16(binbuf) x = ((len(binbuf) - offset - 1) * c0 - c1) % 255 if (x <= 0): x += 255 y = 510 - c0 - x if (y > 255): y -= 255 return chb(x) + chb(y)
[ "def", "fletcher16_checkbytes", "(", "binbuf", ",", "offset", ")", ":", "# type: (bytes, int) -> bytes", "# This is based on the GPLed C implementation in Zebra <http://www.zebra.org/> # noqa: E501", "if", "len", "(", "binbuf", ")", "<", "offset", ":", "raise", "Exception", ...
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/utils.py#L531-L558