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
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/utils/textimport.py
python
CSVImportWidget.__update_column_type_edit
(self)
[]
def __update_column_type_edit(self): # Update the 'Column type' edit control based on current column # selection smodel = self.dataview.selectionModel() model = self.dataview.model() cb = self.column_type_edit_cb columns = smodel.selectedColumns(0) types = {model.headerData(c.column(), Qt.Horizontal, TablePreviewModel.ColumnTypeRole) for c in columns} types = {ColumnType.Auto if t is None else t for t in types} if len(types) == 0: # no selection, disabled cb.setCurrentIndex(-1) cb.setEnabled(False) elif len(types) == 1: idx = cb.findData(types.pop(), Qt.UserRole) cb.setCurrentIndex(idx) cb.setEnabled(True) else: cb.setCurrentIndex(-1) cb.setEnabled(True)
[ "def", "__update_column_type_edit", "(", "self", ")", ":", "# Update the 'Column type' edit control based on current column", "# selection", "smodel", "=", "self", ".", "dataview", ".", "selectionModel", "(", ")", "model", "=", "self", ".", "dataview", ".", "model", "...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/utils/textimport.py#L1019-L1041
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_13/paramiko/message.py
python
Message.get_list
(self)
return self.get_string().split(',')
Fetch a list of strings from the stream. These are trivially encoded as comma-separated values in a string. @return: a list of strings. @rtype: list of strings
Fetch a list of strings from the stream. These are trivially encoded as comma-separated values in a string.
[ "Fetch", "a", "list", "of", "strings", "from", "the", "stream", ".", "These", "are", "trivially", "encoded", "as", "comma", "-", "separated", "values", "in", "a", "string", "." ]
def get_list(self): """ Fetch a list of strings from the stream. These are trivially encoded as comma-separated values in a string. @return: a list of strings. @rtype: list of strings """ return self.get_string().split(',')
[ "def", "get_list", "(", "self", ")", ":", "return", "self", ".", "get_string", "(", ")", ".", "split", "(", "','", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_13/paramiko/message.py#L177-L185
junsukchoe/ADL
dab2e78163bd96970ec9ae41de62835332dbf4fe
tensorpack/callbacks/graph.py
python
DumpTensors.__init__
(self, names)
Args: names (list[str]): names of tensors
Args: names (list[str]): names of tensors
[ "Args", ":", "names", "(", "list", "[", "str", "]", ")", ":", "names", "of", "tensors" ]
def __init__(self, names): """ Args: names (list[str]): names of tensors """ assert isinstance(names, (list, tuple)), names self._names = names dir = logger.get_logger_dir() def fn(*args): dic = {} for name, val in zip(self._names, args): dic[name] = val fname = os.path.join( dir, 'DumpTensor-{}.npz'.format(self.global_step)) np.savez(fname, **dic) super(DumpTensors, self).__init__(names, fn)
[ "def", "__init__", "(", "self", ",", "names", ")", ":", "assert", "isinstance", "(", "names", ",", "(", "list", ",", "tuple", ")", ")", ",", "names", "self", ".", "_names", "=", "names", "dir", "=", "logger", ".", "get_logger_dir", "(", ")", "def", ...
https://github.com/junsukchoe/ADL/blob/dab2e78163bd96970ec9ae41de62835332dbf4fe/tensorpack/callbacks/graph.py#L151-L167
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/idna/uts46data.py
python
_seg_44
()
return [ (0xFC3F, 'M', u'ู„ุฌ'), (0xFC40, 'M', u'ู„ุญ'), (0xFC41, 'M', u'ู„ุฎ'), (0xFC42, 'M', u'ู„ู…'), (0xFC43, 'M', u'ู„ู‰'), (0xFC44, 'M', u'ู„ูŠ'), (0xFC45, 'M', u'ู…ุฌ'), (0xFC46, 'M', u'ู…ุญ'), (0xFC47, 'M', u'ู…ุฎ'), (0xFC48, 'M', u'ู…ู…'), (0xFC49, 'M', u'ู…ู‰'), (0xFC4A, 'M', u'ู…ูŠ'), (0xFC4B, 'M', u'ู†ุฌ'), (0xFC4C, 'M', u'ู†ุญ'), (0xFC4D, 'M', u'ู†ุฎ'), (0xFC4E, 'M', u'ู†ู…'), (0xFC4F, 'M', u'ู†ู‰'), (0xFC50, 'M', u'ู†ูŠ'), (0xFC51, 'M', u'ู‡ุฌ'), (0xFC52, 'M', u'ู‡ู…'), (0xFC53, 'M', u'ู‡ู‰'), (0xFC54, 'M', u'ู‡ูŠ'), (0xFC55, 'M', u'ูŠุฌ'), (0xFC56, 'M', u'ูŠุญ'), (0xFC57, 'M', u'ูŠุฎ'), (0xFC58, 'M', u'ูŠู…'), (0xFC59, 'M', u'ูŠู‰'), (0xFC5A, 'M', u'ูŠูŠ'), (0xFC5B, 'M', u'ุฐูฐ'), (0xFC5C, 'M', u'ุฑูฐ'), (0xFC5D, 'M', u'ู‰ูฐ'), (0xFC5E, '3', u' ูŒู‘'), (0xFC5F, '3', u' ูู‘'), (0xFC60, '3', u' ูŽู‘'), (0xFC61, '3', u' ูู‘'), (0xFC62, '3', u' ูู‘'), (0xFC63, '3', u' ู‘ูฐ'), (0xFC64, 'M', u'ุฆุฑ'), (0xFC65, 'M', u'ุฆุฒ'), (0xFC66, 'M', u'ุฆู…'), (0xFC67, 'M', u'ุฆู†'), (0xFC68, 'M', u'ุฆู‰'), (0xFC69, 'M', u'ุฆูŠ'), (0xFC6A, 'M', u'ุจุฑ'), (0xFC6B, 'M', u'ุจุฒ'), (0xFC6C, 'M', u'ุจู…'), (0xFC6D, 'M', u'ุจู†'), (0xFC6E, 'M', u'ุจู‰'), (0xFC6F, 'M', u'ุจูŠ'), (0xFC70, 'M', u'ุชุฑ'), (0xFC71, 'M', u'ุชุฒ'), (0xFC72, 'M', u'ุชู…'), (0xFC73, 'M', u'ุชู†'), (0xFC74, 'M', u'ุชู‰'), (0xFC75, 'M', u'ุชูŠ'), (0xFC76, 'M', u'ุซุฑ'), (0xFC77, 'M', u'ุซุฒ'), (0xFC78, 'M', u'ุซู…'), (0xFC79, 'M', u'ุซู†'), (0xFC7A, 'M', u'ุซู‰'), (0xFC7B, 'M', u'ุซูŠ'), (0xFC7C, 'M', u'ูู‰'), (0xFC7D, 'M', u'ููŠ'), (0xFC7E, 'M', u'ู‚ู‰'), (0xFC7F, 'M', u'ู‚ูŠ'), (0xFC80, 'M', u'ูƒุง'), (0xFC81, 'M', u'ูƒู„'), (0xFC82, 'M', u'ูƒู…'), (0xFC83, 'M', u'ูƒู‰'), (0xFC84, 'M', u'ูƒูŠ'), (0xFC85, 'M', u'ู„ู…'), (0xFC86, 'M', u'ู„ู‰'), (0xFC87, 'M', u'ู„ูŠ'), (0xFC88, 'M', u'ู…ุง'), (0xFC89, 'M', u'ู…ู…'), (0xFC8A, 'M', u'ู†ุฑ'), (0xFC8B, 'M', u'ู†ุฒ'), (0xFC8C, 'M', u'ู†ู…'), (0xFC8D, 'M', u'ู†ู†'), (0xFC8E, 'M', u'ู†ู‰'), (0xFC8F, 'M', u'ู†ูŠ'), (0xFC90, 'M', u'ู‰ูฐ'), (0xFC91, 'M', u'ูŠุฑ'), (0xFC92, 'M', u'ูŠุฒ'), (0xFC93, 'M', u'ูŠู…'), (0xFC94, 'M', u'ูŠู†'), (0xFC95, 'M', u'ูŠู‰'), (0xFC96, 'M', u'ูŠูŠ'), (0xFC97, 'M', u'ุฆุฌ'), (0xFC98, 'M', u'ุฆุญ'), (0xFC99, 'M', u'ุฆุฎ'), (0xFC9A, 'M', u'ุฆู…'), (0xFC9B, 'M', u'ุฆู‡'), (0xFC9C, 'M', u'ุจุฌ'), (0xFC9D, 'M', u'ุจุญ'), (0xFC9E, 'M', u'ุจุฎ'), (0xFC9F, 'M', u'ุจู…'), (0xFCA0, 'M', u'ุจู‡'), (0xFCA1, 'M', u'ุชุฌ'), (0xFCA2, 'M', u'ุชุญ'), ]
[]
def _seg_44(): return [ (0xFC3F, 'M', u'ู„ุฌ'), (0xFC40, 'M', u'ู„ุญ'), (0xFC41, 'M', u'ู„ุฎ'), (0xFC42, 'M', u'ู„ู…'), (0xFC43, 'M', u'ู„ู‰'), (0xFC44, 'M', u'ู„ูŠ'), (0xFC45, 'M', u'ู…ุฌ'), (0xFC46, 'M', u'ู…ุญ'), (0xFC47, 'M', u'ู…ุฎ'), (0xFC48, 'M', u'ู…ู…'), (0xFC49, 'M', u'ู…ู‰'), (0xFC4A, 'M', u'ู…ูŠ'), (0xFC4B, 'M', u'ู†ุฌ'), (0xFC4C, 'M', u'ู†ุญ'), (0xFC4D, 'M', u'ู†ุฎ'), (0xFC4E, 'M', u'ู†ู…'), (0xFC4F, 'M', u'ู†ู‰'), (0xFC50, 'M', u'ู†ูŠ'), (0xFC51, 'M', u'ู‡ุฌ'), (0xFC52, 'M', u'ู‡ู…'), (0xFC53, 'M', u'ู‡ู‰'), (0xFC54, 'M', u'ู‡ูŠ'), (0xFC55, 'M', u'ูŠุฌ'), (0xFC56, 'M', u'ูŠุญ'), (0xFC57, 'M', u'ูŠุฎ'), (0xFC58, 'M', u'ูŠู…'), (0xFC59, 'M', u'ูŠู‰'), (0xFC5A, 'M', u'ูŠูŠ'), (0xFC5B, 'M', u'ุฐูฐ'), (0xFC5C, 'M', u'ุฑูฐ'), (0xFC5D, 'M', u'ู‰ูฐ'), (0xFC5E, '3', u' ูŒู‘'), (0xFC5F, '3', u' ูู‘'), (0xFC60, '3', u' ูŽู‘'), (0xFC61, '3', u' ูู‘'), (0xFC62, '3', u' ูู‘'), (0xFC63, '3', u' ู‘ูฐ'), (0xFC64, 'M', u'ุฆุฑ'), (0xFC65, 'M', u'ุฆุฒ'), (0xFC66, 'M', u'ุฆู…'), (0xFC67, 'M', u'ุฆู†'), (0xFC68, 'M', u'ุฆู‰'), (0xFC69, 'M', u'ุฆูŠ'), (0xFC6A, 'M', u'ุจุฑ'), (0xFC6B, 'M', u'ุจุฒ'), (0xFC6C, 'M', u'ุจู…'), (0xFC6D, 'M', u'ุจู†'), (0xFC6E, 'M', u'ุจู‰'), (0xFC6F, 'M', u'ุจูŠ'), (0xFC70, 'M', u'ุชุฑ'), (0xFC71, 'M', u'ุชุฒ'), (0xFC72, 'M', u'ุชู…'), (0xFC73, 'M', u'ุชู†'), (0xFC74, 'M', u'ุชู‰'), (0xFC75, 'M', u'ุชูŠ'), (0xFC76, 'M', u'ุซุฑ'), (0xFC77, 'M', u'ุซุฒ'), (0xFC78, 'M', u'ุซู…'), (0xFC79, 'M', u'ุซู†'), (0xFC7A, 'M', u'ุซู‰'), (0xFC7B, 'M', u'ุซูŠ'), (0xFC7C, 'M', u'ูู‰'), (0xFC7D, 'M', u'ููŠ'), (0xFC7E, 'M', u'ู‚ู‰'), (0xFC7F, 'M', u'ู‚ูŠ'), (0xFC80, 'M', u'ูƒุง'), (0xFC81, 'M', u'ูƒู„'), (0xFC82, 'M', u'ูƒู…'), (0xFC83, 'M', u'ูƒู‰'), (0xFC84, 'M', u'ูƒูŠ'), (0xFC85, 'M', u'ู„ู…'), (0xFC86, 'M', u'ู„ู‰'), (0xFC87, 'M', u'ู„ูŠ'), (0xFC88, 'M', u'ู…ุง'), (0xFC89, 'M', u'ู…ู…'), (0xFC8A, 'M', u'ู†ุฑ'), (0xFC8B, 'M', u'ู†ุฒ'), (0xFC8C, 'M', u'ู†ู…'), (0xFC8D, 'M', u'ู†ู†'), (0xFC8E, 'M', u'ู†ู‰'), (0xFC8F, 'M', u'ู†ูŠ'), (0xFC90, 'M', u'ู‰ูฐ'), (0xFC91, 'M', u'ูŠุฑ'), (0xFC92, 'M', u'ูŠุฒ'), (0xFC93, 'M', u'ูŠู…'), (0xFC94, 'M', u'ูŠู†'), (0xFC95, 'M', u'ูŠู‰'), (0xFC96, 'M', u'ูŠูŠ'), (0xFC97, 'M', u'ุฆุฌ'), (0xFC98, 'M', u'ุฆุญ'), (0xFC99, 'M', u'ุฆุฎ'), (0xFC9A, 'M', u'ุฆู…'), (0xFC9B, 'M', u'ุฆู‡'), (0xFC9C, 'M', u'ุจุฌ'), (0xFC9D, 'M', u'ุจุญ'), (0xFC9E, 'M', u'ุจุฎ'), (0xFC9F, 'M', u'ุจู…'), (0xFCA0, 'M', u'ุจู‡'), (0xFCA1, 'M', u'ุชุฌ'), (0xFCA2, 'M', u'ุชุญ'), ]
[ "def", "_seg_44", "(", ")", ":", "return", "[", "(", "0xFC3F", ",", "'M'", ",", "u'ู„ุฌ'),", "", "", "(", "0xFC40", ",", "'M'", ",", "u'ู„ุญ'),", "", "", "(", "0xFC41", ",", "'M'", ",", "u'ู„ุฎ'),", "", "", "(", "0xFC42", ",", "'M'", ",", "u'ู„ู…'),", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/idna/uts46data.py#L4584-L4686
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py
python
dictOf
( key, value )
return Dict( ZeroOrMore( Group ( key + value ) ) )
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields.
[ "Helper", "to", "easily", "and", "clearly", "define", "a", "dictionary", "by", "specifying", "the", "respective", "patterns", "for", "the", "key", "and", "value", ".", "Takes", "care", "of", "defining", "the", "C", "{", "L", "{", "Dict", "}}", "C", "{", ...
def dictOf( key, value ): """ Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, thereby leaving the significant key text. The value pattern can include named results, so that the C{Dict} results can include named token fields. Example:: text = "shape: SQUARE posn: upper left color: light blue texture: burlap" attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)) print(OneOrMore(attr_expr).parseString(text).dump()) attr_label = label attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join) # similar to Dict, but simpler call format result = dictOf(attr_label, attr_value).parseString(text) print(result.dump()) print(result['shape']) print(result.shape) # object attribute access works too print(result.asDict()) prints:: [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']] - color: light blue - posn: upper left - shape: SQUARE - texture: burlap SQUARE SQUARE {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'} """ return Dict( ZeroOrMore( Group ( key + value ) ) )
[ "def", "dictOf", "(", "key", ",", "value", ")", ":", "return", "Dict", "(", "ZeroOrMore", "(", "Group", "(", "key", "+", "value", ")", ")", ")" ]
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pkg_resources/_vendor/pyparsing.py#L4605-L4638
scikit-hep/awkward-0.x
dd885bef15814f588b58944d2505296df4aaae0e
awkward0/array/union.py
python
UnionArray.boolmask
(self, maskedwhen=True)
return out
[]
def boolmask(self, maskedwhen=True): self._valid() arrays = [self._util_boolmask(x, maskedwhen) for x in self._contents] out = self.numpy.empty(len(self), self.MASKTYPE) for tag, array in enumerate(arrays): mask = (self._tags == tag) out[mask] = array[self._index[mask]] return out
[ "def", "boolmask", "(", "self", ",", "maskedwhen", "=", "True", ")", ":", "self", ".", "_valid", "(", ")", "arrays", "=", "[", "self", ".", "_util_boolmask", "(", "x", ",", "maskedwhen", ")", "for", "x", "in", "self", ".", "_contents", "]", "out", ...
https://github.com/scikit-hep/awkward-0.x/blob/dd885bef15814f588b58944d2505296df4aaae0e/awkward0/array/union.py#L432-L439
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/thirdparty/pydes/pyDes.py
python
des.encrypt
(self, data, pad=None, padmode=None)
return self.crypt(data, des.ENCRYPT)
encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes.
encrypt(data, [pad], [padmode]) -> bytes
[ "encrypt", "(", "data", "[", "pad", "]", "[", "padmode", "]", ")", "-", ">", "bytes" ]
def encrypt(self, data, pad=None, padmode=None): """encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be a multiple of 8 bytes if the padding character is supplied, or the padmode is set to PAD_PKCS5, as bytes will then added to ensure the be padded data is a multiple of 8 bytes. """ data = self._guardAgainstUnicode(data) if pad is not None: pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT)
[ "def", "encrypt", "(", "self", ",", "data", ",", "pad", "=", "None", ",", "padmode", "=", "None", ")", ":", "data", "=", "self", ".", "_guardAgainstUnicode", "(", "data", ")", "if", "pad", "is", "not", "None", ":", "pad", "=", "self", ".", "_guardA...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/thirdparty/pydes/pyDes.py#L642-L659
rcorcs/NatI
fdf014f4292afdc95250add7b6658468043228e1
en/parser/nltk_lite/draw/plot.py
python
PlotFrameI.postscript
(self, filename)
Print the contents of the plot to the given file
Print the contents of the plot to the given file
[ "Print", "the", "contents", "of", "the", "plot", "to", "the", "given", "file" ]
def postscript(self, filename): 'Print the contents of the plot to the given file' raise AssertionError, 'PlotFrameI is an interface'
[ "def", "postscript", "(", "self", ",", "filename", ")", ":", "raise", "AssertionError", ",", "'PlotFrameI is an interface'" ]
https://github.com/rcorcs/NatI/blob/fdf014f4292afdc95250add7b6658468043228e1/en/parser/nltk_lite/draw/plot.py#L77-L79
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/special/basic.py
python
euler
(n)
return specfun.eulerb(n1)[:(n+1)]
Euler numbers E0..En (inclusive). References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html
Euler numbers E0..En (inclusive).
[ "Euler", "numbers", "E0", "..", "En", "(", "inclusive", ")", "." ]
def euler(n): """Euler numbers E0..En (inclusive). References ---------- .. [1] Zhang, Shanjie and Jin, Jianming. "Computation of Special Functions", John Wiley and Sons, 1996. http://jin.ece.illinois.edu/specfunc.html """ if not isscalar(n) or (n < 0): raise ValueError("n must be a non-negative integer.") n = int(n) if (n < 2): n1 = 2 else: n1 = n return specfun.eulerb(n1)[:(n+1)]
[ "def", "euler", "(", "n", ")", ":", "if", "not", "isscalar", "(", "n", ")", "or", "(", "n", "<", "0", ")", ":", "raise", "ValueError", "(", "\"n must be a non-negative integer.\"", ")", "n", "=", "int", "(", "n", ")", "if", "(", "n", "<", "2", ")...
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/special/basic.py#L1563-L1580
git-cola/git-cola
b48b8028e0c3baf47faf7b074b9773737358163d
cola/app.py
python
Timer.elapsed
(self, key)
return entry[1] - entry[0]
Return the elapsed time for a timer
Return the elapsed time for a timer
[ "Return", "the", "elapsed", "time", "for", "a", "timer" ]
def elapsed(self, key): """Return the elapsed time for a timer""" entry = self._data[key] return entry[1] - entry[0]
[ "def", "elapsed", "(", "self", ",", "key", ")", ":", "entry", "=", "self", ".", "_data", "[", "key", "]", "return", "entry", "[", "1", "]", "-", "entry", "[", "0", "]" ]
https://github.com/git-cola/git-cola/blob/b48b8028e0c3baf47faf7b074b9773737358163d/cola/app.py#L570-L573
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/werkzeug/local.py
python
LocalProxy._get_current_object
(self)
Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.
Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.
[ "Return", "the", "current", "object", ".", "This", "is", "useful", "if", "you", "want", "the", "real", "object", "behind", "the", "proxy", "at", "a", "time", "for", "performance", "reasons", "or", "because", "you", "want", "to", "pass", "the", "object", ...
def _get_current_object(self): """Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. """ if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__) except AttributeError: raise RuntimeError('no object bound to %s' % self.__name__)
[ "def", "_get_current_object", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ".", "__local", ",", "'__release_local__'", ")", ":", "return", "self", ".", "__local", "(", ")", "try", ":", "return", "getattr", "(", "self", ".", "__local", ",",...
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/werkzeug/local.py#L289-L299
spesmilo/electrum
bdbd59300fbd35b01605e66145458e5f396108e8
electrum/exchange_rate.py
python
BitcoinVenezuela.history_ccys
(self)
return ['ARS', 'EUR', 'USD', 'VEF']
[]
def history_ccys(self): return ['ARS', 'EUR', 'USD', 'VEF']
[ "def", "history_ccys", "(", "self", ")", ":", "return", "[", "'ARS'", ",", "'EUR'", ",", "'USD'", ",", "'VEF'", "]" ]
https://github.com/spesmilo/electrum/blob/bdbd59300fbd35b01605e66145458e5f396108e8/electrum/exchange_rate.py#L181-L182
pyansys/pymapdl
c07291fc062b359abf0e92b95a92d753a95ef3d7
ansys/mapdl/core/_commands/solution/ocean.py
python
Ocean.ocdata
(self, val1="", val2="", val3="", val14="", **kwargs)
return self.run(command, **kwargs)
Defines an ocean load using non-table data. APDL Command: OCDATA Parameters ---------- val1, val2, val3, . . . , val14 Values describing the basic ocean load or a wave condition. Notes ----- The OCDATA command specifies non-table data that defines the ocean load, such as the depth of the ocean to the mud line, the ratio of added mass over added mass for a circular cross section, or the wave type to apply. The terms VAL1, VAL2, etc. are specialized according to the input set required for the given ocean load. The program interprets the data input via the OCDATA command within the context of the most recently issued OCTYPE command. Input values in the order indicated. This command is also valid in PREP7. You can define the following ocean data types: For a better understanding of how to set up a basic ocean type, see Figure: 5:: Basic Ocean Data Type Components . DEPTH -- The depth of the ocean (that is, the distance between the mean sea level and the mud line). The water surface is assumed to be level in the XY plane, with Z being positive upwards. This value is required and must be positive. MATOC -- The material number of the ocean. This value is required and is used to input the required density. It is also used to input the viscosity if the Reynolds number is used (OCTABLE). KFLOOD -- The inside-outside fluid-interaction key: For beam subtype CTUBE and HREC used with BEAM188 or BEAM189 and ocean loading, KFLOOD is always set to 1. Cay -- The ratio of added mass of the external fluid over the mass of the fluid displaced by the element cross section in the y direction (normal). The added mass represents the mass of the external fluid (ocean water) that moves with the pipe, beam, or link element when the element moves in the element y direction during a dynamic analysis. If no value is specified, and the coefficient of inertia CMy is not specified (OCTABLE), both values default to 0.0. If no value is specified, but CMy is specified, this value defaults to Cay = CMy - 1.0. If this value should be 0.0, enter 0.0. Caz -- The ratio of added mass of the external fluid over the mass of a cross section in the element z direction (normal). The added mass represents the mass of the external fluid (ocean water) that moves with the pipe, beam, or link element when the element moves in the element z direction during a dynamic analysis. If no value is specified, and Cay is specified, this value defaults to Cay. If no value is specified, and the coefficient of inertia CMz is not specified (OCTABLE), both values default to 0.0. If no value is specified, but CMz is specified, this value defaults to Cay = CMz - 1.0. If this value should be 0.0, enter 0.0. Cb -- The ratio of buoyancy force used over buoyancy force based on the outside diameter and water density. Accept the default value in most cases. Adjust this option only when you must account for additional hardware (such as a control valve) attached to the pipe exterior. A non-default value may lead to small non-physical inconsistencies; testing is therefore recommended for non-default values. If no value is specified, this value defaults to 1.0. If this value should be 0.0 (useful when troubleshooting your input), enter 0.0. Zmsl -- A vertical offset from the global origin to the mean sea level. The default value is zero (meaning that the origin is located at the mean sea level). Two example cases for Zmsl are: A structure with its origin on the sea floor (Zmsl = DEPTH). A tidal change (tc) above the mean sea level (Zmsl = tc, and DEPTH becomes DEPTH + tc) Ktable -- The dependency of VAL1 on the OCTABLE command: KWAVE -- The incident wave type: THETA -- Angle of the wave direction ฮธ from the global Cartesian X axis toward the global Cartesian Y axis (in degrees). WAVELOC (valid when KWAVE = 0 through 3, and 101+) -- The wave location type: SPECTRUM (valid when KWAVE = 5 through 7) -- The wave spectrum type: KCRC -- The wave-current interaction key. Adjustments to the current profile are available via the KCRC constant of the water motion table. Typically, these options are used only when the wave amplitude is large relative to the water depth, such that significant wave-current interaction exists.
Defines an ocean load using non-table data.
[ "Defines", "an", "ocean", "load", "using", "non", "-", "table", "data", "." ]
def ocdata(self, val1="", val2="", val3="", val14="", **kwargs): """Defines an ocean load using non-table data. APDL Command: OCDATA Parameters ---------- val1, val2, val3, . . . , val14 Values describing the basic ocean load or a wave condition. Notes ----- The OCDATA command specifies non-table data that defines the ocean load, such as the depth of the ocean to the mud line, the ratio of added mass over added mass for a circular cross section, or the wave type to apply. The terms VAL1, VAL2, etc. are specialized according to the input set required for the given ocean load. The program interprets the data input via the OCDATA command within the context of the most recently issued OCTYPE command. Input values in the order indicated. This command is also valid in PREP7. You can define the following ocean data types: For a better understanding of how to set up a basic ocean type, see Figure: 5:: Basic Ocean Data Type Components . DEPTH -- The depth of the ocean (that is, the distance between the mean sea level and the mud line). The water surface is assumed to be level in the XY plane, with Z being positive upwards. This value is required and must be positive. MATOC -- The material number of the ocean. This value is required and is used to input the required density. It is also used to input the viscosity if the Reynolds number is used (OCTABLE). KFLOOD -- The inside-outside fluid-interaction key: For beam subtype CTUBE and HREC used with BEAM188 or BEAM189 and ocean loading, KFLOOD is always set to 1. Cay -- The ratio of added mass of the external fluid over the mass of the fluid displaced by the element cross section in the y direction (normal). The added mass represents the mass of the external fluid (ocean water) that moves with the pipe, beam, or link element when the element moves in the element y direction during a dynamic analysis. If no value is specified, and the coefficient of inertia CMy is not specified (OCTABLE), both values default to 0.0. If no value is specified, but CMy is specified, this value defaults to Cay = CMy - 1.0. If this value should be 0.0, enter 0.0. Caz -- The ratio of added mass of the external fluid over the mass of a cross section in the element z direction (normal). The added mass represents the mass of the external fluid (ocean water) that moves with the pipe, beam, or link element when the element moves in the element z direction during a dynamic analysis. If no value is specified, and Cay is specified, this value defaults to Cay. If no value is specified, and the coefficient of inertia CMz is not specified (OCTABLE), both values default to 0.0. If no value is specified, but CMz is specified, this value defaults to Cay = CMz - 1.0. If this value should be 0.0, enter 0.0. Cb -- The ratio of buoyancy force used over buoyancy force based on the outside diameter and water density. Accept the default value in most cases. Adjust this option only when you must account for additional hardware (such as a control valve) attached to the pipe exterior. A non-default value may lead to small non-physical inconsistencies; testing is therefore recommended for non-default values. If no value is specified, this value defaults to 1.0. If this value should be 0.0 (useful when troubleshooting your input), enter 0.0. Zmsl -- A vertical offset from the global origin to the mean sea level. The default value is zero (meaning that the origin is located at the mean sea level). Two example cases for Zmsl are: A structure with its origin on the sea floor (Zmsl = DEPTH). A tidal change (tc) above the mean sea level (Zmsl = tc, and DEPTH becomes DEPTH + tc) Ktable -- The dependency of VAL1 on the OCTABLE command: KWAVE -- The incident wave type: THETA -- Angle of the wave direction ฮธ from the global Cartesian X axis toward the global Cartesian Y axis (in degrees). WAVELOC (valid when KWAVE = 0 through 3, and 101+) -- The wave location type: SPECTRUM (valid when KWAVE = 5 through 7) -- The wave spectrum type: KCRC -- The wave-current interaction key. Adjustments to the current profile are available via the KCRC constant of the water motion table. Typically, these options are used only when the wave amplitude is large relative to the water depth, such that significant wave-current interaction exists. """ command = f"OCDATA,{val1},{val2},{val3},{val14}" return self.run(command, **kwargs)
[ "def", "ocdata", "(", "self", ",", "val1", "=", "\"\"", ",", "val2", "=", "\"\"", ",", "val3", "=", "\"\"", ",", "val14", "=", "\"\"", ",", "*", "*", "kwargs", ")", ":", "command", "=", "f\"OCDATA,{val1},{val2},{val3},{val14}\"", "return", "self", ".", ...
https://github.com/pyansys/pymapdl/blob/c07291fc062b359abf0e92b95a92d753a95ef3d7/ansys/mapdl/core/_commands/solution/ocean.py#L2-L120
openstack/glance
502fa0ffc8970c087c5924742231812c0da6a114
glance/common/utils.py
python
cooperative_iter
(iter)
Return an iterator which schedules after each iteration. This can prevent eventlet thread starvation. :param iter: an iterator to wrap
Return an iterator which schedules after each iteration. This can prevent eventlet thread starvation.
[ "Return", "an", "iterator", "which", "schedules", "after", "each", "iteration", ".", "This", "can", "prevent", "eventlet", "thread", "starvation", "." ]
def cooperative_iter(iter): """ Return an iterator which schedules after each iteration. This can prevent eventlet thread starvation. :param iter: an iterator to wrap """ try: for chunk in iter: sleep(0) yield chunk except Exception as err: with excutils.save_and_reraise_exception(): msg = _LE("Error: cooperative_iter exception %s") % err LOG.error(msg)
[ "def", "cooperative_iter", "(", "iter", ")", ":", "try", ":", "for", "chunk", "in", "iter", ":", "sleep", "(", "0", ")", "yield", "chunk", "except", "Exception", "as", "err", ":", "with", "excutils", ".", "save_and_reraise_exception", "(", ")", ":", "msg...
https://github.com/openstack/glance/blob/502fa0ffc8970c087c5924742231812c0da6a114/glance/common/utils.py#L96-L110
matterport/Mask_RCNN
3deaec5d902d16e1daf56b62d5971d428dc920bc
mrcnn/utils.py
python
box_refinement_graph
(box, gt_box)
return result
Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]
Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)]
[ "Compute", "refinement", "needed", "to", "transform", "box", "to", "gt_box", ".", "box", "and", "gt_box", "are", "[", "N", "(", "y1", "x1", "y2", "x2", ")", "]" ]
def box_refinement_graph(box, gt_box): """Compute refinement needed to transform box to gt_box. box and gt_box are [N, (y1, x1, y2, x2)] """ box = tf.cast(box, tf.float32) gt_box = tf.cast(gt_box, tf.float32) height = box[:, 2] - box[:, 0] width = box[:, 3] - box[:, 1] center_y = box[:, 0] + 0.5 * height center_x = box[:, 1] + 0.5 * width gt_height = gt_box[:, 2] - gt_box[:, 0] gt_width = gt_box[:, 3] - gt_box[:, 1] gt_center_y = gt_box[:, 0] + 0.5 * gt_height gt_center_x = gt_box[:, 1] + 0.5 * gt_width dy = (gt_center_y - center_y) / height dx = (gt_center_x - center_x) / width dh = tf.log(gt_height / height) dw = tf.log(gt_width / width) result = tf.stack([dy, dx, dh, dw], axis=1) return result
[ "def", "box_refinement_graph", "(", "box", ",", "gt_box", ")", ":", "box", "=", "tf", ".", "cast", "(", "box", ",", "tf", ".", "float32", ")", "gt_box", "=", "tf", ".", "cast", "(", "gt_box", ",", "tf", ".", "float32", ")", "height", "=", "box", ...
https://github.com/matterport/Mask_RCNN/blob/3deaec5d902d16e1daf56b62d5971d428dc920bc/mrcnn/utils.py#L183-L206
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
scripts/monitoring/cron-send-elb-status.py
python
get_instance_name
(zagg_client_file)
return host_name
Get this instance name
Get this instance name
[ "Get", "this", "instance", "name" ]
def get_instance_name(zagg_client_file): ''' Get this instance name ''' with open(zagg_client_file, 'r') as f: config = yaml.load(f) host_name = config["host"]["name"] return host_name
[ "def", "get_instance_name", "(", "zagg_client_file", ")", ":", "with", "open", "(", "zagg_client_file", ",", "'r'", ")", "as", "f", ":", "config", "=", "yaml", ".", "load", "(", "f", ")", "host_name", "=", "config", "[", "\"host\"", "]", "[", "\"name\"",...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/scripts/monitoring/cron-send-elb-status.py#L74-L80
mesalock-linux/mesapy
ed546d59a21b36feb93e2309d5c6b75aa0ad95c9
lib-python/2.7/logging/handlers.py
python
WatchedFileHandler.emit
(self, record)
Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. First check if the underlying file has changed, and if it has, close the old stream and reopen the file to get the current stream. """ # Reduce the chance of race conditions by stat'ing by path only # once and then fstat'ing our new fd if we opened a new log stream. # See issue #14632: Thanks to John Mulligan for the problem report # and patch. try: # stat the file by path, checking for existence sres = os.stat(self.baseFilename) except OSError as err: if err.errno == errno.ENOENT: sres = None else: raise # compare file system stat with that of our stream file handle if not sres or sres[ST_DEV] != self.dev or sres[ST_INO] != self.ino: if self.stream is not None: # we have an open file handle, clean it up self.stream.flush() self.stream.close() self.stream = None # See Issue #21742: _open () might fail. # open a new file handle and get new stat info from that fd self.stream = self._open() self._statstream() logging.FileHandler.emit(self, record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "# Reduce the chance of race conditions by stat'ing by path only", "# once and then fstat'ing our new fd if we opened a new log stream.", "# See issue #14632: Thanks to John Mulligan for the problem report", "# and patch.", "try", ":", ...
https://github.com/mesalock-linux/mesapy/blob/ed546d59a21b36feb93e2309d5c6b75aa0ad95c9/lib-python/2.7/logging/handlers.py#L400-L430
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/db/backends/oracle/base.py
python
DatabaseOperations._get_trigger_name
(self, table)
return '%s_TR' % util.truncate_name(table, name_length).upper()
[]
def _get_trigger_name(self, table): name_length = self.max_name_length() - 3 return '%s_TR' % util.truncate_name(table, name_length).upper()
[ "def", "_get_trigger_name", "(", "self", ",", "table", ")", ":", "name_length", "=", "self", ".", "max_name_length", "(", ")", "-", "3", "return", "'%s_TR'", "%", "util", ".", "truncate_name", "(", "table", ",", "name_length", ")", ".", "upper", "(", ")"...
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/db/backends/oracle/base.py#L407-L409
ganeti/ganeti
d340a9ddd12f501bef57da421b5f9b969a4ba905
lib/client/gnt_group.py
python
AddGroup
(opts, args)
return base.GetResult(None, opts, SubmitOrSend(op, opts))
Add a node group to the cluster. @param opts: the command line options selected by the user @type args: list @param args: a list of length 1 with the name of the group to create @rtype: int @return: the desired exit code
Add a node group to the cluster.
[ "Add", "a", "node", "group", "to", "the", "cluster", "." ]
def AddGroup(opts, args): """Add a node group to the cluster. @param opts: the command line options selected by the user @type args: list @param args: a list of length 1 with the name of the group to create @rtype: int @return: the desired exit code """ ipolicy = CreateIPolicyFromOpts( minmax_ispecs=opts.ipolicy_bounds_specs, ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio, ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio, ipolicy_disk_templates=opts.ipolicy_disk_templates, group_ipolicy=True) (group_name,) = args diskparams = dict(opts.diskparams) if opts.disk_state: disk_state = utils.FlatToDict(opts.disk_state) else: disk_state = {} hv_state = dict(opts.hv_state) op = opcodes.OpGroupAdd(group_name=group_name, ndparams=opts.ndparams, alloc_policy=opts.alloc_policy, diskparams=diskparams, ipolicy=ipolicy, hv_state=hv_state, disk_state=disk_state) return base.GetResult(None, opts, SubmitOrSend(op, opts))
[ "def", "AddGroup", "(", "opts", ",", "args", ")", ":", "ipolicy", "=", "CreateIPolicyFromOpts", "(", "minmax_ispecs", "=", "opts", ".", "ipolicy_bounds_specs", ",", "ipolicy_vcpu_ratio", "=", "opts", ".", "ipolicy_vcpu_ratio", ",", "ipolicy_spindle_ratio", "=", "o...
https://github.com/ganeti/ganeti/blob/d340a9ddd12f501bef57da421b5f9b969a4ba905/lib/client/gnt_group.py#L52-L83
openstack/cinder
23494a6d6c51451688191e1847a458f1d3cdcaa5
cinder/volume/drivers/dell_emc/powermax/common.py
python
PowerMaxCommon._get_initiator_check_flag
(self)
return self.configuration.safe_get('initiator_check')
Reads the configuration for initator_check flag. :returns: flag
Reads the configuration for initator_check flag.
[ "Reads", "the", "configuration", "for", "initator_check", "flag", "." ]
def _get_initiator_check_flag(self): """Reads the configuration for initator_check flag. :returns: flag """ return self.configuration.safe_get('initiator_check')
[ "def", "_get_initiator_check_flag", "(", "self", ")", ":", "return", "self", ".", "configuration", ".", "safe_get", "(", "'initiator_check'", ")" ]
https://github.com/openstack/cinder/blob/23494a6d6c51451688191e1847a458f1d3cdcaa5/cinder/volume/drivers/dell_emc/powermax/common.py#L365-L370
kamalgill/flask-appengine-template
11760f83faccbb0d0afe416fc58e67ecfb4643c2
src/lib/gae_mini_profiler/sampling_profiler.py
python
Profile.run
(self, fxn)
Run function with samping profiler enabled, saving results.
Run function with samping profiler enabled, saving results.
[ "Run", "function", "with", "samping", "profiler", "enabled", "saving", "results", "." ]
def run(self, fxn): """Run function with samping profiler enabled, saving results.""" if not hasattr(threading, "current_thread"): # Sampling profiler is not supported in Python2.5 logging.warn("The sampling profiler is not supported in Python2.5") return fxn() # Store the thread id for the current request's thread. This lets # the inspecting thread know which thread to inspect. self.current_request_thread_id = threading.current_thread().ident # Start the thread that will be periodically inspecting the frame # stack of this current request thread self.inspecting_thread = InspectingThread(profile=self) self.inspecting_thread.start() try: # Run the request fxn which will be inspected by the inspecting # thread. return fxn() finally: # Stop and clear the inspecting thread self.inspecting_thread.stop() self.inspecting_thread = None
[ "def", "run", "(", "self", ",", "fxn", ")", ":", "if", "not", "hasattr", "(", "threading", ",", "\"current_thread\"", ")", ":", "# Sampling profiler is not supported in Python2.5", "logging", ".", "warn", "(", "\"The sampling profiler is not supported in Python2.5\"", "...
https://github.com/kamalgill/flask-appengine-template/blob/11760f83faccbb0d0afe416fc58e67ecfb4643c2/src/lib/gae_mini_profiler/sampling_profiler.py#L153-L176
rembo10/headphones
b3199605be1ebc83a7a8feab6b1e99b64014187c
lib/mutagen/apev2.py
python
_CIDictProxy.__getitem__
(self, key)
return self.__dict[key.lower()]
[]
def __getitem__(self, key): return self.__dict[key.lower()]
[ "def", "__getitem__", "(", "self", ",", "key", ")", ":", "return", "self", ".", "__dict", "[", "key", ".", "lower", "(", ")", "]" ]
https://github.com/rembo10/headphones/blob/b3199605be1ebc83a7a8feab6b1e99b64014187c/lib/mutagen/apev2.py#L252-L253
Source-Python-Dev-Team/Source.Python
d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb
addons/source-python/packages/site-packages/docutils/parsers/rst/roles.py
python
set_implicit_options
(role_fn)
Add customization options to role functions, unless explicitly set or disabled.
Add customization options to role functions, unless explicitly set or disabled.
[ "Add", "customization", "options", "to", "role", "functions", "unless", "explicitly", "set", "or", "disabled", "." ]
def set_implicit_options(role_fn): """ Add customization options to role functions, unless explicitly set or disabled. """ if not hasattr(role_fn, 'options') or role_fn.options is None: role_fn.options = {'class': directives.class_option} elif 'class' not in role_fn.options: role_fn.options['class'] = directives.class_option
[ "def", "set_implicit_options", "(", "role_fn", ")", ":", "if", "not", "hasattr", "(", "role_fn", ",", "'options'", ")", "or", "role_fn", ".", "options", "is", "None", ":", "role_fn", ".", "options", "=", "{", "'class'", ":", "directives", ".", "class_optio...
https://github.com/Source-Python-Dev-Team/Source.Python/blob/d0ffd8ccbd1e9923c9bc44936f20613c1c76b7fb/addons/source-python/packages/site-packages/docutils/parsers/rst/roles.py#L168-L176
linuxmint/mintupdate
476059f9f977cd1d0d7a451c64931a7a9ffd4bbf
usr/lib/linuxmint/mintUpdate/checkAPT.py
python
APTCheck.get_kernel_version_from_meta_package
(self, pkg)
return None
[]
def get_kernel_version_from_meta_package(self, pkg): for dependency in pkg.dependencies: if not dependency.target_versions or not dependency.rawtype == "Depends": return None deppkg = dependency.target_versions[0] if deppkg.source_name in ("linux", "linux-signed"): return deppkg.source_version if deppkg.source_name.startswith("linux-meta"): return self.get_kernel_version_from_meta_package(deppkg) return None
[ "def", "get_kernel_version_from_meta_package", "(", "self", ",", "pkg", ")", ":", "for", "dependency", "in", "pkg", ".", "dependencies", ":", "if", "not", "dependency", ".", "target_versions", "or", "not", "dependency", ".", "rawtype", "==", "\"Depends\"", ":", ...
https://github.com/linuxmint/mintupdate/blob/476059f9f977cd1d0d7a451c64931a7a9ffd4bbf/usr/lib/linuxmint/mintUpdate/checkAPT.py#L163-L172
biolab/orange2
db40a9449cb45b507d63dcd5739b223f9cffb8e6
Orange/OrangeCanvas/scheme/signalmanager.py
python
SignalManager.pause
(self)
Pause the updates.
Pause the updates.
[ "Pause", "the", "updates", "." ]
def pause(self): """ Pause the updates. """ if self.__state != SignalManager.Paused: self.__state = SignalManager.Paused self.stateChanged.emit(SignalManager.Paused)
[ "def", "pause", "(", "self", ")", ":", "if", "self", ".", "__state", "!=", "SignalManager", ".", "Paused", ":", "self", ".", "__state", "=", "SignalManager", ".", "Paused", "self", ".", "stateChanged", ".", "emit", "(", "SignalManager", ".", "Paused", ")...
https://github.com/biolab/orange2/blob/db40a9449cb45b507d63dcd5739b223f9cffb8e6/Orange/OrangeCanvas/scheme/signalmanager.py#L126-L133
openfisca/openfisca-france
207a58191be6830716693f94d37846f1e5037b51
openfisca_france/model/prelevements_obligatoires/impot_revenu/reductions_impot.py
python
doment.formula_2015_01_01
(foyer_fiscal, period, parameters)
return ( fhbi + fhbj + fhbk + fhbm + fhbn + fhbo + fhbp + fhbr + fhbs + fhbt + fhbu + fhbw + fhbx + fhby + fhbz + fhcb + fhcc + fhcd + fhce + fhcg + fhaa + fhab + fhac + fhae + fhaf + fhag + fhah + fhaj + fhak + fhal + fham + fhao + fhap + fhaq + fhar + fhat + fhau + fhav + fhaw + fhay + fhba + fhbb + fhbe + fhbg + fhsa + fhsb + fhsf + fhsg + fhsc + fhsh + fhse + fhsj + fhsk + fhsl + fhsp + fhsq + fhsm + fhsr + fhso + fhst + fhsu + fhsv + fhsw + fhsz + fhta + fhtb + fhtd + fhkt + fhku + fhlh + fhli + fhmb + fhmc + fhmn + fhnu + fhnv + fhnw + fhny + fhpa + fhpb + fhpd + fhpe + fhpf + fhph + fhpi + fhpj + fhpl + fhpm + fhpn + fhpo + fhpp + fhpr + fhps + fhpt + fhpu + fhpw + fhpx + fhpy + fhqe + fhqf + fhqg + fhqi + fhqo + fhqp + fhqr + fhqv + fhrg + fhri + fhrj + fhrk + fhrl + fhrm + fhro + fhrp + fhrq + fhrr + fhrt + fhru + fhrv + fhrw + fhry )
Investissements dans les DOM-TOM dans le cadre d'une entreprise.
Investissements dans les DOM-TOM dans le cadre d'une entreprise.
[ "Investissements", "dans", "les", "DOM", "-", "TOM", "dans", "le", "cadre", "d", "une", "entreprise", "." ]
def formula_2015_01_01(foyer_fiscal, period, parameters): ''' Investissements dans les DOM-TOM dans le cadre d'une entreprise. ''' fhaa = foyer_fiscal('fhaa', period) fhab = foyer_fiscal('fhab', period) fhac = foyer_fiscal('fhac', period) fhae = foyer_fiscal('fhae', period) fhaf = foyer_fiscal('fhaf', period) fhag = foyer_fiscal('fhag', period) fhah = foyer_fiscal('fhah', period) fhaj = foyer_fiscal('fhaj', period) fhak = foyer_fiscal('fhak', period) fhal = foyer_fiscal('fhal', period) fham = foyer_fiscal('fhal', period) fhao = foyer_fiscal('fhao', period) fhap = foyer_fiscal('fhap', period) fhaq = foyer_fiscal('fhaq', period) fhar = foyer_fiscal('fhar', period) fhat = foyer_fiscal('fhat', period) fhau = foyer_fiscal('fhau', period) fhav = foyer_fiscal('fhav', period) fhaw = foyer_fiscal('fhaw', period) fhay = foyer_fiscal('fhay', period) fhba = foyer_fiscal('fhba', period) fhbb = foyer_fiscal('fhbb', period) fhbe = foyer_fiscal('fhbe', period) fhbg = foyer_fiscal('fhbg', period) fhbi = foyer_fiscal('fhbi', period) fhbj = foyer_fiscal('fhbj', period) fhbk = foyer_fiscal('fhbk', period) fhbm = foyer_fiscal('fhbm', period) fhbn = foyer_fiscal('fhbn', period) fhbo = foyer_fiscal('fhbo', period) fhbp = foyer_fiscal('fhbp', period) fhbr = foyer_fiscal('fhbr', period) fhbs = foyer_fiscal('fhbs', period) fhbt = foyer_fiscal('fhbt', period) fhbu = foyer_fiscal('fhbu', period) fhbw = foyer_fiscal('fhbw', period) fhbx = foyer_fiscal('fhbx', period) fhby = foyer_fiscal('fhby', period) fhbz = foyer_fiscal('fhbz', period) fhcb = foyer_fiscal('fhcb', period) fhcc = foyer_fiscal('fhcc', period) fhcd = foyer_fiscal('fhcd', period) fhce = foyer_fiscal('fhce', period) fhcg = foyer_fiscal('fhcg', period) fhkt = foyer_fiscal('fhkt', period) fhku = foyer_fiscal('fhku', period) fhlh = foyer_fiscal('fhlh', period) fhli = foyer_fiscal('fhli', period) fhmb = foyer_fiscal('fhmb', period) fhmc = foyer_fiscal('fhmc', period) fhmn = foyer_fiscal('fhmn', period) fhnu = foyer_fiscal('fhnu', period) fhnv = foyer_fiscal('fhnv', period) fhnw = foyer_fiscal('fhnw', period) fhny = foyer_fiscal('fhny', period) fhpa = foyer_fiscal('fhpa', period) fhpb = foyer_fiscal('fhpb', period) fhpd = foyer_fiscal('fhpd', period) fhpe = foyer_fiscal('fhpe', period) fhpf = foyer_fiscal('fhpf', period) fhph = foyer_fiscal('fhph', period) fhpi = foyer_fiscal('fhpi', period) fhpj = foyer_fiscal('fhpj', period) fhpl = foyer_fiscal('fhpl', period) fhpm = foyer_fiscal('fhpm', period) fhpn = foyer_fiscal('fhpn', period) fhpo = foyer_fiscal('fhpo', period) fhpp = foyer_fiscal('fhpp', period) fhpr = foyer_fiscal('fhpr', period) fhps = foyer_fiscal('fhps', period) fhpt = foyer_fiscal('fhpt', period) fhpu = foyer_fiscal('fhpu', period) fhpw = foyer_fiscal('fhpw', period) fhpx = foyer_fiscal('fhpx', period) fhpy = foyer_fiscal('fhpy', period) fhqe = foyer_fiscal('fhqe', period) fhqf = foyer_fiscal('fhqf', period) fhqg = foyer_fiscal('fhqg', period) fhqi = foyer_fiscal('fhqi', period) fhqo = foyer_fiscal('fhqo', period) fhqp = foyer_fiscal('fhqp', period) fhqr = foyer_fiscal('fhqr', period) fhqv = foyer_fiscal('fhqv', period) fhrg = foyer_fiscal('fhrg', period) fhri = foyer_fiscal('fhri', period) fhrj = foyer_fiscal('fhrj', period) fhrk = foyer_fiscal('fhrk', period) fhrl = foyer_fiscal('fhrl', period) fhrm = foyer_fiscal('fhrm', period) fhro = foyer_fiscal('fhro', period) fhrp = foyer_fiscal('fhrp', period) fhrq = foyer_fiscal('fhrq', period) fhrr = foyer_fiscal('fhrr', period) fhrt = foyer_fiscal('fhrt', period) fhru = foyer_fiscal('fhru', period) fhrv = foyer_fiscal('fhrv', period) fhrw = foyer_fiscal('fhrw', period) fhry = foyer_fiscal('fhry', period) fhsa = foyer_fiscal('fhsa', period) fhsb = foyer_fiscal('fhsb', period) fhsc = foyer_fiscal('fhsc', period) fhse = foyer_fiscal('fhse', period) fhsf = foyer_fiscal('fhsf', period) fhsg = foyer_fiscal('fhsg', period) fhsh = foyer_fiscal('fhsh', period) fhsj = foyer_fiscal('fhsj', period) fhsk = foyer_fiscal('fhsk', period) fhsl = foyer_fiscal('fhsl', period) fhsm = foyer_fiscal('fhsm', period) fhso = foyer_fiscal('fhso', period) fhsp = foyer_fiscal('fhsp', period) fhsq = foyer_fiscal('fhsq', period) fhsr = foyer_fiscal('fhsr', period) fhst = foyer_fiscal('fhst', period) fhsu = foyer_fiscal('fhsu', period) fhsv = foyer_fiscal('fhsv', period) fhsw = foyer_fiscal('fhsw', period) fhsz = foyer_fiscal('fhsz', period) fhta = foyer_fiscal('fhta', period) fhtb = foyer_fiscal('fhtb', period) fhtd = foyer_fiscal('fhtd', period) return ( fhbi + fhbj + fhbk + fhbm + fhbn + fhbo + fhbp + fhbr + fhbs + fhbt + fhbu + fhbw + fhbx + fhby + fhbz + fhcb + fhcc + fhcd + fhce + fhcg + fhaa + fhab + fhac + fhae + fhaf + fhag + fhah + fhaj + fhak + fhal + fham + fhao + fhap + fhaq + fhar + fhat + fhau + fhav + fhaw + fhay + fhba + fhbb + fhbe + fhbg + fhsa + fhsb + fhsf + fhsg + fhsc + fhsh + fhse + fhsj + fhsk + fhsl + fhsp + fhsq + fhsm + fhsr + fhso + fhst + fhsu + fhsv + fhsw + fhsz + fhta + fhtb + fhtd + fhkt + fhku + fhlh + fhli + fhmb + fhmc + fhmn + fhnu + fhnv + fhnw + fhny + fhpa + fhpb + fhpd + fhpe + fhpf + fhph + fhpi + fhpj + fhpl + fhpm + fhpn + fhpo + fhpp + fhpr + fhps + fhpt + fhpu + fhpw + fhpx + fhpy + fhqe + fhqf + fhqg + fhqi + fhqo + fhqp + fhqr + fhqv + fhrg + fhri + fhrj + fhrk + fhrl + fhrm + fhro + fhrp + fhrq + fhrr + fhrt + fhru + fhrv + fhrw + fhry )
[ "def", "formula_2015_01_01", "(", "foyer_fiscal", ",", "period", ",", "parameters", ")", ":", "fhaa", "=", "foyer_fiscal", "(", "'fhaa'", ",", "period", ")", "fhab", "=", "foyer_fiscal", "(", "'fhab'", ",", "period", ")", "fhac", "=", "foyer_fiscal", "(", ...
https://github.com/openfisca/openfisca-france/blob/207a58191be6830716693f94d37846f1e5037b51/openfisca_france/model/prelevements_obligatoires/impot_revenu/reductions_impot.py#L1332-L1469
linxid/Machine_Learning_Study_Path
558e82d13237114bbb8152483977806fc0c222af
Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pkg_resources/_vendor/pyparsing.py
python
GoToColumn.parseImpl
( self, instring, loc, doActions=True )
return newloc, ret
[]
def parseImpl( self, instring, loc, doActions=True ): thiscol = col( loc, instring ) if thiscol > self.col: raise ParseException( instring, loc, "Text not in expected column", self ) newloc = loc + self.col - thiscol ret = instring[ loc: newloc ] return newloc, ret
[ "def", "parseImpl", "(", "self", ",", "instring", ",", "loc", ",", "doActions", "=", "True", ")", ":", "thiscol", "=", "col", "(", "loc", ",", "instring", ")", "if", "thiscol", ">", "self", ".", "col", ":", "raise", "ParseException", "(", "instring", ...
https://github.com/linxid/Machine_Learning_Study_Path/blob/558e82d13237114bbb8152483977806fc0c222af/Machine Learning In Action/Chapter4-NaiveBayes/venv/Lib/site-packages/pkg_resources/_vendor/pyparsing.py#L3080-L3086
rsmusllp/king-phisher
6acbbd856f849d407cc904c075441e0cf13c25cf
king_phisher/server/aaa.py
python
AuthenticatedSession.__init__
(self, user)
:param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User`
:param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User`
[ ":", "param", "user", ":", "The", "user", "object", "of", "the", "authenticated", "user", ".", ":", "type", "user", ":", ":", "py", ":", "class", ":", "~king_phisher", ".", "server", ".", "database", ".", "models", ".", "User" ]
def __init__(self, user): """ :param user: The user object of the authenticated user. :type user: :py:class:`~king_phisher.server.database.models.User` """ self.user = user.id self.user_access_level = user.access_level self.user_is_admin = user.is_admin self.created = db_models.current_timestamp() self.last_seen = self.created self._event_socket = None
[ "def", "__init__", "(", "self", ",", "user", ")", ":", "self", ".", "user", "=", "user", ".", "id", "self", ".", "user_access_level", "=", "user", ".", "access_level", "self", ".", "user_is_admin", "=", "user", ".", "is_admin", "self", ".", "created", ...
https://github.com/rsmusllp/king-phisher/blob/6acbbd856f849d407cc904c075441e0cf13c25cf/king_phisher/server/aaa.py#L78-L88
ctxis/CAPE
dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82
lib/cuckoo/core/database.py
python
Database.add_url
(self, url, timeout=0, package="", options="", priority=1, custom="", machine="", platform="", tags=None, memory=False, enforce_timeout=False, clock=None, shrike_url=None, shrike_msg=None, shrike_sid = None, shrike_refer=None, parent_id=None)
return self.add(URL(url), timeout, package, options, priority, custom, machine, platform, tags, memory, enforce_timeout, clock, shrike_url, shrike_msg, shrike_sid, shrike_refer, parent_id)
Add a task to database from url. @param url: url. @param timeout: selected timeout. @param options: analysis options. @param priority: analysis priority. @param custom: custom options. @param machine: selected machine. @param platform: platform. @param tags: tags for machine selection @param memory: toggle full memory dump. @param enforce_timeout: toggle full timeout execution. @param clock: virtual machine clock time @return: cursor or None.
Add a task to database from url.
[ "Add", "a", "task", "to", "database", "from", "url", "." ]
def add_url(self, url, timeout=0, package="", options="", priority=1, custom="", machine="", platform="", tags=None, memory=False, enforce_timeout=False, clock=None, shrike_url=None, shrike_msg=None, shrike_sid = None, shrike_refer=None, parent_id=None): """Add a task to database from url. @param url: url. @param timeout: selected timeout. @param options: analysis options. @param priority: analysis priority. @param custom: custom options. @param machine: selected machine. @param platform: platform. @param tags: tags for machine selection @param memory: toggle full memory dump. @param enforce_timeout: toggle full timeout execution. @param clock: virtual machine clock time @return: cursor or None. """ # Convert empty strings and None values to a valid int if not timeout: timeout = 0 if not priority: priority = 1 return self.add(URL(url), timeout, package, options, priority, custom, machine, platform, tags, memory, enforce_timeout, clock, shrike_url, shrike_msg, shrike_sid, shrike_refer, parent_id)
[ "def", "add_url", "(", "self", ",", "url", ",", "timeout", "=", "0", ",", "package", "=", "\"\"", ",", "options", "=", "\"\"", ",", "priority", "=", "1", ",", "custom", "=", "\"\"", ",", "machine", "=", "\"\"", ",", "platform", "=", "\"\"", ",", ...
https://github.com/ctxis/CAPE/blob/dae9fa6a254ecdbabeb7eb0d2389fa63722c1e82/lib/cuckoo/core/database.py#L1167-L1195
google-research/exoplanet-ml
3dfe65f7ae44443b124ae87b000c317237c7dc00
exoplanet-ml/light_curve/fast_ops/python/postproc.py
python
ValueErrorOnFalse
(ok, *output_args)
return output
Raises ValueError if not ok, otherwise returns the output arguments.
Raises ValueError if not ok, otherwise returns the output arguments.
[ "Raises", "ValueError", "if", "not", "ok", "otherwise", "returns", "the", "output", "arguments", "." ]
def ValueErrorOnFalse(ok, *output_args): """Raises ValueError if not ok, otherwise returns the output arguments.""" n_outputs = len(output_args) if n_outputs < 2: raise ValueError( "Expected 2 or more output_args. Got: {}".format(n_outputs)) if not ok: error = output_args[-1] raise ValueError(error) if n_outputs == 2: output = output_args[0] else: output = output_args[0:-1] return output
[ "def", "ValueErrorOnFalse", "(", "ok", ",", "*", "output_args", ")", ":", "n_outputs", "=", "len", "(", "output_args", ")", "if", "n_outputs", "<", "2", ":", "raise", "ValueError", "(", "\"Expected 2 or more output_args. Got: {}\"", ".", "format", "(", "n_output...
https://github.com/google-research/exoplanet-ml/blob/3dfe65f7ae44443b124ae87b000c317237c7dc00/exoplanet-ml/light_curve/fast_ops/python/postproc.py#L23-L39
iclavera/learning_to_adapt
bd7d99ba402521c96631e7d09714128f549db0f1
learning_to_adapt/mujoco_py/mjviewer.py
python
MjViewer.should_stop
(self)
return glfw.window_should_close(self.window)
[]
def should_stop(self): return glfw.window_should_close(self.window)
[ "def", "should_stop", "(", "self", ")", ":", "return", "glfw", ".", "window_should_close", "(", "self", ".", "window", ")" ]
https://github.com/iclavera/learning_to_adapt/blob/bd7d99ba402521c96631e7d09714128f549db0f1/learning_to_adapt/mujoco_py/mjviewer.py#L308-L309
binaryage/drydrop
2f27e15befd247255d89f9120eeee44851b82c4a
dryapp/drydrop/app/meta/yaml_listener.py
python
EventHandler.SequenceStart
(self, event, loader)
Handle start of sequence event
Handle start of sequence event
[ "Handle", "start", "of", "sequence", "event" ]
def SequenceStart(self, event, loader): """Handle start of sequence event"""
[ "def", "SequenceStart", "(", "self", ",", "event", ",", "loader", ")", ":" ]
https://github.com/binaryage/drydrop/blob/2f27e15befd247255d89f9120eeee44851b82c4a/dryapp/drydrop/app/meta/yaml_listener.py#L68-L69
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py
python
_DomainGreaterEqual.__call__
(self, x)
return umath.less(x, self.critical_value)
Executes the call behavior.
Executes the call behavior.
[ "Executes", "the", "call", "behavior", "." ]
def __call__ (self, x): "Executes the call behavior." return umath.less(x, self.critical_value)
[ "def", "__call__", "(", "self", ",", "x", ")", ":", "return", "umath", ".", "less", "(", "x", ",", "self", ".", "critical_value", ")" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/numpy/ma/core.py#L807-L809
PyHDI/veriloggen
2382d200deabf59cfcfd741f5eba371010aaf2bb
veriloggen/types/componentgen.py
python
ComponentGen.mkPortMapInterrupt
(self, name)
return portmap
[]
def mkPortMapInterrupt(self, name): portmap = self.doc.createElement('spirit:portMap') portmap.appendChild(self.mkLogicalPort('INTERRUPT')) portmap.appendChild(self.mkPhysicalPortInterrupt(name)) return portmap
[ "def", "mkPortMapInterrupt", "(", "self", ",", "name", ")", ":", "portmap", "=", "self", ".", "doc", ".", "createElement", "(", "'spirit:portMap'", ")", "portmap", ".", "appendChild", "(", "self", ".", "mkLogicalPort", "(", "'INTERRUPT'", ")", ")", "portmap"...
https://github.com/PyHDI/veriloggen/blob/2382d200deabf59cfcfd741f5eba371010aaf2bb/veriloggen/types/componentgen.py#L526-L530
raffaele-forte/climber
5530a780446e35b1ce977bae140557050fe0b47c
Exscript/servers/HTTPd.py
python
HTTPd.add_account
(self, username, password)
Adds a username/password pair that HTTP clients may use to log in. @type username: str @param username: The name of the user. @type password: str @param password: The user's password.
Adds a username/password pair that HTTP clients may use to log in.
[ "Adds", "a", "username", "/", "password", "pair", "that", "HTTP", "clients", "may", "use", "to", "log", "in", "." ]
def add_account(self, username, password): """ Adds a username/password pair that HTTP clients may use to log in. @type username: str @param username: The name of the user. @type password: str @param password: The user's password. """ self.accounts[username] = password
[ "def", "add_account", "(", "self", ",", "username", ",", "password", ")", ":", "self", ".", "accounts", "[", "username", "]", "=", "password" ]
https://github.com/raffaele-forte/climber/blob/5530a780446e35b1ce977bae140557050fe0b47c/Exscript/servers/HTTPd.py#L191-L200
mozilla/PyPOM
9cb84df9d27b428b4e7423d1bbe6502e92990154
src/pypom/region.py
python
Region.find_elements
(self, strategy, locator)
return self.driver_adapter.find_elements(strategy, locator, root=self.root)
Finds elements on the page. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target elements. :type strategy: str :type locator: str :return: List of :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.element_list.ElementList` :rtype: list
Finds elements on the page.
[ "Finds", "elements", "on", "the", "page", "." ]
def find_elements(self, strategy, locator): """Finds elements on the page. :param strategy: Location strategy to use. See :py:class:`~selenium.webdriver.common.by.By` or :py:attr:`~pypom.splinter_driver.ALLOWED_STRATEGIES`. :param locator: Location of target elements. :type strategy: str :type locator: str :return: List of :py:class:`~selenium.webdriver.remote.webelement.WebElement` or :py:class:`~splinter.element_list.ElementList` :rtype: list """ return self.driver_adapter.find_elements(strategy, locator, root=self.root)
[ "def", "find_elements", "(", "self", ",", "strategy", ",", "locator", ")", ":", "return", "self", ".", "driver_adapter", ".", "find_elements", "(", "strategy", ",", "locator", ",", "root", "=", "self", ".", "root", ")" ]
https://github.com/mozilla/PyPOM/blob/9cb84df9d27b428b4e7423d1bbe6502e92990154/src/pypom/region.py#L108-L119
ethz-asl/hierarchical_loc
3c9e32e9e01e5f4694fb796fd1db276f88f361fb
retrievalnet/retrievalnet/datasets/base_dataset.py
python
BaseDataset._get_data
(self, dataset, split_name, **config)
Reads the dataset splits using the Tensorflow `tf.data` API. This method should create a `tf.data.Dataset` object for the given data split, with named components defined through a dictionary mapping strings to tensors. It typically performs operations such as reading data from a file or from a Python generator, shuffling the elements or applying data augmentation to the training split. It should however NOT batch the dataset (left to the model). Arguments: dataset: An object returned by the `_init_dataset` method. split_name: A string, the name of the requested split, either `"training"`, `"validation"` or `"test"`. config: A configuration dictionary, given during the object instantiantion. Returns: An object of type `tf.data.Dataset` corresponding to the corresponding split.
Reads the dataset splits using the Tensorflow `tf.data` API.
[ "Reads", "the", "dataset", "splits", "using", "the", "Tensorflow", "tf", ".", "data", "API", "." ]
def _get_data(self, dataset, split_name, **config): """Reads the dataset splits using the Tensorflow `tf.data` API. This method should create a `tf.data.Dataset` object for the given data split, with named components defined through a dictionary mapping strings to tensors. It typically performs operations such as reading data from a file or from a Python generator, shuffling the elements or applying data augmentation to the training split. It should however NOT batch the dataset (left to the model). Arguments: dataset: An object returned by the `_init_dataset` method. split_name: A string, the name of the requested split, either `"training"`, `"validation"` or `"test"`. config: A configuration dictionary, given during the object instantiantion. Returns: An object of type `tf.data.Dataset` corresponding to the corresponding split. """ raise NotImplementedError
[ "def", "_get_data", "(", "self", ",", "dataset", ",", "split_name", ",", "*", "*", "config", ")", ":", "raise", "NotImplementedError" ]
https://github.com/ethz-asl/hierarchical_loc/blob/3c9e32e9e01e5f4694fb796fd1db276f88f361fb/retrievalnet/retrievalnet/datasets/base_dataset.py#L41-L60
itailang/SampleNet
442459abc54f9e14f0966a169a094a98febd32eb
classification/structural_losses/tf_approxmatch.py
python
_match_cost_grad
(op, grad_cost)
return [ grad_1 * tf.expand_dims(tf.expand_dims(grad_cost, 1), 2), grad_2 * tf.expand_dims(tf.expand_dims(grad_cost, 1), 2), None, ]
[]
def _match_cost_grad(op, grad_cost): xyz1 = op.inputs[0] xyz2 = op.inputs[1] match = op.inputs[2] grad_1, grad_2 = approxmatch_module.match_cost_grad(xyz1, xyz2, match) return [ grad_1 * tf.expand_dims(tf.expand_dims(grad_cost, 1), 2), grad_2 * tf.expand_dims(tf.expand_dims(grad_cost, 1), 2), None, ]
[ "def", "_match_cost_grad", "(", "op", ",", "grad_cost", ")", ":", "xyz1", "=", "op", ".", "inputs", "[", "0", "]", "xyz2", "=", "op", ".", "inputs", "[", "1", "]", "match", "=", "op", ".", "inputs", "[", "2", "]", "grad_1", ",", "grad_2", "=", ...
https://github.com/itailang/SampleNet/blob/442459abc54f9e14f0966a169a094a98febd32eb/classification/structural_losses/tf_approxmatch.py#L55-L64
huzhifeng/py12306
e163b070dee39008443fd08ac04e176ef88f2476
py12306.py
python
MyOrder.checkOrderInfo
(self)
[]
def checkOrderInfo(self): if self.checkRandCodeAnsyn('passenger') == RET_ERR: return RET_ERR passengerTicketStr = '' oldPassengerStr = '' passenger_seat_detail = '0' # TODO [0->้šๆœบ][1->ไธ‹้“บ][2->ไธญ้“บ][3->ไธŠ้“บ] for p in self.passengers: if p['index'] != 1: passengerTicketStr += 'N_' oldPassengerStr += '1_' passengerTicketStr += '%s,%s,%s,%s,%s,%s,%s,' % ( p['seattype'], passenger_seat_detail, p['tickettype'], p['name'], p['cardtype'], p['id'], p['phone']) oldPassengerStr += '%s,%s,%s,' % ( p['name'], p['cardtype'], p['id']) passengerTicketStr += 'N' oldPassengerStr += '1_' self.passengerTicketStr = passengerTicketStr self.oldPassengerStr = oldPassengerStr print(u'ๆฃ€ๆŸฅ่ฎขๅ•...') url = 'https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo' parameters = [ ('cancel_flag', '2'), # TODO ('bed_level_order_num', '000000000000000000000000000000'), # TODO ('passengerTicketStr', self.passengerTicketStr), ('oldPassengerStr', self.oldPassengerStr), ('tour_flag', self.tour_flag), ('randCode', self.captcha), #('NzA4MTc1', 'NmYyYzZkYWY2OWZkNzg2YQ%3D%3D'), # TODO ('_json_att', ''), ('REPEAT_SUBMIT_TOKEN', self.repeatSubmitToken), ] payload = urllib.urlencode(parameters) r = self.post(url, payload) if not r: print(u'ๆฃ€ๆŸฅ่ฎขๅ•ๅผ‚ๅธธ') return RET_ERR # {"validateMessagesShowId":"_validatorMessage","status":true,"httpstatus":200,"data":{"submitStatus":true},"messages":[],"validateMessages":{}} obj = r.json() if ( hasKeys(obj, ['status', 'httpstatus', 'data']) and hasKeys(obj['data'], ['submitStatus']) and obj['status'] and obj['data']['submitStatus']): print(u'ๆฃ€ๆŸฅ่ฎขๅ•ๆˆๅŠŸ') return RET_OK else: print(u'ๆฃ€ๆŸฅ่ฎขๅ•ๅคฑ่ดฅ') dumpObj(obj) return RET_ERR
[ "def", "checkOrderInfo", "(", "self", ")", ":", "if", "self", ".", "checkRandCodeAnsyn", "(", "'passenger'", ")", "==", "RET_ERR", ":", "return", "RET_ERR", "passengerTicketStr", "=", "''", "oldPassengerStr", "=", "''", "passenger_seat_detail", "=", "'0'", "# TO...
https://github.com/huzhifeng/py12306/blob/e163b070dee39008443fd08ac04e176ef88f2476/py12306.py#L1222-L1280
galaxyproject/galaxy
4c03520f05062e0f4a1b3655dc0b7452fda69943
lib/tool_shed/webapp/controllers/repository.py
python
RepositoryController.get_repository_type
(self, trans, **kwd)
return str(repository.type)
Given a repository name and owner, return the type.
Given a repository name and owner, return the type.
[ "Given", "a", "repository", "name", "and", "owner", "return", "the", "type", "." ]
def get_repository_type(self, trans, **kwd): """Given a repository name and owner, return the type.""" repository_name = kwd['name'] repository_owner = kwd['owner'] repository = repository_util.get_repository_by_name_and_owner(trans.app, repository_name, repository_owner) return str(repository.type)
[ "def", "get_repository_type", "(", "self", ",", "trans", ",", "*", "*", "kwd", ")", ":", "repository_name", "=", "kwd", "[", "'name'", "]", "repository_owner", "=", "kwd", "[", "'owner'", "]", "repository", "=", "repository_util", ".", "get_repository_by_name_...
https://github.com/galaxyproject/galaxy/blob/4c03520f05062e0f4a1b3655dc0b7452fda69943/lib/tool_shed/webapp/controllers/repository.py#L1278-L1283
mailgyc/doudizhu
c76d0ffa26421402abdf6c06d5713a9368b5d167
doudizhu/contrib/db/torndb.py
python
Connection.execute_many
(self, query: str, args)
return self.insert_many(query, args)
Executes the given query against all the given param sequences. We return the last rowid from the query.
Executes the given query against all the given param sequences. We return the last rowid from the query.
[ "Executes", "the", "given", "query", "against", "all", "the", "given", "param", "sequences", ".", "We", "return", "the", "last", "rowid", "from", "the", "query", "." ]
def execute_many(self, query: str, args): """Executes the given query against all the given param sequences. We return the last rowid from the query. """ return self.insert_many(query, args)
[ "def", "execute_many", "(", "self", ",", "query", ":", "str", ",", "args", ")", ":", "return", "self", ".", "insert_many", "(", "query", ",", "args", ")" ]
https://github.com/mailgyc/doudizhu/blob/c76d0ffa26421402abdf6c06d5713a9368b5d167/doudizhu/contrib/db/torndb.py#L99-L103
gwpy/gwpy
82becd78d166a32985cb657a54d0d39f6a207739
gwpy/table/io/losc.py
python
_mask_replace
(value, dtype)
return value
Replace `value` with the default for the given `dtype` If not default is set for the ``dtype``, just return the value unchanged.
Replace `value` with the default for the given `dtype`
[ "Replace", "value", "with", "the", "default", "for", "the", "given", "dtype" ]
def _mask_replace(value, dtype): """Replace `value` with the default for the given `dtype` If not default is set for the ``dtype``, just return the value unchanged. """ for type_, replacement in _FILL_VALUE.items(): if issubclass(dtype, type_): return replacement return value
[ "def", "_mask_replace", "(", "value", ",", "dtype", ")", ":", "for", "type_", ",", "replacement", "in", "_FILL_VALUE", ".", "items", "(", ")", ":", "if", "issubclass", "(", "dtype", ",", "type_", ")", ":", "return", "replacement", "return", "value" ]
https://github.com/gwpy/gwpy/blob/82becd78d166a32985cb657a54d0d39f6a207739/gwpy/table/io/losc.py#L79-L88
demisto/content
5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07
Packs/MobileIronUEM/Integrations/MobileIronCORE/MobileIronCORE.py
python
execute_fetch_incidents_command
(client)
runs the fetch incidents task. :type client: ``Client`` :param client: MobileIron client to use
runs the fetch incidents task.
[ "runs", "the", "fetch", "incidents", "task", "." ]
def execute_fetch_incidents_command(client): """ runs the fetch incidents task. :type client: ``Client`` :param client: MobileIron client to use """ params = demisto.params() admin_space_id = params.get('admin_space_id') incident_type = params.get('incidentType') max_fetch = min(int(params.get('max_fetch')), 200) incidents = fetch_incidents(client=client, admin_space_id=admin_space_id, incident_type=incident_type, max_fetch=max_fetch) demisto.incidents(incidents)
[ "def", "execute_fetch_incidents_command", "(", "client", ")", ":", "params", "=", "demisto", ".", "params", "(", ")", "admin_space_id", "=", "params", ".", "get", "(", "'admin_space_id'", ")", "incident_type", "=", "params", ".", "get", "(", "'incidentType'", ...
https://github.com/demisto/content/blob/5c664a65b992ac8ca90ac3f11b1b2cdf11ee9b07/Packs/MobileIronUEM/Integrations/MobileIronCORE/MobileIronCORE.py#L325-L339
avidLearnerInProgress/python-automation-scripts
859cbbf72571673500cfc0fbcf493beaed48b7c5
pdf-to-text-converter/pdfToText.py
python
absolute_path_shortner
(absolute_path)
return tail
[]
def absolute_path_shortner(absolute_path): #same as os.getcwd() returns filename after removing directory name head,tail=os.path.split(absolute_path) return tail
[ "def", "absolute_path_shortner", "(", "absolute_path", ")", ":", "#same as os.getcwd() returns filename after removing directory name", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "absolute_path", ")", "return", "tail" ]
https://github.com/avidLearnerInProgress/python-automation-scripts/blob/859cbbf72571673500cfc0fbcf493beaed48b7c5/pdf-to-text-converter/pdfToText.py#L11-L13
ipython/ipython
c0abea7a6dfe52c1f74c9d0387d4accadba7cc14
IPython/core/inputtransformer.py
python
InputTransformer.reset
(self)
Return, transformed any lines that the transformer has accumulated, and reset its internal state. Must be overridden by subclasses.
Return, transformed any lines that the transformer has accumulated, and reset its internal state.
[ "Return", "transformed", "any", "lines", "that", "the", "transformer", "has", "accumulated", "and", "reset", "its", "internal", "state", "." ]
def reset(self): """Return, transformed any lines that the transformer has accumulated, and reset its internal state. Must be overridden by subclasses. """ pass
[ "def", "reset", "(", "self", ")", ":", "pass" ]
https://github.com/ipython/ipython/blob/c0abea7a6dfe52c1f74c9d0387d4accadba7cc14/IPython/core/inputtransformer.py#L58-L64
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/template/__init__.py
python
TriggerUpdateCoordinator._attach_triggers
(self, start_event=None)
Attach the triggers.
Attach the triggers.
[ "Attach", "the", "triggers", "." ]
async def _attach_triggers(self, start_event=None) -> None: """Attach the triggers.""" if start_event is not None: self._unsub_start = None self._unsub_trigger = await trigger_helper.async_initialize_triggers( self.hass, self.config[CONF_TRIGGER], self._handle_triggered, DOMAIN, self.name, self.logger.log, start_event is not None, )
[ "async", "def", "_attach_triggers", "(", "self", ",", "start_event", "=", "None", ")", "->", "None", ":", "if", "start_event", "is", "not", "None", ":", "self", ".", "_unsub_start", "=", "None", "self", ".", "_unsub_trigger", "=", "await", "trigger_helper", ...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/template/__init__.py#L150-L163
deschler/django-modeltranslation
391e2b33b86e935a9000f65e75a9a96f3af98e81
modeltranslation/widgets.py
python
ClearableWidgetWrapper.value_from_datadict
(self, data, files, name)
return self.widget.value_from_datadict(data, files, name)
If the clear checkbox is checked returns the configured empty value, completely ignoring the original input.
If the clear checkbox is checked returns the configured empty value, completely ignoring the original input.
[ "If", "the", "clear", "checkbox", "is", "checked", "returns", "the", "configured", "empty", "value", "completely", "ignoring", "the", "original", "input", "." ]
def value_from_datadict(self, data, files, name): """ If the clear checkbox is checked returns the configured empty value, completely ignoring the original input. """ clear = self.checkbox.value_from_datadict(data, files, self.clear_checkbox_name(name)) if clear: return self.empty_value return self.widget.value_from_datadict(data, files, name)
[ "def", "value_from_datadict", "(", "self", ",", "data", ",", "files", ",", "name", ")", ":", "clear", "=", "self", ".", "checkbox", ".", "value_from_datadict", "(", "data", ",", "files", ",", "self", ".", "clear_checkbox_name", "(", "name", ")", ")", "if...
https://github.com/deschler/django-modeltranslation/blob/391e2b33b86e935a9000f65e75a9a96f3af98e81/modeltranslation/widgets.py#L82-L90
mlcommons/training
4a4d5a0b7efe99c680306b1940749211d4238a84
translation/tensorflow/transformer/model/transformer.py
python
Transformer.predict
(self, encoder_outputs, encoder_decoder_attention_bias)
return {"outputs": top_decoded_ids, "scores": top_scores}
Return predicted sequence.
Return predicted sequence.
[ "Return", "predicted", "sequence", "." ]
def predict(self, encoder_outputs, encoder_decoder_attention_bias): """Return predicted sequence.""" batch_size = tf.shape(encoder_outputs)[0] input_length = tf.shape(encoder_outputs)[1] max_decode_length = input_length + self.params.extra_decode_length symbols_to_logits_fn = self._get_symbols_to_logits_fn(max_decode_length) # Create initial set of IDs that will be passed into symbols_to_logits_fn. initial_ids = tf.zeros([batch_size], dtype=tf.int32) # Create cache storing decoder attention values for each layer. cache = { "layer_%d" % layer: { "k": tf.zeros([batch_size, 0, self.params.hidden_size]), "v": tf.zeros([batch_size, 0, self.params.hidden_size]), } for layer in range(self.params.num_hidden_layers)} # Add encoder output and attention bias to the cache. cache["encoder_outputs"] = encoder_outputs cache["encoder_decoder_attention_bias"] = encoder_decoder_attention_bias # Use beam search to find the top beam_size sequences and scores. mlperf_log.transformer_print( key=mlperf_log.MODEL_HP_SEQ_BEAM_SEARCH, value={ "vocab_size": self.params.vocab_size, "beam_size": self.params.beam_size, "alpha": self.params.alpha, "extra_decode_length": self.params.extra_decode_length}) decoded_ids, scores = beam_search.sequence_beam_search( symbols_to_logits_fn=symbols_to_logits_fn, initial_ids=initial_ids, initial_cache=cache, vocab_size=self.params.vocab_size, beam_size=self.params.beam_size, alpha=self.params.alpha, max_decode_length=max_decode_length, eos_id=EOS_ID) # Get the top sequence for each batch element top_decoded_ids = decoded_ids[:, 0, 1:] top_scores = scores[:, 0] return {"outputs": top_decoded_ids, "scores": top_scores}
[ "def", "predict", "(", "self", ",", "encoder_outputs", ",", "encoder_decoder_attention_bias", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "encoder_outputs", ")", "[", "0", "]", "input_length", "=", "tf", ".", "shape", "(", "encoder_outputs", ")", "...
https://github.com/mlcommons/training/blob/4a4d5a0b7efe99c680306b1940749211d4238a84/translation/tensorflow/transformer/model/transformer.py#L217-L261
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/waas/waas_client_composite_operations.py
python
WaasClientCompositeOperations.update_captchas_and_wait_for_state
(self, waas_policy_id, captchas, wait_for_states=[], operation_kwargs={}, waiter_kwargs={})
Calls :py:func:`~oci.waas.WaasClient.update_captchas` and waits for the :py:class:`~oci.waas.models.WorkRequest` to enter the given state(s). :param str waas_policy_id: (required) The `OCID`__ of the WAAS policy. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[Captcha] captchas: (required) A list of CAPTCHA details. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.waas.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.waas.WaasClient.update_captchas` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
Calls :py:func:`~oci.waas.WaasClient.update_captchas` and waits for the :py:class:`~oci.waas.models.WorkRequest` to enter the given state(s).
[ "Calls", ":", "py", ":", "func", ":", "~oci", ".", "waas", ".", "WaasClient", ".", "update_captchas", "and", "waits", "for", "the", ":", "py", ":", "class", ":", "~oci", ".", "waas", ".", "models", ".", "WorkRequest", "to", "enter", "the", "given", "...
def update_captchas_and_wait_for_state(self, waas_policy_id, captchas, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}): """ Calls :py:func:`~oci.waas.WaasClient.update_captchas` and waits for the :py:class:`~oci.waas.models.WorkRequest` to enter the given state(s). :param str waas_policy_id: (required) The `OCID`__ of the WAAS policy. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param list[Captcha] captchas: (required) A list of CAPTCHA details. :param list[str] wait_for_states: An array of states to wait on. These should be valid values for :py:attr:`~oci.waas.models.WorkRequest.status` :param dict operation_kwargs: A dictionary of keyword arguments to pass to :py:func:`~oci.waas.WaasClient.update_captchas` :param dict waiter_kwargs: A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds`` as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait """ operation_result = self.client.update_captchas(waas_policy_id, captchas, **operation_kwargs) if not wait_for_states: return operation_result lowered_wait_for_states = [w.lower() for w in wait_for_states] wait_for_resource_id = operation_result.headers['opc-work-request-id'] try: waiter_result = oci.wait_until( self.client, self.client.get_work_request(wait_for_resource_id), evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states, **waiter_kwargs ) result_to_return = waiter_result return result_to_return except Exception as e: raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
[ "def", "update_captchas_and_wait_for_state", "(", "self", ",", "waas_policy_id", ",", "captchas", ",", "wait_for_states", "=", "[", "]", ",", "operation_kwargs", "=", "{", "}", ",", "waiter_kwargs", "=", "{", "}", ")", ":", "operation_result", "=", "self", "."...
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/waas/waas_client_composite_operations.py#L579-L620
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/rcsetup.py
python
_make_type_validator
(cls, *, allow_none=False)
return validator
Return a validator that converts inputs to *cls* or raises (and possibly allows ``None`` as well).
Return a validator that converts inputs to *cls* or raises (and possibly allows ``None`` as well).
[ "Return", "a", "validator", "that", "converts", "inputs", "to", "*", "cls", "*", "or", "raises", "(", "and", "possibly", "allows", "None", "as", "well", ")", "." ]
def _make_type_validator(cls, *, allow_none=False): """ Return a validator that converts inputs to *cls* or raises (and possibly allows ``None`` as well). """ def validator(s): if (allow_none and (s is None or isinstance(s, str) and s.lower() == "none")): return None if cls is str and not isinstance(s, str): _api.warn_deprecated( "3.5", message="Support for setting an rcParam that expects a " "str value to a non-str value is deprecated since %(since)s " "and support will be removed %(removal)s.") try: return cls(s) except (TypeError, ValueError) as e: raise ValueError( f'Could not convert {s!r} to {cls.__name__}') from e validator.__name__ = f"validate_{cls.__name__}" if allow_none: validator.__name__ += "_or_None" validator.__qualname__ = ( validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__) return validator
[ "def", "_make_type_validator", "(", "cls", ",", "*", ",", "allow_none", "=", "False", ")", ":", "def", "validator", "(", "s", ")", ":", "if", "(", "allow_none", "and", "(", "s", "is", "None", "or", "isinstance", "(", "s", ",", "str", ")", "and", "s...
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/rcsetup.py#L174-L200
marinho/geraldo
868ebdce67176d9b6205cddc92476f642c783fff
site/newsite/django_1_0/django/views/debug.py
python
empty_urlconf
(request)
return HttpResponse(t.render(c), mimetype='text/html')
Create an empty URLconf 404 error response.
Create an empty URLconf 404 error response.
[ "Create", "an", "empty", "URLconf", "404", "error", "response", "." ]
def empty_urlconf(request): "Create an empty URLconf 404 error response." t = Template(EMPTY_URLCONF_TEMPLATE, name='Empty URLConf template') c = Context({ 'project_name': settings.SETTINGS_MODULE.split('.')[0] }) return HttpResponse(t.render(c), mimetype='text/html')
[ "def", "empty_urlconf", "(", "request", ")", ":", "t", "=", "Template", "(", "EMPTY_URLCONF_TEMPLATE", ",", "name", "=", "'Empty URLConf template'", ")", "c", "=", "Context", "(", "{", "'project_name'", ":", "settings", ".", "SETTINGS_MODULE", ".", "split", "(...
https://github.com/marinho/geraldo/blob/868ebdce67176d9b6205cddc92476f642c783fff/site/newsite/django_1_0/django/views/debug.py#L266-L272
openstack/nova
b49b7663e1c3073917d5844b81d38db8e86d05c4
nova/db/main/api.py
python
instance_fault_get_by_instance_uuids
( context, instance_uuids, latest=False, )
return output
Get all instance faults for the provided instance_uuids. :param instance_uuids: List of UUIDs of instances to grab faults for :param latest: Optional boolean indicating we should only return the latest fault for the instance
Get all instance faults for the provided instance_uuids.
[ "Get", "all", "instance", "faults", "for", "the", "provided", "instance_uuids", "." ]
def instance_fault_get_by_instance_uuids( context, instance_uuids, latest=False, ): """Get all instance faults for the provided instance_uuids. :param instance_uuids: List of UUIDs of instances to grab faults for :param latest: Optional boolean indicating we should only return the latest fault for the instance """ if not instance_uuids: return {} faults_tbl = models.InstanceFault.__table__ # NOTE(rpodolyaka): filtering by instance_uuids is performed in both # code branches below for the sake of a better query plan. On change, # make sure to update the other one as well. query = model_query(context, models.InstanceFault, [faults_tbl], read_deleted='no') if latest: # NOTE(jaypipes): We join instance_faults to a derived table of the # latest faults per instance UUID. The SQL produced below looks like # this: # # SELECT instance_faults.* # FROM instance_faults # JOIN ( # SELECT instance_uuid, MAX(id) AS max_id # FROM instance_faults # WHERE instance_uuid IN ( ... ) # AND deleted = 0 # GROUP BY instance_uuid # ) AS latest_faults # ON instance_faults.id = latest_faults.max_id; latest_faults = model_query( context, models.InstanceFault, [faults_tbl.c.instance_uuid, sql.func.max(faults_tbl.c.id).label('max_id')], read_deleted='no' ).filter( faults_tbl.c.instance_uuid.in_(instance_uuids) ).group_by( faults_tbl.c.instance_uuid ).subquery(name="latest_faults") query = query.join(latest_faults, faults_tbl.c.id == latest_faults.c.max_id) else: query = query.filter( models.InstanceFault.instance_uuid.in_(instance_uuids) ).order_by(expression.desc("id")) output = {} for instance_uuid in instance_uuids: output[instance_uuid] = [] for row in query: output[row.instance_uuid].append(row._asdict()) return output
[ "def", "instance_fault_get_by_instance_uuids", "(", "context", ",", "instance_uuids", ",", "latest", "=", "False", ",", ")", ":", "if", "not", "instance_uuids", ":", "return", "{", "}", "faults_tbl", "=", "models", ".", "InstanceFault", ".", "__table__", "# NOTE...
https://github.com/openstack/nova/blob/b49b7663e1c3073917d5844b81d38db8e86d05c4/nova/db/main/api.py#L3730-L3790
styxit/HTPC-Manager
490697460b4fa1797106aece27d873bc256b2ff1
libs/cherrypy/wsgiserver/wsgiserver2.py
python
CP_fileobject.sendall
(self, data)
Sendall for non-blocking sockets.
Sendall for non-blocking sockets.
[ "Sendall", "for", "non", "-", "blocking", "sockets", "." ]
def sendall(self, data): """Sendall for non-blocking sockets.""" while data: try: bytes_sent = self.send(data) data = data[bytes_sent:] except socket.error, e: if e.args[0] not in socket_errors_nonblocking: raise
[ "def", "sendall", "(", "self", ",", "data", ")", ":", "while", "data", ":", "try", ":", "bytes_sent", "=", "self", ".", "send", "(", "data", ")", "data", "=", "data", "[", "bytes_sent", ":", "]", "except", "socket", ".", "error", ",", "e", ":", "...
https://github.com/styxit/HTPC-Manager/blob/490697460b4fa1797106aece27d873bc256b2ff1/libs/cherrypy/wsgiserver/wsgiserver2.py#L966-L974
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/elementtree/ElementTree.py
python
TreeBuilder.data
(self, data)
[]
def data(self, data): self._data.append(data)
[ "def", "data", "(", "self", ",", "data", ")", ":", "self", ".", "_data", ".", "append", "(", "data", ")" ]
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/elementtree/ElementTree.py#L1101-L1102
larryhastings/gilectomy
4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a
Lib/fractions.py
python
Fraction.__ge__
(a, b)
return a._richcmp(b, operator.ge)
a >= b
a >= b
[ "a", ">", "=", "b" ]
def __ge__(a, b): """a >= b""" return a._richcmp(b, operator.ge)
[ "def", "__ge__", "(", "a", ",", "b", ")", ":", "return", "a", ".", "_richcmp", "(", "b", ",", "operator", ".", "ge", ")" ]
https://github.com/larryhastings/gilectomy/blob/4315ec3f1d6d4f813cc82ce27a24e7f784dbfc1a/Lib/fractions.py#L618-L620
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/extensions_v1beta1_scale.py
python
ExtensionsV1beta1Scale.__repr__
(self)
return self.to_str()
For `print` and `pprint`
For `print` and `pprint`
[ "For", "print", "and", "pprint" ]
def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
[ "def", "__repr__", "(", "self", ")", ":", "return", "self", ".", "to_str", "(", ")" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/extensions_v1beta1_scale.py#L202-L206
caiiiac/Machine-Learning-with-Python
1a26c4467da41ca4ebc3d5bd789ea942ef79422f
MachineLearning/venv/lib/python3.5/site-packages/scipy/signal/ltisys.py
python
TransferFunction.num
(self)
return self._num
Numerator of the `TransferFunction` system.
Numerator of the `TransferFunction` system.
[ "Numerator", "of", "the", "TransferFunction", "system", "." ]
def num(self): """Numerator of the `TransferFunction` system.""" return self._num
[ "def", "num", "(", "self", ")", ":", "return", "self", ".", "_num" ]
https://github.com/caiiiac/Machine-Learning-with-Python/blob/1a26c4467da41ca4ebc3d5bd789ea942ef79422f/MachineLearning/venv/lib/python3.5/site-packages/scipy/signal/ltisys.py#L774-L776
volatilityfoundation/volatility3
168b0d0b053ab97a7cb096ef2048795cc54d885f
volatility3/framework/symbols/intermed.py
python
ISFormatTable.clear_symbol_cache
(self)
Clears the symbol cache of the symbol table.
Clears the symbol cache of the symbol table.
[ "Clears", "the", "symbol", "cache", "of", "the", "symbol", "table", "." ]
def clear_symbol_cache(self) -> None: """Clears the symbol cache of the symbol table.""" self._symbol_cache.clear()
[ "def", "clear_symbol_cache", "(", "self", ")", "->", "None", ":", "self", ".", "_symbol_cache", ".", "clear", "(", ")" ]
https://github.com/volatilityfoundation/volatility3/blob/168b0d0b053ab97a7cb096ef2048795cc54d885f/volatility3/framework/symbols/intermed.py#L315-L317
criteo/biggraphite
1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30
biggraphite/drivers/elasticsearch.py
python
document_from_metric
(metric)
return data
Creates an ElasticSearch document from a Metric.
Creates an ElasticSearch document from a Metric.
[ "Creates", "an", "ElasticSearch", "document", "from", "a", "Metric", "." ]
def document_from_metric(metric): """Creates an ElasticSearch document from a Metric.""" config = metric.metadata.as_string_dict() components = _components_from_name(metric.name) name = bg_metric.sanitize_metric_name(metric.name) data = {"depth": len(components) - 1, "name": name} for i, component in enumerate(components): data["p%d" % i] = component data.update( { "uuid": metric.id, "created_on": metric.created_on or datetime.datetime.now(), "updated_on": metric.updated_on or datetime.datetime.now(), "read_on": metric.read_on or None, "config": config, } ) return data
[ "def", "document_from_metric", "(", "metric", ")", ":", "config", "=", "metric", ".", "metadata", ".", "as_string_dict", "(", ")", "components", "=", "_components_from_name", "(", "metric", ".", "name", ")", "name", "=", "bg_metric", ".", "sanitize_metric_name",...
https://github.com/criteo/biggraphite/blob/1f647ada6b3f2b2f3fb4e59d326f73a2c891fc30/biggraphite/drivers/elasticsearch.py#L202-L221
kupferlauncher/kupfer
1c1e9bcbce05a82f503f68f8b3955c20b02639b3
oldplugins/vim/plugin.py
python
RecentsSource.initialize
(self)
Set up change monitor
Set up change monitor
[ "Set", "up", "change", "monitor" ]
def initialize(self): """Set up change monitor""" viminfofile = os.path.expanduser(self.vim_viminfo_file) gfile = gio.File(viminfofile) self.monitor = gfile.monitor_file(gio.FILE_MONITOR_NONE, None) if self.monitor: self.monitor.connect("changed", self._changed)
[ "def", "initialize", "(", "self", ")", ":", "viminfofile", "=", "os", ".", "path", ".", "expanduser", "(", "self", ".", "vim_viminfo_file", ")", "gfile", "=", "gio", ".", "File", "(", "viminfofile", ")", "self", ".", "monitor", "=", "gfile", ".", "moni...
https://github.com/kupferlauncher/kupfer/blob/1c1e9bcbce05a82f503f68f8b3955c20b02639b3/oldplugins/vim/plugin.py#L59-L65
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/bdb.py
python
checkfuncname
(b, frame)
return True
Return True if break should happen here. Whether a break should happen depends on the way that b (the breakpoint) was set. If it was set via line number, check if b.line is the same as the one in the frame. If it was set via function name, check if this is the right function and if it is on the first executable line.
Return True if break should happen here.
[ "Return", "True", "if", "break", "should", "happen", "here", "." ]
def checkfuncname(b, frame): """Return True if break should happen here. Whether a break should happen depends on the way that b (the breakpoint) was set. If it was set via line number, check if b.line is the same as the one in the frame. If it was set via function name, check if this is the right function and if it is on the first executable line. """ if not b.funcname: # Breakpoint was set via line number. if b.line != frame.f_lineno: # Breakpoint was set at a line with a def statement and the function # defined is called: don't break. return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False # We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True
[ "def", "checkfuncname", "(", "b", ",", "frame", ")", ":", "if", "not", "b", ".", "funcname", ":", "# Breakpoint was set via line number.", "if", "b", ".", "line", "!=", "frame", ".", "f_lineno", ":", "# Breakpoint was set at a line with a def statement and the functio...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/bdb.py#L758-L787
edisonlz/fastor
342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3
base/site-packages/tencentcloud/cvm/v20170312/models.py
python
InquiryPriceResetInstancesTypeRequest.__init__
(self)
:param InstanceIds: ไธ€ไธชๆˆ–ๅคšไธชๅพ…ๆ“ไฝœ็š„ๅฎžไพ‹IDใ€‚ๅฏ้€š่ฟ‡[`DescribeInstances`](https://cloud.tencent.com/document/api/213/15728)ๆŽฅๅฃ่ฟ”ๅ›žๅ€ผไธญ็š„`InstanceId`่Žทๅ–ใ€‚ๆฏๆฌก่ฏทๆฑ‚ๆ‰น้‡ๅฎžไพ‹็š„ไธŠ้™ไธบ1ใ€‚ :type InstanceIds: list of str :param InstanceType: ๅฎžไพ‹ๆœบๅž‹ใ€‚ไธๅŒๅฎžไพ‹ๆœบๅž‹ๆŒ‡ๅฎšไบ†ไธๅŒ็š„่ต„ๆบ่ง„ๆ ผ๏ผŒๅ…ทไฝ“ๅ–ๅ€ผๅฏๅ‚่ง้™„่กจๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅฏน็…ง่กจ๏ผŒไนŸๅฏไปฅ่ฐƒ็”จๆŸฅ่ฏขๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅˆ—่กจๆŽฅๅฃ่Žทๅพ—ๆœ€ๆ–ฐ็š„่ง„ๆ ผ่กจใ€‚ :type InstanceType: str :param ForceStop: ๆ˜ฏๅฆๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹้€‰ๆ‹ฉๅผบๅˆถๅ…ณๆœบใ€‚ๅปบ่ฎฎๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹ๅ…ˆๆ‰‹ๅŠจๅ…ณๆœบ๏ผŒ็„ถๅŽๅ†้‡็ฝฎ็”จๆˆทๅฏ†็ ใ€‚ๅ–ๅ€ผ่Œƒๅ›ด๏ผš<br><li>TRUE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><li>FALSE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽไธ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><br>้ป˜่ฎคๅ–ๅ€ผ๏ผšFALSEใ€‚<br><br>ๅผบๅˆถๅ…ณๆœบ็š„ๆ•ˆๆžœ็ญ‰ๅŒไบŽๅ…ณ้—ญ็‰ฉ็†่ฎก็ฎ—ๆœบ็š„็”ตๆบๅผ€ๅ…ณใ€‚ๅผบๅˆถๅ…ณๆœบๅฏ่ƒฝไผšๅฏผ่‡ดๆ•ฐๆฎไธขๅคฑๆˆ–ๆ–‡ไปถ็ณป็ปŸๆŸๅ๏ผŒ่ฏทไป…ๅœจๆœๅŠกๅ™จไธ่ƒฝๆญฃๅธธๅ…ณๆœบๆ—ถไฝฟ็”จใ€‚ :type ForceStop: bool
:param InstanceIds: ไธ€ไธชๆˆ–ๅคšไธชๅพ…ๆ“ไฝœ็š„ๅฎžไพ‹IDใ€‚ๅฏ้€š่ฟ‡[`DescribeInstances`](https://cloud.tencent.com/document/api/213/15728)ๆŽฅๅฃ่ฟ”ๅ›žๅ€ผไธญ็š„`InstanceId`่Žทๅ–ใ€‚ๆฏๆฌก่ฏทๆฑ‚ๆ‰น้‡ๅฎžไพ‹็š„ไธŠ้™ไธบ1ใ€‚ :type InstanceIds: list of str :param InstanceType: ๅฎžไพ‹ๆœบๅž‹ใ€‚ไธๅŒๅฎžไพ‹ๆœบๅž‹ๆŒ‡ๅฎšไบ†ไธๅŒ็š„่ต„ๆบ่ง„ๆ ผ๏ผŒๅ…ทไฝ“ๅ–ๅ€ผๅฏๅ‚่ง้™„่กจๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅฏน็…ง่กจ๏ผŒไนŸๅฏไปฅ่ฐƒ็”จๆŸฅ่ฏขๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅˆ—่กจๆŽฅๅฃ่Žทๅพ—ๆœ€ๆ–ฐ็š„่ง„ๆ ผ่กจใ€‚ :type InstanceType: str :param ForceStop: ๆ˜ฏๅฆๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹้€‰ๆ‹ฉๅผบๅˆถๅ…ณๆœบใ€‚ๅปบ่ฎฎๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹ๅ…ˆๆ‰‹ๅŠจๅ…ณๆœบ๏ผŒ็„ถๅŽๅ†้‡็ฝฎ็”จๆˆทๅฏ†็ ใ€‚ๅ–ๅ€ผ่Œƒๅ›ด๏ผš<br><li>TRUE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><li>FALSE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽไธ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><br>้ป˜่ฎคๅ–ๅ€ผ๏ผšFALSEใ€‚<br><br>ๅผบๅˆถๅ…ณๆœบ็š„ๆ•ˆๆžœ็ญ‰ๅŒไบŽๅ…ณ้—ญ็‰ฉ็†่ฎก็ฎ—ๆœบ็š„็”ตๆบๅผ€ๅ…ณใ€‚ๅผบๅˆถๅ…ณๆœบๅฏ่ƒฝไผšๅฏผ่‡ดๆ•ฐๆฎไธขๅคฑๆˆ–ๆ–‡ไปถ็ณป็ปŸๆŸๅ๏ผŒ่ฏทไป…ๅœจๆœๅŠกๅ™จไธ่ƒฝๆญฃๅธธๅ…ณๆœบๆ—ถไฝฟ็”จใ€‚ :type ForceStop: bool
[ ":", "param", "InstanceIds", ":", "ไธ€ไธชๆˆ–ๅคšไธชๅพ…ๆ“ไฝœ็š„ๅฎžไพ‹IDใ€‚ๅฏ้€š่ฟ‡", "[", "DescribeInstances", "]", "(", "https", ":", "//", "cloud", ".", "tencent", ".", "com", "/", "document", "/", "api", "/", "213", "/", "15728", ")", "ๆŽฅๅฃ่ฟ”ๅ›žๅ€ผไธญ็š„", "InstanceId", "่Žทๅ–ใ€‚ๆฏๆฌก่ฏทๆฑ‚ๆ‰น้‡ๅฎžไพ‹็š„ไธŠ้™ไธบ1ใ€‚", ":",...
def __init__(self): """ :param InstanceIds: ไธ€ไธชๆˆ–ๅคšไธชๅพ…ๆ“ไฝœ็š„ๅฎžไพ‹IDใ€‚ๅฏ้€š่ฟ‡[`DescribeInstances`](https://cloud.tencent.com/document/api/213/15728)ๆŽฅๅฃ่ฟ”ๅ›žๅ€ผไธญ็š„`InstanceId`่Žทๅ–ใ€‚ๆฏๆฌก่ฏทๆฑ‚ๆ‰น้‡ๅฎžไพ‹็š„ไธŠ้™ไธบ1ใ€‚ :type InstanceIds: list of str :param InstanceType: ๅฎžไพ‹ๆœบๅž‹ใ€‚ไธๅŒๅฎžไพ‹ๆœบๅž‹ๆŒ‡ๅฎšไบ†ไธๅŒ็š„่ต„ๆบ่ง„ๆ ผ๏ผŒๅ…ทไฝ“ๅ–ๅ€ผๅฏๅ‚่ง้™„่กจๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅฏน็…ง่กจ๏ผŒไนŸๅฏไปฅ่ฐƒ็”จๆŸฅ่ฏขๅฎžไพ‹่ต„ๆบ่ง„ๆ ผๅˆ—่กจๆŽฅๅฃ่Žทๅพ—ๆœ€ๆ–ฐ็š„่ง„ๆ ผ่กจใ€‚ :type InstanceType: str :param ForceStop: ๆ˜ฏๅฆๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹้€‰ๆ‹ฉๅผบๅˆถๅ…ณๆœบใ€‚ๅปบ่ฎฎๅฏน่ฟ่กŒไธญ็š„ๅฎžไพ‹ๅ…ˆๆ‰‹ๅŠจๅ…ณๆœบ๏ผŒ็„ถๅŽๅ†้‡็ฝฎ็”จๆˆทๅฏ†็ ใ€‚ๅ–ๅ€ผ่Œƒๅ›ด๏ผš<br><li>TRUE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><li>FALSE๏ผš่กจ็คบๅœจๆญฃๅธธๅ…ณๆœบๅคฑ่ดฅๅŽไธ่ฟ›่กŒๅผบๅˆถๅ…ณๆœบ<br><br>้ป˜่ฎคๅ–ๅ€ผ๏ผšFALSEใ€‚<br><br>ๅผบๅˆถๅ…ณๆœบ็š„ๆ•ˆๆžœ็ญ‰ๅŒไบŽๅ…ณ้—ญ็‰ฉ็†่ฎก็ฎ—ๆœบ็š„็”ตๆบๅผ€ๅ…ณใ€‚ๅผบๅˆถๅ…ณๆœบๅฏ่ƒฝไผšๅฏผ่‡ดๆ•ฐๆฎไธขๅคฑๆˆ–ๆ–‡ไปถ็ณป็ปŸๆŸๅ๏ผŒ่ฏทไป…ๅœจๆœๅŠกๅ™จไธ่ƒฝๆญฃๅธธๅ…ณๆœบๆ—ถไฝฟ็”จใ€‚ :type ForceStop: bool """ self.InstanceIds = None self.InstanceType = None self.ForceStop = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "InstanceIds", "=", "None", "self", ".", "InstanceType", "=", "None", "self", ".", "ForceStop", "=", "None" ]
https://github.com/edisonlz/fastor/blob/342078a18363ac41d3c6b1ab29dbdd44fdb0b7b3/base/site-packages/tencentcloud/cvm/v20170312/models.py#L2019-L2030
benedekrozemberczki/littleballoffur
dbfec92c0ead8c5da134c9aead7987c7a36234b4
littleballoffur/sampler.py
python
Sampler._check_number_of_edges
(self, graph)
Checking the size of the graph -- edges.
Checking the size of the graph -- edges.
[ "Checking", "the", "size", "of", "the", "graph", "--", "edges", "." ]
def _check_number_of_edges(self, graph): """Checking the size of the graph -- edges.""" if self.number_of_edges > self.backend.get_number_of_edges(graph): raise ValueError( "The number of edges is too large. Please see requirements." )
[ "def", "_check_number_of_edges", "(", "self", ",", "graph", ")", ":", "if", "self", ".", "number_of_edges", ">", "self", ".", "backend", ".", "get_number_of_edges", "(", "graph", ")", ":", "raise", "ValueError", "(", "\"The number of edges is too large. Please see r...
https://github.com/benedekrozemberczki/littleballoffur/blob/dbfec92c0ead8c5da134c9aead7987c7a36234b4/littleballoffur/sampler.py#L71-L76
eirannejad/pyRevit
49c0b7eb54eb343458ce1365425e6552d0c47d44
pyrevitlib/rpw/db/wall.py
python
WallType.category
(self)
return self.get_category(wrapped=True)
Wrapped ``DB.Category`` of the ``DB.Wall``
Wrapped ``DB.Category`` of the ``DB.Wall``
[ "Wrapped", "DB", ".", "Category", "of", "the", "DB", ".", "Wall" ]
def category(self): """ Wrapped ``DB.Category`` of the ``DB.Wall`` """ deprecate_warning('Wall.category', 'Wall.get_category()') return self.get_category(wrapped=True)
[ "def", "category", "(", "self", ")", ":", "deprecate_warning", "(", "'Wall.category'", ",", "'Wall.get_category()'", ")", "return", "self", ".", "get_category", "(", "wrapped", "=", "True", ")" ]
https://github.com/eirannejad/pyRevit/blob/49c0b7eb54eb343458ce1365425e6552d0c47d44/pyrevitlib/rpw/db/wall.py#L144-L147
zulip/zulip
19f891968de50d43920af63526c823bdd233cdee
zerver/lib/message.py
python
get_recent_conversations_recipient_id
( user_profile: UserProfile, recipient_id: int, sender_id: int )
return recipient_id
Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure.
Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure.
[ "Helper", "for", "doing", "lookups", "of", "the", "recipient_id", "that", "get_recent_private_conversations", "would", "have", "used", "to", "record", "that", "message", "in", "its", "data", "structure", "." ]
def get_recent_conversations_recipient_id( user_profile: UserProfile, recipient_id: int, sender_id: int ) -> int: """Helper for doing lookups of the recipient_id that get_recent_private_conversations would have used to record that message in its data structure. """ my_recipient_id = user_profile.recipient_id if recipient_id == my_recipient_id: return UserProfile.objects.values_list("recipient_id", flat=True).get(id=sender_id) return recipient_id
[ "def", "get_recent_conversations_recipient_id", "(", "user_profile", ":", "UserProfile", ",", "recipient_id", ":", "int", ",", "sender_id", ":", "int", ")", "->", "int", ":", "my_recipient_id", "=", "user_profile", ".", "recipient_id", "if", "recipient_id", "==", ...
https://github.com/zulip/zulip/blob/19f891968de50d43920af63526c823bdd233cdee/zerver/lib/message.py#L1321-L1331
EricSteinberger/PokerRL
e02ea667061b96912e424231da071b6f20a262f7
PokerRL/rl/neural/NetWrapperBase.py
python
NetWrapperBase.__init__
(self, net, env_bldr, args, owner, device)
[]
def __init__(self, net, env_bldr, args, owner, device): self._env_bldr = env_bldr self._args = args self.owner = owner self.device = device self._criterion = rl_util.str_to_loss_cls(self._args.loss_str) self.loss_last_batch = None self._net = net
[ "def", "__init__", "(", "self", ",", "net", ",", "env_bldr", ",", "args", ",", "owner", ",", "device", ")", ":", "self", ".", "_env_bldr", "=", "env_bldr", "self", ".", "_args", "=", "args", "self", ".", "owner", "=", "owner", "self", ".", "device", ...
https://github.com/EricSteinberger/PokerRL/blob/e02ea667061b96912e424231da071b6f20a262f7/PokerRL/rl/neural/NetWrapperBase.py#L11-L20
pydata/xarray
9226c7ac87b3eb246f7a7e49f8f0f23d68951624
xarray/core/duck_array_ops.py
python
datetime_to_numeric
(array, offset=None, datetime_unit=None, dtype=float)
Convert an array containing datetime-like data to numerical values. Convert the datetime array to a timedelta relative to an offset. Parameters ---------- array : array-like Input data offset : None, datetime or cftime.datetime Datetime offset. If None, this is set by default to the array's minimum value to reduce round off errors. datetime_unit : {None, Y, M, W, D, h, m, s, ms, us, ns, ps, fs, as} If not None, convert output to a given datetime unit. Note that some conversions are not allowed due to non-linear relationships between units. dtype : dtype Output dtype. Returns ------- array Numerical representation of datetime object relative to an offset. Notes ----- Some datetime unit conversions won't work, for example from days to years, even though some calendars would allow for them (e.g. no_leap). This is because there is no `cftime.timedelta` object.
Convert an array containing datetime-like data to numerical values. Convert the datetime array to a timedelta relative to an offset. Parameters ---------- array : array-like Input data offset : None, datetime or cftime.datetime Datetime offset. If None, this is set by default to the array's minimum value to reduce round off errors. datetime_unit : {None, Y, M, W, D, h, m, s, ms, us, ns, ps, fs, as} If not None, convert output to a given datetime unit. Note that some conversions are not allowed due to non-linear relationships between units. dtype : dtype Output dtype. Returns ------- array Numerical representation of datetime object relative to an offset. Notes ----- Some datetime unit conversions won't work, for example from days to years, even though some calendars would allow for them (e.g. no_leap). This is because there is no `cftime.timedelta` object.
[ "Convert", "an", "array", "containing", "datetime", "-", "like", "data", "to", "numerical", "values", ".", "Convert", "the", "datetime", "array", "to", "a", "timedelta", "relative", "to", "an", "offset", ".", "Parameters", "----------", "array", ":", "array", ...
def datetime_to_numeric(array, offset=None, datetime_unit=None, dtype=float): """Convert an array containing datetime-like data to numerical values. Convert the datetime array to a timedelta relative to an offset. Parameters ---------- array : array-like Input data offset : None, datetime or cftime.datetime Datetime offset. If None, this is set by default to the array's minimum value to reduce round off errors. datetime_unit : {None, Y, M, W, D, h, m, s, ms, us, ns, ps, fs, as} If not None, convert output to a given datetime unit. Note that some conversions are not allowed due to non-linear relationships between units. dtype : dtype Output dtype. Returns ------- array Numerical representation of datetime object relative to an offset. Notes ----- Some datetime unit conversions won't work, for example from days to years, even though some calendars would allow for them (e.g. no_leap). This is because there is no `cftime.timedelta` object. """ # TODO: make this function dask-compatible? # Set offset to minimum if not given if offset is None: if array.dtype.kind in "Mm": offset = _datetime_nanmin(array) else: offset = min(array) # Compute timedelta object. # For np.datetime64, this can silently yield garbage due to overflow. # One option is to enforce 1970-01-01 as the universal offset. array = array - offset # Scalar is converted to 0d-array if not hasattr(array, "dtype"): array = np.array(array) # Convert timedelta objects to float by first converting to microseconds. if array.dtype.kind in "O": return py_timedelta_to_float(array, datetime_unit or "ns").astype(dtype) # Convert np.NaT to np.nan elif array.dtype.kind in "mM": # Convert to specified timedelta units. if datetime_unit: array = array / np.timedelta64(1, datetime_unit) return np.where(isnull(array), np.nan, array.astype(dtype))
[ "def", "datetime_to_numeric", "(", "array", ",", "offset", "=", "None", ",", "datetime_unit", "=", "None", ",", "dtype", "=", "float", ")", ":", "# TODO: make this function dask-compatible?", "# Set offset to minimum if not given", "if", "offset", "is", "None", ":", ...
https://github.com/pydata/xarray/blob/9226c7ac87b3eb246f7a7e49f8f0f23d68951624/xarray/core/duck_array_ops.py#L416-L468
danecjensen/subscribely
4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0
src/werkzeug/wrappers.py
python
WWWAuthenticateMixin.www_authenticate
(self)
return parse_www_authenticate_header(header, on_update)
The `WWW-Authenticate` header in a parsed form.
The `WWW-Authenticate` header in a parsed form.
[ "The", "WWW", "-", "Authenticate", "header", "in", "a", "parsed", "form", "." ]
def www_authenticate(self): """The `WWW-Authenticate` header in a parsed form.""" def on_update(www_auth): if not www_auth and 'www-authenticate' in self.headers: del self.headers['www-authenticate'] elif www_auth: self.headers['WWW-Authenticate'] = www_auth.to_header() header = self.headers.get('www-authenticate') return parse_www_authenticate_header(header, on_update)
[ "def", "www_authenticate", "(", "self", ")", ":", "def", "on_update", "(", "www_auth", ")", ":", "if", "not", "www_auth", "and", "'www-authenticate'", "in", "self", ".", "headers", ":", "del", "self", ".", "headers", "[", "'www-authenticate'", "]", "elif", ...
https://github.com/danecjensen/subscribely/blob/4d6ac60358b5fe26f0c01be68f1ba063df3b1ea0/src/werkzeug/wrappers.py#L1608-L1616
LiuChangFreeman/C--Compiler
99fd44982c54310e8eba4133653e3d9a7736a499
SyntaxParser/BackUp/Materials/Sample/prettytable.py
python
from_html_one
(html_code, **kwargs)
return tables[0]
Generates a PrettyTables from a string of HTML code which contains only a single <Table>
Generates a PrettyTables from a string of HTML code which contains only a single <Table>
[ "Generates", "a", "PrettyTables", "from", "a", "string", "of", "HTML", "code", "which", "contains", "only", "a", "single", "<Table", ">" ]
def from_html_one(html_code, **kwargs): """ Generates a PrettyTables from a string of HTML code which contains only a single <Table> """ tables = from_html(html_code, **kwargs) try: assert len(tables) == 1 except AssertionError: raise Exception("More than one <Table> in provided HTML code! Use from_html instead.") return tables[0]
[ "def", "from_html_one", "(", "html_code", ",", "*", "*", "kwargs", ")", ":", "tables", "=", "from_html", "(", "html_code", ",", "*", "*", "kwargs", ")", "try", ":", "assert", "len", "(", "tables", ")", "==", "1", "except", "AssertionError", ":", "raise...
https://github.com/LiuChangFreeman/C--Compiler/blob/99fd44982c54310e8eba4133653e3d9a7736a499/SyntaxParser/BackUp/Materials/Sample/prettytable.py#L1444-L1455
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Ubuntu_12/pyasn1/type/univ.py
python
Integer.__rpow__
(self, value)
return self.clone(pow(value, self._value))
[]
def __rpow__(self, value): return self.clone(pow(value, self._value))
[ "def", "__rpow__", "(", "self", ",", "value", ")", ":", "return", "self", ".", "clone", "(", "pow", "(", "value", ",", "self", ".", "_value", ")", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Ubuntu_12/pyasn1/type/univ.py#L43-L43
qxf2/qxf2-page-object-model
8b2978e5bd2a5413d581f9e29a2098e5f5e742fd
endpoints/API_Interface.py
python
API_Interface.__init__
(self, url, session_flag=False)
Constructor
Constructor
[ "Constructor" ]
def __init__(self, url, session_flag=False): "Constructor" # make base_url available to all API endpoints self.request_obj = requests if session_flag: self.create_session() self.base_url = url
[ "def", "__init__", "(", "self", ",", "url", ",", "session_flag", "=", "False", ")", ":", "# make base_url available to all API endpoints", "self", ".", "request_obj", "=", "requests", "if", "session_flag", ":", "self", ".", "create_session", "(", ")", "self", "....
https://github.com/qxf2/qxf2-page-object-model/blob/8b2978e5bd2a5413d581f9e29a2098e5f5e742fd/endpoints/API_Interface.py#L14-L20
EvilCult/moviecatcher
6e6b1476e43fbaa7f13a16535e11133d8cc4f980
Bl/Play.py
python
Play.__authDownload
(self, authKey)
[]
def __authDownload (self, authKey) : self.Player.downLinkStat = {'err': 0, 'msg': ''} self.bdAuth['input'] = authKey self.Player.showCloudLink() threading.Thread(target = self.__bdDownload).start()
[ "def", "__authDownload", "(", "self", ",", "authKey", ")", ":", "self", ".", "Player", ".", "downLinkStat", "=", "{", "'err'", ":", "0", ",", "'msg'", ":", "''", "}", "self", ".", "bdAuth", "[", "'input'", "]", "=", "authKey", "self", ".", "Player", ...
https://github.com/EvilCult/moviecatcher/blob/6e6b1476e43fbaa7f13a16535e11133d8cc4f980/Bl/Play.py#L118-L122
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/chat/v2/credential.py
python
CredentialInstance.__repr__
(self)
return '<Twilio.Chat.V2.CredentialInstance {}>'.format(context)
Provide a friendly representation :returns: Machine friendly representation :rtype: str
Provide a friendly representation
[ "Provide", "a", "friendly", "representation" ]
def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) return '<Twilio.Chat.V2.CredentialInstance {}>'.format(context)
[ "def", "__repr__", "(", "self", ")", ":", "context", "=", "' '", ".", "join", "(", "'{}={}'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "_solution", ".", "items", "(", ")", ")", "return", "'<Twilio.Chat.V2.Cre...
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/chat/v2/credential.py#L442-L450
PythonCharmers/python-future
80523f383fbba1c6de0551e19d0277e73e69573c
src/future/backports/http/server.py
python
BaseHTTPRequestHandler.send_error
(self, code, message=None)
Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user.
Send and log an error reply.
[ "Send", "and", "log", "an", "error", "reply", "." ]
def send_error(self, code, message=None): """Send and log an error reply. Arguments are the error code, and a detailed message. The detailed message defaults to the short entry matching the response code. This sends an error response (so it must be called before any output has been generated), logs the error, and finally sends a piece of HTML explaining the error to the user. """ try: shortmsg, longmsg = self.responses[code] except KeyError: shortmsg, longmsg = '???', '???' if message is None: message = shortmsg explain = longmsg self.log_error("code %d, message %s", code, message) # using _quote_html to prevent Cross Site Scripting attacks (see bug #1100201) content = (self.error_message_format % {'code': code, 'message': _quote_html(message), 'explain': explain}) self.send_response(code, message) self.send_header("Content-Type", self.error_content_type) self.send_header('Connection', 'close') self.end_headers() if self.command != 'HEAD' and code >= 200 and code not in (204, 304): self.wfile.write(content.encode('UTF-8', 'replace'))
[ "def", "send_error", "(", "self", ",", "code", ",", "message", "=", "None", ")", ":", "try", ":", "shortmsg", ",", "longmsg", "=", "self", ".", "responses", "[", "code", "]", "except", "KeyError", ":", "shortmsg", ",", "longmsg", "=", "'???'", ",", "...
https://github.com/PythonCharmers/python-future/blob/80523f383fbba1c6de0551e19d0277e73e69573c/src/future/backports/http/server.py#L410-L439
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py
python
StashedUninstallPathSet._get_file_stash
(self, path)
return save_dir.path
Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.
Stashes a file.
[ "Stashes", "a", "file", "." ]
def _get_file_stash(self, path): # type: (str) -> str """Stashes a file. If no root has been provided, one will be created for the directory in the user's temp directory.""" path = os.path.normcase(path) head, old_head = os.path.dirname(path), None save_dir = None while head != old_head: try: save_dir = self._save_dirs[head] break except KeyError: pass head, old_head = os.path.dirname(head), head else: # Did not find any suitable root head = os.path.dirname(path) save_dir = TempDirectory(kind='uninstall') save_dir.create() self._save_dirs[head] = save_dir relpath = os.path.relpath(path, head) if relpath and relpath != os.path.curdir: return os.path.join(save_dir.path, relpath) return save_dir.path
[ "def", "_get_file_stash", "(", "self", ",", "path", ")", ":", "# type: (str) -> str", "path", "=", "os", ".", "path", ".", "normcase", "(", "path", ")", "head", ",", "old_head", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", ",", "None", "...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py#L231-L258
inasafe/inasafe
355eb2ce63f516b9c26af0c86a24f99e53f63f87
safe/gui/tools/minimum_needs/needs_manager_dialog.py
python
NeedsManagerDialog.__init__
(self, parent=None, dock=None)
Constructor for the minimum needs dialog. :param parent: Parent widget of this dialog. :type parent: QWidget :param dock: Dock widget instance that we can notify of changes. :type dock: Dock
Constructor for the minimum needs dialog.
[ "Constructor", "for", "the", "minimum", "needs", "dialog", "." ]
def __init__(self, parent=None, dock=None): """Constructor for the minimum needs dialog. :param parent: Parent widget of this dialog. :type parent: QWidget :param dock: Dock widget instance that we can notify of changes. :type dock: Dock """ QtWidgets.QDialog.__init__(self, parent) # List of parameters with the translated name. self.resource_parameters = { 'Resource name': tr('Resource name'), 'Resource description': tr('Resource description'), 'Unit': tr('Unit'), 'Units': tr('Units'), 'Unit abbreviation': tr('Unit abbreviation'), 'Minimum allowed': tr('Minimum allowed'), 'Maximum allowed': tr('Maximum allowed'), 'Default': tr('Default'), 'Frequency': tr('Frequency'), 'Readable sentence': tr('Readable sentence') } self.setupUi(self) icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.setWindowIcon(QtGui.QIcon(icon)) self.dock = dock # These are in the little button bar at the bottom # 'Remove resource' button # noinspection PyUnresolvedReferences self.remove_resource_button.clicked.connect(self.remove_resource) self.remove_resource_button.setIcon( QIcon(os.path.join( resources_path(), 'img', 'icons', 'remove.svg'))) # Add resource # noinspection PyUnresolvedReferences self.add_resource_button.clicked.connect(self.add_new_resource) self.add_resource_button.setIcon( QIcon(os.path.join( resources_path(), 'img', 'icons', 'add.svg'))) # Edit resource # noinspection PyUnresolvedReferences self.edit_resource_button.clicked.connect(self.edit_resource) self.edit_resource_button.setIcon( QIcon(os.path.join( resources_path(), 'img', 'icons', 'edit.svg'))) # Discard changes to a resource self.discard_changes_button = QPushButton(self.tr('Discard changes')) self.button_box.addButton( self.discard_changes_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.discard_changes_button.clicked.connect(self.discard_changes) # Restore defaults profiles self.restore_defaults_button = QPushButton(self.tr('Restore defaults')) self.button_box.addButton( self.restore_defaults_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.restore_defaults_button.clicked.connect(self.restore_defaults) # Save changes to a resource self.save_resource_button = QPushButton(self.tr('Save resource')) self.button_box.addButton( self.save_resource_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.save_resource_button.clicked.connect(self.save_resource) # Export profile button self.export_profile_button = QPushButton(self.tr('Export ...')) self.button_box.addButton( self.export_profile_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.export_profile_button.clicked.connect(self.export_profile) # Import profile button self.import_profile_button = QPushButton(self.tr('Import ...')) self.button_box.addButton( self.import_profile_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.import_profile_button.clicked.connect(self.import_profile) # New profile button self.new_profile_button = QPushButton(self.tr('New')) self.button_box.addButton( self.new_profile_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.new_profile_button.clicked.connect(self.new_profile) # Save profile button self.save_profile_button = QPushButton(self.tr('Save')) self.button_box.addButton( self.save_profile_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.save_profile_button.clicked.connect(self.save_profile) # 'Save as' profile button self.save_profile_as_button = QPushButton(self.tr('Save as')) self.button_box.addButton( self.save_profile_as_button, QDialogButtonBox.ActionRole) # noinspection PyUnresolvedReferences self.save_profile_as_button.clicked.connect( self.save_profile_as) # Set up things for context help self.help_button = self.button_box.button( QtWidgets.QDialogButtonBox.Help) # Allow toggling the help button self.help_button.setCheckable(True) self.help_button.toggled.connect(self.help_toggled) self.main_stacked_widget.setCurrentIndex(1) self.minimum_needs = NeedsProfile() self.edit_item = None # Remove profile button # noinspection PyUnresolvedReferences self.remove_profile_button.clicked.connect(self.remove_profile) # These are all buttons that will get hidden on context change # to the profile editing view self.profile_editing_buttons = list() self.profile_editing_buttons.append(self.remove_resource_button) self.profile_editing_buttons.append(self.add_resource_button) self.profile_editing_buttons.append(self.edit_resource_button) self.profile_editing_buttons.append(self.export_profile_button) self.profile_editing_buttons.append(self.import_profile_button) self.profile_editing_buttons.append(self.new_profile_button) self.profile_editing_buttons.append(self.save_profile_button) self.profile_editing_buttons.append(self.save_profile_as_button) # We also keep a list of all widgets to disable in context of resource # editing (not hidden, just disabled) self.profile_editing_widgets = self.profile_editing_buttons self.profile_editing_widgets.append(self.remove_profile_button) self.profile_editing_widgets.append(self.profile_combo) # These are all buttons that will get hidden on context change # to the resource editing view self.resource_editing_buttons = list() self.resource_editing_buttons.append(self.discard_changes_button) self.resource_editing_buttons.append(self.save_resource_button) for item in self.resource_editing_buttons: item.hide() self.load_profiles() # Next 2 lines fixes issues #1388 #1389 #1390 #1391 if self.profile_combo.count() > 0: self.select_profile(0) # initial sync profile_combo and resource list self.clear_resource_list() self.populate_resource_list() self.set_up_resource_parameters() # Only do this afterward load_profiles to avoid the resource list # being updated # noinspection PyUnresolvedReferences self.profile_combo.activated.connect(self.select_profile) # noinspection PyUnresolvedReferences self.stacked_widget.currentChanged.connect(self.page_changed) self.select_profile(self.profile_combo.currentIndex())
[ "def", "__init__", "(", "self", ",", "parent", "=", "None", ",", "dock", "=", "None", ")", ":", "QtWidgets", ".", "QDialog", ".", "__init__", "(", "self", ",", "parent", ")", "# List of parameters with the translated name.", "self", ".", "resource_parameters", ...
https://github.com/inasafe/inasafe/blob/355eb2ce63f516b9c26af0c86a24f99e53f63f87/safe/gui/tools/minimum_needs/needs_manager_dialog.py#L57-L217
CozySynthesizer/cozy
d7b2c0ee575057dea4ebec201d579f0ecd785b1b
cozy/codegen/optimization.py
python
histogram
(e : Exp)
return (stm, h)
Compute a histogram of the elements in the iterable `e`. Returns an unoptimized statement that declares and constructs a histogram map and the fresh variable that got declared.
Compute a histogram of the elements in the iterable `e`.
[ "Compute", "a", "histogram", "of", "the", "elements", "in", "the", "iterable", "e", "." ]
def histogram(e : Exp) -> (Stm, EVar): """Compute a histogram of the elements in the iterable `e`. Returns an unoptimized statement that declares and constructs a histogram map and the fresh variable that got declared. """ elem_type = e.type.elem_type h = fresh_var(TMap(elem_type, INT), "histogram") x = fresh_var(elem_type, "x") count = fresh_var(INT, "count") stm = seq([ SDecl(h, EEmptyMap().with_type(h.type)), SForEach(x, e, SMapUpdate(h, x, count, SAssign(count, EBinOp(count, "+", ONE).with_type(INT))))]) return (stm, h)
[ "def", "histogram", "(", "e", ":", "Exp", ")", "->", "(", "Stm", ",", "EVar", ")", ":", "elem_type", "=", "e", ".", "type", ".", "elem_type", "h", "=", "fresh_var", "(", "TMap", "(", "elem_type", ",", "INT", ")", ",", "\"histogram\"", ")", "x", "...
https://github.com/CozySynthesizer/cozy/blob/d7b2c0ee575057dea4ebec201d579f0ecd785b1b/cozy/codegen/optimization.py#L29-L44
bigzhao/Keyword_Extraction
afac907856d46429806f051d75896ac111039b57
jieba/__init__.py
python
Tokenizer.get_dict_file
(self)
[]
def get_dict_file(self): if self.dictionary == DEFAULT_DICT: return get_module_res(DEFAULT_DICT_NAME) else: return open(self.dictionary, 'rb')
[ "def", "get_dict_file", "(", "self", ")", ":", "if", "self", ".", "dictionary", "==", "DEFAULT_DICT", ":", "return", "get_module_res", "(", "DEFAULT_DICT_NAME", ")", "else", ":", "return", "open", "(", "self", ".", "dictionary", ",", "'rb'", ")" ]
https://github.com/bigzhao/Keyword_Extraction/blob/afac907856d46429806f051d75896ac111039b57/jieba/__init__.py#L350-L354
ultrabug/py3status
80ec45a9db0712b0de55f83291c321f6fceb6a6d
py3status/modules/google_calendar.py
python
Py3status._build_response
(self)
return {"events": responses}
Builds the composite response to be output by the module by looping through all events and formatting the necessary strings. Returns: A composite containing the individual response for each event.
Builds the composite response to be output by the module by looping through all events and formatting the necessary strings.
[ "Builds", "the", "composite", "response", "to", "be", "output", "by", "the", "module", "by", "looping", "through", "all", "events", "and", "formatting", "the", "necessary", "strings", "." ]
def _build_response(self): """ Builds the composite response to be output by the module by looping through all events and formatting the necessary strings. Returns: A composite containing the individual response for each event. """ responses = [] self.event_urls = [] for index, event in enumerate(self.events): self.py3.threshold_get_color(index + 1, "event") self.py3.threshold_get_color(index + 1, "time") event_dict = {} event_dict["summary"] = event.get("summary") event_dict["location"] = event.get("location") event_dict["description"] = event.get("description") self.event_urls.append( event.get(self.preferred_event_link, event.get("htmlLink")) ) if event["start"].get("date") is not None: start_dt = self._gstr_to_date(event["start"].get("date")) end_dt = self._gstr_to_date(event["end"].get("date")) else: start_dt = self._gstr_to_datetime(event["start"].get("dateTime")) end_dt = self._gstr_to_datetime(event["end"].get("dateTime")) if end_dt < datetime.datetime.now(tzlocal()): continue event_dict["start_time"] = self._datetime_to_str(start_dt, self.format_time) event_dict["end_time"] = self._datetime_to_str(end_dt, self.format_time) event_dict["start_date"] = self._datetime_to_str(start_dt, self.format_date) event_dict["end_date"] = self._datetime_to_str(end_dt, self.format_date) time_delta = self._delta_time(start_dt) if time_delta["days"] < 0: time_delta = self._delta_time(end_dt) is_current = True else: is_current = False event_dict["format_timer"] = self._format_timedelta( index, time_delta, is_current ) if self.warn_threshold > 0: self._check_warn_threshold(time_delta, event_dict) event_formatted = self.py3.safe_format( self.format_event, { "is_toggled": self.button_states[index], "summary": event_dict["summary"], "location": event_dict["location"], "description": event_dict["description"], "start_time": event_dict["start_time"], "end_time": event_dict["end_time"], "start_date": event_dict["start_date"], "end_date": event_dict["end_date"], "format_timer": event_dict["format_timer"], }, ) self.py3.composite_update(event_formatted, {"index": index}) responses.append(event_formatted) self.no_update = False format_separator = self.py3.safe_format(self.format_separator) self.py3.composite_update(format_separator, {"index": "sep"}) responses = self.py3.composite_join(format_separator, responses) return {"events": responses}
[ "def", "_build_response", "(", "self", ")", ":", "responses", "=", "[", "]", "self", ".", "event_urls", "=", "[", "]", "for", "index", ",", "event", "in", "enumerate", "(", "self", ".", "events", ")", ":", "self", ".", "py3", ".", "threshold_get_color"...
https://github.com/ultrabug/py3status/blob/80ec45a9db0712b0de55f83291c321f6fceb6a6d/py3status/modules/google_calendar.py#L398-L475
hhursev/recipe-scrapers
478b9ddb0dda02b17b14f299eea729bef8131aa9
recipe_scrapers/tasty.py
python
Tasty.instructions
(self)
return self.schema.instructions()
[]
def instructions(self): return self.schema.instructions()
[ "def", "instructions", "(", "self", ")", ":", "return", "self", ".", "schema", ".", "instructions", "(", ")" ]
https://github.com/hhursev/recipe-scrapers/blob/478b9ddb0dda02b17b14f299eea729bef8131aa9/recipe_scrapers/tasty.py#L24-L25
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/logging/__init__.py
python
info
(msg, *args, **kwargs)
Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format.
[ "Log", "a", "message", "with", "severity", "INFO", "on", "the", "root", "logger", ".", "If", "the", "logger", "has", "no", "handlers", "call", "basicConfig", "()", "to", "add", "a", "console", "handler", "with", "a", "pre", "-", "defined", "format", "." ...
def info(msg, *args, **kwargs): """ Log a message with severity 'INFO' on the root logger. If the logger has no handlers, call basicConfig() to add a console handler with a pre-defined format. """ if len(root.handlers) == 0: basicConfig() root.info(msg, *args, **kwargs)
[ "def", "info", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "root", ".", "handlers", ")", "==", "0", ":", "basicConfig", "(", ")", "root", ".", "info", "(", "msg", ",", "*", "args", ",", "*", "*", "kwargs...
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/logging/__init__.py#L1986-L1994
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/hooks/files/git_multimail_upstream.py
python
AnnotatedTagChange.generate_delete_summary
(self, push)
Called when a non-annotated reference is updated.
Called when a non-annotated reference is updated.
[ "Called", "when", "a", "non", "-", "annotated", "reference", "is", "updated", "." ]
def generate_delete_summary(self, push): """Called when a non-annotated reference is updated.""" for line in self.expand_lines(TAG_DELETED_TEMPLATE): yield line yield self.expand(" tag was %(oldrev_short)s\n") yield "\n"
[ "def", "generate_delete_summary", "(", "self", ",", "push", ")", ":", "for", "line", "in", "self", ".", "expand_lines", "(", "TAG_DELETED_TEMPLATE", ")", ":", "yield", "line", "yield", "self", ".", "expand", "(", "\" tag was %(oldrev_short)s\\n\"", ")", "yiel...
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/hooks/files/git_multimail_upstream.py#L1997-L2004
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/bdf/bdf_interface/add_methods.py
python
AddMethods._add_dresp_object
(self, dresp: Union[DRESP1, DRESP2, DRESP3])
adds a DRESP1/DRESP2/DRESP3 object
adds a DRESP1/DRESP2/DRESP3 object
[ "adds", "a", "DRESP1", "/", "DRESP2", "/", "DRESP3", "object" ]
def _add_dresp_object(self, dresp: Union[DRESP1, DRESP2, DRESP3]) -> None: """adds a DRESP1/DRESP2/DRESP3 object""" key = dresp.dresp_id assert key not in self.model.dresps, 'DRESPx=%s old=\n%snew=\n%s' % ( key, self.model.dresps[key], dresp) assert key > 0 self.model.dresps[key] = dresp self.model._type_to_id_map[dresp.type].append(key)
[ "def", "_add_dresp_object", "(", "self", ",", "dresp", ":", "Union", "[", "DRESP1", ",", "DRESP2", ",", "DRESP3", "]", ")", "->", "None", ":", "key", "=", "dresp", ".", "dresp_id", "assert", "key", "not", "in", "self", ".", "model", ".", "dresps", ",...
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/bdf/bdf_interface/add_methods.py#L1397-L1404
morganstanley/treadmill
f18267c665baf6def4374d21170198f63ff1cde4
lib/python/treadmill/presence.py
python
kill_node
(zkclient, node)
Kills app, endpoints, and server node.
Kills app, endpoints, and server node.
[ "Kills", "app", "endpoints", "and", "server", "node", "." ]
def kill_node(zkclient, node): """Kills app, endpoints, and server node.""" _LOGGER.info('killing node: %s', node) try: zkutils.get(zkclient, z.path.server(node)) except kazoo.client.NoNodeError: _LOGGER.info('node does not exist.') return apps = zkclient.get_children(z.path.placement(node)) for app in apps: _LOGGER.info('removing app presence: %s', app) try: manifest = zkutils.get(zkclient, z.path.scheduled(app)) app_presence = EndpointPresence(zkclient, manifest, hostname=node, appname=app) app_presence.unregister_running() app_presence.unregister_endpoints() except kazoo.client.NoNodeError: _LOGGER.info('app %s no longer scheduled.', app) _LOGGER.info('removing server presence: %s', node) unregister_server(zkclient, node)
[ "def", "kill_node", "(", "zkclient", ",", "node", ")", ":", "_LOGGER", ".", "info", "(", "'killing node: %s'", ",", "node", ")", "try", ":", "zkutils", ".", "get", "(", "zkclient", ",", "z", ".", "path", ".", "server", "(", "node", ")", ")", "except"...
https://github.com/morganstanley/treadmill/blob/f18267c665baf6def4374d21170198f63ff1cde4/lib/python/treadmill/presence.py#L224-L248
conan7882/adversarial-autoencoders
4960f252784a7dd2fbe203d7dad65938b57ee9c2
src/helper/trainer.py
python
Trainer.valid_semisupervised_epoch
(self, sess, dataflow, summary_writer=None)
[]
def valid_semisupervised_epoch(self, sess, dataflow, summary_writer=None): dataflow.setup(epoch_val=0, batch_size=dataflow.batch_size) display_name_list = ['cls_loss', 'cls_accuracy'] cur_summary = None step = 0 cls_loss_sum = 0 cls_accuracy_sum = 0 while dataflow.epochs_completed < 1: step += 1 batch_data = dataflow.next_batch_dict() im = batch_data['im'] label = batch_data['label'] cls_loss, cls_accuracy = sess.run( [self._cls_valid_loss_op, self._cls_v_accuracy_op], feed_dict={self._cls_v_model.image: im, self._cls_v_model.label: label}) cls_loss_sum += cls_loss cls_accuracy_sum += cls_accuracy print('[Valid]: ', end='') display(self.global_step, step, [cls_loss_sum, cls_accuracy_sum], display_name_list, 'valid', summary_val=cur_summary, summary_writer=summary_writer)
[ "def", "valid_semisupervised_epoch", "(", "self", ",", "sess", ",", "dataflow", ",", "summary_writer", "=", "None", ")", ":", "dataflow", ".", "setup", "(", "epoch_val", "=", "0", ",", "batch_size", "=", "dataflow", ".", "batch_size", ")", "display_name_list",...
https://github.com/conan7882/adversarial-autoencoders/blob/4960f252784a7dd2fbe203d7dad65938b57ee9c2/src/helper/trainer.py#L90-L117
DxCx/plugin.video.9anime
34358c2f701e5ddf19d3276926374a16f63f7b6a
resources/lib/ui/js2py/es6/babel.py
python
PyJs_anonymous_3992_
(require, module, exports, this, arguments, var=var)
[]
def PyJs_anonymous_3992_(require, module, exports, this, arguments, var=var): var = Scope({u'this':this, u'require':require, u'exports':exports, u'module':module, u'arguments':arguments}, var) var.registers([u'require', u'exports', u'module']) PyJs_Object_3993_ = Js({u'75':Js(8490.0),u'83':Js(383.0),u'107':Js(8490.0),u'115':Js(383.0),u'181':Js(924.0),u'197':Js(8491.0),u'383':Js(83.0),u'452':Js(453.0),u'453':Js(452.0),u'455':Js(456.0),u'456':Js(455.0),u'458':Js(459.0),u'459':Js(458.0),u'497':Js(498.0),u'498':Js(497.0),u'837':Js(8126.0),u'914':Js(976.0),u'917':Js(1013.0),u'920':Js(1012.0),u'921':Js(8126.0),u'922':Js(1008.0),u'924':Js(181.0),u'928':Js(982.0),u'929':Js(1009.0),u'931':Js(962.0),u'934':Js(981.0),u'937':Js(8486.0),u'962':Js(931.0),u'976':Js(914.0),u'977':Js(1012.0),u'981':Js(934.0),u'982':Js(928.0),u'1008':Js(922.0),u'1009':Js(929.0),u'1012':Js([Js(920.0), Js(977.0)]),u'1013':Js(917.0),u'7776':Js(7835.0),u'7835':Js(7776.0),u'8126':Js([Js(837.0), Js(921.0)]),u'8486':Js(937.0),u'8490':Js(75.0),u'8491':Js(197.0),u'66560':Js(66600.0),u'66561':Js(66601.0),u'66562':Js(66602.0),u'66563':Js(66603.0),u'66564':Js(66604.0),u'66565':Js(66605.0),u'66566':Js(66606.0),u'66567':Js(66607.0),u'66568':Js(66608.0),u'66569':Js(66609.0),u'66570':Js(66610.0),u'66571':Js(66611.0),u'66572':Js(66612.0),u'66573':Js(66613.0),u'66574':Js(66614.0),u'66575':Js(66615.0),u'66576':Js(66616.0),u'66577':Js(66617.0),u'66578':Js(66618.0),u'66579':Js(66619.0),u'66580':Js(66620.0),u'66581':Js(66621.0),u'66582':Js(66622.0),u'66583':Js(66623.0),u'66584':Js(66624.0),u'66585':Js(66625.0),u'66586':Js(66626.0),u'66587':Js(66627.0),u'66588':Js(66628.0),u'66589':Js(66629.0),u'66590':Js(66630.0),u'66591':Js(66631.0),u'66592':Js(66632.0),u'66593':Js(66633.0),u'66594':Js(66634.0),u'66595':Js(66635.0),u'66596':Js(66636.0),u'66597':Js(66637.0),u'66598':Js(66638.0),u'66599':Js(66639.0),u'66600':Js(66560.0),u'66601':Js(66561.0),u'66602':Js(66562.0),u'66603':Js(66563.0),u'66604':Js(66564.0),u'66605':Js(66565.0),u'66606':Js(66566.0),u'66607':Js(66567.0),u'66608':Js(66568.0),u'66609':Js(66569.0),u'66610':Js(66570.0),u'66611':Js(66571.0),u'66612':Js(66572.0),u'66613':Js(66573.0),u'66614':Js(66574.0),u'66615':Js(66575.0),u'66616':Js(66576.0),u'66617':Js(66577.0),u'66618':Js(66578.0),u'66619':Js(66579.0),u'66620':Js(66580.0),u'66621':Js(66581.0),u'66622':Js(66582.0),u'66623':Js(66583.0),u'66624':Js(66584.0),u'66625':Js(66585.0),u'66626':Js(66586.0),u'66627':Js(66587.0),u'66628':Js(66588.0),u'66629':Js(66589.0),u'66630':Js(66590.0),u'66631':Js(66591.0),u'66632':Js(66592.0),u'66633':Js(66593.0),u'66634':Js(66594.0),u'66635':Js(66595.0),u'66636':Js(66596.0),u'66637':Js(66597.0),u'66638':Js(66598.0),u'66639':Js(66599.0),u'68736':Js(68800.0),u'68737':Js(68801.0),u'68738':Js(68802.0),u'68739':Js(68803.0),u'68740':Js(68804.0),u'68741':Js(68805.0),u'68742':Js(68806.0),u'68743':Js(68807.0),u'68744':Js(68808.0),u'68745':Js(68809.0),u'68746':Js(68810.0),u'68747':Js(68811.0),u'68748':Js(68812.0),u'68749':Js(68813.0),u'68750':Js(68814.0),u'68751':Js(68815.0),u'68752':Js(68816.0),u'68753':Js(68817.0),u'68754':Js(68818.0),u'68755':Js(68819.0),u'68756':Js(68820.0),u'68757':Js(68821.0),u'68758':Js(68822.0),u'68759':Js(68823.0),u'68760':Js(68824.0),u'68761':Js(68825.0),u'68762':Js(68826.0),u'68763':Js(68827.0),u'68764':Js(68828.0),u'68765':Js(68829.0),u'68766':Js(68830.0),u'68767':Js(68831.0),u'68768':Js(68832.0),u'68769':Js(68833.0),u'68770':Js(68834.0),u'68771':Js(68835.0),u'68772':Js(68836.0),u'68773':Js(68837.0),u'68774':Js(68838.0),u'68775':Js(68839.0),u'68776':Js(68840.0),u'68777':Js(68841.0),u'68778':Js(68842.0),u'68779':Js(68843.0),u'68780':Js(68844.0),u'68781':Js(68845.0),u'68782':Js(68846.0),u'68783':Js(68847.0),u'68784':Js(68848.0),u'68785':Js(68849.0),u'68786':Js(68850.0),u'68800':Js(68736.0),u'68801':Js(68737.0),u'68802':Js(68738.0),u'68803':Js(68739.0),u'68804':Js(68740.0),u'68805':Js(68741.0),u'68806':Js(68742.0),u'68807':Js(68743.0),u'68808':Js(68744.0),u'68809':Js(68745.0),u'68810':Js(68746.0),u'68811':Js(68747.0),u'68812':Js(68748.0),u'68813':Js(68749.0),u'68814':Js(68750.0),u'68815':Js(68751.0),u'68816':Js(68752.0),u'68817':Js(68753.0),u'68818':Js(68754.0),u'68819':Js(68755.0),u'68820':Js(68756.0),u'68821':Js(68757.0),u'68822':Js(68758.0),u'68823':Js(68759.0),u'68824':Js(68760.0),u'68825':Js(68761.0),u'68826':Js(68762.0),u'68827':Js(68763.0),u'68828':Js(68764.0),u'68829':Js(68765.0),u'68830':Js(68766.0),u'68831':Js(68767.0),u'68832':Js(68768.0),u'68833':Js(68769.0),u'68834':Js(68770.0),u'68835':Js(68771.0),u'68836':Js(68772.0),u'68837':Js(68773.0),u'68838':Js(68774.0),u'68839':Js(68775.0),u'68840':Js(68776.0),u'68841':Js(68777.0),u'68842':Js(68778.0),u'68843':Js(68779.0),u'68844':Js(68780.0),u'68845':Js(68781.0),u'68846':Js(68782.0),u'68847':Js(68783.0),u'68848':Js(68784.0),u'68849':Js(68785.0),u'68850':Js(68786.0),u'71840':Js(71872.0),u'71841':Js(71873.0),u'71842':Js(71874.0),u'71843':Js(71875.0),u'71844':Js(71876.0),u'71845':Js(71877.0),u'71846':Js(71878.0),u'71847':Js(71879.0),u'71848':Js(71880.0),u'71849':Js(71881.0),u'71850':Js(71882.0),u'71851':Js(71883.0),u'71852':Js(71884.0),u'71853':Js(71885.0),u'71854':Js(71886.0),u'71855':Js(71887.0),u'71856':Js(71888.0),u'71857':Js(71889.0),u'71858':Js(71890.0),u'71859':Js(71891.0),u'71860':Js(71892.0),u'71861':Js(71893.0),u'71862':Js(71894.0),u'71863':Js(71895.0),u'71864':Js(71896.0),u'71865':Js(71897.0),u'71866':Js(71898.0),u'71867':Js(71899.0),u'71868':Js(71900.0),u'71869':Js(71901.0),u'71870':Js(71902.0),u'71871':Js(71903.0),u'71872':Js(71840.0),u'71873':Js(71841.0),u'71874':Js(71842.0),u'71875':Js(71843.0),u'71876':Js(71844.0),u'71877':Js(71845.0),u'71878':Js(71846.0),u'71879':Js(71847.0),u'71880':Js(71848.0),u'71881':Js(71849.0),u'71882':Js(71850.0),u'71883':Js(71851.0),u'71884':Js(71852.0),u'71885':Js(71853.0),u'71886':Js(71854.0),u'71887':Js(71855.0),u'71888':Js(71856.0),u'71889':Js(71857.0),u'71890':Js(71858.0),u'71891':Js(71859.0),u'71892':Js(71860.0),u'71893':Js(71861.0),u'71894':Js(71862.0),u'71895':Js(71863.0),u'71896':Js(71864.0),u'71897':Js(71865.0),u'71898':Js(71866.0),u'71899':Js(71867.0),u'71900':Js(71868.0),u'71901':Js(71869.0),u'71902':Js(71870.0),u'71903':Js(71871.0)}) var.get(u'module').put(u'exports', PyJs_Object_3993_)
[ "def", "PyJs_anonymous_3992_", "(", "require", ",", "module", ",", "exports", ",", "this", ",", "arguments", ",", "var", "=", "var", ")", ":", "var", "=", "Scope", "(", "{", "u'this'", ":", "this", ",", "u'require'", ":", "require", ",", "u'exports'", ...
https://github.com/DxCx/plugin.video.9anime/blob/34358c2f701e5ddf19d3276926374a16f63f7b6a/resources/lib/ui/js2py/es6/babel.py#L45102-L45106
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/physics/gaussopt.py
python
ThinLens.__new__
(cls, f)
return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
[]
def __new__(cls, f): f = sympify(f) return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
[ "def", "__new__", "(", "cls", ",", "f", ")", ":", "f", "=", "sympify", "(", "f", ")", "return", "RayTransferMatrix", ".", "__new__", "(", "cls", ",", "1", ",", "0", ",", "-", "1", "/", "f", ",", "1", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/physics/gaussopt.py#L349-L351
toastdriven/restless
ce18b02886cce6d182d60661cb5c2eeeac215cf6
restless/fl.py
python
FlaskResource.build_endpoint_name
(cls, name, endpoint_prefix=None)
return '_'.join([endpoint_prefix, name])
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name for a URL. :param name: The name for the URL (ex. 'detail') :type name: string :param endpoint_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate a prefix based on the class name. Ex: ``BlogPostResource`` -> ``api_blogpost_list`` :type endpoint_prefix: string :returns: The final name :rtype: string
Given a ``name`` & an optional ``endpoint_prefix``, this generates a name for a URL.
[ "Given", "a", "name", "&", "an", "optional", "endpoint_prefix", "this", "generates", "a", "name", "for", "a", "URL", "." ]
def build_endpoint_name(cls, name, endpoint_prefix=None): """ Given a ``name`` & an optional ``endpoint_prefix``, this generates a name for a URL. :param name: The name for the URL (ex. 'detail') :type name: string :param endpoint_prefix: (Optional) A prefix for the URL's name (for resolving). The default is ``None``, which will autocreate a prefix based on the class name. Ex: ``BlogPostResource`` -> ``api_blogpost_list`` :type endpoint_prefix: string :returns: The final name :rtype: string """ if endpoint_prefix is None: endpoint_prefix = 'api_{}'.format( cls.__name__.replace('Resource', '').lower() ) endpoint_prefix = endpoint_prefix.rstrip('_') return '_'.join([endpoint_prefix, name])
[ "def", "build_endpoint_name", "(", "cls", ",", "name", ",", "endpoint_prefix", "=", "None", ")", ":", "if", "endpoint_prefix", "is", "None", ":", "endpoint_prefix", "=", "'api_{}'", ".", "format", "(", "cls", ".", "__name__", ".", "replace", "(", "'Resource'...
https://github.com/toastdriven/restless/blob/ce18b02886cce6d182d60661cb5c2eeeac215cf6/restless/fl.py#L59-L82
aiven/pghoard
1de0d2e33bf087b7ce3b6af556bbf941acfac3a4
pghoard/fetcher.py
python
FileFetchManager.__init__
(self, app_config, mp_manager, transfer_provider)
[]
def __init__(self, app_config, mp_manager, transfer_provider): self.config = app_config self.last_activity = time.monotonic() self.lock = threading.RLock() self.max_idle_age = 10 * 60 self.mp_manager = mp_manager self.process = None self.result_queue = None self.task_queue = None self.transfer_provider = transfer_provider
[ "def", "__init__", "(", "self", ",", "app_config", ",", "mp_manager", ",", "transfer_provider", ")", ":", "self", ".", "config", "=", "app_config", "self", ".", "last_activity", "=", "time", ".", "monotonic", "(", ")", "self", ".", "lock", "=", "threading"...
https://github.com/aiven/pghoard/blob/1de0d2e33bf087b7ce3b6af556bbf941acfac3a4/pghoard/fetcher.py#L19-L28
Netflix/security_monkey
c28592ffd518fa399527d26262683fc860c30eef
security_monkey/watchers/elastic_ip.py
python
ElasticIP.slurp
(self)
return item_list, exception_map
:returns: item_list - list of Elastic IPs. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception
:returns: item_list - list of Elastic IPs. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception
[ ":", "returns", ":", "item_list", "-", "list", "of", "Elastic", "IPs", ".", ":", "returns", ":", "exception_map", "-", "A", "dict", "where", "the", "keys", "are", "a", "tuple", "containing", "the", "location", "of", "the", "exception", "and", "the", "val...
def slurp(self): """ :returns: item_list - list of Elastic IPs. :returns: exception_map - A dict where the keys are a tuple containing the location of the exception and the value is the actual exception """ self.prep_for_slurp() item_list = [] exception_map = {} from security_monkey.common.sts_connect import connect for account in self.accounts: try: ec2 = connect(account, 'ec2') regions = ec2.get_all_regions() except Exception as e: # EC2ResponseError # Some Accounts don't subscribe to EC2 and will throw an exception here. exc = BotoConnectionIssue(str(e), self.index, account, None) self.slurp_exception((self.index, account), exc, exception_map, source="{}-watcher".format(self.index)) continue for region in regions: app.logger.debug("Checking {}/{}/{}".format(self.index, account, region.name)) try: rec2 = connect(account, 'boto3.ec2.client', region=region) el_ips = self.wrap_aws_rate_limited_call( rec2.describe_addresses ) # Retrieve account tags to later match assigned EIP to instance tags = self.wrap_aws_rate_limited_call( rec2.describe_tags ) except Exception as e: if region.name not in TROUBLE_REGIONS: exc = BotoConnectionIssue(str(e), self.index, account, region.name) self.slurp_exception((self.index, account, region.name), exc, exception_map, source="{}-watcher".format(self.index)) continue app.logger.debug("Found {} {}".format(len(el_ips), self.i_am_plural)) for ip in el_ips['Addresses']: if self.check_ignore_list(str(ip['PublicIp'])): continue instance_name = None instance_tags = [x['Value'] for x in tags['Tags'] if x['Key'] == "Name" and x.get('ResourceId') == ip.get('InstanceId')] if instance_tags: (instance_name,) = instance_tags if self.check_ignore_list(instance_name): continue item_config = { "assigned_to": instance_name, "public_ip": ip.get('PublicIp'), "instance_id": ip.get('InstanceId'), "domain": ip.get('Domain'), "allocation_id": ip.get('AllocationId'), "association_id": ip.get('AssociationId'), "network_interface_id": ip.get('NetworkInterfaceId'), "network_interface_owner_id": ip.get('NetworkInterfaceOwnerId'), "private_ip_address": ip.get('PrivateIpAddress') } ip_label = "{0}".format(ip.get('PublicIp')) item = ElasticIPItem(region=region.name, account=account, name=ip_label, config=item_config, source_watcher=self) item_list.append(item) return item_list, exception_map
[ "def", "slurp", "(", "self", ")", ":", "self", ".", "prep_for_slurp", "(", ")", "item_list", "=", "[", "]", "exception_map", "=", "{", "}", "from", "security_monkey", ".", "common", ".", "sts_connect", "import", "connect", "for", "account", "in", "self", ...
https://github.com/Netflix/security_monkey/blob/c28592ffd518fa399527d26262683fc860c30eef/security_monkey/watchers/elastic_ip.py#L46-L119
F8LEFT/DecLLVM
d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c
python/idaapi.py
python
term_output_buffer
(*args)
return _idaapi.term_output_buffer(*args)
term_output_buffer() Use this function to terminate an output buffer.
term_output_buffer()
[ "term_output_buffer", "()" ]
def term_output_buffer(*args): """ term_output_buffer() Use this function to terminate an output buffer. """ return _idaapi.term_output_buffer(*args)
[ "def", "term_output_buffer", "(", "*", "args", ")", ":", "return", "_idaapi", ".", "term_output_buffer", "(", "*", "args", ")" ]
https://github.com/F8LEFT/DecLLVM/blob/d38e45e3d0dd35634adae1d0cf7f96f3bd96e74c/python/idaapi.py#L49387-L49394
spender-sandbox/cuckoo-modified
eb93ef3d41b8fee51b4330306dcd315d8101e021
lib/cuckoo/common/abstracts.py
python
Signature.check_ip
(self, pattern, regex=False, all=False)
return None
Checks for an IP address being contacted. @param pattern: string or expression to check for. @param regex: boolean representing if the pattern is a regular expression or not and therefore should be compiled. @param all: boolean representing if all results should be returned in a set or not @return: depending on the value of param 'all', either a set of matched items or the first matched item
Checks for an IP address being contacted.
[ "Checks", "for", "an", "IP", "address", "being", "contacted", "." ]
def check_ip(self, pattern, regex=False, all=False): """Checks for an IP address being contacted. @param pattern: string or expression to check for. @param regex: boolean representing if the pattern is a regular expression or not and therefore should be compiled. @param all: boolean representing if all results should be returned in a set or not @return: depending on the value of param 'all', either a set of matched items or the first matched item """ if all: retset = set() if not "network" in self.results: return None hosts = self.results["network"].get("hosts") if not hosts: return None for item in hosts: ret = self._check_value(pattern=pattern, subject=item["ip"], regex=regex, all=all, ignorecase=False) if ret: if all: retset.update(ret) else: return item["ip"] if all and len(retset) > 0: return retset return None
[ "def", "check_ip", "(", "self", ",", "pattern", ",", "regex", "=", "False", ",", "all", "=", "False", ")", ":", "if", "all", ":", "retset", "=", "set", "(", ")", "if", "not", "\"network\"", "in", "self", ".", "results", ":", "return", "None", "host...
https://github.com/spender-sandbox/cuckoo-modified/blob/eb93ef3d41b8fee51b4330306dcd315d8101e021/lib/cuckoo/common/abstracts.py#L1083-L1119
MobileChromeApps/mobile-chrome-apps
ab60c264e23624917a8ac9973d43a0b44e5f96c4
chrome-cordova/gcmServer/xmpp/protocol.py
python
Presence.__init__
(self, to=None, typ=None, priority=None, show=None, status=None, attrs={}, frm=None, timestamp=None, payload=[], xmlns=NS_CLIENT, node=None)
Create presence object. You can specify recipient, type of message, priority, show and status values any additional attributes, sender of the presence, timestamp, any additional payload (f.e. jabber:x:delay element) and namespace in one go. Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as presence.
Create presence object. You can specify recipient, type of message, priority, show and status values any additional attributes, sender of the presence, timestamp, any additional payload (f.e. jabber:x:delay element) and namespace in one go. Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as presence.
[ "Create", "presence", "object", ".", "You", "can", "specify", "recipient", "type", "of", "message", "priority", "show", "and", "status", "values", "any", "additional", "attributes", "sender", "of", "the", "presence", "timestamp", "any", "additional", "payload", ...
def __init__(self, to=None, typ=None, priority=None, show=None, status=None, attrs={}, frm=None, timestamp=None, payload=[], xmlns=NS_CLIENT, node=None): """ Create presence object. You can specify recipient, type of message, priority, show and status values any additional attributes, sender of the presence, timestamp, any additional payload (f.e. jabber:x:delay element) and namespace in one go. Alternatively you can pass in the other XML object as the 'node' parameted to replicate it as presence. """ Protocol.__init__(self, 'presence', to=to, typ=typ, attrs=attrs, frm=frm, payload=payload, timestamp=timestamp, xmlns=xmlns, node=node) if priority: self.setPriority(priority) if show: self.setShow(show) if status: self.setStatus(status)
[ "def", "__init__", "(", "self", ",", "to", "=", "None", ",", "typ", "=", "None", ",", "priority", "=", "None", ",", "show", "=", "None", ",", "status", "=", "None", ",", "attrs", "=", "{", "}", ",", "frm", "=", "None", ",", "timestamp", "=", "N...
https://github.com/MobileChromeApps/mobile-chrome-apps/blob/ab60c264e23624917a8ac9973d43a0b44e5f96c4/chrome-cordova/gcmServer/xmpp/protocol.py#L451-L458
matrix-org/sydent
14a4993c8756c51c874a766a5229730309322b2e
sydent/http/servlets/store_invite_servlet.py
python
StoreInviteServlet.redact_email_address
(self, address: str)
return redacted_username + "@" + redacted_domain
Redacts the content of a 3PID address. Redacts both the email's username and domain independently. :param address: The address to redact. :return: The redacted address.
Redacts the content of a 3PID address. Redacts both the email's username and domain independently.
[ "Redacts", "the", "content", "of", "a", "3PID", "address", ".", "Redacts", "both", "the", "email", "s", "username", "and", "domain", "independently", "." ]
def redact_email_address(self, address: str) -> str: """ Redacts the content of a 3PID address. Redacts both the email's username and domain independently. :param address: The address to redact. :return: The redacted address. """ # Extract strings from the address username, domain = address.split("@", 1) # Obfuscate strings redacted_username = self._redact( username, self.sydent.config.email.username_obfuscate_characters ) redacted_domain = self._redact( domain, self.sydent.config.email.domain_obfuscate_characters ) return redacted_username + "@" + redacted_domain
[ "def", "redact_email_address", "(", "self", ",", "address", ":", "str", ")", "->", "str", ":", "# Extract strings from the address", "username", ",", "domain", "=", "address", ".", "split", "(", "\"@\"", ",", "1", ")", "# Obfuscate strings", "redacted_username", ...
https://github.com/matrix-org/sydent/blob/14a4993c8756c51c874a766a5229730309322b2e/sydent/http/servlets/store_invite_servlet.py#L206-L226
robbievanleeuwen/section-properties
ce5f014937c07cb9479136bbed00816a4f7f1d48
sectionproperties/post/post.py
python
setup_plot
(pause)
Executes code required to set up a matplotlib figure. :param bool pause: If set to true, the figure pauses the script until the window is closed. If set to false, the script continues immediately after the window is rendered.
Executes code required to set up a matplotlib figure.
[ "Executes", "code", "required", "to", "set", "up", "a", "matplotlib", "figure", "." ]
def setup_plot(pause): """Executes code required to set up a matplotlib figure. :param bool pause: If set to true, the figure pauses the script until the window is closed. If set to false, the script continues immediately after the window is rendered. """ if not pause: plt.ion() plt.show() else: plt.ioff()
[ "def", "setup_plot", "(", "pause", ")", ":", "if", "not", "pause", ":", "plt", ".", "ion", "(", ")", "plt", ".", "show", "(", ")", "else", ":", "plt", ".", "ioff", "(", ")" ]
https://github.com/robbievanleeuwen/section-properties/blob/ce5f014937c07cb9479136bbed00816a4f7f1d48/sectionproperties/post/post.py#L5-L16
kapicorp/kapitan
ad925478023f8b7a0ccc99762b77babf1064a8df
kapitan/resources.py
python
gzip_b64
(obj)
return base64.b64encode(compressed_obj).decode("UTF-8")
returns base64-encoded gzip-compressed obj
returns base64-encoded gzip-compressed obj
[ "returns", "base64", "-", "encoded", "gzip", "-", "compressed", "obj" ]
def gzip_b64(obj): """returns base64-encoded gzip-compressed obj""" obj_bytes = obj.encode("UTF-8") buf = io.BytesIO() with gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=9, mtime=0) as f: f.write(obj_bytes) compressed_obj = buf.getvalue() return base64.b64encode(compressed_obj).decode("UTF-8")
[ "def", "gzip_b64", "(", "obj", ")", ":", "obj_bytes", "=", "obj", ".", "encode", "(", "\"UTF-8\"", ")", "buf", "=", "io", ".", "BytesIO", "(", ")", "with", "gzip", ".", "GzipFile", "(", "fileobj", "=", "buf", ",", "mode", "=", "\"wb\"", ",", "compr...
https://github.com/kapicorp/kapitan/blob/ad925478023f8b7a0ccc99762b77babf1064a8df/kapitan/resources.py#L93-L100
thomasvs/morituri
135b2f7bf27721177e3aeb1d26403f1b29116599
morituri/program/cdrdao.py
python
DiscInfoTask.__init__
(self, device=None)
@param device: the device to rip from @type device: str
[]
def __init__(self, device=None): """ @param device: the device to rip from @type device: str """ self.debug('creating DiscInfoTask for device %r', device) CDRDAOTask.__init__(self) self.options = ['disk-info', ] if device: self.options.extend(['--device', device, ]) self.parser = LineParser(self)
[ "def", "__init__", "(", "self", ",", "device", "=", "None", ")", ":", "self", ".", "debug", "(", "'creating DiscInfoTask for device %r'", ",", "device", ")", "CDRDAOTask", ".", "__init__", "(", "self", ")", "self", ".", "options", "=", "[", "'disk-info'", ...
https://github.com/thomasvs/morituri/blob/135b2f7bf27721177e3aeb1d26403f1b29116599/morituri/program/cdrdao.py#L288-L300
shiweibsw/Translation-Tools
2fbbf902364e557fa7017f9a74a8797b7440c077
venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py
python
ResourceManager.resource_isdir
(self, package_or_requirement, resource_name)
return get_provider(package_or_requirement).resource_isdir( resource_name )
Is the named resource an existing directory?
Is the named resource an existing directory?
[ "Is", "the", "named", "resource", "an", "existing", "directory?" ]
def resource_isdir(self, package_or_requirement, resource_name): """Is the named resource an existing directory?""" return get_provider(package_or_requirement).resource_isdir( resource_name )
[ "def", "resource_isdir", "(", "self", ",", "package_or_requirement", ",", "resource_name", ")", ":", "return", "get_provider", "(", "package_or_requirement", ")", ".", "resource_isdir", "(", "resource_name", ")" ]
https://github.com/shiweibsw/Translation-Tools/blob/2fbbf902364e557fa7017f9a74a8797b7440c077/venv/Lib/site-packages/pip-9.0.3-py3.6.egg/pip/_vendor/pkg_resources/__init__.py#L1194-L1198
harry159821/XiamiForLinuxProject
93d75d7652548d02ba386c961bc8afb5550a530e
PIL/TiffImagePlugin.py
python
TiffImageFile._load_libtiff
(self)
return Image.Image.load(self)
Overload method triggered when we detect a g3/g4 tiff Calls out to lib tiff
Overload method triggered when we detect a g3/g4 tiff Calls out to lib tiff
[ "Overload", "method", "triggered", "when", "we", "detect", "a", "g3", "/", "g4", "tiff", "Calls", "out", "to", "lib", "tiff" ]
def _load_libtiff(self): """ Overload method triggered when we detect a g3/g4 tiff Calls out to lib tiff """ pixel = Image.Image.load(self) if self.tile is None: raise IOError("cannot load this image") if not self.tile: return pixel self.load_prepare() if not len(self.tile) == 1: raise IOError("Not exactly one tile") d, e, o, a = self.tile[0] d = Image._getdecoder(self.mode, d, a, self.decoderconfig) try: d.setimage(self.im, e) except ValueError: raise IOError("Couldn't set the image") if hasattr(self.fp, "getvalue"): # We've got a stringio like thing passed in. Yay for all in memory. # The decoder needs the entire file in one shot, so there's not # a lot we can do here other than give it the entire file. # unless we could do something like get the address of the underlying # string for stringio. # # Rearranging for supporting byteio items, since they have a fileno # that returns an IOError if there's no underlying fp. Easier to deal # with here by reordering. if Image.DEBUG: print ("have getvalue. just sending in a string from getvalue") n,e = d.decode(self.fp.getvalue()) elif hasattr(self.fp, "fileno"): # we've got a actual file on disk, pass in the fp. if Image.DEBUG: print ("have fileno, calling fileno version of the decoder.") self.fp.seek(0) n,e = d.decode(b"fpfp") # 4 bytes, otherwise the trace might error out else: # we have something else. if Image.DEBUG: print ("don't have fileno or getvalue. just reading") # UNDONE -- so much for that buffer size thing. n, e = d.decode(self.fp.read()) self.tile = [] self.readonly = 0 self.fp = None # might be shared if e < 0: raise IOError(e) self.load_end() return Image.Image.load(self)
[ "def", "_load_libtiff", "(", "self", ")", ":", "pixel", "=", "Image", ".", "Image", ".", "load", "(", "self", ")", "if", "self", ".", "tile", "is", "None", ":", "raise", "IOError", "(", "\"cannot load this image\"", ")", "if", "not", "self", ".", "tile...
https://github.com/harry159821/XiamiForLinuxProject/blob/93d75d7652548d02ba386c961bc8afb5550a530e/PIL/TiffImagePlugin.py#L617-L676
elbayadm/attn2d
982653439dedc7306e484e00b3dfb90e2cd7c9e1
examples/pervasive/modules/archive/densenet_cascade.py
python
_DenseLayer.forward
(self, prev_features, encoder_mask=None, decoder_mask=None, incremental_state=None)
return x
Memory efficient forward pass with checkpointing Each DenseLayer splits its forward into: - bottleneck_function - therest_function Prev_features as list of features in (B, C, Tt, Ts) Returns the new features alone (B, g, Tt, Ts)
Memory efficient forward pass with checkpointing Each DenseLayer splits its forward into: - bottleneck_function - therest_function Prev_features as list of features in (B, C, Tt, Ts) Returns the new features alone (B, g, Tt, Ts)
[ "Memory", "efficient", "forward", "pass", "with", "checkpointing", "Each", "DenseLayer", "splits", "its", "forward", "into", ":", "-", "bottleneck_function", "-", "therest_function", "Prev_features", "as", "list", "of", "features", "in", "(", "B", "C", "Tt", "Ts...
def forward(self, prev_features, encoder_mask=None, decoder_mask=None, incremental_state=None): """ Memory efficient forward pass with checkpointing Each DenseLayer splits its forward into: - bottleneck_function - therest_function Prev_features as list of features in (B, C, Tt, Ts) Returns the new features alone (B, g, Tt, Ts) """ if self.memory_efficient and any( prev_feature.requires_grad for prev_feature in prev_features ): # Does not keep intermediate values, # but recompute them in the backward pass: # tradeoff btw memory & compute x = cp.checkpoint( self.bottleneck_function, *prev_features ) else: x = self.bottleneck_function(*prev_features) x = self.mconv2(x, incremental_state) if encoder_mask is not None: x = x.masked_fill(encoder_mask.unsqueeze(1).unsqueeze(1), 0) if decoder_mask is not None: x = x.masked_fill(decoder_mask.unsqueeze(1).unsqueeze(-1), 0) if self.drop_rate: x = F.dropout(x, p=self.drop_rate, training=self.training) return x
[ "def", "forward", "(", "self", ",", "prev_features", ",", "encoder_mask", "=", "None", ",", "decoder_mask", "=", "None", ",", "incremental_state", "=", "None", ")", ":", "if", "self", ".", "memory_efficient", "and", "any", "(", "prev_feature", ".", "requires...
https://github.com/elbayadm/attn2d/blob/982653439dedc7306e484e00b3dfb90e2cd7c9e1/examples/pervasive/modules/archive/densenet_cascade.py#L114-L147