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
VitaliyRodnenko/geeknote
6bc226133c0d4d2902a76d4d2ac85964aac9bae7
geeknote/out.py
python
GetUserCredentials
()
return (login, password)
Prompts the user for a username and password.
Prompts the user for a username and password.
[ "Prompts", "the", "user", "for", "a", "username", "and", "password", "." ]
def GetUserCredentials(): """Prompts the user for a username and password.""" try: login = None password = None if login is None: login = rawInput("Login: ") if password is None: password = rawInput("Password: ", True) except (KeyboardInterrupt, SystemExit), e: if e.message: tools.exit(e.message) else: tools.exit return (login, password)
[ "def", "GetUserCredentials", "(", ")", ":", "try", ":", "login", "=", "None", "password", "=", "None", "if", "login", "is", "None", ":", "login", "=", "rawInput", "(", "\"Login: \"", ")", "if", "password", "is", "None", ":", "password", "=", "rawInput", ...
https://github.com/VitaliyRodnenko/geeknote/blob/6bc226133c0d4d2902a76d4d2ac85964aac9bae7/geeknote/out.py#L99-L115
graphbrain/graphbrain
96cb902d9e22d8dc8c2110ff3176b9aafdeba444
graphbrain/scripts/generate-parser-training-data.py
python
TrainingDataGenerator.__init__
(self, lang=None, parser_class=None)
[]
def __init__(self, lang=None, parser_class=None): self.parser = create_parser(lang=lang, parser_class=parser_class) self.sentences = set() self.tokens = 0 self.correct_edges = 0 self.ignored = 0 self.input_files = None self.sentence = None self.source = None self.atoms = None self.spacy_sentence = None self.token2atom = None
[ "def", "__init__", "(", "self", ",", "lang", "=", "None", ",", "parser_class", "=", "None", ")", ":", "self", ".", "parser", "=", "create_parser", "(", "lang", "=", "lang", ",", "parser_class", "=", "parser_class", ")", "self", ".", "sentences", "=", "...
https://github.com/graphbrain/graphbrain/blob/96cb902d9e22d8dc8c2110ff3176b9aafdeba444/graphbrain/scripts/generate-parser-training-data.py#L22-L36
learningequality/ka-lite
571918ea668013dcf022286ea85eff1c5333fb8b
kalite/packages/bundled/django/core/files/uploadhandler.py
python
FileUploadHandler.handle_raw_input
(self, input_data, META, content_length, boundary, encoding=None)
Handle the raw input from the client. Parameters: :input_data: An object that supports reading via .read(). :META: ``request.META``. :content_length: The (integer) value of the Content-Length header from the client. :boundary: The boundary from the Content-Type header. Be sure to prepend two '--'.
Handle the raw input from the client.
[ "Handle", "the", "raw", "input", "from", "the", "client", "." ]
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): """ Handle the raw input from the client. Parameters: :input_data: An object that supports reading via .read(). :META: ``request.META``. :content_length: The (integer) value of the Content-Length header from the client. :boundary: The boundary from the Content-Type header. Be sure to prepend two '--'. """ pass
[ "def", "handle_raw_input", "(", "self", ",", "input_data", ",", "META", ",", "content_length", ",", "boundary", ",", "encoding", "=", "None", ")", ":", "pass" ]
https://github.com/learningequality/ka-lite/blob/571918ea668013dcf022286ea85eff1c5333fb8b/kalite/packages/bundled/django/core/files/uploadhandler.py#L70-L86
TDAmeritrade/stumpy
7c97df98cb4095afae775ab71870d4d5a14776c7
stumpy/maamp.py
python
_get_first_maamp_profile
( start, T_A, T_B, m, excl_zone, T_B_subseq_isfinite, include=None, discords=False )
return P, I
Multi-dimensional wrapper to compute the non-normalized (i.e., without z-normalization multi-dimensional matrix profile and multi-dimensional matrix profile index for a given window within the times series or sequence that is denoted by the `start` index. Essentially, this is a convenience wrapper around `_multi_mass_absolute`. This is a convenience wrapper for the `_maamp_multi_distance_profile` function but does not return the multi-dimensional matrix profile subspace. Parameters ---------- start : int The window index to calculate the first multi-dimensional matrix profile, multi-dimensional matrix profile indices, and multi-dimensional subspace. T_A : numpy.ndarray The time series or sequence for which the multi-dimensional matrix profile, multi-dimensional matrix profile indices, and multi-dimensional subspace will be returned T_B : numpy.ndarray The time series or sequence that contains your query subsequences m : int Window size excl_zone : int The half width for the exclusion zone relative to the `start`. T_B_subseq_isfinite : numpy.ndarray A boolean array that indicates whether a subsequence in `Q` contains a `np.nan`/`np.inf` value (False) include : numpy.ndarray, default None A list of (zero-based) indices corresponding to the dimensions in `T` that must be included in the constrained multidimensional motif search. For more information, see Section IV D in: `DOI: 10.1109/ICDM.2017.66 \ <https://www.cs.ucr.edu/~eamonn/Motif_Discovery_ICDM.pdf>`__ discords : bool, default False When set to `True`, this reverses the distance profile to favor discords rather than motifs. Note that indices in `include` are still maintained and respected. Returns ------- P : numpy.ndarray Multi-dimensional matrix profile for the window with index equal to `start` I : numpy.ndarray Multi-dimensional matrix profile indices for the window with index equal to `start`
Multi-dimensional wrapper to compute the non-normalized (i.e., without z-normalization multi-dimensional matrix profile and multi-dimensional matrix profile index for a given window within the times series or sequence that is denoted by the `start` index. Essentially, this is a convenience wrapper around `_multi_mass_absolute`. This is a convenience wrapper for the `_maamp_multi_distance_profile` function but does not return the multi-dimensional matrix profile subspace.
[ "Multi", "-", "dimensional", "wrapper", "to", "compute", "the", "non", "-", "normalized", "(", "i", ".", "e", ".", "without", "z", "-", "normalization", "multi", "-", "dimensional", "matrix", "profile", "and", "multi", "-", "dimensional", "matrix", "profile"...
def _get_first_maamp_profile( start, T_A, T_B, m, excl_zone, T_B_subseq_isfinite, include=None, discords=False ): """ Multi-dimensional wrapper to compute the non-normalized (i.e., without z-normalization multi-dimensional matrix profile and multi-dimensional matrix profile index for a given window within the times series or sequence that is denoted by the `start` index. Essentially, this is a convenience wrapper around `_multi_mass_absolute`. This is a convenience wrapper for the `_maamp_multi_distance_profile` function but does not return the multi-dimensional matrix profile subspace. Parameters ---------- start : int The window index to calculate the first multi-dimensional matrix profile, multi-dimensional matrix profile indices, and multi-dimensional subspace. T_A : numpy.ndarray The time series or sequence for which the multi-dimensional matrix profile, multi-dimensional matrix profile indices, and multi-dimensional subspace will be returned T_B : numpy.ndarray The time series or sequence that contains your query subsequences m : int Window size excl_zone : int The half width for the exclusion zone relative to the `start`. T_B_subseq_isfinite : numpy.ndarray A boolean array that indicates whether a subsequence in `Q` contains a `np.nan`/`np.inf` value (False) include : numpy.ndarray, default None A list of (zero-based) indices corresponding to the dimensions in `T` that must be included in the constrained multidimensional motif search. For more information, see Section IV D in: `DOI: 10.1109/ICDM.2017.66 \ <https://www.cs.ucr.edu/~eamonn/Motif_Discovery_ICDM.pdf>`__ discords : bool, default False When set to `True`, this reverses the distance profile to favor discords rather than motifs. Note that indices in `include` are still maintained and respected. Returns ------- P : numpy.ndarray Multi-dimensional matrix profile for the window with index equal to `start` I : numpy.ndarray Multi-dimensional matrix profile indices for the window with index equal to `start` """ D = _maamp_multi_distance_profile( start, T_A, T_B, m, excl_zone, T_B_subseq_isfinite, include, discords ) d = T_A.shape[0] P = np.full(d, np.inf, dtype=np.float64) I = np.full(d, -1, dtype=np.int64) for i in range(d): min_index = np.argmin(D[i]) I[i] = min_index P[i] = D[i, min_index] if np.isinf(P[i]): # pragma nocover I[i] = -1 return P, I
[ "def", "_get_first_maamp_profile", "(", "start", ",", "T_A", ",", "T_B", ",", "m", ",", "excl_zone", ",", "T_B_subseq_isfinite", ",", "include", "=", "None", ",", "discords", "=", "False", ")", ":", "D", "=", "_maamp_multi_distance_profile", "(", "start", ",...
https://github.com/TDAmeritrade/stumpy/blob/7c97df98cb4095afae775ab71870d4d5a14776c7/stumpy/maamp.py#L252-L325
RaphielGang/Telegram-Paperplane
d9e6c466902dd573ddf8c805e9dc484f972a62f1
userbot/modules/dbhelper.py
python
block_pm
(userid)
return True
[]
async def block_pm(userid): if await approval(userid) is False: return False MONGO.pmpermit.update_one({"user_id": userid}, {"$set": {"approval": False}}) return True
[ "async", "def", "block_pm", "(", "userid", ")", ":", "if", "await", "approval", "(", "userid", ")", "is", "False", ":", "return", "False", "MONGO", ".", "pmpermit", ".", "update_one", "(", "{", "\"user_id\"", ":", "userid", "}", ",", "{", "\"$set\"", "...
https://github.com/RaphielGang/Telegram-Paperplane/blob/d9e6c466902dd573ddf8c805e9dc484f972a62f1/userbot/modules/dbhelper.py#L259-L265
UCL-INGI/INGInious
60f10cb4c375ce207471043e76bd813220b95399
inginious/frontend/pages/course_admin/utils.py
python
make_csv
(data)
return response
Returns the content of a CSV file with the data of the dict/list data
Returns the content of a CSV file with the data of the dict/list data
[ "Returns", "the", "content", "of", "a", "CSV", "file", "with", "the", "data", "of", "the", "dict", "/", "list", "data" ]
def make_csv(data): """ Returns the content of a CSV file with the data of the dict/list data """ # Convert sub-dicts to news cols for entry in data: rval = entry if isinstance(data, dict): rval = data[entry] todel = [] toadd = {} for key, val in rval.items(): if isinstance(val, dict): for key2, val2 in val.items(): toadd[str(key) + "[" + str(key2) + "]"] = val2 todel.append(key) for k in todel: del rval[k] for k, v in toadd.items(): rval[k] = v # Convert everything to CSV columns = set() output = [[]] if isinstance(data, dict): output[0].append("id") for entry in data: for col in data[entry]: columns.add(col) else: for entry in data: for col in entry: columns.add(col) columns = sorted(columns) for col in columns: output[0].append(col) if isinstance(data, dict): for entry in data: new_output = [str(entry)] for col in columns: new_output.append(str(data[entry][col]) if col in data[entry] else "") output.append(new_output) else: for entry in data: new_output = [] for col in columns: new_output.append(str(entry[col]) if col in entry else "") output.append(new_output) csv_string = io.StringIO() csv_writer = UnicodeWriter(csv_string) for row in output: csv_writer.writerow(row) csv_string.seek(0) response = Response(response=csv_string.read(), content_type='text/csv; charset=utf-8') response.headers['Content-disposition'] = 'attachment; filename=export.csv' return response
[ "def", "make_csv", "(", "data", ")", ":", "# Convert sub-dicts to news cols", "for", "entry", "in", "data", ":", "rval", "=", "entry", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "rval", "=", "data", "[", "entry", "]", "todel", "=", "[", "]...
https://github.com/UCL-INGI/INGInious/blob/60f10cb4c375ce207471043e76bd813220b95399/inginious/frontend/pages/course_admin/utils.py#L280-L337
scipy/scipy
e0a749f01e79046642ccfdc419edbf9e7ca141ad
scipy/io/_idl.py
python
_read_arraydesc
(f)
return arraydesc
Function to read in an array descriptor
Function to read in an array descriptor
[ "Function", "to", "read", "in", "an", "array", "descriptor" ]
def _read_arraydesc(f): '''Function to read in an array descriptor''' arraydesc = {'arrstart': _read_long(f)} if arraydesc['arrstart'] == 8: _skip_bytes(f, 4) arraydesc['nbytes'] = _read_long(f) arraydesc['nelements'] = _read_long(f) arraydesc['ndims'] = _read_long(f) _skip_bytes(f, 8) arraydesc['nmax'] = _read_long(f) arraydesc['dims'] = [_read_long(f) for _ in range(arraydesc['nmax'])] elif arraydesc['arrstart'] == 18: warnings.warn("Using experimental 64-bit array read") _skip_bytes(f, 8) arraydesc['nbytes'] = _read_uint64(f) arraydesc['nelements'] = _read_uint64(f) arraydesc['ndims'] = _read_long(f) _skip_bytes(f, 8) arraydesc['nmax'] = 8 arraydesc['dims'] = [] for d in range(arraydesc['nmax']): v = _read_long(f) if v != 0: raise Exception("Expected a zero in ARRAY_DESC") arraydesc['dims'].append(_read_long(f)) else: raise Exception("Unknown ARRSTART: %i" % arraydesc['arrstart']) return arraydesc
[ "def", "_read_arraydesc", "(", "f", ")", ":", "arraydesc", "=", "{", "'arrstart'", ":", "_read_long", "(", "f", ")", "}", "if", "arraydesc", "[", "'arrstart'", "]", "==", "8", ":", "_skip_bytes", "(", "f", ",", "4", ")", "arraydesc", "[", "'nbytes'", ...
https://github.com/scipy/scipy/blob/e0a749f01e79046642ccfdc419edbf9e7ca141ad/scipy/io/_idl.py#L444-L488
PyCQA/astroid
a815443f62faae05249621a396dcf0afd884a619
astroid/nodes/scoped_nodes/scoped_nodes.py
python
ClassDef.implicit_locals
(self)
return locals_
Get implicitly defined class definition locals. :returns: the the name and Const pair for each local :rtype: tuple(tuple(str, node_classes.Const), ...)
Get implicitly defined class definition locals.
[ "Get", "implicitly", "defined", "class", "definition", "locals", "." ]
def implicit_locals(self): """Get implicitly defined class definition locals. :returns: the the name and Const pair for each local :rtype: tuple(tuple(str, node_classes.Const), ...) """ locals_ = (("__module__", self.special_attributes.attr___module__),) # __qualname__ is defined in PEP3155 locals_ += (("__qualname__", self.special_attributes.attr___qualname__),) return locals_
[ "def", "implicit_locals", "(", "self", ")", ":", "locals_", "=", "(", "(", "\"__module__\"", ",", "self", ".", "special_attributes", ".", "attr___module__", ")", ",", ")", "# __qualname__ is defined in PEP3155", "locals_", "+=", "(", "(", "\"__qualname__\"", ",", ...
https://github.com/PyCQA/astroid/blob/a815443f62faae05249621a396dcf0afd884a619/astroid/nodes/scoped_nodes/scoped_nodes.py#L2271-L2280
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.4/django/utils/translation/trans_real.py
python
ngettext
(singular, plural, number)
return do_ntranslate(singular, plural, number, 'ngettext')
Returns a UTF-8 bytestring of the translation of either the singular or plural, based on the number.
Returns a UTF-8 bytestring of the translation of either the singular or plural, based on the number.
[ "Returns", "a", "UTF", "-", "8", "bytestring", "of", "the", "translation", "of", "either", "the", "singular", "or", "plural", "based", "on", "the", "number", "." ]
def ngettext(singular, plural, number): """ Returns a UTF-8 bytestring of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, 'ngettext')
[ "def", "ngettext", "(", "singular", ",", "plural", ",", "number", ")", ":", "return", "do_ntranslate", "(", "singular", ",", "plural", ",", "number", ",", "'ngettext'", ")" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.4/django/utils/translation/trans_real.py#L308-L313
gmate/gmate
83312e64e0c115a9842500e4eb8617d3f5f4025b
plugins/gedit2/zencoding/zencoding/filters/html.py
python
make_attributes_string
(tag, profile)
return attrs
Creates HTML attributes string from tag according to profile settings @type tag: ZenNode @type profile: dict
Creates HTML attributes string from tag according to profile settings
[ "Creates", "HTML", "attributes", "string", "from", "tag", "according", "to", "profile", "settings" ]
def make_attributes_string(tag, profile): """ Creates HTML attributes string from tag according to profile settings @type tag: ZenNode @type profile: dict """ # make attribute string attrs = '' attr_quote = profile['attr_quotes'] == 'single' and "'" or '"' cursor = profile['place_cursor'] and zen_coding.get_caret_placeholder() or '' # process other attributes for a in tag.attributes: attr_name = profile['attr_case'] == 'upper' and a['name'].upper() or a['name'].lower() attrs += ' ' + attr_name + '=' + attr_quote + (a['value'] or cursor) + attr_quote return attrs
[ "def", "make_attributes_string", "(", "tag", ",", "profile", ")", ":", "# make attribute string", "attrs", "=", "''", "attr_quote", "=", "profile", "[", "'attr_quotes'", "]", "==", "'single'", "and", "\"'\"", "or", "'\"'", "cursor", "=", "profile", "[", "'plac...
https://github.com/gmate/gmate/blob/83312e64e0c115a9842500e4eb8617d3f5f4025b/plugins/gedit2/zencoding/zencoding/filters/html.py#L13-L29
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
openedx/core/djangoapps/content/block_structure/transformer_registry.py
python
TransformerRegistry.get_write_version_hash
(cls)
return b64encode(hash_obj.digest()).decode('utf-8')
Returns a deterministic hash value of the WRITE_VERSION of all registered transformers.
Returns a deterministic hash value of the WRITE_VERSION of all registered transformers.
[ "Returns", "a", "deterministic", "hash", "value", "of", "the", "WRITE_VERSION", "of", "all", "registered", "transformers", "." ]
def get_write_version_hash(cls): """ Returns a deterministic hash value of the WRITE_VERSION of all registered transformers. """ hash_obj = sha1() sorted_transformers = sorted(cls.get_registered_transformers(), key=lambda t: t.name()) for transformer in sorted_transformers: hash_obj.update((transformer.name()).encode()) hash_obj.update((str(transformer.WRITE_VERSION)).encode()) return b64encode(hash_obj.digest()).decode('utf-8')
[ "def", "get_write_version_hash", "(", "cls", ")", ":", "hash_obj", "=", "sha1", "(", ")", "sorted_transformers", "=", "sorted", "(", "cls", ".", "get_registered_transformers", "(", ")", ",", "key", "=", "lambda", "t", ":", "t", ".", "name", "(", ")", ")"...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/openedx/core/djangoapps/content/block_structure/transformer_registry.py#L42-L54
JonathonLuiten/PReMVOS
2666acaae0f1b4bd7d88a0cfb9b7cf5c5de12a4b
code/proposal_net/viz.py
python
draw_mask
(im, mask, alpha=0.5, color=None)
return im
Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically
Overlay a mask on top of the image.
[ "Overlay", "a", "mask", "on", "top", "of", "the", "image", "." ]
def draw_mask(im, mask, alpha=0.5, color=None): """ Overlay a mask on top of the image. Args: im: a 3-channel uint8 image in BGR mask: a binary 1-channel image of the same size color: if None, will choose automatically """ if color is None: color = PALETTE_RGB[np.random.choice(len(PALETTE_RGB))][::-1] im = np.where(np.repeat((mask > 0)[:, :, None], 3, axis=2), im * (1 - alpha) + color * alpha, im) im = im.astype('uint8') return im
[ "def", "draw_mask", "(", "im", ",", "mask", ",", "alpha", "=", "0.5", ",", "color", "=", "None", ")", ":", "if", "color", "is", "None", ":", "color", "=", "PALETTE_RGB", "[", "np", ".", "random", ".", "choice", "(", "len", "(", "PALETTE_RGB", ")", ...
https://github.com/JonathonLuiten/PReMVOS/blob/2666acaae0f1b4bd7d88a0cfb9b7cf5c5de12a4b/code/proposal_net/viz.py#L93-L107
SforAiDl/Neural-Voice-Cloning-With-Few-Samples
33fb609427657c9492f46507184ecba4dcc272b0
train_dv3.py
python
TextDataSource.__init__
(self, data_root, speaker_id=None)
[]
def __init__(self, data_root, speaker_id=None): self.data_root = data_root self.speaker_ids = None self.multi_speaker = False # If not None, filter by speaker_id self.speaker_id = speaker_id
[ "def", "__init__", "(", "self", ",", "data_root", ",", "speaker_id", "=", "None", ")", ":", "self", ".", "data_root", "=", "data_root", "self", ".", "speaker_ids", "=", "None", "self", ".", "multi_speaker", "=", "False", "# If not None, filter by speaker_id", ...
https://github.com/SforAiDl/Neural-Voice-Cloning-With-Few-Samples/blob/33fb609427657c9492f46507184ecba4dcc272b0/train_dv3.py#L98-L103
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Linux/aarch64/ucs2/cryptography/hazmat/primitives/asymmetric/rsa.py
python
rsa_crt_dmp1
(private_exponent, p)
return private_exponent % (p - 1)
Compute the CRT private_exponent % (p - 1) value from the RSA private_exponent (d) and p.
Compute the CRT private_exponent % (p - 1) value from the RSA private_exponent (d) and p.
[ "Compute", "the", "CRT", "private_exponent", "%", "(", "p", "-", "1", ")", "value", "from", "the", "RSA", "private_exponent", "(", "d", ")", "and", "p", "." ]
def rsa_crt_dmp1(private_exponent, p): """ Compute the CRT private_exponent % (p - 1) value from the RSA private_exponent (d) and p. """ return private_exponent % (p - 1)
[ "def", "rsa_crt_dmp1", "(", "private_exponent", ",", "p", ")", ":", "return", "private_exponent", "%", "(", "p", "-", "1", ")" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Linux/aarch64/ucs2/cryptography/hazmat/primitives/asymmetric/rsa.py#L199-L204
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/PIL/MpoImagePlugin.py
python
_accept
(prefix)
return JpegImagePlugin._accept(prefix)
[]
def _accept(prefix): return JpegImagePlugin._accept(prefix)
[ "def", "_accept", "(", "prefix", ")", ":", "return", "JpegImagePlugin", ".", "_accept", "(", "prefix", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/PIL/MpoImagePlugin.py#L26-L27
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/rings/polynomial/multi_polynomial_element.py
python
MPolynomial_element._lmul_
(self, a)
return self.__class__(self.parent(),self.__element.scalar_lmult(a))
Left Scalar Multiplication EXAMPLES: Note that it is not really possible to do a meaningful example since sage mpoly rings refuse to have non-commutative bases. :: sage: R.<x,y> = QQbar[] sage: f = (x + y) sage: 3*f 3*x + 3*y
Left Scalar Multiplication
[ "Left", "Scalar", "Multiplication" ]
def _lmul_(self, a): """ Left Scalar Multiplication EXAMPLES: Note that it is not really possible to do a meaningful example since sage mpoly rings refuse to have non-commutative bases. :: sage: R.<x,y> = QQbar[] sage: f = (x + y) sage: 3*f 3*x + 3*y """ return self.__class__(self.parent(),self.__element.scalar_lmult(a))
[ "def", "_lmul_", "(", "self", ",", "a", ")", ":", "return", "self", ".", "__class__", "(", "self", ".", "parent", "(", ")", ",", "self", ".", "__element", ".", "scalar_lmult", "(", "a", ")", ")" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/rings/polynomial/multi_polynomial_element.py#L264-L281
coderSkyChen/Action_Recognition_Zoo
92ec5ec3efeee852aec5c057798298cd3a8e58ae
model_zoo/models/slim/deployment/model_deploy.py
python
DeploymentConfig.variables_device
(self)
Returns the device to use for variables created inside the clone. Returns: A value suitable for `tf.device()`.
Returns the device to use for variables created inside the clone.
[ "Returns", "the", "device", "to", "use", "for", "variables", "created", "inside", "the", "clone", "." ]
def variables_device(self): """Returns the device to use for variables created inside the clone. Returns: A value suitable for `tf.device()`. """ device = '' if self._num_ps_tasks > 0: device += self._ps_device device += '/device:CPU:0' class _PSDeviceChooser(object): """Slim device chooser for variables when using PS.""" def __init__(self, device, tasks): self._device = device self._tasks = tasks self._task = 0 def choose(self, op): if op.device: return op.device node_def = op if isinstance(op, tf.NodeDef) else op.node_def if node_def.op == 'Variable': t = self._task self._task = (self._task + 1) % self._tasks d = '%s/task:%d' % (self._device, t) return d else: return op.device if not self._num_ps_tasks: return device else: chooser = _PSDeviceChooser(device, self._num_ps_tasks) return chooser.choose
[ "def", "variables_device", "(", "self", ")", ":", "device", "=", "''", "if", "self", ".", "_num_ps_tasks", ">", "0", ":", "device", "+=", "self", ".", "_ps_device", "device", "+=", "'/device:CPU:0'", "class", "_PSDeviceChooser", "(", "object", ")", ":", "\...
https://github.com/coderSkyChen/Action_Recognition_Zoo/blob/92ec5ec3efeee852aec5c057798298cd3a8e58ae/model_zoo/models/slim/deployment/model_deploy.py#L646-L681
atlassian-api/atlassian-python-api
6d8545a790c3aae10b75bdc225fb5c3a0aee44db
atlassian/bamboo.py
python
Bamboo.get_groups
(self, start=0, limit=25)
return self.get(url, params=params)
Retrieve a paginated list of groups. The authenticated user must have restricted administrative permission or higher to use this resource. :param start: :param limit: :return:
Retrieve a paginated list of groups. The authenticated user must have restricted administrative permission or higher to use this resource. :param start: :param limit: :return:
[ "Retrieve", "a", "paginated", "list", "of", "groups", ".", "The", "authenticated", "user", "must", "have", "restricted", "administrative", "permission", "or", "higher", "to", "use", "this", "resource", ".", ":", "param", "start", ":", ":", "param", "limit", ...
def get_groups(self, start=0, limit=25): """ Retrieve a paginated list of groups. The authenticated user must have restricted administrative permission or higher to use this resource. :param start: :param limit: :return: """ params = {"limit": limit, "start": start} url = "rest/api/latest/admin/groups" return self.get(url, params=params)
[ "def", "get_groups", "(", "self", ",", "start", "=", "0", ",", "limit", "=", "25", ")", ":", "params", "=", "{", "\"limit\"", ":", "limit", ",", "\"start\"", ":", "start", "}", "url", "=", "\"rest/api/latest/admin/groups\"", "return", "self", ".", "get",...
https://github.com/atlassian-api/atlassian-python-api/blob/6d8545a790c3aae10b75bdc225fb5c3a0aee44db/atlassian/bamboo.py#L673-L683
subuser-security/subuser
8072271f8fc3dded60b048c2dee878f9840c126a
subuserlib/classes/subuserSubmodules/run/runReadyImage.py
python
RunReadyImage.generateImagePreparationDockerfile
(self)
return dockerfileContents
There is still some preparation that needs to be done before an image is ready to be run. But this preparation requires run time information, so we cannot preform that preparation at build time.
There is still some preparation that needs to be done before an image is ready to be run. But this preparation requires run time information, so we cannot preform that preparation at build time.
[ "There", "is", "still", "some", "preparation", "that", "needs", "to", "be", "done", "before", "an", "image", "is", "ready", "to", "be", "run", ".", "But", "this", "preparation", "requires", "run", "time", "information", "so", "we", "cannot", "preform", "th...
def generateImagePreparationDockerfile(self): """ There is still some preparation that needs to be done before an image is ready to be run. But this preparation requires run time information, so we cannot preform that preparation at build time. """ dockerfileContents = "FROM "+self.subuser.imageId+"\n" dockerfileContents += "RUN useradd --uid="+str(self.user.endUser.uid)+" subuser ;export exitstatus=$? ; if [ $exitstatus -eq 4 ] ; then echo uid exists ; elif [ $exitstatus -eq 9 ]; then echo username exists. ; else exit $exitstatus ; fi\n" dockerfileContents += "RUN test -d /home/subuser || mkdir /home/subuser && chown subuser /home/subuser\n" if self.subuser.permissions["serial-devices"]: dockerfileContents += "RUN groupadd dialout; export exitstatus=$? ; if [ $exitstatus -eq 4 ] ; then echo gid exists ; elif [ $exitstatus -eq 9 ]; then echo groupname exists. ; else exit $exitstatus ; fi\n" dockerfileContents += "RUN groupadd uucp; export exitstatus=$? ; if [ $exitstatus -eq 4 ] ; then echo gid exists ; elif [ $exitstatus -eq 9 ]; then echo groupname exists. ; else exit $exitstatus ; fi\n" dockerfileContents += "RUN usermod -a -G dialout "+self.user.endUser.name+"\n" dockerfileContents += "RUN usermod -a -G uucp "+self.user.endUser.name+"\n" if self.subuser.permissions["sudo"]: dockerfileContents += "RUN (umask 337; echo \""+self.user.endUser.name+" ALL=(ALL) NOPASSWD: ALL\" > /etc/sudoers.d/allowsudo )\n" return dockerfileContents
[ "def", "generateImagePreparationDockerfile", "(", "self", ")", ":", "dockerfileContents", "=", "\"FROM \"", "+", "self", ".", "subuser", ".", "imageId", "+", "\"\\n\"", "dockerfileContents", "+=", "\"RUN useradd --uid=\"", "+", "str", "(", "self", ".", "user", "."...
https://github.com/subuser-security/subuser/blob/8072271f8fc3dded60b048c2dee878f9840c126a/subuserlib/classes/subuserSubmodules/run/runReadyImage.py#L48-L62
sagemath/sage
f9b2db94f675ff16963ccdefba4f1a3393b3fe0d
src/sage/modules/free_module.py
python
FreeModule_submodule_field.has_user_basis
(self)
return False
Return ``True`` if the basis of this free module is specified by the user, as opposed to being the default echelon form. EXAMPLES:: sage: V = QQ^3 sage: W = V.subspace([[2,'1/2', 1]]) sage: W.has_user_basis() False sage: W = V.subspace_with_basis([[2,'1/2',1]]) sage: W.has_user_basis() True
Return ``True`` if the basis of this free module is specified by the user, as opposed to being the default echelon form.
[ "Return", "True", "if", "the", "basis", "of", "this", "free", "module", "is", "specified", "by", "the", "user", "as", "opposed", "to", "being", "the", "default", "echelon", "form", "." ]
def has_user_basis(self): """ Return ``True`` if the basis of this free module is specified by the user, as opposed to being the default echelon form. EXAMPLES:: sage: V = QQ^3 sage: W = V.subspace([[2,'1/2', 1]]) sage: W.has_user_basis() False sage: W = V.subspace_with_basis([[2,'1/2',1]]) sage: W.has_user_basis() True """ return False
[ "def", "has_user_basis", "(", "self", ")", ":", "return", "False" ]
https://github.com/sagemath/sage/blob/f9b2db94f675ff16963ccdefba4f1a3393b3fe0d/src/sage/modules/free_module.py#L7335-L7351
nathanborror/django-basic-apps
3a90090857549ea4198a72c44f45f6edb238e2a8
basic/blog/templatetags/blog.py
python
get_blogroll
(parser, token)
return BlogRolls(var_name)
Gets all blogroll links. Syntax:: {% get_blogroll as [var_name] %} Example usage:: {% get_blogroll as blogroll_list %}
Gets all blogroll links.
[ "Gets", "all", "blogroll", "links", "." ]
def get_blogroll(parser, token): """ Gets all blogroll links. Syntax:: {% get_blogroll as [var_name] %} Example usage:: {% get_blogroll as blogroll_list %} """ try: tag_name, arg = token.contents.split(None, 1) except ValueError: raise template.TemplateSyntaxError, "%s tag requires arguments" % token.contents.split()[0] m = re.search(r'as (\w+)', arg) if not m: raise template.TemplateSyntaxError, "%s tag had invalid arguments" % tag_name var_name = m.groups()[0] return BlogRolls(var_name)
[ "def", "get_blogroll", "(", "parser", ",", "token", ")", ":", "try", ":", "tag_name", ",", "arg", "=", "token", ".", "contents", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "raise", "template", ".", "TemplateSyntaxError", ",", ...
https://github.com/nathanborror/django-basic-apps/blob/3a90090857549ea4198a72c44f45f6edb238e2a8/basic/blog/templatetags/blog.py#L120-L140
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/sets/sets.py
python
FiniteSet._eval_evalf
(self, prec)
return FiniteSet(elem.evalf(prec) for elem in self)
[]
def _eval_evalf(self, prec): return FiniteSet(elem.evalf(prec) for elem in self)
[ "def", "_eval_evalf", "(", "self", ",", "prec", ")", ":", "return", "FiniteSet", "(", "elem", ".", "evalf", "(", "prec", ")", "for", "elem", "in", "self", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/sets/sets.py#L1590-L1591
wireservice/leather
a10c27e0c073a6307133a7a2ad4db0268f02bf4b
leather/chart.py
python
Chart.set_x_axis
(self, axis)
Set an :class:`.Axis` class for this chart.
Set an :class:`.Axis` class for this chart.
[ "Set", "an", ":", "class", ":", ".", "Axis", "class", "for", "this", "chart", "." ]
def set_x_axis(self, axis): """ Set an :class:`.Axis` class for this chart. """ self._axes[X] = axis
[ "def", "set_x_axis", "(", "self", ",", "axis", ")", ":", "self", ".", "_axes", "[", "X", "]", "=", "axis" ]
https://github.com/wireservice/leather/blob/a10c27e0c073a6307133a7a2ad4db0268f02bf4b/leather/chart.py#L82-L86
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx_bisect.py
python
_update_cmd_if_stripped
(cmd_to_update)
return cmd_to_update
[]
def _update_cmd_if_stripped(cmd_to_update): if mx._opts.strip_jars and cmd_to_update.find('--strip-jars') == -1: cmd_to_update = re.sub(r'\b(mx)\b', 'mx --strip-jars', cmd_to_update) return cmd_to_update
[ "def", "_update_cmd_if_stripped", "(", "cmd_to_update", ")", ":", "if", "mx", ".", "_opts", ".", "strip_jars", "and", "cmd_to_update", ".", "find", "(", "'--strip-jars'", ")", "==", "-", "1", ":", "cmd_to_update", "=", "re", ".", "sub", "(", "r'\\b(mx)\\b'",...
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx_bisect.py#L92-L95
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/commands/search.py
python
SearchCommand.__init__
(self, *args, **kw)
[]
def __init__(self, *args, **kw): super(SearchCommand, self).__init__(*args, **kw) self.cmd_opts.add_option( '-i', '--index', dest='index', metavar='URL', default=PyPI.pypi_url, help='Base URL of Python Package Index (default %default)') self.parser.insert_option_group(0, self.cmd_opts)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kw", ")", ":", "super", "(", "SearchCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kw", ")", "self", ".", "cmd_opts", ".", "add_option", "(", "'-i'"...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter8-Regression/venv/Lib/site-packages/pip-9.0.1-py3.6.egg/pip/commands/search.py#L30-L39
kennethreitz-archive/requests3
69eb662703b40db58fdc6c095d0fe130c56649bb
requests3/_hooks.py
python
dispatch_hook
(key, hooks, hook_data, **kwargs)
return hook_data
Dispatches a hook dictionary on a given piece of data.
Dispatches a hook dictionary on a given piece of data.
[ "Dispatches", "a", "hook", "dictionary", "on", "a", "given", "piece", "of", "data", "." ]
def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, "__call__"): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
[ "def", "dispatch_hook", "(", "key", ",", "hooks", ",", "hook_data", ",", "*", "*", "kwargs", ")", ":", "hooks", "=", "hooks", "or", "{", "}", "hooks", "=", "hooks", ".", "get", "(", "key", ")", "if", "hooks", ":", "if", "hasattr", "(", "hooks", "...
https://github.com/kennethreitz-archive/requests3/blob/69eb662703b40db58fdc6c095d0fe130c56649bb/requests3/_hooks.py#L21-L32
Mingtzge/2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement
42ad9686f3c3bde0d29a8bc6bcb0e3afb35fb3c3
pytorch-CycleGAN-and-pix2pix/util/html.py
python
HTML.add_images
(self, ims, txts, links, width=400)
add images to the HTML file Parameters: ims (str list) -- a list of image paths txts (str list) -- a list of image names shown on the website links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page
add images to the HTML file
[ "add", "images", "to", "the", "HTML", "file" ]
def add_images(self, ims, txts, links, width=400): """add images to the HTML file Parameters: ims (str list) -- a list of image paths txts (str list) -- a list of image names shown on the website links (str list) -- a list of hyperref links; when you click an image, it will redirect you to a new page """ self.t = table(border=1, style="table-layout: fixed;") # Insert a table self.doc.add(self.t) with self.t: with tr(): for im, txt, link in zip(ims, txts, links): with td(style="word-wrap: break-word;", halign="center", valign="top"): with p(): with a(href=os.path.join('images', link)): img(style="width:%dpx" % width, src=os.path.join('images', im)) br() p(txt)
[ "def", "add_images", "(", "self", ",", "ims", ",", "txts", ",", "links", ",", "width", "=", "400", ")", ":", "self", ".", "t", "=", "table", "(", "border", "=", "1", ",", "style", "=", "\"table-layout: fixed;\"", ")", "# Insert a table", "self", ".", ...
https://github.com/Mingtzge/2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement/blob/42ad9686f3c3bde0d29a8bc6bcb0e3afb35fb3c3/pytorch-CycleGAN-and-pix2pix/util/html.py#L48-L66
pyRiemann/pyRiemann
30c2cd7204d19f1a60d3b7945dfd8ee3c46a8df8
pyriemann/utils/mean.py
python
mean_covariance
(covmats, metric='riemann', sample_weight=None, *args)
return C
Return the mean covariance matrix according to the metric :param covmats: Covariance matrices, (n_matrices, n_channels, n_channels) :param metric: the metric (default 'riemann'), can be : 'riemann', 'logeuclid', 'euclid', 'logdet', 'identity', 'wasserstein', 'ale', 'alm', 'harmonic', 'kullback_sym' or a callable function :param sample_weight: the weight of each matrix :param args: the argument passed to the sub function :returns: the mean covariance matrix, (n_channels, n_channels)
Return the mean covariance matrix according to the metric
[ "Return", "the", "mean", "covariance", "matrix", "according", "to", "the", "metric" ]
def mean_covariance(covmats, metric='riemann', sample_weight=None, *args): """Return the mean covariance matrix according to the metric :param covmats: Covariance matrices, (n_matrices, n_channels, n_channels) :param metric: the metric (default 'riemann'), can be : 'riemann', 'logeuclid', 'euclid', 'logdet', 'identity', 'wasserstein', 'ale', 'alm', 'harmonic', 'kullback_sym' or a callable function :param sample_weight: the weight of each matrix :param args: the argument passed to the sub function :returns: the mean covariance matrix, (n_channels, n_channels) """ if callable(metric): C = metric(covmats, sample_weight=sample_weight, *args) else: C = mean_methods[metric](covmats, sample_weight=sample_weight, *args) return C
[ "def", "mean_covariance", "(", "covmats", ",", "metric", "=", "'riemann'", ",", "sample_weight", "=", "None", ",", "*", "args", ")", ":", "if", "callable", "(", "metric", ")", ":", "C", "=", "metric", "(", "covmats", ",", "sample_weight", "=", "sample_we...
https://github.com/pyRiemann/pyRiemann/blob/30c2cd7204d19f1a60d3b7945dfd8ee3c46a8df8/pyriemann/utils/mean.py#L380-L396
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/seq/seq.py
python
Seq.Delay
(self, delay)
return self
[]
def Delay(self, delay): self.next_kwargs['delay'] = delay return self
[ "def", "Delay", "(", "self", ",", "delay", ")", ":", "self", ".", "next_kwargs", "[", "'delay'", "]", "=", "delay", "return", "self" ]
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/seq/seq.py#L276-L278
pdm-project/pdm
34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b
pdm/models/specifiers.py
python
PySpecSet.is_impossible
(self)
return self._lower_bound >= self._upper_bound
Check whether the specifierset contains any valid versions.
Check whether the specifierset contains any valid versions.
[ "Check", "whether", "the", "specifierset", "contains", "any", "valid", "versions", "." ]
def is_impossible(self) -> bool: """Check whether the specifierset contains any valid versions.""" if self._lower_bound == Version.MIN or self._upper_bound == Version.MAX: return False return self._lower_bound >= self._upper_bound
[ "def", "is_impossible", "(", "self", ")", "->", "bool", ":", "if", "self", ".", "_lower_bound", "==", "Version", ".", "MIN", "or", "self", ".", "_upper_bound", "==", "Version", ".", "MAX", ":", "return", "False", "return", "self", ".", "_lower_bound", ">...
https://github.com/pdm-project/pdm/blob/34ba2ea48bf079044b0ca8c0017f3c0e7d9e198b/pdm/models/specifiers.py#L199-L203
Diaoul/subliminal
e25589dbcc5b2455bf9f0b49cf2083bb0eae449f
subliminal/score.py
python
compute_score
(subtitle, video, hearing_impaired=None)
return score
Compute the score of the `subtitle` against the `video` with `hearing_impaired` preference. :func:`compute_score` uses the :meth:`Subtitle.get_matches <subliminal.subtitle.Subtitle.get_matches>` method and applies the scores (either from :data:`episode_scores` or :data:`movie_scores`) after some processing. :param subtitle: the subtitle to compute the score of. :type subtitle: :class:`~subliminal.subtitle.Subtitle` :param video: the video to compute the score against. :type video: :class:`~subliminal.video.Video` :param bool hearing_impaired: hearing impaired preference. :return: score of the subtitle. :rtype: int
Compute the score of the `subtitle` against the `video` with `hearing_impaired` preference.
[ "Compute", "the", "score", "of", "the", "subtitle", "against", "the", "video", "with", "hearing_impaired", "preference", "." ]
def compute_score(subtitle, video, hearing_impaired=None): """Compute the score of the `subtitle` against the `video` with `hearing_impaired` preference. :func:`compute_score` uses the :meth:`Subtitle.get_matches <subliminal.subtitle.Subtitle.get_matches>` method and applies the scores (either from :data:`episode_scores` or :data:`movie_scores`) after some processing. :param subtitle: the subtitle to compute the score of. :type subtitle: :class:`~subliminal.subtitle.Subtitle` :param video: the video to compute the score against. :type video: :class:`~subliminal.video.Video` :param bool hearing_impaired: hearing impaired preference. :return: score of the subtitle. :rtype: int """ logger.info('Computing score of %r for video %r with %r', subtitle, video, dict(hearing_impaired=hearing_impaired)) # get the scores dict scores = get_scores(video) logger.debug('Using scores %r', scores) # get the matches matches = subtitle.get_matches(video) logger.debug('Found matches %r', matches) # on hash match, discard everything else if 'hash' in matches: logger.debug('Keeping only hash match') matches &= {'hash'} # handle equivalent matches if isinstance(video, Episode): if 'title' in matches: logger.debug('Adding title match equivalent') matches.add('episode') if 'series_imdb_id' in matches: logger.debug('Adding series_imdb_id match equivalent') matches |= {'series', 'year', 'country'} if 'imdb_id' in matches: logger.debug('Adding imdb_id match equivalents') matches |= {'series', 'year', 'country', 'season', 'episode'} if 'tvdb_id' in matches: logger.debug('Adding tvdb_id match equivalents') matches |= {'series', 'year', 'country', 'season', 'episode'} if 'series_tvdb_id' in matches: logger.debug('Adding series_tvdb_id match equivalents') matches |= {'series', 'year', 'country'} elif isinstance(video, Movie): if 'imdb_id' in matches: logger.debug('Adding imdb_id match equivalents') matches |= {'title', 'year', 'country'} # handle hearing impaired if hearing_impaired is not None and subtitle.hearing_impaired == hearing_impaired: logger.debug('Matched hearing_impaired') matches.add('hearing_impaired') # compute the score score = sum((scores.get(match, 0) for match in matches)) logger.info('Computed score %r with final matches %r', score, matches) # ensure score is within valid bounds assert 0 <= score <= scores['hash'] + scores['hearing_impaired'] return score
[ "def", "compute_score", "(", "subtitle", ",", "video", ",", "hearing_impaired", "=", "None", ")", ":", "logger", ".", "info", "(", "'Computing score of %r for video %r with %r'", ",", "subtitle", ",", "video", ",", "dict", "(", "hearing_impaired", "=", "hearing_im...
https://github.com/Diaoul/subliminal/blob/e25589dbcc5b2455bf9f0b49cf2083bb0eae449f/subliminal/score.py#L90-L154
cogeotiff/rio-tiler
d045ac953238a4246de3cab0361cd1755dab0e90
rio_tiler/mosaic/methods/defaults.py
python
LastBandHigh.data
(self)
Return data and mask.
Return data and mask.
[ "Return", "data", "and", "mask", "." ]
def data(self): """Return data and mask.""" if self.tile is not None: return ( self.tile.data[:-1], (~self.tile.mask[0] * 255).astype(self.tile.dtype), ) else: return None, None
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "tile", "is", "not", "None", ":", "return", "(", "self", ".", "tile", ".", "data", "[", ":", "-", "1", "]", ",", "(", "~", "self", ".", "tile", ".", "mask", "[", "0", "]", "*", "255",...
https://github.com/cogeotiff/rio-tiler/blob/d045ac953238a4246de3cab0361cd1755dab0e90/rio_tiler/mosaic/methods/defaults.py#L137-L145
sagemath/sagenb
67a73cbade02639bc08265f28f3165442113ad4d
sagenb/notebook/worksheet.py
python
Worksheet.basic
(self)
return d
Output a dictionary of basic Python objects that defines the configuration of this worksheet, except the actual cells and the data files in the DATA directory and images and other data in the individual cell directories. EXAMPLES:: sage: import sagenb.notebook.worksheet sage: W = sagenb.notebook.worksheet.Worksheet('test', 0, tmp_dir(), owner='sage') sage: sorted((W.basic().items())) [('auto_publish', False), ('collaborators', []), ('id_number', 0), ('last_change', ('sage', ...)), ('live_3D', False), ('name', u'test'), ('owner', 'sage'), ('pretty_print', False), ('published_id_number', None), ('ratings', []), ('saved_by_info', {}), ('system', None), ('tags', {'sage': [1]}), ('viewers', []), ('worksheet_that_was_published', ('sage', 0))]
Output a dictionary of basic Python objects that defines the configuration of this worksheet, except the actual cells and the data files in the DATA directory and images and other data in the individual cell directories.
[ "Output", "a", "dictionary", "of", "basic", "Python", "objects", "that", "defines", "the", "configuration", "of", "this", "worksheet", "except", "the", "actual", "cells", "and", "the", "data", "files", "in", "the", "DATA", "directory", "and", "images", "and", ...
def basic(self): """ Output a dictionary of basic Python objects that defines the configuration of this worksheet, except the actual cells and the data files in the DATA directory and images and other data in the individual cell directories. EXAMPLES:: sage: import sagenb.notebook.worksheet sage: W = sagenb.notebook.worksheet.Worksheet('test', 0, tmp_dir(), owner='sage') sage: sorted((W.basic().items())) [('auto_publish', False), ('collaborators', []), ('id_number', 0), ('last_change', ('sage', ...)), ('live_3D', False), ('name', u'test'), ('owner', 'sage'), ('pretty_print', False), ('published_id_number', None), ('ratings', []), ('saved_by_info', {}), ('system', None), ('tags', {'sage': [1]}), ('viewers', []), ('worksheet_that_was_published', ('sage', 0))] """ try: published_id_number = int(os.path.split(self.__published_version)[1]) except AttributeError: published_id_number = None try: ws_pub = self.__worksheet_came_from except AttributeError: ws_pub = (self.owner(), self.id_number()) try: saved_by_info = self.__saved_by_info except AttributeError: saved_by_info = {} d = {############# # basic identification 'name': unicode(self.name()), 'id_number': int(self.id_number()), ############# # default type of computation system that evaluates cells 'system': self.system(), ############# # permission: who can look at the worksheet 'owner': self.owner(), 'viewers': self.viewers(), 'collaborators': self.collaborators(), ############# # publishing worksheets (am I published?); auto-publish me? # If this worksheet is published, then the published_id_number # is the id of the published version of this worksheet. Otherwise, # it is None. 'published_id_number': published_id_number, # If this is a published worksheet, then ws_pub # is a 2-tuple ('username', id_number) of a non-published # worksheet. Otherwise ws_pub is None. 'worksheet_that_was_published': ws_pub, # Whether or not this worksheet should automatically be # republished when changed. 'auto_publish': self.is_auto_publish(), # Appearance: e.g., whether to pretty print this # worksheet by default 'pretty_print': self.pretty_print(), # Whether to load 3-D live. Should only be set to # true by the user as worksheets with more than 1 or 2 # live (interactive) 3-D plots may bog down because of # javascript overload. 'live_3D': self.live_3D(), # what other users think of this worksheet: list of # triples # (username, rating, comment) 'ratings': self.ratings(), #??? 'saved_by_info':saved_by_info, # dictionary mapping usernames to list of tags that # reflect what the tages are for that user. A tag can be # an integer: # 0,1,2 (=ARCHIVED,ACTIVE,TRASH), # or a string (not yet supported). # This is used for now to fill in the __user_views. 'tags': self.tags(), # information about when this worksheet was last changed, # and by whom: # last_change = ('username', time.time()) 'last_change': self.last_change(), } return d
[ "def", "basic", "(", "self", ")", ":", "try", ":", "published_id_number", "=", "int", "(", "os", ".", "path", ".", "split", "(", "self", ".", "__published_version", ")", "[", "1", "]", ")", "except", "AttributeError", ":", "published_id_number", "=", "No...
https://github.com/sagemath/sagenb/blob/67a73cbade02639bc08265f28f3165442113ad4d/sagenb/notebook/worksheet.py#L285-L374
enzienaudio/hvcc
30e47328958d600c54889e2a254c3f17f2b2fd06
generators/ir2c/SignalLorenz.py
python
SignalLorenz.get_C_header_set
(clazz)
return {"HvSignalLorenz.h"}
[]
def get_C_header_set(clazz): return {"HvSignalLorenz.h"}
[ "def", "get_C_header_set", "(", "clazz", ")", ":", "return", "{", "\"HvSignalLorenz.h\"", "}" ]
https://github.com/enzienaudio/hvcc/blob/30e47328958d600c54889e2a254c3f17f2b2fd06/generators/ir2c/SignalLorenz.py#L24-L25
Blockstream/satellite
ceb46a00e176c43a6b4170359f6948663a0616bb
blocksatcli/update.py
python
UpdateCache.has_update
(self)
return 'cli_update' in self.data and \ self.data['cli_update'] is not None
Returns whether there is an update available for the CLI
Returns whether there is an update available for the CLI
[ "Returns", "whether", "there", "is", "an", "update", "available", "for", "the", "CLI" ]
def has_update(self): """Returns whether there is an update available for the CLI""" return 'cli_update' in self.data and \ self.data['cli_update'] is not None
[ "def", "has_update", "(", "self", ")", ":", "return", "'cli_update'", "in", "self", ".", "data", "and", "self", ".", "data", "[", "'cli_update'", "]", "is", "not", "None" ]
https://github.com/Blockstream/satellite/blob/ceb46a00e176c43a6b4170359f6948663a0616bb/blocksatcli/update.py#L50-L53
NetEaseGame/iOS-private-api-checker
c9dc24bda7398c0d33553dce2c968d308ee968e7
app/dbs/inc/Redis.py
python
RedisQueue.put
(self, item)
return self.__db.rpush(self.key, item)
Put item into the queue.
Put item into the queue.
[ "Put", "item", "into", "the", "queue", "." ]
def put(self, item): """Put item into the queue.""" return self.__db.rpush(self.key, item)
[ "def", "put", "(", "self", ",", "item", ")", ":", "return", "self", ".", "__db", ".", "rpush", "(", "self", ".", "key", ",", "item", ")" ]
https://github.com/NetEaseGame/iOS-private-api-checker/blob/c9dc24bda7398c0d33553dce2c968d308ee968e7/app/dbs/inc/Redis.py#L112-L114
home-assistant-libs/pytradfri
ef2614b0ccdf628abc3b9559dc00b95ec6e4bd72
examples/debug_info.py
python
bold
(str)
return "\033[1;30m%s\033[0;0m" % str
Bold.
Bold.
[ "Bold", "." ]
def bold(str): """Bold.""" return "\033[1;30m%s\033[0;0m" % str
[ "def", "bold", "(", "str", ")", ":", "return", "\"\\033[1;30m%s\\033[0;0m\"", "%", "str" ]
https://github.com/home-assistant-libs/pytradfri/blob/ef2614b0ccdf628abc3b9559dc00b95ec6e4bd72/examples/debug_info.py#L103-L105
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_openshift_3.2/library/oc_secret.py
python
Yedit.delete
(self, path)
return (True, self.yaml_dict)
remove path from a dict
remove path from a dict
[ "remove", "path", "from", "a", "dict" ]
def delete(self, path): ''' remove path from a dict''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry == None: return (False, self.yaml_dict) result = Yedit.remove_entry(self.yaml_dict, path, self.separator) if not result: return (False, self.yaml_dict) return (True, self.yaml_dict)
[ "def", "delete", "(", "self", ",", "path", ")", ":", "try", ":", "entry", "=", "Yedit", ".", "get_entry", "(", "self", ".", "yaml_dict", ",", "path", ",", "self", ".", "separator", ")", "except", "KeyError", "as", "_", ":", "entry", "=", "None", "i...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oc_secret.py#L759-L773
sciter-sdk/pysciter
f3f4cfe6fd774d2e045b23e79326086cd7288fc6
sciter/dom.py
python
Element.clear
(self)
return self
Clear content of the element.
Clear content of the element.
[ "Clear", "content", "of", "the", "element", "." ]
def clear(self): """Clear content of the element.""" ok = _api.SciterSetElementText(self, None, 0) self._throw_if(ok) return self
[ "def", "clear", "(", "self", ")", ":", "ok", "=", "_api", ".", "SciterSetElementText", "(", "self", ",", "None", ",", "0", ")", "self", ".", "_throw_if", "(", "ok", ")", "return", "self" ]
https://github.com/sciter-sdk/pysciter/blob/f3f4cfe6fd774d2e045b23e79326086cd7288fc6/sciter/dom.py#L428-L432
evilhero/mylar
dbee01d7e48e8c717afa01b2de1946c5d0b956cb
lib/requests/models.py
python
Response.json
(self, **kwargs)
return json.loads(self.text, **kwargs)
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
Returns the json-encoded content of a response, if any.
[ "Returns", "the", "json", "-", "encoded", "content", "of", "a", "response", "if", "any", "." ]
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect # UTF-8, -16 or -32. Detect which one to use; If the detection or # decoding fails, fall back to `self.text` (using chardet to make # a best guess). encoding = guess_json_utf(self.content) if encoding is not None: try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: # Wrong UTF codec detected; usually because it's not UTF-8 # but some other 8-bit codec. This is an RFC violation, # and the server didn't bother to tell us what codec *was* # used. pass return json.loads(self.text, **kwargs)
[ "def", "json", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "encoding", "and", "len", "(", "self", ".", "content", ")", ">", "3", ":", "# No encoding set. JSON RFC 4627 section 3 states we should expect", "# UTF-8, -16 or -32. Detect w...
https://github.com/evilhero/mylar/blob/dbee01d7e48e8c717afa01b2de1946c5d0b956cb/lib/requests/models.py#L798-L819
oracle/graalpython
577e02da9755d916056184ec441c26e00b70145c
graalpython/lib-python/3/xml/dom/expatbuilder.py
python
FragmentBuilder.external_entity_ref_handler
(self, context, base, systemId, publicId)
[]
def external_entity_ref_handler(self, context, base, systemId, publicId): if systemId == _FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID: # this entref is the one that we made to put the subtree # in; all of our given input is parsed in here. old_document = self.document old_cur_node = self.curNode parser = self._parser.ExternalEntityParserCreate(context) # put the real document back, parse into the fragment to return self.document = self.originalDocument self.fragment = self.document.createDocumentFragment() self.curNode = self.fragment try: parser.Parse(self._source, 1) finally: self.curNode = old_cur_node self.document = old_document self._source = None return -1 else: return ExpatBuilder.external_entity_ref_handler( self, context, base, systemId, publicId)
[ "def", "external_entity_ref_handler", "(", "self", ",", "context", ",", "base", ",", "systemId", ",", "publicId", ")", ":", "if", "systemId", "==", "_FRAGMENT_BUILDER_INTERNAL_SYSTEM_ID", ":", "# this entref is the one that we made to put the subtree", "# in; all of our given...
https://github.com/oracle/graalpython/blob/577e02da9755d916056184ec441c26e00b70145c/graalpython/lib-python/3/xml/dom/expatbuilder.py#L688-L708
amirzed/provisionpad
51d2a886f46b5090b6fb8b91c18c3043ec36ae42
src/provisionpad/aws/aws_sg.py
python
AWSsgFuncs.set_sg_http_egress
(self, sgid)
modifies the security group to only ssh ingress and no egress Parameters: sgid (str): the id of the security group Returns: -
modifies the security group to only ssh ingress and no egress
[ "modifies", "the", "security", "group", "to", "only", "ssh", "ingress", "and", "no", "egress" ]
def set_sg_http_egress(self, sgid): ''' modifies the security group to only ssh ingress and no egress Parameters: sgid (str): the id of the security group Returns: - ''' securitygroup = self.ec2.SecurityGroup(sgid) securitygroup.authorize_egress( IpPermissions=[ {'IpProtocol': 'tcp', 'FromPort': 80, 'ToPort': 80, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 443, 'ToPort': 443, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}], 'Ipv6Ranges': [{'CidrIpv6': '::/0'}]}, ] )
[ "def", "set_sg_http_egress", "(", "self", ",", "sgid", ")", ":", "securitygroup", "=", "self", ".", "ec2", ".", "SecurityGroup", "(", "sgid", ")", "securitygroup", ".", "authorize_egress", "(", "IpPermissions", "=", "[", "{", "'IpProtocol'", ":", "'tcp'", ",...
https://github.com/amirzed/provisionpad/blob/51d2a886f46b5090b6fb8b91c18c3043ec36ae42/src/provisionpad/aws/aws_sg.py#L46-L71
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/util/timeout.py
python
Timeout.connect_timeout
(self)
return min(self._connect, self.total)
Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None
Get the value to use when setting a connection timeout.
[ "Get", "the", "value", "to", "use", "when", "setting", "a", "connection", "timeout", "." ]
def connect_timeout(self): """ Get the value to use when setting a connection timeout. This will be a positive float or integer, the value None (never timeout), or the default system timeout. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None """ if self.total is None: return self._connect if self._connect is None or self._connect is self.DEFAULT_TIMEOUT: return self.total return min(self._connect, self.total)
[ "def", "connect_timeout", "(", "self", ")", ":", "if", "self", ".", "total", "is", "None", ":", "return", "self", ".", "_connect", "if", "self", ".", "_connect", "is", "None", "or", "self", ".", "_connect", "is", "self", ".", "DEFAULT_TIMEOUT", ":", "r...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/urllib3/util/timeout.py#L196-L211
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/fate_arch/abc/_storage.py
python
StorageSessionABC.get_table
(self, name, namespace)
[]
def get_table(self, name, namespace) -> StorageTableABC: ...
[ "def", "get_table", "(", "self", ",", "name", ",", "namespace", ")", "->", "StorageTableABC", ":", "..." ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/fate_arch/abc/_storage.py#L209-L210
cylc/cylc-flow
5ec221143476c7c616c156b74158edfbcd83794a
cylc/flow/network/graphql.py
python
AstDocArguments.has_arg_val
(self, arg_name, arg_value)
return False
Search through document definitions for argument value. Args: arg_name (str): Field argument to search for. arg_value (Any): Argument value required. Returns: Boolean
Search through document definitions for argument value.
[ "Search", "through", "document", "definitions", "for", "argument", "value", "." ]
def has_arg_val(self, arg_name, arg_value): """Search through document definitions for argument value. Args: arg_name (str): Field argument to search for. arg_value (Any): Argument value required. Returns: Boolean """ for components in self.operation_defs.values(): defn = components['definition'] if ( defn.operation not in STRIP_OPS or getattr( defn.name, 'value', None) == 'IntrospectionQuery' ): continue if self.args_selection_search( components['definition'].selection_set, components['variables'], components['parent_type'], arg_name, arg_value, ): return True return False
[ "def", "has_arg_val", "(", "self", ",", "arg_name", ",", "arg_value", ")", ":", "for", "components", "in", "self", ".", "operation_defs", ".", "values", "(", ")", ":", "defn", "=", "components", "[", "'definition'", "]", "if", "(", "defn", ".", "operatio...
https://github.com/cylc/cylc-flow/blob/5ec221143476c7c616c156b74158edfbcd83794a/cylc/flow/network/graphql.py#L184-L212
pynag/pynag
e72cf7ce2395263e2b3080cae0ece2b03dbbfa27
pynag/Utils/states.py
python
service_state_to_int
(state)
Converts from strings like OK to states like 0. Args: State: string. Can be in the form of 'ok', 'warning', 'critical', '1', etc. Returns: Integer. A nagios corresponding to the free text state inputted. Raises: UnknownState: If no match can be found for 'state'. Examples: >>> service_state_to_int('ok') 0 >>> service_state_to_int('Warning') 1 >>> service_state_to_int('critical') 2 >>> service_state_to_int('UNKNOWN') 3 >>> service_state_to_int('0') 0 >>> service_state_to_int('1') 1 >>> service_state_to_int('2') 2 >>> service_state_to_int('3') 3 >>> service_state_to_int('foo') Traceback (most recent call last): .. UnknownState: Do not know how to handle state foo
Converts from strings like OK to states like 0.
[ "Converts", "from", "strings", "like", "OK", "to", "states", "like", "0", "." ]
def service_state_to_int(state): """Converts from strings like OK to states like 0. Args: State: string. Can be in the form of 'ok', 'warning', 'critical', '1', etc. Returns: Integer. A nagios corresponding to the free text state inputted. Raises: UnknownState: If no match can be found for 'state'. Examples: >>> service_state_to_int('ok') 0 >>> service_state_to_int('Warning') 1 >>> service_state_to_int('critical') 2 >>> service_state_to_int('UNKNOWN') 3 >>> service_state_to_int('0') 0 >>> service_state_to_int('1') 1 >>> service_state_to_int('2') 2 >>> service_state_to_int('3') 3 >>> service_state_to_int('foo') Traceback (most recent call last): .. UnknownState: Do not know how to handle state foo """ text = str(state).lower() try: return _SERVICE_TEXT_TO_INT[text] except KeyError: raise UnknownState('Do not know how to handle state %s' % state)
[ "def", "service_state_to_int", "(", "state", ")", ":", "text", "=", "str", "(", "state", ")", ".", "lower", "(", ")", "try", ":", "return", "_SERVICE_TEXT_TO_INT", "[", "text", "]", "except", "KeyError", ":", "raise", "UnknownState", "(", "'Do not know how t...
https://github.com/pynag/pynag/blob/e72cf7ce2395263e2b3080cae0ece2b03dbbfa27/pynag/Utils/states.py#L67-L106
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/access/enumeration.py
python
Enumeration.searchTable
(self)
return []
[]
def searchTable(self): warnMsg = "on Microsoft Access it is not possible to search tables" logger.warn(warnMsg) return []
[ "def", "searchTable", "(", "self", ")", ":", "warnMsg", "=", "\"on Microsoft Access it is not possible to search tables\"", "logger", ".", "warn", "(", "warnMsg", ")", "return", "[", "]" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/access/enumeration.py#L63-L67
DeepX-inc/machina
f93bb6f5aca1feccd71fc509bd6370d2015e2d85
machina/logger.py
python
_type
(string, has_invisible=True)
The least generic type (type(None), int, float, str, unicode). >>> _type(None) is type(None) True >>> _type("foo") is type("") True >>> _type("1") is type(1) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True
The least generic type (type(None), int, float, str, unicode).
[ "The", "least", "generic", "type", "(", "type", "(", "None", ")", "int", "float", "str", "unicode", ")", "." ]
def _type(string, has_invisible=True): """The least generic type (type(None), int, float, str, unicode). >>> _type(None) is type(None) True >>> _type("foo") is type("") True >>> _type("1") is type(1) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True >>> _type('\x1b[31m42\x1b[0m') is type(42) True """ if has_invisible and \ (isinstance(string, _text_type) or isinstance(string, _binary_type)): string = _strip_invisible(string) if string is None: return _none_type elif hasattr(string, "isoformat"): # datetime.datetime, date, and time return _text_type elif _isint(string): return int elif _isnumber(string): return float elif isinstance(string, _binary_type): return _binary_type else: return _text_type
[ "def", "_type", "(", "string", ",", "has_invisible", "=", "True", ")", ":", "if", "has_invisible", "and", "(", "isinstance", "(", "string", ",", "_text_type", ")", "or", "isinstance", "(", "string", ",", "_binary_type", ")", ")", ":", "string", "=", "_st...
https://github.com/DeepX-inc/machina/blob/f93bb6f5aca1feccd71fc509bd6370d2015e2d85/machina/logger.py#L296-L327
pyqt/examples
843bb982917cecb2350b5f6d7f42c9b7fb142ec1
src/pyqt-official/richtext/textedit/textedit.py
python
TextEdit.closeEvent
(self, e)
[]
def closeEvent(self, e): if self.maybeSave(): e.accept() else: e.ignore()
[ "def", "closeEvent", "(", "self", ",", "e", ")", ":", "if", "self", ".", "maybeSave", "(", ")", ":", "e", ".", "accept", "(", ")", "else", ":", "e", ".", "ignore", "(", ")" ]
https://github.com/pyqt/examples/blob/843bb982917cecb2350b5f6d7f42c9b7fb142ec1/src/pyqt-official/richtext/textedit/textedit.py#L121-L125
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/core/servers/basehttp.py
python
ServerHandler.write
(self, data)
write()' callable as specified by PEP 3333
write()' callable as specified by PEP 3333
[ "write", "()", "callable", "as", "specified", "by", "PEP", "3333" ]
def write(self, data): """'write()' callable as specified by PEP 3333""" assert isinstance(data, bytes), "write() argument must be bytestring" if not self.status: raise AssertionError("write() before start_response()") elif not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() else: self.bytes_sent += len(data) # XXX check Content-Length and truncate if too many bytes written? # If data is too large, socket will choke, so write chunks no larger # than 32MB at a time. length = len(data) if length > 33554432: offset = 0 while offset < length: chunk_size = min(33554432, length) self._write(data[offset:offset+chunk_size]) self._flush() offset += chunk_size else: self._write(data) self._flush()
[ "def", "write", "(", "self", ",", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", ",", "\"write() argument must be bytestring\"", "if", "not", "self", ".", "status", ":", "raise", "AssertionError", "(", "\"write() before start_response()\...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/servers/basehttp.py#L77-L106
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/re.py
python
_compile_repl
(repl, pattern)
return sre_parse.parse_template(repl, pattern)
[]
def _compile_repl(repl, pattern): # internal: compile replacement pattern return sre_parse.parse_template(repl, pattern)
[ "def", "_compile_repl", "(", "repl", ",", "pattern", ")", ":", "# internal: compile replacement pattern", "return", "sre_parse", ".", "parse_template", "(", "repl", ",", "pattern", ")" ]
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter5-LogisticRegression/venv/Lib/re.py#L315-L317
kanzure/nanoengineer
874e4c9f8a9190f093625b267f9767e19f82e6c4
cad/src/PM/PM_MolecularModelingKit.py
python
PM_MolecularModelingKit.updateElementViewer
(self)
return
Update the view in the element viewer (if present)
Update the view in the element viewer (if present)
[ "Update", "the", "view", "in", "the", "element", "viewer", "(", "if", "present", ")" ]
def updateElementViewer(self): """ Update the view in the element viewer (if present) """ if not self.elementViewer: return from graphics.widgets.ThumbView import MMKitView assert isinstance(self.elementViewer, MMKitView) self.elementViewer.resetView() self.elementViewer.changeHybridType(self.atomType) self.elementViewer.refreshDisplay(self.element, self.viewerDisplay) return
[ "def", "updateElementViewer", "(", "self", ")", ":", "if", "not", "self", ".", "elementViewer", ":", "return", "from", "graphics", ".", "widgets", ".", "ThumbView", "import", "MMKitView", "assert", "isinstance", "(", "self", ".", "elementViewer", ",", "MMKitVi...
https://github.com/kanzure/nanoengineer/blob/874e4c9f8a9190f093625b267f9767e19f82e6c4/cad/src/PM/PM_MolecularModelingKit.py#L180-L192
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/sklearn/multiclass.py
python
_partial_fit_ovo_binary
(estimator, X, y, i, j)
return _partial_fit_binary(estimator, X[cond], y_binary)
Partially fit a single binary estimator(one-vs-one).
Partially fit a single binary estimator(one-vs-one).
[ "Partially", "fit", "a", "single", "binary", "estimator", "(", "one", "-", "vs", "-", "one", ")", "." ]
def _partial_fit_ovo_binary(estimator, X, y, i, j): """Partially fit a single binary estimator(one-vs-one).""" cond = np.logical_or(y == i, y == j) y = y[cond] y_binary = np.zeros_like(y) y_binary[y == j] = 1 return _partial_fit_binary(estimator, X[cond], y_binary)
[ "def", "_partial_fit_ovo_binary", "(", "estimator", ",", "X", ",", "y", ",", "i", ",", "j", ")", ":", "cond", "=", "np", ".", "logical_or", "(", "y", "==", "i", ",", "y", "==", "j", ")", "y", "=", "y", "[", "cond", "]", "y_binary", "=", "np", ...
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/sklearn/multiclass.py#L422-L429
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/werkzeug/formparser.py
python
is_valid_multipart_boundary
(boundary)
return _multipart_boundary_re.match(boundary) is not None
Checks if the string given is a valid multipart boundary.
Checks if the string given is a valid multipart boundary.
[ "Checks", "if", "the", "string", "given", "is", "a", "valid", "multipart", "boundary", "." ]
def is_valid_multipart_boundary(boundary): """Checks if the string given is a valid multipart boundary.""" return _multipart_boundary_re.match(boundary) is not None
[ "def", "is_valid_multipart_boundary", "(", "boundary", ")", ":", "return", "_multipart_boundary_re", ".", "match", "(", "boundary", ")", "is", "not", "None" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/werkzeug/formparser.py#L243-L245
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/template/defaultfilters.py
python
last
(value)
Returns the last item in a list
Returns the last item in a list
[ "Returns", "the", "last", "item", "in", "a", "list" ]
def last(value): "Returns the last item in a list" try: return value[-1] except IndexError: return u''
[ "def", "last", "(", "value", ")", ":", "try", ":", "return", "value", "[", "-", "1", "]", "except", "IndexError", ":", "return", "u''" ]
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/template/defaultfilters.py#L532-L537
mozman/ezdxf
59d0fc2ea63f5cf82293428f5931da7e9f9718e9
src/ezdxf/entities/appdata.py
python
AppData.__contains__
(self, appid: str)
return uniform_appid(appid) in self.data
Returns ``True`` if application-defined data exist for `appid`.
Returns ``True`` if application-defined data exist for `appid`.
[ "Returns", "True", "if", "application", "-", "defined", "data", "exist", "for", "appid", "." ]
def __contains__(self, appid: str) -> bool: """Returns ``True`` if application-defined data exist for `appid`.""" return uniform_appid(appid) in self.data
[ "def", "__contains__", "(", "self", ",", "appid", ":", "str", ")", "->", "bool", ":", "return", "uniform_appid", "(", "appid", ")", "in", "self", ".", "data" ]
https://github.com/mozman/ezdxf/blob/59d0fc2ea63f5cf82293428f5931da7e9f9718e9/src/ezdxf/entities/appdata.py#L36-L38
brendano/tweetmotif
1b0b1e3a941745cd5a26eba01f554688b7c4b27e
everything_else/djfrontend/django-1.0.2/contrib/localflavor/is_/forms.py
python
ISIdNumberField._format
(self, value)
return smart_unicode(value[:6]+'-'+value[6:])
Takes in the value in canonical form and returns it in the common display format.
Takes in the value in canonical form and returns it in the common display format.
[ "Takes", "in", "the", "value", "in", "canonical", "form", "and", "returns", "it", "in", "the", "common", "display", "format", "." ]
def _format(self, value): """ Takes in the value in canonical form and returns it in the common display format. """ return smart_unicode(value[:6]+'-'+value[6:])
[ "def", "_format", "(", "self", ",", "value", ")", ":", "return", "smart_unicode", "(", "value", "[", ":", "6", "]", "+", "'-'", "+", "value", "[", "6", ":", "]", ")" ]
https://github.com/brendano/tweetmotif/blob/1b0b1e3a941745cd5a26eba01f554688b7c4b27e/everything_else/djfrontend/django-1.0.2/contrib/localflavor/is_/forms.py#L51-L56
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/powerwall/binary_sensor.py
python
PowerWallGridServicesActiveSensor.is_on
(self)
return self.coordinator.data[POWERWALL_API_GRID_SERVICES_ACTIVE]
Grid services is active.
Grid services is active.
[ "Grid", "services", "is", "active", "." ]
def is_on(self): """Grid services is active.""" return self.coordinator.data[POWERWALL_API_GRID_SERVICES_ACTIVE]
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "POWERWALL_API_GRID_SERVICES_ACTIVE", "]" ]
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/powerwall/binary_sensor.py#L125-L127
exaile/exaile
a7b58996c5c15b3aa7b9975ac13ee8f784ef4689
plugins/minimode/controls.py
python
RatingControl.do_rating_changed
(self, rating)
Updates the rating of the currently playing track
Updates the rating of the currently playing track
[ "Updates", "the", "rating", "of", "the", "currently", "playing", "track" ]
def do_rating_changed(self, rating): """ Updates the rating of the currently playing track """ if player.PLAYER.current is not None: player.PLAYER.current.set_rating(rating) maximum = settings.get_option('rating/maximum', 5) event.log_event('rating_changed', self, 100 * rating / maximum)
[ "def", "do_rating_changed", "(", "self", ",", "rating", ")", ":", "if", "player", ".", "PLAYER", ".", "current", "is", "not", "None", ":", "player", ".", "PLAYER", ".", "current", ".", "set_rating", "(", "rating", ")", "maximum", "=", "settings", ".", ...
https://github.com/exaile/exaile/blob/a7b58996c5c15b3aa7b9975ac13ee8f784ef4689/plugins/minimode/controls.py#L562-L569
mcedit/pymclevel
8bf7b3d76479e007a51f3055198a8bcddb626c84
gprof2dot.py
python
Main.compress_function_name
(self, name)
return name
Compress function name according to the user preferences.
Compress function name according to the user preferences.
[ "Compress", "function", "name", "according", "to", "the", "user", "preferences", "." ]
def compress_function_name(self, name): """Compress function name according to the user preferences.""" if self.options.strip: name = self.strip_function_name(name) if self.options.wrap: name = self.wrap_function_name(name) # TODO: merge functions with same resulting name return name
[ "def", "compress_function_name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "options", ".", "strip", ":", "name", "=", "self", ".", "strip_function_name", "(", "name", ")", "if", "self", ".", "options", ".", "wrap", ":", "name", "=", "self"...
https://github.com/mcedit/pymclevel/blob/8bf7b3d76479e007a51f3055198a8bcddb626c84/gprof2dot.py#L2579-L2590
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
src/transformers/models/speech_to_text_2/processing_speech_to_text_2.py
python
Speech2Text2Processor.from_pretrained
(cls, pretrained_model_name_or_path, **kwargs)
return cls(feature_extractor=feature_extractor, tokenizer=tokenizer)
r""" Instantiate a [`Speech2Text2Processor`] from a pretrained Speech2Text2 processor. <Tip> This class method is simply calling AutoFeatureExtractor's [`~PreTrainedFeatureExtractor.from_pretrained`] and Speech2Text2Tokenizer's [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`]. Please refer to the docstrings of the methods above for more information. </Tip> Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a feature extractor file saved using the [`~PreTrainedFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved feature extractor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. **kwargs Additional keyword arguments passed along to both [`PreTrainedFeatureExtractor`] and [`PreTrainedTokenizer`]
r""" Instantiate a [`Speech2Text2Processor`] from a pretrained Speech2Text2 processor.
[ "r", "Instantiate", "a", "[", "Speech2Text2Processor", "]", "from", "a", "pretrained", "Speech2Text2", "processor", "." ]
def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a [`Speech2Text2Processor`] from a pretrained Speech2Text2 processor. <Tip> This class method is simply calling AutoFeatureExtractor's [`~PreTrainedFeatureExtractor.from_pretrained`] and Speech2Text2Tokenizer's [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`]. Please refer to the docstrings of the methods above for more information. </Tip> Args: pretrained_model_name_or_path (`str` or `os.PathLike`): This can be either: - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`. - a path to a *directory* containing a feature extractor file saved using the [`~PreTrainedFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`. - a path or url to a saved feature extractor JSON *file*, e.g., `./my_model_directory/preprocessor_config.json`. **kwargs Additional keyword arguments passed along to both [`PreTrainedFeatureExtractor`] and [`PreTrainedTokenizer`] """ feature_extractor = AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path, **kwargs) tokenizer = Speech2Text2Tokenizer.from_pretrained(pretrained_model_name_or_path, **kwargs) return cls(feature_extractor=feature_extractor, tokenizer=tokenizer)
[ "def", "from_pretrained", "(", "cls", ",", "pretrained_model_name_or_path", ",", "*", "*", "kwargs", ")", ":", "feature_extractor", "=", "AutoFeatureExtractor", ".", "from_pretrained", "(", "pretrained_model_name_or_path", ",", "*", "*", "kwargs", ")", "tokenizer", ...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/src/transformers/models/speech_to_text_2/processing_speech_to_text_2.py#L78-L108
AllenInstitute/bmtk
9c02811a4e1e8695c25de658301d9477bb289298
bmtk/simulator/core/simulation_config.py
python
SimulationConfig.build_env
(self, force=False)
Creates the folder(s) set in 'output' section, sets up logging and copies over the configuration
Creates the folder(s) set in 'output' section, sets up logging and copies over the configuration
[ "Creates", "the", "folder", "(", "s", ")", "set", "in", "output", "section", "sets", "up", "logging", "and", "copies", "over", "the", "configuration" ]
def build_env(self, force=False): """Creates the folder(s) set in 'output' section, sets up logging and copies over the configuration""" if self.env_built and not force: return self._set_logging() self.io.setup_output_dir(self.output_dir, self.log_file, self.overwrite_output) self.copy_to_output() self.env_built = True
[ "def", "build_env", "(", "self", ",", "force", "=", "False", ")", ":", "if", "self", ".", "env_built", "and", "not", "force", ":", "return", "self", ".", "_set_logging", "(", ")", "self", ".", "io", ".", "setup_output_dir", "(", "self", ".", "output_di...
https://github.com/AllenInstitute/bmtk/blob/9c02811a4e1e8695c25de658301d9477bb289298/bmtk/simulator/core/simulation_config.py#L91-L99
fab-jul/imgcomp-cvpr
f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c
code/other_codecs.py
python
bpg_image_info
(p)
Relevant format spec: magic number 4 bytes header stuff 2 bytes width variable, ue7 height variable, ue7 picture_data_length variable, ue7. If zero: remaining data is image
Relevant format spec: magic number 4 bytes header stuff 2 bytes width variable, ue7 height variable, ue7 picture_data_length variable, ue7. If zero: remaining data is image
[ "Relevant", "format", "spec", ":", "magic", "number", "4", "bytes", "header", "stuff", "2", "bytes", "width", "variable", "ue7", "height", "variable", "ue7", "picture_data_length", "variable", "ue7", ".", "If", "zero", ":", "remaining", "data", "is", "image" ]
def bpg_image_info(p): """ Relevant format spec: magic number 4 bytes header stuff 2 bytes width variable, ue7 height variable, ue7 picture_data_length variable, ue7. If zero: remaining data is image """ with open(p, 'rb') as f: magic = f.read(4) expected_magic = bytearray.fromhex('425047fb') assert magic == expected_magic, 'Not a BPG file it seems: {}'.format(p) header_info = f.read(2) width = _read_ue7(f) height = _read_ue7(f) picture_data_length = _read_ue7(f) num_bytes_for_picture = _number_of_bytes_until_eof(f) if picture_data_length == 0 else picture_data_length return BPGImageInfo(width, height, num_bytes_for_picture)
[ "def", "bpg_image_info", "(", "p", ")", ":", "with", "open", "(", "p", ",", "'rb'", ")", "as", "f", ":", "magic", "=", "f", ".", "read", "(", "4", ")", "expected_magic", "=", "bytearray", ".", "fromhex", "(", "'425047fb'", ")", "assert", "magic", "...
https://github.com/fab-jul/imgcomp-cvpr/blob/f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c/code/other_codecs.py#L422-L440
pydata/xarray
9226c7ac87b3eb246f7a7e49f8f0f23d68951624
xarray/core/indexing.py
python
create_mask
(indexer, shape, data=None)
return mask
Create a mask for indexing with a fill-value. Parameters ---------- indexer : ExplicitIndexer Indexer with -1 in integer or ndarray value to indicate locations in the result that should be masked. shape : tuple Shape of the array being indexed. data : optional Data for which mask is being created. If data is a dask arrays, its chunks are used as a hint for chunks on the resulting mask. If data is a sparse array, the returned mask is also a sparse array. Returns ------- mask : bool, np.ndarray, SparseArray or dask.array.Array with dtype=bool Same type as data. Has the same shape as the indexing result.
Create a mask for indexing with a fill-value.
[ "Create", "a", "mask", "for", "indexing", "with", "a", "fill", "-", "value", "." ]
def create_mask(indexer, shape, data=None): """Create a mask for indexing with a fill-value. Parameters ---------- indexer : ExplicitIndexer Indexer with -1 in integer or ndarray value to indicate locations in the result that should be masked. shape : tuple Shape of the array being indexed. data : optional Data for which mask is being created. If data is a dask arrays, its chunks are used as a hint for chunks on the resulting mask. If data is a sparse array, the returned mask is also a sparse array. Returns ------- mask : bool, np.ndarray, SparseArray or dask.array.Array with dtype=bool Same type as data. Has the same shape as the indexing result. """ if isinstance(indexer, OuterIndexer): key = _outer_to_vectorized_indexer(indexer, shape).tuple assert not any(isinstance(k, slice) for k in key) mask = _masked_result_drop_slice(key, data) elif isinstance(indexer, VectorizedIndexer): key = indexer.tuple base_mask = _masked_result_drop_slice(key, data) slice_shape = tuple( np.arange(*k.indices(size)).size for k, size in zip(key, shape) if isinstance(k, slice) ) expanded_mask = base_mask[(Ellipsis,) + (np.newaxis,) * len(slice_shape)] mask = duck_array_ops.broadcast_to(expanded_mask, base_mask.shape + slice_shape) elif isinstance(indexer, BasicIndexer): mask = any(k == -1 for k in indexer.tuple) else: raise TypeError("unexpected key type: {}".format(type(indexer))) return mask
[ "def", "create_mask", "(", "indexer", ",", "shape", ",", "data", "=", "None", ")", ":", "if", "isinstance", "(", "indexer", ",", "OuterIndexer", ")", ":", "key", "=", "_outer_to_vectorized_indexer", "(", "indexer", ",", "shape", ")", ".", "tuple", "assert"...
https://github.com/pydata/xarray/blob/9226c7ac87b3eb246f7a7e49f8f0f23d68951624/xarray/core/indexing.py#L1014-L1056
USEPA/WNTR
2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc
wntr/network/model.py
python
LinkRegistry.psvs
(self)
Generator to get all PSVs Yields ------ name : str The name of the valve link : PSValve The valve object
Generator to get all PSVs Yields ------ name : str The name of the valve link : PSValve The valve object
[ "Generator", "to", "get", "all", "PSVs", "Yields", "------", "name", ":", "str", "The", "name", "of", "the", "valve", "link", ":", "PSValve", "The", "valve", "object" ]
def psvs(self): """Generator to get all PSVs Yields ------ name : str The name of the valve link : PSValve The valve object """ for name in self._psvs: yield name, self._data[name]
[ "def", "psvs", "(", "self", ")", ":", "for", "name", "in", "self", ".", "_psvs", ":", "yield", "name", ",", "self", ".", "_data", "[", "name", "]" ]
https://github.com/USEPA/WNTR/blob/2f92bab5736da6ef3591fc4b0229ec1ac6cd6fcc/wntr/network/model.py#L2547-L2559
wistbean/learn_python3_spider
73c873f4845f4385f097e5057407d03dd37a117b
stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py
python
IntervalDifferential.__init__
(self, intervals, default=60)
@type intervals: C{list} of C{int}, C{long}, or C{float} param @param intervals: The intervals between instants. @type default: C{int}, C{long}, or C{float} @param default: The duration to generate if the intervals list becomes empty.
@type intervals: C{list} of C{int}, C{long}, or C{float} param @param intervals: The intervals between instants.
[ "@type", "intervals", ":", "C", "{", "list", "}", "of", "C", "{", "int", "}", "C", "{", "long", "}", "or", "C", "{", "float", "}", "param", "@param", "intervals", ":", "The", "intervals", "between", "instants", "." ]
def __init__(self, intervals, default=60): """ @type intervals: C{list} of C{int}, C{long}, or C{float} param @param intervals: The intervals between instants. @type default: C{int}, C{long}, or C{float} @param default: The duration to generate if the intervals list becomes empty. """ self.intervals = intervals[:] self.default = default
[ "def", "__init__", "(", "self", ",", "intervals", ",", "default", "=", "60", ")", ":", "self", ".", "intervals", "=", "intervals", "[", ":", "]", "self", ".", "default", "=", "default" ]
https://github.com/wistbean/learn_python3_spider/blob/73c873f4845f4385f097e5057407d03dd37a117b/stackoverflow/venv/lib/python3.6/site-packages/twisted/python/util.py#L519-L529
dpressel/mead-baseline
9987e6b37fa6525a4ddc187c305e292a718f59a9
baseline/reader.py
python
IndexPairLabelReader.convert_to_example_single
(self, vocabs: Dict[str, str], text1: List[str], text2: List[str])
return example_dict
Convert to a concatenated vector. Useful for BERT-style models :param vocabs: Vocabs to use :param text1: First text :param text2: Second text :return: An example dict
Convert to a concatenated vector. Useful for BERT-style models
[ "Convert", "to", "a", "concatenated", "vector", ".", "Useful", "for", "BERT", "-", "style", "models" ]
def convert_to_example_single(self, vocabs: Dict[str, str], text1: List[str], text2: List[str]) -> Dict[str, object]: """Convert to a concatenated vector. Useful for BERT-style models :param vocabs: Vocabs to use :param text1: First text :param text2: Second text :return: An example dict """ example_dict = dict() for key, vectorizer in self.vectorizers.items(): v = vocabs[key] vec_1, lengths = vectorizer.run(text1, v) vec_1 = vec_1[:lengths] vec_2, lengths = vectorizer.run(text2, v) vec_2 = vec_2[:lengths] if self.start_tokens_1: vec_1 = np.concatenate([np.array([v[x] for x in self.start_tokens_1]), vec_1]) if self.end_tokens_1: vec_1 = np.concatenate([vec_1, np.array([v[x] for x in self.end_tokens_1])]) if self.start_tokens_2: vec_2 = np.concatenate([np.array([v[x] for x in self.start_tokens_2]), vec_2]) if self.end_tokens_2: vec_2 = np.concatenate([vec_2, np.array([v[x] for x in self.end_tokens_2])]) lengths_1 = vec_1.shape[-1] lengths_2 = vec_2.shape[-1] total_length = lengths_1 + lengths_2 vec = np.concatenate([vec_1, vec_2]) extend = vectorizer.mxlen - total_length if extend < 0: logger.warning(f"total length {total_length} exceeds allocated vectorizer width of {vectorizer.mxlen}") vec = vec[:vectorizer.mxlen] elif extend > 0: vec = np.concatenate([vec, np.full(extend, Offsets.PAD, vec.dtype)]) example_dict[key] = vec if self.use_token_type: token_type = np.zeros_like(vec) token_type[lengths_1:] = 1 example_dict[f"{key}_tt"] = token_type return example_dict
[ "def", "convert_to_example_single", "(", "self", ",", "vocabs", ":", "Dict", "[", "str", ",", "str", "]", ",", "text1", ":", "List", "[", "str", "]", ",", "text2", ":", "List", "[", "str", "]", ")", "->", "Dict", "[", "str", ",", "object", "]", "...
https://github.com/dpressel/mead-baseline/blob/9987e6b37fa6525a4ddc187c305e292a718f59a9/baseline/reader.py#L1026-L1069
bslatkin/effectivepython
4ae6f3141291ea137eb29a245bf889dbc8091713
example_code/item_39.py
python
PathInputData.read
(self)
[]
def read(self): with open(self.path) as f: return f.read()
[ "def", "read", "(", "self", ")", ":", "with", "open", "(", "self", ".", "path", ")", "as", "f", ":", "return", "f", ".", "read", "(", ")" ]
https://github.com/bslatkin/effectivepython/blob/4ae6f3141291ea137eb29a245bf889dbc8091713/example_code/item_39.py#L159-L161
pyparallel/pyparallel
11e8c6072d48c8f13641925d17b147bf36ee0ba3
Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/computation/pytables.py
python
Expr.evaluate
(self)
return self.condition, self.filter
create and return the numexpr condition and filter
create and return the numexpr condition and filter
[ "create", "and", "return", "the", "numexpr", "condition", "and", "filter" ]
def evaluate(self): """ create and return the numexpr condition and filter """ try: self.condition = self.terms.prune(ConditionBinOp) except AttributeError: raise ValueError("cannot process expression [{0}], [{1}] is not a " "valid condition".format(self.expr, self)) try: self.filter = self.terms.prune(FilterBinOp) except AttributeError: raise ValueError("cannot process expression [{0}], [{1}] is not a " "valid filter".format(self.expr, self)) return self.condition, self.filter
[ "def", "evaluate", "(", "self", ")", ":", "try", ":", "self", ".", "condition", "=", "self", ".", "terms", ".", "prune", "(", "ConditionBinOp", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "\"cannot process expression [{0}], [{1}] is not a \""...
https://github.com/pyparallel/pyparallel/blob/11e8c6072d48c8f13641925d17b147bf36ee0ba3/Lib/site-packages/pandas-0.17.0-py3.3-win-amd64.egg/pandas/computation/pytables.py#L576-L590
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
pypy/module/cpyext/cdatetime.py
python
_PyDate_FromDate
(space, year, month, day, w_type)
return space.call_function( w_type, space.newint(year), space.newint(month), space.newint(day))
Return a datetime.date object with the specified year, month and day.
Return a datetime.date object with the specified year, month and day.
[ "Return", "a", "datetime", ".", "date", "object", "with", "the", "specified", "year", "month", "and", "day", "." ]
def _PyDate_FromDate(space, year, month, day, w_type): """Return a datetime.date object with the specified year, month and day. """ year = rffi.cast(lltype.Signed, year) month = rffi.cast(lltype.Signed, month) day = rffi.cast(lltype.Signed, day) return space.call_function( w_type, space.newint(year), space.newint(month), space.newint(day))
[ "def", "_PyDate_FromDate", "(", "space", ",", "year", ",", "month", ",", "day", ",", "w_type", ")", ":", "year", "=", "rffi", ".", "cast", "(", "lltype", ".", "Signed", ",", "year", ")", "month", "=", "rffi", ".", "cast", "(", "lltype", ".", "Signe...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/pypy/module/cpyext/cdatetime.py#L187-L195
kaaedit/kaa
e6a8819a5ecba04b7db8303bd5736b5a7c9b822d
kaa/cursor.py
python
Cursor.refresh
(self, top=None, middle=None, bottom=None, align_always=False)
[]
def refresh(self, top=None, middle=None, bottom=None, align_always=False): self.pos, y, x = self.wnd.locate_cursor( self.pos, top=top, middle=middle, bottom=bottom, align_always=align_always) assert self.pos is not None self.last_screenpos = (x, y)
[ "def", "refresh", "(", "self", ",", "top", "=", "None", ",", "middle", "=", "None", ",", "bottom", "=", "None", ",", "align_always", "=", "False", ")", ":", "self", ".", "pos", ",", "y", ",", "x", "=", "self", ".", "wnd", ".", "locate_cursor", "(...
https://github.com/kaaedit/kaa/blob/e6a8819a5ecba04b7db8303bd5736b5a7c9b822d/kaa/cursor.py#L10-L16
Kozea/pygal
8267b03535ff55789a30bf66b798302adad88623
pygal/svg.py
python
Svg.serie
(self, serie)
return dict( plot=self.node( self.graph.nodes['plot'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), overlay=self.node( self.graph.nodes['overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), text_overlay=self.node( self.graph.nodes['text_overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ) )
Make serie node
Make serie node
[ "Make", "serie", "node" ]
def serie(self, serie): """Make serie node""" return dict( plot=self.node( self.graph.nodes['plot'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), overlay=self.node( self.graph.nodes['overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), text_overlay=self.node( self.graph.nodes['text_overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ) )
[ "def", "serie", "(", "self", ",", "serie", ")", ":", "return", "dict", "(", "plot", "=", "self", ".", "node", "(", "self", ".", "graph", ".", "nodes", "[", "'plot'", "]", ",", "class_", "=", "'series serie-%d color-%d'", "%", "(", "serie", ".", "inde...
https://github.com/Kozea/pygal/blob/8267b03535ff55789a30bf66b798302adad88623/pygal/svg.py#L225-L240
floooh/fips
5ce5aebfc7c69778cab03ef5f8830928f2bad6d4
mod/tools/clion.py
python
write_workspace_settings
(fips_dir, proj_dir, cfg)
write the CLion *.xml files required to open the project
write the CLion *.xml files required to open the project
[ "write", "the", "CLion", "*", ".", "xml", "files", "required", "to", "open", "the", "project" ]
def write_workspace_settings(fips_dir, proj_dir, cfg): '''write the CLion *.xml files required to open the project ''' log.info("=== writing JetBrains CLion config files...") clion_dir = proj_dir + '/.idea' if not os.path.isdir(clion_dir): os.makedirs(clion_dir) write_clion_module_files(fips_dir, proj_dir, cfg) write_clion_workspace_file(fips_dir, proj_dir, cfg)
[ "def", "write_workspace_settings", "(", "fips_dir", ",", "proj_dir", ",", "cfg", ")", ":", "log", ".", "info", "(", "\"=== writing JetBrains CLion config files...\"", ")", "clion_dir", "=", "proj_dir", "+", "'/.idea'", "if", "not", "os", ".", "path", ".", "isdir...
https://github.com/floooh/fips/blob/5ce5aebfc7c69778cab03ef5f8830928f2bad6d4/mod/tools/clion.py#L109-L117
Qiskit/qiskit-terra
b66030e3b9192efdd3eb95cf25c6545fe0a13da4
qiskit/transpiler/coupling.py
python
CouplingMap.largest_connected_component
(self)
return max(rx.weakly_connected_components(self.graph), key=len)
Return a set of qubits in the largest connected component.
Return a set of qubits in the largest connected component.
[ "Return", "a", "set", "of", "qubits", "in", "the", "largest", "connected", "component", "." ]
def largest_connected_component(self): """Return a set of qubits in the largest connected component.""" return max(rx.weakly_connected_components(self.graph), key=len)
[ "def", "largest_connected_component", "(", "self", ")", ":", "return", "max", "(", "rx", ".", "weakly_connected_components", "(", "self", ".", "graph", ")", ",", "key", "=", "len", ")" ]
https://github.com/Qiskit/qiskit-terra/blob/b66030e3b9192efdd3eb95cf25c6545fe0a13da4/qiskit/transpiler/coupling.py#L396-L398
freqtrade/freqtrade
13651fd3be8d5ce8dcd7c94b920bda4e00b75aca
freqtrade/exchange/exchange.py
python
Exchange._init_ccxt
(self, exchange_config: Dict[str, Any], ccxt_module: CcxtModuleType = ccxt, ccxt_kwargs: Dict = {})
return api
Initialize ccxt with given config and return valid ccxt instance.
Initialize ccxt with given config and return valid ccxt instance.
[ "Initialize", "ccxt", "with", "given", "config", "and", "return", "valid", "ccxt", "instance", "." ]
def _init_ccxt(self, exchange_config: Dict[str, Any], ccxt_module: CcxtModuleType = ccxt, ccxt_kwargs: Dict = {}) -> ccxt.Exchange: """ Initialize ccxt with given config and return valid ccxt instance. """ # Find matching class for the given exchange name name = exchange_config['name'] if not is_exchange_known_ccxt(name, ccxt_module): raise OperationalException(f'Exchange {name} is not supported by ccxt') ex_config = { 'apiKey': exchange_config.get('key'), 'secret': exchange_config.get('secret'), 'password': exchange_config.get('password'), 'uid': exchange_config.get('uid', ''), } if ccxt_kwargs: logger.info('Applying additional ccxt config: %s', ccxt_kwargs) if self._headers: # Inject static headers after the above output to not confuse users. ccxt_kwargs = deep_merge_dicts({'headers': self._headers}, ccxt_kwargs) if ccxt_kwargs: ex_config.update(ccxt_kwargs) try: api = getattr(ccxt_module, name.lower())(ex_config) except (KeyError, AttributeError) as e: raise OperationalException(f'Exchange {name} is not supported') from e except ccxt.BaseError as e: raise OperationalException(f"Initialization of ccxt failed. Reason: {e}") from e self.set_sandbox(api, exchange_config, name) return api
[ "def", "_init_ccxt", "(", "self", ",", "exchange_config", ":", "Dict", "[", "str", ",", "Any", "]", ",", "ccxt_module", ":", "CcxtModuleType", "=", "ccxt", ",", "ccxt_kwargs", ":", "Dict", "=", "{", "}", ")", "->", "ccxt", ".", "Exchange", ":", "# Find...
https://github.com/freqtrade/freqtrade/blob/13651fd3be8d5ce8dcd7c94b920bda4e00b75aca/freqtrade/exchange/exchange.py#L182-L217
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/smtplib.py
python
SMTP.rcpt
(self, recip, options=[])
return self.getreply()
SMTP 'rcpt' command -- indicates 1 recipient for this mail.
SMTP 'rcpt' command -- indicates 1 recipient for this mail.
[ "SMTP", "rcpt", "command", "--", "indicates", "1", "recipient", "for", "this", "mail", "." ]
def rcpt(self, recip, options=[]): """SMTP 'rcpt' command -- indicates 1 recipient for this mail.""" optionlist = '' if options and self.does_esmtp: optionlist = ' ' + ' '.join(options) self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist)) return self.getreply()
[ "def", "rcpt", "(", "self", ",", "recip", ",", "options", "=", "[", "]", ")", ":", "optionlist", "=", "''", "if", "options", "and", "self", ".", "does_esmtp", ":", "optionlist", "=", "' '", "+", "' '", ".", "join", "(", "options", ")", "self", ".",...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/smtplib.py#L465-L471
AlessandroZ/LaZagne
30623c9138e2387d10f6631007f954f2a4ead06d
Windows/lazagne/config/DPAPI/masterkey.py
python
MasterKeyPool.get_password
(self, guid)
return self.keys.get(guid, {}).get('password')
Returns the password found corresponding to the given GUID.
Returns the password found corresponding to the given GUID.
[ "Returns", "the", "password", "found", "corresponding", "to", "the", "given", "GUID", "." ]
def get_password(self, guid): """ Returns the password found corresponding to the given GUID. """ return self.keys.get(guid, {}).get('password')
[ "def", "get_password", "(", "self", ",", "guid", ")", ":", "return", "self", ".", "keys", ".", "get", "(", "guid", ",", "{", "}", ")", ".", "get", "(", "'password'", ")" ]
https://github.com/AlessandroZ/LaZagne/blob/30623c9138e2387d10f6631007f954f2a4ead06d/Windows/lazagne/config/DPAPI/masterkey.py#L278-L282
jgagneastro/coffeegrindsize
22661ebd21831dba4cf32bfc6ba59fe3d49f879c
App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/ndimage/_ni_support.py
python
_normalize_sequence
(input, rank)
return normalized
If input is a scalar, create a sequence of length equal to the rank by duplicating the input. If input is a sequence, check if its length is equal to the length of array.
If input is a scalar, create a sequence of length equal to the rank by duplicating the input. If input is a sequence, check if its length is equal to the length of array.
[ "If", "input", "is", "a", "scalar", "create", "a", "sequence", "of", "length", "equal", "to", "the", "rank", "by", "duplicating", "the", "input", ".", "If", "input", "is", "a", "sequence", "check", "if", "its", "length", "is", "equal", "to", "the", "le...
def _normalize_sequence(input, rank): """If input is a scalar, create a sequence of length equal to the rank by duplicating the input. If input is a sequence, check if its length is equal to the length of array. """ is_str = isinstance(input, string_types) if hasattr(input, '__iter__') and not is_str: normalized = list(input) if len(normalized) != rank: err = "sequence argument must have length equal to input rank" raise RuntimeError(err) else: normalized = [input] * rank return normalized
[ "def", "_normalize_sequence", "(", "input", ",", "rank", ")", ":", "is_str", "=", "isinstance", "(", "input", ",", "string_types", ")", "if", "hasattr", "(", "input", ",", "'__iter__'", ")", "and", "not", "is_str", ":", "normalized", "=", "list", "(", "i...
https://github.com/jgagneastro/coffeegrindsize/blob/22661ebd21831dba4cf32bfc6ba59fe3d49f879c/App/dist/coffeegrindsize.app/Contents/Resources/lib/python3.7/scipy/ndimage/_ni_support.py#L55-L68
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/orm/nodes/data/array/projection.py
python
ProjectionData.set_orbitals
(self, **kwargs)
This method is inherited from OrbitalData, but is blocked here. If used will raise a NotImplementedError
This method is inherited from OrbitalData, but is blocked here. If used will raise a NotImplementedError
[ "This", "method", "is", "inherited", "from", "OrbitalData", "but", "is", "blocked", "here", ".", "If", "used", "will", "raise", "a", "NotImplementedError" ]
def set_orbitals(self, **kwargs): # pylint: disable=arguments-differ """ This method is inherited from OrbitalData, but is blocked here. If used will raise a NotImplementedError """ raise NotImplementedError( 'You cannot set orbitals using this class!' ' This class is for setting orbitals and ' ' projections only!' )
[ "def", "set_orbitals", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=arguments-differ", "raise", "NotImplementedError", "(", "'You cannot set orbitals using this class!'", "' This class is for setting orbitals and '", "' projections only!'", ")" ]
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/orm/nodes/data/array/projection.py#L293-L302
jbjorne/TEES
caf19a4a1352ac59f5dc13a8684cc42ce4342d9d
configure.py
python
buildMenus
()
return "Configure TEES"
[]
def buildMenus(): Menu("Classifier", None, [ Option("1", "Compile from source", toggle=False), Option("i", "Install", handler=Classifiers.SVMMultiClassClassifier.install), Option("s", "Skip")], svmMenuInitializer) Menu("Install Directory", None, [ Option("1", "Change DATAPATH", dataInput="defaultInstallDir"), Option("2", "Change TEES_SETTINGS", dataInput="configFilePath"), Option("c", "Continue", "Classifier", isDefault=True, handler=initLocalSettings)], pathMenuInitializer) Menu("Configure TEES", """ Welcome to using the Turku Event Extraction System (TEES)! In order to work, TEES depends on a number of other programs, which have to be set up before use. The classifier (1) is required for all uses of the system. The models (2) are required for predicting events and together with the preprocessing tools (4) can be used on any unprocessed text. The corpora (3) are used for testing the performance of a model or for training a new model. If you are unsure which components you need, just install everything (the default choice). You can also rerun configure.py at any time later to install missing components. To make a choice, type the option's key and press enter, or just press enter for the default option. The '*' sign indicates the default option and brackets a selectable one. """, [ Option("1", "Install classifier (SVM Multiclass)", toggle=True), Option("2", "Install models (TEES models for BioNLP'09-13 and DDI'11-13)", toggle=True), Option("3", "Install corpora (BioNLP'09-13 and DDI'11-13)", toggle=True), Option("4", "Install preprocessing tools (BANNER, BLLIP parser etc)", toggle=True), Option("c", "Continue and install selected items", "Install Directory", isDefault=True), Option("q", "Quit", handler=sys.exit), ]) Menu("Models", "Install TEES models\n", [ Option("1", "Redownload already downloaded files", toggle=False), Option.SPACE, Option("i", "Install", isDefault=True), Option("s", "Skip")], modelsMenuInitializer) Menu("Corpora", "Install corpora\n", [ Option("1", "Redownload already downloaded files", toggle=False), Option.SPACE, Option("2", "Install BioNLP'09 (GENIA) corpus", toggle=False), Option("3", "Install BioNLP'11 corpora", toggle=False), Option("4", "Install BioNLP'13 corpora", toggle=False), Option.SPACE, Option("5", "Install DDI'11 (Drug-Drug Interactions) corpus", toggle=False), Option("6", "Install DDI'13 (Drug-Drug Interactions) corpus", toggle=False), Option.SPACE, Option("7", "Install BioNLP evaluators", toggle=False), Option.SPACE, Option("i", "Install", isDefault=True), Option("s", "Skip")], corpusMenuInitializer) Menu("Tools", """ The tools are required for processing unannotated text and can be used as part of TEES, or independently through their wrappers. For information and usage conditions, see https://github.com/jbjorne/TEES/wiki/Licenses. Some of the tools need to be compiled from source, this will take a while. The external tools used by TEES are: The GENIA Sentence Splitter of Tokyo University (Tsuruoka Y. et. al.) The BANNER named entity recognizer by Robert Leaman et. al. The BLLIP parser of Brown University (Charniak E., Johnson M. et. al.) The Stanford Parser of the Stanford Natural Language Processing Group """, [ Option("1", "Redownload already downloaded files", toggle=False), Option.SPACE, Option("2", "Install GENIA Sentence Splitter", toggle=False), Option("3", "Install BANNER named entity recognizer", toggle=False), Option("4", "Install BLLIP parser", toggle=False), Option("5", "Install Stanford Parser", toggle=False), Option.SPACE, Option("i", "Install", isDefault=True), Option("s", "Skip")], toolsMenuInitializer) return "Configure TEES"
[ "def", "buildMenus", "(", ")", ":", "Menu", "(", "\"Classifier\"", ",", "None", ",", "[", "Option", "(", "\"1\"", ",", "\"Compile from source\"", ",", "toggle", "=", "False", ")", ",", "Option", "(", "\"i\"", ",", "\"Install\"", ",", "handler", "=", "Cla...
https://github.com/jbjorne/TEES/blob/caf19a4a1352ac59f5dc13a8684cc42ce4342d9d/configure.py#L313-L403
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/ttk.py
python
Treeview.see
(self, item)
Ensure that item is visible. Sets all of item's ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.
Ensure that item is visible.
[ "Ensure", "that", "item", "is", "visible", "." ]
def see(self, item): """Ensure that item is visible. Sets all of item's ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.""" self.tk.call(self._w, "see", item)
[ "def", "see", "(", "self", ",", "item", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"see\"", ",", "item", ")" ]
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/CPython/27/Lib/lib-tk/ttk.py#L1408-L1414
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django_wsgiserver/wsgiserver/wsgiserver2.py
python
WSGIGateway_10.get_environ
(self)
return env
Return a new environ dict targeting the given wsgi.version
Return a new environ dict targeting the given wsgi.version
[ "Return", "a", "new", "environ", "dict", "targeting", "the", "given", "wsgi", ".", "version" ]
def get_environ(self): """Return a new environ dict targeting the given wsgi.version""" req = self.req env = { # set a non-standard environ entry so the WSGI app can know what # the *real* server protocol is (and what features to support). # See http://www.faqs.org/rfcs/rfc2145.html. 'ACTUAL_SERVER_PROTOCOL': req.server.protocol, 'PATH_INFO': req.path, 'QUERY_STRING': req.qs, 'REMOTE_ADDR': req.conn.remote_addr or '', 'REMOTE_PORT': str(req.conn.remote_port or ''), 'REQUEST_METHOD': req.method, 'REQUEST_URI': req.uri, 'SCRIPT_NAME': '', 'SERVER_NAME': req.server.server_name, # Bah. "SERVER_PROTOCOL" is actually the REQUEST protocol. 'SERVER_PROTOCOL': req.request_protocol, 'SERVER_SOFTWARE': req.server.software, 'wsgi.errors': sys.stderr, 'wsgi.input': req.rfile, 'wsgi.multiprocess': False, 'wsgi.multithread': True, 'wsgi.run_once': False, 'wsgi.url_scheme': req.scheme, 'wsgi.version': (1, 0), } if isinstance(req.server.bind_addr, basestring): # AF_UNIX. This isn't really allowed by WSGI, which doesn't # address unix domain sockets. But it's better than nothing. env["SERVER_PORT"] = "" else: env["SERVER_PORT"] = str(req.server.bind_addr[1]) # Request headers for k, v in req.inheaders.iteritems(): env["HTTP_" + k.upper().replace("-", "_")] = v # CONTENT_TYPE/CONTENT_LENGTH ct = env.pop("HTTP_CONTENT_TYPE", None) if ct is not None: env["CONTENT_TYPE"] = ct cl = env.pop("HTTP_CONTENT_LENGTH", None) if cl is not None: env["CONTENT_LENGTH"] = cl if req.conn.ssl_env: env.update(req.conn.ssl_env) return env
[ "def", "get_environ", "(", "self", ")", ":", "req", "=", "self", ".", "req", "env", "=", "{", "# set a non-standard environ entry so the WSGI app can know what", "# the *real* server protocol is (and what features to support).", "# See http://www.faqs.org/rfcs/rfc2145.html.", "'ACT...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django_wsgiserver/wsgiserver/wsgiserver2.py#L2233-L2283
XX-net/XX-Net
a9898cfcf0084195fb7e69b6bc834e59aecdf14f
python3.8.2/Lib/ssl.py
python
SSLObject.session
(self)
return self._sslobj.session
The SSLSession for client socket.
The SSLSession for client socket.
[ "The", "SSLSession", "for", "client", "socket", "." ]
def session(self): """The SSLSession for client socket.""" return self._sslobj.session
[ "def", "session", "(", "self", ")", ":", "return", "self", ".", "_sslobj", ".", "session" ]
https://github.com/XX-net/XX-Net/blob/a9898cfcf0084195fb7e69b6bc834e59aecdf14f/python3.8.2/Lib/ssl.py#L855-L857
pypa/pip
7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4
src/pip/_vendor/distlib/_backport/tarfile.py
python
_Stream.write
(self, s)
Write string s to the stream.
Write string s to the stream.
[ "Write", "string", "s", "to", "the", "stream", "." ]
def write(self, s): """Write string s to the stream. """ if self.comptype == "gz": self.crc = self.zlib.crc32(s, self.crc) self.pos += len(s) if self.comptype != "tar": s = self.cmp.compress(s) self.__write(s)
[ "def", "write", "(", "self", ",", "s", ")", ":", "if", "self", ".", "comptype", "==", "\"gz\"", ":", "self", ".", "crc", "=", "self", ".", "zlib", ".", "crc32", "(", "s", ",", "self", ".", "crc", ")", "self", ".", "pos", "+=", "len", "(", "s"...
https://github.com/pypa/pip/blob/7f8a6844037fb7255cfd0d34ff8e8cf44f2598d4/src/pip/_vendor/distlib/_backport/tarfile.py#L469-L477
inspurer/WorkAttendanceSystem
1221e2d67bdf5bb15fe99517cc3ded58ccb066df
V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/html5lib/_inputstream.py
python
EncodingBytes.skip
(self, chars=spaceCharactersBytes)
return None
Skip past a list of characters
Skip past a list of characters
[ "Skip", "past", "a", "list", "of", "characters" ]
def skip(self, chars=spaceCharactersBytes): """Skip past a list of characters""" p = self.position # use property for the error-checking while p < len(self): c = self[p:p + 1] if c not in chars: self._position = p return c p += 1 self._position = p return None
[ "def", "skip", "(", "self", ",", "chars", "=", "spaceCharactersBytes", ")", ":", "p", "=", "self", ".", "position", "# use property for the error-checking", "while", "p", "<", "len", "(", "self", ")", ":", "c", "=", "self", "[", "p", ":", "p", "+", "1"...
https://github.com/inspurer/WorkAttendanceSystem/blob/1221e2d67bdf5bb15fe99517cc3ded58ccb066df/V2.0/venv/Lib/site-packages/pip-9.0.1-py3.5.egg/pip/_vendor/html5lib/_inputstream.py#L640-L650
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/widgets/standard.py
python
WidgetMixin.__init__
(self)
[]
def __init__(self): self._unmaximized_rect = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "_unmaximized_rect", "=", "{", "}" ]
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/widgets/standard.py#L28-L29
google/clusterfuzz
f358af24f414daa17a3649b143e71ea71871ef59
src/clusterfuzz/_internal/config/db_config.py
python
get_value_for_job
(data, target_job_type)
return result
Parses a value for a particular job type. If job type is not found, return the default value.
Parses a value for a particular job type. If job type is not found, return the default value.
[ "Parses", "a", "value", "for", "a", "particular", "job", "type", ".", "If", "job", "type", "is", "not", "found", "return", "the", "default", "value", "." ]
def get_value_for_job(data, target_job_type): """Parses a value for a particular job type. If job type is not found, return the default value.""" # All data is in a single line, just return that. if ';' not in data: return data result = '' for line in data.splitlines(): job_type, value = (line.strip()).split(';') if job_type == target_job_type or (job_type == 'default' and not result): result = value return result
[ "def", "get_value_for_job", "(", "data", ",", "target_job_type", ")", ":", "# All data is in a single line, just return that.", "if", "';'", "not", "in", "data", ":", "return", "data", "result", "=", "''", "for", "line", "in", "data", ".", "splitlines", "(", ")"...
https://github.com/google/clusterfuzz/blob/f358af24f414daa17a3649b143e71ea71871ef59/src/clusterfuzz/_internal/config/db_config.py#L49-L62
CvvT/dumpDex
92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1
python/idaapi.py
python
unregister_custom_data_format
(*args)
return _idaapi.unregister_custom_data_format(*args)
unregister_custom_data_format(dtid, dfid) -> bool Unregisters a custom data format @param dtid: data type id @param dfid: data format id @return: Boolean
unregister_custom_data_format(dtid, dfid) -> bool
[ "unregister_custom_data_format", "(", "dtid", "dfid", ")", "-", ">", "bool" ]
def unregister_custom_data_format(*args): """ unregister_custom_data_format(dtid, dfid) -> bool Unregisters a custom data format @param dtid: data type id @param dfid: data format id @return: Boolean """ return _idaapi.unregister_custom_data_format(*args)
[ "def", "unregister_custom_data_format", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "unregister_custom_data_format", "(", "*", "args", ")" ]
https://github.com/CvvT/dumpDex/blob/92ab3b7e996194a06bf1dd5538a4954e8a5ee9c1/python/idaapi.py#L23430-L23440
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/cli_opts.py
python
_SplitKeyVal
(opt, data, parse_prefixes)
return kv_dict
Convert a KeyVal string into a dict. This function will convert a key=val[,...] string into a dict. Empty values will be converted specially: keys which have the prefix 'no_' will have the value=False and the prefix stripped, keys with the prefix "-" will have value=None and the prefix stripped, and the others will have value=True. @type opt: string @param opt: a string holding the option name for which we process the data, used in building error messages @type data: string @param data: a string of the format key=val,key=val,... @type parse_prefixes: bool @param parse_prefixes: whether to handle prefixes specially @rtype: dict @return: {key=val, key=val} @raises errors.ParameterError: if there are duplicate keys
Convert a KeyVal string into a dict.
[ "Convert", "a", "KeyVal", "string", "into", "a", "dict", "." ]
def _SplitKeyVal(opt, data, parse_prefixes): """Convert a KeyVal string into a dict. This function will convert a key=val[,...] string into a dict. Empty values will be converted specially: keys which have the prefix 'no_' will have the value=False and the prefix stripped, keys with the prefix "-" will have value=None and the prefix stripped, and the others will have value=True. @type opt: string @param opt: a string holding the option name for which we process the data, used in building error messages @type data: string @param data: a string of the format key=val,key=val,... @type parse_prefixes: bool @param parse_prefixes: whether to handle prefixes specially @rtype: dict @return: {key=val, key=val} @raises errors.ParameterError: if there are duplicate keys """ kv_dict = {} if data: for elem in utils.UnescapeAndSplit(data, sep=","): if "=" in elem: key, val = elem.split("=", 1) elif parse_prefixes: if elem.startswith(NO_PREFIX): key, val = elem[len(NO_PREFIX):], False elif elem.startswith(UN_PREFIX): key, val = elem[len(UN_PREFIX):], None else: key, val = elem, True else: raise errors.ParameterError("Missing value for key '%s' in option %s" % (elem, opt)) if key in kv_dict: raise errors.ParameterError("Duplicate key '%s' in option %s" % (key, opt)) kv_dict[key] = val return kv_dict
[ "def", "_SplitKeyVal", "(", "opt", ",", "data", ",", "parse_prefixes", ")", ":", "kv_dict", "=", "{", "}", "if", "data", ":", "for", "elem", "in", "utils", ".", "UnescapeAndSplit", "(", "data", ",", "sep", "=", "\",\"", ")", ":", "if", "\"=\"", "in",...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/cli_opts.py#L297-L337
keiffster/program-y
8c99b56f8c32f01a7b9887b5daae9465619d0385
src/programy/storage/stores/sql/store/lookups.py
python
SQLLookupsStore.process_line
(self, name, fields, verbose=False)
return False
[]
def process_line(self, name, fields, verbose=False): if fields and len(fields) == 2: result = self.add_to_lookup(fields[0].upper(), fields[1].upper()) if verbose is True: outputLog(self, "Key=[%s], Value={%s]" % (fields[0].upper(), fields[1].upper())) return result return False
[ "def", "process_line", "(", "self", ",", "name", ",", "fields", ",", "verbose", "=", "False", ")", ":", "if", "fields", "and", "len", "(", "fields", ")", "==", "2", ":", "result", "=", "self", ".", "add_to_lookup", "(", "fields", "[", "0", "]", "."...
https://github.com/keiffster/program-y/blob/8c99b56f8c32f01a7b9887b5daae9465619d0385/src/programy/storage/stores/sql/store/lookups.py#L88-L94
merkremont/LineVodka
c2fa74107cecf00dd17416b62e4eb579e2c7bbaf
LineAlpha/LineThrift/TalkService.py
python
Client.sendChatChecked
(self, seq, consumer, lastMessageId)
Parameters: - seq - consumer - lastMessageId
Parameters: - seq - consumer - lastMessageId
[ "Parameters", ":", "-", "seq", "-", "consumer", "-", "lastMessageId" ]
def sendChatChecked(self, seq, consumer, lastMessageId): """ Parameters: - seq - consumer - lastMessageId """ self.send_sendChatChecked(seq, consumer, lastMessageId) self.recv_sendChatChecked()
[ "def", "sendChatChecked", "(", "self", ",", "seq", ",", "consumer", ",", "lastMessageId", ")", ":", "self", ".", "send_sendChatChecked", "(", "seq", ",", "consumer", ",", "lastMessageId", ")", "self", ".", "recv_sendChatChecked", "(", ")" ]
https://github.com/merkremont/LineVodka/blob/c2fa74107cecf00dd17416b62e4eb579e2c7bbaf/LineAlpha/LineThrift/TalkService.py#L6357-L6365
uqfoundation/dill
1094a28f685a330181e6894d0294509b1da08f3c
dill/source.py
python
_namespace
(obj)
return qual
_namespace(obj); return namespace hierarchy (as a list of names) for the given object. For an instance, find the class hierarchy. For example: >>> from functools import partial >>> p = partial(int, base=2) >>> _namespace(p) [\'functools\', \'partial\']
_namespace(obj); return namespace hierarchy (as a list of names) for the given object. For an instance, find the class hierarchy.
[ "_namespace", "(", "obj", ")", ";", "return", "namespace", "hierarchy", "(", "as", "a", "list", "of", "names", ")", "for", "the", "given", "object", ".", "For", "an", "instance", "find", "the", "class", "hierarchy", "." ]
def _namespace(obj): """_namespace(obj); return namespace hierarchy (as a list of names) for the given object. For an instance, find the class hierarchy. For example: >>> from functools import partial >>> p = partial(int, base=2) >>> _namespace(p) [\'functools\', \'partial\'] """ # mostly for functions and modules and such #FIXME: 'wrong' for decorators and curried functions try: #XXX: needs some work and testing on different types module = qual = str(getmodule(obj)).split()[1].strip('"').strip("'") qual = qual.split('.') if ismodule(obj): return qual # get name of a lambda, function, etc name = getname(obj) or obj.__name__ # failing, raise AttributeError # check special cases (NoneType, ...) if module in ['builtins','__builtin__']: # BuiltinFunctionType if _intypes(name): return ['types'] + [name] return qual + [name] #XXX: can be wrong for some aliased objects except: pass # special case: numpy.inf and numpy.nan (we don't want them as floats) if str(obj) in ['inf','nan','Inf','NaN']: # is more, but are they needed? return ['numpy'] + [str(obj)] # mostly for classes and class instances and such module = getattr(obj.__class__, '__module__', None) qual = str(obj.__class__) try: qual = qual[qual.index("'")+1:-2] except ValueError: pass # str(obj.__class__) made the 'try' unnecessary qual = qual.split(".") if module in ['builtins','__builtin__']: # check special cases (NoneType, Ellipsis, ...) if qual[-1] == 'ellipsis': qual[-1] = 'EllipsisType' if _intypes(qual[-1]): module = 'types' #XXX: BuiltinFunctionType qual = [module] + qual return qual
[ "def", "_namespace", "(", "obj", ")", ":", "# mostly for functions and modules and such", "#FIXME: 'wrong' for decorators and curried functions", "try", ":", "#XXX: needs some work and testing on different types", "module", "=", "qual", "=", "str", "(", "getmodule", "(", "obj",...
https://github.com/uqfoundation/dill/blob/1094a28f685a330181e6894d0294509b1da08f3c/dill/source.py#L633-L672
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
ansible/roles/lib_openshift_3.2/library/oadm_router.py
python
Yedit.read
(self)
return contents
read from file
read from file
[ "read", "from", "file" ]
def read(self): ''' read from file ''' # check if it exists if self.filename == None or not self.file_exists(): return None contents = None with open(self.filename) as yfd: contents = yfd.read() return contents
[ "def", "read", "(", "self", ")", ":", "# check if it exists", "if", "self", ".", "filename", "==", "None", "or", "not", "self", ".", "file_exists", "(", ")", ":", "return", "None", "contents", "=", "None", "with", "open", "(", "self", ".", "filename", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/ansible/roles/lib_openshift_3.2/library/oadm_router.py#L671-L681
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/bds/bds_client.py
python
BdsClient.delete_bds_metastore_configuration
(self, bds_instance_id, metastore_config_id, **kwargs)
Delete the BDS metastore configuration represented by the provided ID. :param str bds_instance_id: (required) The OCID of the cluster. :param str metastore_config_id: (required) The metastore configuration ID :param str opc_request_id: (optional) The client request ID for tracing. :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/bds/delete_bds_metastore_configuration.py.html>`__ to see an example of how to use delete_bds_metastore_configuration API.
Delete the BDS metastore configuration represented by the provided ID.
[ "Delete", "the", "BDS", "metastore", "configuration", "represented", "by", "the", "provided", "ID", "." ]
def delete_bds_metastore_configuration(self, bds_instance_id, metastore_config_id, **kwargs): """ Delete the BDS metastore configuration represented by the provided ID. :param str bds_instance_id: (required) The OCID of the cluster. :param str metastore_config_id: (required) The metastore configuration ID :param str opc_request_id: (optional) The client request ID for tracing. :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/bds/delete_bds_metastore_configuration.py.html>`__ to see an example of how to use delete_bds_metastore_configuration API. """ resource_path = "/bdsInstances/{bdsInstanceId}/metastoreConfigs/{metastoreConfigId}" method = "DELETE" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "opc_request_id", "if_match" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "delete_bds_metastore_configuration got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "bdsInstanceId": bds_instance_id, "metastoreConfigId": metastore_config_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "opc-request-id": kwargs.get("opc_request_id", missing), "if-match": kwargs.get("if_match", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params) else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params)
[ "def", "delete_bds_metastore_configuration", "(", "self", ",", "bds_instance_id", ",", "metastore_config_id", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/bdsInstances/{bdsInstanceId}/metastoreConfigs/{metastoreConfigId}\"", "method", "=", "\"DELETE\"", "# Don...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/bds/bds_client.py#L1249-L1337
theotherp/nzbhydra
4b03d7f769384b97dfc60dade4806c0fc987514e
libs/cookielib.py
python
request_host
(request)
return host.lower()
Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison.
Return request-host, as defined by RFC 2965.
[ "Return", "request", "-", "host", "as", "defined", "by", "RFC", "2965", "." ]
def request_host(request): """Return request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. """ url = request.get_full_url() host = urlparse.urlparse(url)[1] if host == "": host = request.get_header("Host", "") # remove port, if present host = cut_port_re.sub("", host, 1) return host.lower()
[ "def", "request_host", "(", "request", ")", ":", "url", "=", "request", ".", "get_full_url", "(", ")", "host", "=", "urlparse", ".", "urlparse", "(", "url", ")", "[", "1", "]", "if", "host", "==", "\"\"", ":", "host", "=", "request", ".", "get_header...
https://github.com/theotherp/nzbhydra/blob/4b03d7f769384b97dfc60dade4806c0fc987514e/libs/cookielib.py#L598-L612
dmitry-k/yandex_smart_home
9d068203d80891bc946618a4cc0a435ee9184d74
custom_components/yandex_smart_home/capability_mode.py
python
ModeCapability.supported
(self)
return bool(self.supported_yandex_modes)
Test if capability is supported.
Test if capability is supported.
[ "Test", "if", "capability", "is", "supported", "." ]
def supported(self) -> bool: """Test if capability is supported.""" return bool(self.supported_yandex_modes)
[ "def", "supported", "(", "self", ")", "->", "bool", ":", "return", "bool", "(", "self", ".", "supported_yandex_modes", ")" ]
https://github.com/dmitry-k/yandex_smart_home/blob/9d068203d80891bc946618a4cc0a435ee9184d74/custom_components/yandex_smart_home/capability_mode.py#L35-L37
graalvm/mx
29c0debab406352df3af246be2f8973be5db69ae
mx.py
python
_tmpPomFile
(dist, versionGetter, validateMetadata='none')
return tmp.name
[]
def _tmpPomFile(dist, versionGetter, validateMetadata='none'): tmp = tempfile.NamedTemporaryFile('w', suffix='.pom', delete=False) tmp.write(_genPom(dist, versionGetter, validateMetadata)) tmp.close() return tmp.name
[ "def", "_tmpPomFile", "(", "dist", ",", "versionGetter", ",", "validateMetadata", "=", "'none'", ")", ":", "tmp", "=", "tempfile", ".", "NamedTemporaryFile", "(", "'w'", ",", "suffix", "=", "'.pom'", ",", "delete", "=", "False", ")", "tmp", ".", "write", ...
https://github.com/graalvm/mx/blob/29c0debab406352df3af246be2f8973be5db69ae/mx.py#L11138-L11142
PaddlePaddle/PaddleSpeech
26524031d242876b7fdb71582b0b3a7ea45c7d9d
dataset/thchs30/thchs30.py
python
prepare_dataset
(url, md5sum, target_dir, manifest_path, subset)
Download, unpack and create manifest file.
Download, unpack and create manifest file.
[ "Download", "unpack", "and", "create", "manifest", "file", "." ]
def prepare_dataset(url, md5sum, target_dir, manifest_path, subset): """Download, unpack and create manifest file.""" datadir = os.path.join(target_dir, subset) if not os.path.exists(datadir): filepath = download(url, md5sum, target_dir) unpack(filepath, target_dir) else: print("Skip downloading and unpacking. Data already exists in %s." % target_dir) if subset == 'data_thchs30': create_manifest(datadir, manifest_path)
[ "def", "prepare_dataset", "(", "url", ",", "md5sum", ",", "target_dir", ",", "manifest_path", ",", "subset", ")", ":", "datadir", "=", "os", ".", "path", ".", "join", "(", "target_dir", ",", "subset", ")", "if", "not", "os", ".", "path", ".", "exists",...
https://github.com/PaddlePaddle/PaddleSpeech/blob/26524031d242876b7fdb71582b0b3a7ea45c7d9d/dataset/thchs30/thchs30.py#L156-L167
determined-ai/determined
f637264493acc14f12e66550cb51c520b5d27f6c
harness/determined/tensorboard/util.py
python
find_tb_files
(base_dir: pathlib.Path)
return [file for filetype in tb_file_types for file in base_dir.rglob(filetype)]
Recursively searches through base_dir and subdirectories to find files needed by Tensorboard, currently matching by filenames and extensions. This method is used to sync files generated during training to persistent storage. :param base_dir: starting directory path :return: list of filepaths within base_dir that are relevant Tensorboard files
Recursively searches through base_dir and subdirectories to find files needed by Tensorboard, currently matching by filenames and extensions. This method is used to sync files generated during training to persistent storage.
[ "Recursively", "searches", "through", "base_dir", "and", "subdirectories", "to", "find", "files", "needed", "by", "Tensorboard", "currently", "matching", "by", "filenames", "and", "extensions", ".", "This", "method", "is", "used", "to", "sync", "files", "generated...
def find_tb_files(base_dir: pathlib.Path) -> List[pathlib.Path]: """ Recursively searches through base_dir and subdirectories to find files needed by Tensorboard, currently matching by filenames and extensions. This method is used to sync files generated during training to persistent storage. :param base_dir: starting directory path :return: list of filepaths within base_dir that are relevant Tensorboard files """ if not base_dir.exists(): logging.warning(f"{base_dir} directory does not exist.") return [] return [file for filetype in tb_file_types for file in base_dir.rglob(filetype)]
[ "def", "find_tb_files", "(", "base_dir", ":", "pathlib", ".", "Path", ")", "->", "List", "[", "pathlib", ".", "Path", "]", ":", "if", "not", "base_dir", ".", "exists", "(", ")", ":", "logging", ".", "warning", "(", "f\"{base_dir} directory does not exist.\""...
https://github.com/determined-ai/determined/blob/f637264493acc14f12e66550cb51c520b5d27f6c/harness/determined/tensorboard/util.py#L14-L28
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/chat/v2/service/user/user_binding.py
python
UserBindingInstance.fetch
(self)
return self._proxy.fetch()
Fetch the UserBindingInstance :returns: The fetched UserBindingInstance :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance
Fetch the UserBindingInstance
[ "Fetch", "the", "UserBindingInstance" ]
def fetch(self): """ Fetch the UserBindingInstance :returns: The fetched UserBindingInstance :rtype: twilio.rest.chat.v2.service.user.user_binding.UserBindingInstance """ return self._proxy.fetch()
[ "def", "fetch", "(", "self", ")", ":", "return", "self", ".", "_proxy", ".", "fetch", "(", ")" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v2/service/user/user_binding.py#L420-L427