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
glutanimate/review-heatmap
c758478125b60a81c66c87c35b12b7968ec0a348
src/review_heatmap/libaddon/config/manager_old.py
python
ConfigManager.save
(self, storage_name=None, profile_unload=False, reset=False)
Write config values to their corresponding storages. Automatically fires a reset event if reset_req=True. Keyword Arguments: storage_name {str} -- Storage to save. Saves all storages if left blank (default: {None}). profile_unload {bool} -- whether save has been triggered on profile unload reset {bool} -- whether to reset mw upon save (overwrites reset_req instance attribute)
Write config values to their corresponding storages.
[ "Write", "config", "values", "to", "their", "corresponding", "storages", "." ]
def save(self, storage_name=None, profile_unload=False, reset=False): """ Write config values to their corresponding storages. Automatically fires a reset event if reset_req=True. Keyword Arguments: storage_name {str} -- Storage to save. Saves all storages if left blank (default: {None}). profile_unload {bool} -- whether save has been triggered on profile unload reset {bool} -- whether to reset mw upon save (overwrites reset_req instance attribute) """ if storage_name: storages = [storage_name] # limit to specific storage else: storages = self._storages for name in storages: self._checkStorage(name) saver = getattr(self, "_save" + name.capitalize()) saver(self._config[name]) self._storages[name]["dirty"] = False self.afterSave(reset=reset, profile_unload=profile_unload)
[ "def", "save", "(", "self", ",", "storage_name", "=", "None", ",", "profile_unload", "=", "False", ",", "reset", "=", "False", ")", ":", "if", "storage_name", ":", "storages", "=", "[", "storage_name", "]", "# limit to specific storage", "else", ":", "storag...
https://github.com/glutanimate/review-heatmap/blob/c758478125b60a81c66c87c35b12b7968ec0a348/src/review_heatmap/libaddon/config/manager_old.py#L224-L249
openelections/openelections-core
3c516d8c4cf1166b1868b738a248d48f3378c525
openelex/base/datasource.py
python
BaseDatasource._counties
(self)
Retrieve jurisdictional mappings for a state's counties. Returns: A list of dictionaries containing jurisdiction metadata, as returned by ``jurisdictional_mappings()``.
Retrieve jurisdictional mappings for a state's counties.
[ "Retrieve", "jurisdictional", "mappings", "for", "a", "state", "s", "counties", "." ]
def _counties(self): """ Retrieve jurisdictional mappings for a state's counties. Returns: A list of dictionaries containing jurisdiction metadata, as returned by ``jurisdictional_mappings()``. """ try: return self._cached_counties except AttributeError: county_ocd_re = re.compile(r'ocd-division/country:us/state:' + self.state.lower() + r'/county:[^/]+$') self._cached_counties = [m for m in self.jurisdiction_mappings() if county_ocd_re.match(m['ocd_id'])] return self._cached_counties
[ "def", "_counties", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_cached_counties", "except", "AttributeError", ":", "county_ocd_re", "=", "re", ".", "compile", "(", "r'ocd-division/country:us/state:'", "+", "self", ".", "state", ".", "lower", "(...
https://github.com/openelections/openelections-core/blob/3c516d8c4cf1166b1868b738a248d48f3378c525/openelex/base/datasource.py#L252-L268
rhinstaller/anaconda
63edc8680f1b05cbfe11bef28703acba808c5174
pyanaconda/modules/storage/disk_initialization/initialization.py
python
DiskInitializationModule.initialize_labels_enabled
(self)
return self._initialize_labels_enabled
Can be the disk label initialized to the default for your architecture?
Can be the disk label initialized to the default for your architecture?
[ "Can", "be", "the", "disk", "label", "initialized", "to", "the", "default", "for", "your", "architecture?" ]
def initialize_labels_enabled(self): """Can be the disk label initialized to the default for your architecture?""" return self._initialize_labels_enabled
[ "def", "initialize_labels_enabled", "(", "self", ")", ":", "return", "self", ".", "_initialize_labels_enabled" ]
https://github.com/rhinstaller/anaconda/blob/63edc8680f1b05cbfe11bef28703acba808c5174/pyanaconda/modules/storage/disk_initialization/initialization.py#L228-L230
pybrain/pybrain
dcdf32ba1805490cefbc0bdeb227260d304fdb42
pybrain/rl/environments/twoplayergames/capturegame.py
python
CaptureGame._iterPos
(self)
an iterator over all the positions of the board.
an iterator over all the positions of the board.
[ "an", "iterator", "over", "all", "the", "positions", "of", "the", "board", "." ]
def _iterPos(self): """ an iterator over all the positions of the board. """ for i in range(self.size): for j in range(self.size): yield (i, j)
[ "def", "_iterPos", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "size", ")", ":", "for", "j", "in", "range", "(", "self", ".", "size", ")", ":", "yield", "(", "i", ",", "j", ")" ]
https://github.com/pybrain/pybrain/blob/dcdf32ba1805490cefbc0bdeb227260d304fdb42/pybrain/rl/environments/twoplayergames/capturegame.py#L29-L33
shunsukesaito/PIFu
02a6d8643d3267d06cb4a510b30a59e7e07255de
lib/model/BasePIFuNet.py
python
BasePIFuNet.forward
(self, points, images, calibs, transforms=None)
return self.get_preds()
:param points: [B, 3, N] world space coordinates of points :param images: [B, C, H, W] input images :param calibs: [B, 3, 4] calibration matrices for each image :param transforms: Optional [B, 2, 3] image space coordinate transforms :return: [B, Res, N] predictions for each point
:param points: [B, 3, N] world space coordinates of points :param images: [B, C, H, W] input images :param calibs: [B, 3, 4] calibration matrices for each image :param transforms: Optional [B, 2, 3] image space coordinate transforms :return: [B, Res, N] predictions for each point
[ ":", "param", "points", ":", "[", "B", "3", "N", "]", "world", "space", "coordinates", "of", "points", ":", "param", "images", ":", "[", "B", "C", "H", "W", "]", "input", "images", ":", "param", "calibs", ":", "[", "B", "3", "4", "]", "calibratio...
def forward(self, points, images, calibs, transforms=None): ''' :param points: [B, 3, N] world space coordinates of points :param images: [B, C, H, W] input images :param calibs: [B, 3, 4] calibration matrices for each image :param transforms: Optional [B, 2, 3] image space coordinate transforms :return: [B, Res, N] predictions for each point ''' self.filter(images) self.query(points, calibs, transforms) return self.get_preds()
[ "def", "forward", "(", "self", ",", "points", ",", "images", ",", "calibs", ",", "transforms", "=", "None", ")", ":", "self", ".", "filter", "(", "images", ")", "self", ".", "query", "(", "points", ",", "calibs", ",", "transforms", ")", "return", "se...
https://github.com/shunsukesaito/PIFu/blob/02a6d8643d3267d06cb4a510b30a59e7e07255de/lib/model/BasePIFuNet.py#L30-L40
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/pycparser-2.18/pycparser/c_lexer.py
python
CLexer.t_ppline_NEWLINE
(self, t)
r'\n
r'\n
[ "r", "\\", "n" ]
def t_ppline_NEWLINE(self, t): r'\n' if self.pp_line is None: self._error('line number missing in #line', t) else: self.lexer.lineno = int(self.pp_line) if self.pp_filename is not None: self.filename = self.pp_filename t.lexer.begin('INITIAL')
[ "def", "t_ppline_NEWLINE", "(", "self", ",", "t", ")", ":", "if", "self", ".", "pp_line", "is", "None", ":", "self", ".", "_error", "(", "'line number missing in #line'", ",", "t", ")", "else", ":", "self", ".", "lexer", ".", "lineno", "=", "int", "(",...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/pycparser-2.18/pycparser/c_lexer.py#L277-L287
openedx/edx-platform
68dd185a0ab45862a2a61e0f803d7e03d2be71b5
lms/djangoapps/lms_xblock/runtime.py
python
UserTagsService.set_tag
(self, scope, key, value)
return user_course_tag_api.set_course_tag( self._user, self._course_id, key, value )
Set the user tag for the current course and the current user for a given key scope: the current scope of the runtime key: the key that to the value to be set value: the value to set
Set the user tag for the current course and the current user for a given key
[ "Set", "the", "user", "tag", "for", "the", "current", "course", "and", "the", "current", "user", "for", "a", "given", "key" ]
def set_tag(self, scope, key, value): """ Set the user tag for the current course and the current user for a given key scope: the current scope of the runtime key: the key that to the value to be set value: the value to set """ if scope != user_course_tag_api.COURSE_SCOPE: raise ValueError(f"unexpected scope {scope}") return user_course_tag_api.set_course_tag( self._user, self._course_id, key, value )
[ "def", "set_tag", "(", "self", ",", "scope", ",", "key", ",", "value", ")", ":", "if", "scope", "!=", "user_course_tag_api", ".", "COURSE_SCOPE", ":", "raise", "ValueError", "(", "f\"unexpected scope {scope}\"", ")", "return", "user_course_tag_api", ".", "set_co...
https://github.com/openedx/edx-platform/blob/68dd185a0ab45862a2a61e0f803d7e03d2be71b5/lms/djangoapps/lms_xblock/runtime.py#L120-L134
balanced/status.balancedpayments.com
e51a371079a8fa215732be3cfa57497a9d113d35
venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/command/easy_install.py
python
easy_install.expand_basedirs
(self)
Calls `os.path.expanduser` on install_base, install_platbase and root.
Calls `os.path.expanduser` on install_base, install_platbase and root.
[ "Calls", "os", ".", "path", ".", "expanduser", "on", "install_base", "install_platbase", "and", "root", "." ]
def expand_basedirs(self): """Calls `os.path.expanduser` on install_base, install_platbase and root.""" self._expand_attrs(['install_base', 'install_platbase', 'root'])
[ "def", "expand_basedirs", "(", "self", ")", ":", "self", ".", "_expand_attrs", "(", "[", "'install_base'", ",", "'install_platbase'", ",", "'root'", "]", ")" ]
https://github.com/balanced/status.balancedpayments.com/blob/e51a371079a8fa215732be3cfa57497a9d113d35/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/command/easy_install.py#L342-L345
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
build/builder/core/makepyo.py
python
remove_cache
(path)
[]
def remove_cache(path): for parent, dir_list, file_list in os.walk(path): for d in dir_list: d = d.lower() if d == '__pycache__': utils.remove(os.path.join(parent, d)) continue remove_cache(os.path.join(parent, d))
[ "def", "remove_cache", "(", "path", ")", ":", "for", "parent", ",", "dir_list", ",", "file_list", "in", "os", ".", "walk", "(", "path", ")", ":", "for", "d", "in", "dir_list", ":", "d", "=", "d", ".", "lower", "(", ")", "if", "d", "==", "'__pycac...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/build/builder/core/makepyo.py#L45-L52
basho/riak-python-client
91de13a16607cdf553d1a194e762734e3bec4231
riak/client/__init__.py
python
RiakClient.get_decoder
(self, content_type)
return self._decoders.get(content_type)
Get the decoding function for the provided content type. :param content_type: the requested media type :type content_type: str :rtype: function
Get the decoding function for the provided content type.
[ "Get", "the", "decoding", "function", "for", "the", "provided", "content", "type", "." ]
def get_decoder(self, content_type): """ Get the decoding function for the provided content type. :param content_type: the requested media type :type content_type: str :rtype: function """ return self._decoders.get(content_type)
[ "def", "get_decoder", "(", "self", ",", "content_type", ")", ":", "return", "self", ".", "_decoders", ".", "get", "(", "content_type", ")" ]
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/client/__init__.py#L224-L232
JustGlowing/minisom
a4e519f84cb171c164517f1e7d05c42e29a2f169
minisom.py
python
MiniSom.topographic_error
(self, data)
return (distance > t).mean()
Returns the topographic error computed by finding the best-matching and second-best-matching neuron in the map for each input and then evaluating the positions. A sample for which these two nodes are not adjacent counts as an error. The topographic error is given by the the total number of errors divided by the total of samples. If the topographic error is 0, no error occurred. If 1, the topology was not preserved for any of the samples.
Returns the topographic error computed by finding the best-matching and second-best-matching neuron in the map for each input and then evaluating the positions.
[ "Returns", "the", "topographic", "error", "computed", "by", "finding", "the", "best", "-", "matching", "and", "second", "-", "best", "-", "matching", "neuron", "in", "the", "map", "for", "each", "input", "and", "then", "evaluating", "the", "positions", "." ]
def topographic_error(self, data): """Returns the topographic error computed by finding the best-matching and second-best-matching neuron in the map for each input and then evaluating the positions. A sample for which these two nodes are not adjacent counts as an error. The topographic error is given by the the total number of errors divided by the total of samples. If the topographic error is 0, no error occurred. If 1, the topology was not preserved for any of the samples.""" self._check_input_len(data) if self.topology == 'hexagonal': msg = 'Topographic error not implemented for hexagonal topology.' raise NotImplementedError(msg) total_neurons = prod(self._activation_map.shape) if total_neurons == 1: warn('The topographic error is not defined for a 1-by-1 map.') return nan t = 1.42 # b2mu: best 2 matching units b2mu_inds = argsort(self._distance_from_weights(data), axis=1)[:, :2] b2my_xy = unravel_index(b2mu_inds, self._weights.shape[:2]) b2mu_x, b2mu_y = b2my_xy[0], b2my_xy[1] dxdy = hstack([diff(b2mu_x), diff(b2mu_y)]) distance = norm(dxdy, axis=1) return (distance > t).mean()
[ "def", "topographic_error", "(", "self", ",", "data", ")", ":", "self", ".", "_check_input_len", "(", "data", ")", "if", "self", ".", "topology", "==", "'hexagonal'", ":", "msg", "=", "'Topographic error not implemented for hexagonal topology.'", "raise", "NotImplem...
https://github.com/JustGlowing/minisom/blob/a4e519f84cb171c164517f1e7d05c42e29a2f169/minisom.py#L513-L540
mcw0/PoC
ef712a507a7330f78331997f190717fac9029a9c
dahua-telnetd-json.py
python
Dahua_Functions.Telnetd
(self,cmd)
[]
def Telnetd(self,cmd): self.cmd = cmd if self.cmd == 'enable': self.cmd = True elif self.cmd == 'disable': self.cmd = False else: print "[!] Telnetd: Invalid CMD ({})".format(self.cmd) return self.cmd query_args = {"method":"configManager.setConfig", "params": { "name":"Telnet", "table": { "Enable" : self.cmd, }, }, "session":self.SessionID, "id":1} print "[>] Enable telnetd: {}".format(self.cmd) result = json.load(self.JsonSendRequest(query_args)) if not result['result']: print "Resp: ",result print "Error CMD: {}".format(self.string_request) return print result
[ "def", "Telnetd", "(", "self", ",", "cmd", ")", ":", "self", ".", "cmd", "=", "cmd", "if", "self", ".", "cmd", "==", "'enable'", ":", "self", ".", "cmd", "=", "True", "elif", "self", ".", "cmd", "==", "'disable'", ":", "self", ".", "cmd", "=", ...
https://github.com/mcw0/PoC/blob/ef712a507a7330f78331997f190717fac9029a9c/dahua-telnetd-json.py#L150-L177
frescobaldi/frescobaldi
301cc977fc4ba7caa3df9e4bf905212ad5d06912
frescobaldi_app/debuginfo.py
python
_catch_unknown
(f)
return wrapper
Decorate a function, returning "unknown" on import/attribute error.
Decorate a function, returning "unknown" on import/attribute error.
[ "Decorate", "a", "function", "returning", "unknown", "on", "import", "/", "attribute", "error", "." ]
def _catch_unknown(f): """Decorate a function, returning "unknown" on import/attribute error.""" @functools.wraps(f) def wrapper(): try: return f() except (ImportError, AttributeError): return "unknown" return wrapper
[ "def", "_catch_unknown", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", ")", ":", "try", ":", "return", "f", "(", ")", "except", "(", "ImportError", ",", "AttributeError", ")", ":", "return", "\"unknown\"", ...
https://github.com/frescobaldi/frescobaldi/blob/301cc977fc4ba7caa3df9e4bf905212ad5d06912/frescobaldi_app/debuginfo.py#L33-L41
brython-dev/brython
9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3
www/src/Lib/http/client.py
python
HTTPConnection.getresponse
(self)
Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable. If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed.
Get the response from the server.
[ "Get", "the", "response", "from", "the", "server", "." ]
def getresponse(self): """Get the response from the server. If the HTTPConnection is in the correct state, returns an instance of HTTPResponse or of whatever object is returned by the response_class variable. If a request has not been sent or if a previous response has not be handled, ResponseNotReady is raised. If the HTTP response indicates that the connection should be closed, then it will be closed before the response is returned. When the connection is closed, the underlying socket is closed. """ # if a prior response has been completed, then forget about it. if self.__response and self.__response.isclosed(): self.__response = None # if a prior response exists, then it must be completed (otherwise, we # cannot read this response's header to determine the connection-close # behavior) # # note: if a prior response existed, but was connection-close, then the # socket and response were made independent of this HTTPConnection # object since a new request requires that we open a whole new # connection # # this means the prior response had one of two states: # 1) will_close: this connection was reset and the prior socket and # response operate independently # 2) persistent: the response was retained and we await its # isclosed() status to become true. # if self.__state != _CS_REQ_SENT or self.__response: raise ResponseNotReady(self.__state) if self.debuglevel > 0: response = self.response_class(self.sock, self.debuglevel, method=self._method) else: response = self.response_class(self.sock, method=self._method) try: try: response.begin() except ConnectionError: self.close() raise assert response.will_close != _UNKNOWN self.__state = _CS_IDLE if response.will_close: # this effectively passes the connection to the response self.close() else: # remember this, so we can tell when it is complete self.__response = response return response except: response.close() raise
[ "def", "getresponse", "(", "self", ")", ":", "# if a prior response has been completed, then forget about it.", "if", "self", ".", "__response", "and", "self", ".", "__response", ".", "isclosed", "(", ")", ":", "self", ".", "__response", "=", "None", "# if a prior r...
https://github.com/brython-dev/brython/blob/9cba5fb7f43a9b52fff13e89b403e02a1dfaa5f3/www/src/Lib/http/client.py#L1303-L1364
ym2011/POC-EXP
206b22d3a6b2a172359678df33bbc5b2ad04b6c3
K8/Web-Exp/sqlmap/lib/core/target.py
python
_setRequestParams
()
Check and set the parameters and perform checks on 'data' option for HTTP method POST.
Check and set the parameters and perform checks on 'data' option for HTTP method POST.
[ "Check", "and", "set", "the", "parameters", "and", "perform", "checks", "on", "data", "option", "for", "HTTP", "method", "POST", "." ]
def _setRequestParams(): """ Check and set the parameters and perform checks on 'data' option for HTTP method POST. """ if conf.direct: conf.parameters[None] = "direct connection" return testableParameters = False # Perform checks on GET parameters if conf.parameters.get(PLACE.GET): parameters = conf.parameters[PLACE.GET] paramDict = paramToDict(PLACE.GET, parameters) if paramDict: conf.paramDict[PLACE.GET] = paramDict testableParameters = True # Perform checks on POST parameters if conf.method == HTTPMETHOD.POST and conf.data is None: logger.warn("detected empty POST body") conf.data = "" if conf.data is not None: conf.method = HTTPMETHOD.POST if not conf.method or conf.method == HTTPMETHOD.GET else conf.method hintNames = [] def process(match, repl): retVal = match.group(0) if not (conf.testParameter and match.group("name") not in conf.testParameter): retVal = repl while True: _ = re.search(r"\\g<([^>]+)>", retVal) if _: retVal = retVal.replace(_.group(0), match.group(int(_.group(1)) if _.group(1).isdigit() else _.group(1))) else: break if CUSTOM_INJECTION_MARK_CHAR in retVal: hintNames.append((retVal.split(CUSTOM_INJECTION_MARK_CHAR)[0], match.group("name"))) return retVal if kb.processUserMarks is None and CUSTOM_INJECTION_MARK_CHAR in conf.data: message = "custom injection marking character ('%s') found in option " % CUSTOM_INJECTION_MARK_CHAR message += "'--data'. Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException else: kb.processUserMarks = not test or test[0] not in ("n", "N") if kb.processUserMarks: kb.testOnlyCustom = True if not (kb.processUserMarks and CUSTOM_INJECTION_MARK_CHAR in conf.data): if re.search(JSON_RECOGNITION_REGEX, conf.data): message = "JSON data found in %s data. " % conf.method message += "Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif test[0] not in ("n", "N"): conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data) conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER) conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*"[^"]+)"', functools.partial(process, repl=r'\g<1>%s"' % CUSTOM_INJECTION_MARK_CHAR), conf.data) conf.data = re.sub(r'("(?P<name>[^"]+)"\s*:\s*)(-?\d[\d\.]*\b)', functools.partial(process, repl=r'\g<0>%s' % CUSTOM_INJECTION_MARK_CHAR), conf.data) match = re.search(r'(?P<name>[^"]+)"\s*:\s*\[([^\]]+)\]', conf.data) if match and not (conf.testParameter and match.group("name") not in conf.testParameter): _ = match.group(2) _ = re.sub(r'("[^"]+)"', '\g<1>%s"' % CUSTOM_INJECTION_MARK_CHAR, _) _ = re.sub(r'(\A|,|\s+)(-?\d[\d\.]*\b)', '\g<0>%s' % CUSTOM_INJECTION_MARK_CHAR, _) conf.data = conf.data.replace(match.group(0), match.group(0).replace(match.group(2), _)) kb.postHint = POST_HINT.JSON elif re.search(JSON_LIKE_RECOGNITION_REGEX, conf.data): message = "JSON-like data found in %s data. " % conf.method message += "Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif test[0] not in ("n", "N"): conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data) conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER) conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*'[^']+)'", functools.partial(process, repl=r"\g<1>%s'" % CUSTOM_INJECTION_MARK_CHAR), conf.data) conf.data = re.sub(r"('(?P<name>[^']+)'\s*:\s*)(-?\d[\d\.]*\b)", functools.partial(process, repl=r"\g<0>%s" % CUSTOM_INJECTION_MARK_CHAR), conf.data) kb.postHint = POST_HINT.JSON_LIKE elif re.search(ARRAY_LIKE_RECOGNITION_REGEX, conf.data): message = "Array-like data found in %s data. " % conf.method message += "Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif test[0] not in ("n", "N"): conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER) conf.data = re.sub(r"(=[^%s]+)" % DEFAULT_GET_POST_DELIMITER, r"\g<1>%s" % CUSTOM_INJECTION_MARK_CHAR, conf.data) kb.postHint = POST_HINT.ARRAY_LIKE elif re.search(XML_RECOGNITION_REGEX, conf.data): message = "SOAP/XML data found in %s data. " % conf.method message += "Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif test[0] not in ("n", "N"): conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data) conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER) conf.data = re.sub(r"(<(?P<name>[^>]+)( [^<]*)?>)([^<]+)(</\2)", functools.partial(process, repl=r"\g<1>\g<4>%s\g<5>" % CUSTOM_INJECTION_MARK_CHAR), conf.data) kb.postHint = POST_HINT.SOAP if "soap" in conf.data.lower() else POST_HINT.XML elif re.search(MULTIPART_RECOGNITION_REGEX, conf.data): message = "Multipart-like data found in %s data. " % conf.method message += "Do you want to process it? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif test[0] not in ("n", "N"): conf.data = getattr(conf.data, UNENCODED_ORIGINAL_VALUE, conf.data) conf.data = conf.data.replace(CUSTOM_INJECTION_MARK_CHAR, ASTERISK_MARKER) conf.data = re.sub(r"(?si)((Content-Disposition[^\n]+?name\s*=\s*[\"'](?P<name>[^\n]+?)[\"']).+?)(((\r)?\n)+--)", functools.partial(process, repl=r"\g<1>%s\g<4>" % CUSTOM_INJECTION_MARK_CHAR), conf.data) kb.postHint = POST_HINT.MULTIPART if not kb.postHint: if CUSTOM_INJECTION_MARK_CHAR in conf.data: # later processed pass else: place = PLACE.POST conf.parameters[place] = conf.data paramDict = paramToDict(place, conf.data) if paramDict: conf.paramDict[place] = paramDict testableParameters = True else: if CUSTOM_INJECTION_MARK_CHAR not in conf.data: # in case that no usable parameter values has been found conf.parameters[PLACE.POST] = conf.data kb.processUserMarks = True if (kb.postHint and CUSTOM_INJECTION_MARK_CHAR in conf.data) else kb.processUserMarks if re.search(URI_INJECTABLE_REGEX, conf.url, re.I) and not any(place in conf.parameters for place in (PLACE.GET, PLACE.POST)) and not kb.postHint and not CUSTOM_INJECTION_MARK_CHAR in (conf.data or "") and conf.url.startswith("http"): warnMsg = "you've provided target URL without any GET " warnMsg += "parameters (e.g. www.site.com/article.php?id=1) " warnMsg += "and without providing any POST parameters " warnMsg += "through --data option" logger.warn(warnMsg) message = "do you want to try URI injections " message += "in the target URL itself? [Y/n/q] " test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException elif not test or test[0] not in ("n", "N"): conf.url = "%s%s" % (conf.url, CUSTOM_INJECTION_MARK_CHAR) kb.processUserMarks = True for place, value in ((PLACE.URI, conf.url), (PLACE.CUSTOM_POST, conf.data), (PLACE.CUSTOM_HEADER, str(conf.httpHeaders))): _ = re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value or "") if place == PLACE.CUSTOM_HEADER else value or "" if CUSTOM_INJECTION_MARK_CHAR in _: if kb.processUserMarks is None: lut = {PLACE.URI: '-u', PLACE.CUSTOM_POST: '--data', PLACE.CUSTOM_HEADER: '--headers/--user-agent/--referer/--cookie'} message = "custom injection marking character ('%s') found in option " % CUSTOM_INJECTION_MARK_CHAR message += "'%s'. Do you want to process it? [Y/n/q] " % lut[place] test = readInput(message, default="Y") if test and test[0] in ("q", "Q"): raise SqlmapUserQuitException else: kb.processUserMarks = not test or test[0] not in ("n", "N") if kb.processUserMarks: kb.testOnlyCustom = True if "=%s" % CUSTOM_INJECTION_MARK_CHAR in _: warnMsg = "it seems that you've provided empty parameter value(s) " warnMsg += "for testing. Please, always use only valid parameter values " warnMsg += "so sqlmap could be able to run properly" logger.warn(warnMsg) if not kb.processUserMarks: if place == PLACE.URI: query = urlparse.urlsplit(value).query if query: parameters = conf.parameters[PLACE.GET] = query paramDict = paramToDict(PLACE.GET, parameters) if paramDict: conf.url = conf.url.split('?')[0] conf.paramDict[PLACE.GET] = paramDict testableParameters = True elif place == PLACE.CUSTOM_POST: conf.parameters[PLACE.POST] = conf.data paramDict = paramToDict(PLACE.POST, conf.data) if paramDict: conf.paramDict[PLACE.POST] = paramDict testableParameters = True else: conf.parameters[place] = value conf.paramDict[place] = OrderedDict() if place == PLACE.CUSTOM_HEADER: for index in xrange(len(conf.httpHeaders)): header, value = conf.httpHeaders[index] if CUSTOM_INJECTION_MARK_CHAR in re.sub(PROBLEMATIC_CUSTOM_INJECTION_PATTERNS, "", value): parts = value.split(CUSTOM_INJECTION_MARK_CHAR) for i in xrange(len(parts) - 1): conf.paramDict[place]["%s #%d%s" % (header, i + 1, CUSTOM_INJECTION_MARK_CHAR)] = "%s,%s" % (header, "".join("%s%s" % (parts[j], CUSTOM_INJECTION_MARK_CHAR if i == j else "") for j in xrange(len(parts)))) conf.httpHeaders[index] = (header, value.replace(CUSTOM_INJECTION_MARK_CHAR, "")) else: parts = value.split(CUSTOM_INJECTION_MARK_CHAR) for i in xrange(len(parts) - 1): name = None if kb.postHint: for ending, _ in hintNames: if parts[i].endswith(ending): name = "%s %s" % (kb.postHint, _) break if name is None: name = "%s#%s%s" % (("%s " % kb.postHint) if kb.postHint else "", i + 1, CUSTOM_INJECTION_MARK_CHAR) conf.paramDict[place][name] = "".join("%s%s" % (parts[j], CUSTOM_INJECTION_MARK_CHAR if i == j else "") for j in xrange(len(parts))) if place == PLACE.URI and PLACE.GET in conf.paramDict: del conf.paramDict[PLACE.GET] elif place == PLACE.CUSTOM_POST and PLACE.POST in conf.paramDict: del conf.paramDict[PLACE.POST] testableParameters = True if kb.processUserMarks: for item in ("url", "data", "agent", "referer", "cookie"): if conf.get(item): conf[item] = conf[item].replace(CUSTOM_INJECTION_MARK_CHAR, "") # Perform checks on Cookie parameters if conf.cookie: conf.parameters[PLACE.COOKIE] = conf.cookie paramDict = paramToDict(PLACE.COOKIE, conf.cookie) if paramDict: conf.paramDict[PLACE.COOKIE] = paramDict testableParameters = True # Perform checks on header values if conf.httpHeaders: for httpHeader, headerValue in list(conf.httpHeaders): # Url encoding of the header values should be avoided # Reference: http://stackoverflow.com/questions/5085904/is-ok-to-urlencode-the-value-in-headerlocation-value if httpHeader.title() == HTTP_HEADER.USER_AGENT: conf.parameters[PLACE.USER_AGENT] = urldecode(headerValue) condition = any((not conf.testParameter, intersect(conf.testParameter, USER_AGENT_ALIASES, True))) if condition: conf.paramDict[PLACE.USER_AGENT] = {PLACE.USER_AGENT: headerValue} testableParameters = True elif httpHeader.title() == HTTP_HEADER.REFERER: conf.parameters[PLACE.REFERER] = urldecode(headerValue) condition = any((not conf.testParameter, intersect(conf.testParameter, REFERER_ALIASES, True))) if condition: conf.paramDict[PLACE.REFERER] = {PLACE.REFERER: headerValue} testableParameters = True elif httpHeader.title() == HTTP_HEADER.HOST: conf.parameters[PLACE.HOST] = urldecode(headerValue) condition = any((not conf.testParameter, intersect(conf.testParameter, HOST_ALIASES, True))) if condition: conf.paramDict[PLACE.HOST] = {PLACE.HOST: headerValue} testableParameters = True else: condition = intersect(conf.testParameter, [httpHeader], True) if condition: conf.parameters[PLACE.CUSTOM_HEADER] = str(conf.httpHeaders) conf.paramDict[PLACE.CUSTOM_HEADER] = {httpHeader: "%s,%s%s" % (httpHeader, headerValue, CUSTOM_INJECTION_MARK_CHAR)} conf.httpHeaders = [(header, value.replace(CUSTOM_INJECTION_MARK_CHAR, "")) for header, value in conf.httpHeaders] testableParameters = True if not conf.parameters: errMsg = "you did not provide any GET, POST and Cookie " errMsg += "parameter, neither an User-Agent, Referer or Host header value" raise SqlmapGenericException(errMsg) elif not testableParameters: errMsg = "all testable parameters you provided are not present " errMsg += "within the given request data" raise SqlmapGenericException(errMsg) if conf.csrfToken: if not any(conf.csrfToken in _ for _ in (conf.paramDict.get(PLACE.GET, {}), conf.paramDict.get(PLACE.POST, {}))) and not conf.csrfToken in set(_[0].lower() for _ in conf.httpHeaders) and not conf.csrfToken in conf.paramDict.get(PLACE.COOKIE, {}): errMsg = "anti-CSRF token parameter '%s' not " % conf.csrfToken errMsg += "found in provided GET, POST, Cookie or header values" raise SqlmapGenericException(errMsg) else: for place in (PLACE.GET, PLACE.POST, PLACE.COOKIE): for parameter in conf.paramDict.get(place, {}): if any(parameter.lower().count(_) for _ in CSRF_TOKEN_PARAMETER_INFIXES): message = "%s parameter '%s' appears to hold anti-CSRF token. " % (place, parameter) message += "Do you want sqlmap to automatically update it in further requests? [y/N] " test = readInput(message, default="N") if test and test[0] in ("y", "Y"): conf.csrfToken = parameter break
[ "def", "_setRequestParams", "(", ")", ":", "if", "conf", ".", "direct", ":", "conf", ".", "parameters", "[", "None", "]", "=", "\"direct connection\"", "return", "testableParameters", "=", "False", "# Perform checks on GET parameters", "if", "conf", ".", "paramete...
https://github.com/ym2011/POC-EXP/blob/206b22d3a6b2a172359678df33bbc5b2ad04b6c3/K8/Web-Exp/sqlmap/lib/core/target.py#L71-L385
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/sparse.py
python
SparseMatrix.col_list
(self)
return [tuple(k + (self[k],)) for k in sorted(list(self._smat.keys()), key=lambda k: list(reversed(k)))]
Returns a column-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy.matrices import SparseMatrix >>> a=SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.CL [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] See Also ======== col_op row_list
Returns a column-sorted list of non-zero elements of the matrix.
[ "Returns", "a", "column", "-", "sorted", "list", "of", "non", "-", "zero", "elements", "of", "the", "matrix", "." ]
def col_list(self): """Returns a column-sorted list of non-zero elements of the matrix. Examples ======== >>> from sympy.matrices import SparseMatrix >>> a=SparseMatrix(((1, 2), (3, 4))) >>> a Matrix([ [1, 2], [3, 4]]) >>> a.CL [(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)] See Also ======== col_op row_list """ return [tuple(k + (self[k],)) for k in sorted(list(self._smat.keys()), key=lambda k: list(reversed(k)))]
[ "def", "col_list", "(", "self", ")", ":", "return", "[", "tuple", "(", "k", "+", "(", "self", "[", "k", "]", ",", ")", ")", "for", "k", "in", "sorted", "(", "list", "(", "self", ".", "_smat", ".", "keys", "(", ")", ")", ",", "key", "=", "la...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/matrices/sparse.py#L228-L248
facebookarchive/WEASEL
4376c3e6679c4bfaf23d4ac1445a4461860bff40
server/server.py
python
MainMenu.cmdloop
(self, intro=None)
Overload cmdloop to neuter CTRL+C behavior and cause it to print ^C on a newline instead of quitting.
Overload cmdloop to neuter CTRL+C behavior and cause it to print ^C on a newline instead of quitting.
[ "Overload", "cmdloop", "to", "neuter", "CTRL", "+", "C", "behavior", "and", "cause", "it", "to", "print", "^C", "on", "a", "newline", "instead", "of", "quitting", "." ]
def cmdloop(self, intro=None): '''Overload cmdloop to neuter CTRL+C behavior and cause it to print ^C on a newline instead of quitting.''' print(self.intro) while True: try: super(MainMenu, self).cmdloop(intro="") break except KeyboardInterrupt: print('^C')
[ "def", "cmdloop", "(", "self", ",", "intro", "=", "None", ")", ":", "print", "(", "self", ".", "intro", ")", "while", "True", ":", "try", ":", "super", "(", "MainMenu", ",", "self", ")", ".", "cmdloop", "(", "intro", "=", "\"\"", ")", "break", "e...
https://github.com/facebookarchive/WEASEL/blob/4376c3e6679c4bfaf23d4ac1445a4461860bff40/server/server.py#L255-L263
zutianbiao/baize
cf78a4a59b1fed29e825fe94c31dd093d7a747be
APP/APP_web/views.py
python
network_detect_task_query
(request)
return HttpResponse(json.dumps(response_data), content_type="application/json; charset=utf-8")
查询探测任务
查询探测任务
[ "查询探测任务" ]
def network_detect_task_query(request): """ 查询探测任务 """ hostname = request.POST.get('hostname', '') sn = request.POST.get('sn', '') if not sn or not hostname: response_data = { 'success': False, 'msg': u"未传递主机名和sn号" } return HttpResponse(json.dumps(response_data), content_type="application/json; charset=utf-8") try: asset = Asset.objects.get(name=hostname, sn=sn) detect_role = Detect_Role.objects.filter(asset=asset) except Exception, e: response_data = { 'success': True, 'msg': u"未找到该探测源", 'data': [] } return HttpResponse(json.dumps(response_data), content_type="application/json; charset=utf-8") list_task = [] for role in detect_role: try: ping_detect = Ping_Detect.objects.filter(source=role) except Exception, e: ping_detect = [] if ping_detect: for ping in ping_detect: _dt = { "task_id": ping.task.id, "source": ping.source.id, "target": ping.target.target, "target_id": ping.target.id, "steps": ping.steps, "num": ping.num, "interval": ping.interval, "timeout": ping.timeout, "size": ping.size, "modtime": time.mktime(ping.modtime.timetuple()) + 8 * 60 * 60, "type": "ping", } list_task.append(_dt) try: traceroute_detect = Traceroute_Detect.objects.filter(source=role) except Exception, e: traceroute_detect = [] if traceroute_detect: for traceroute in traceroute_detect: _dt = { "task_id": traceroute.task.id, "source": traceroute.source.id, "target": traceroute.target.target, "target_id": traceroute.target.id, "steps": traceroute.steps, "num": traceroute.num, "modtime": time.mktime(traceroute.modtime.timetuple()) + 8 * 60 * 60, "timeout": traceroute.timeout, "type": "traceroute", } list_task.append(_dt) try: curl_detect = Curl_Detect.objects.filter(source=role) except Exception, e: curl_detect = [] if curl_detect: for curl in curl_detect: _dt = { "task_id": curl.task.id, "source": curl.source.id, "target": curl.target.target, "target_id": curl.target.id, "steps": curl.steps, "uri": curl.uri, "modtime": time.mktime(curl.modtime.timetuple()) + 8 * 60 * 60, "timeout_total": curl.timeout_total, "timeout_conn": curl.timeout_conn, "timeout_dns": curl.timeout_dns, "type": "curl", } list_task.append(_dt) response_data = { 'success': True, 'msg': u"成功获取探测任务", 'data': list_task } return HttpResponse(json.dumps(response_data), content_type="application/json; charset=utf-8")
[ "def", "network_detect_task_query", "(", "request", ")", ":", "hostname", "=", "request", ".", "POST", ".", "get", "(", "'hostname'", ",", "''", ")", "sn", "=", "request", ".", "POST", ".", "get", "(", "'sn'", ",", "''", ")", "if", "not", "sn", "or",...
https://github.com/zutianbiao/baize/blob/cf78a4a59b1fed29e825fe94c31dd093d7a747be/APP/APP_web/views.py#L1411-L1500
saltstack/salt
fae5bc757ad0f1716483ce7ae180b451545c2058
salt/modules/boto_rds.py
python
update_parameter_group
( name, parameters, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None, )
Update an RDS parameter group. CLI Example: .. code-block:: bash salt myminion boto_rds.update_parameter_group my-param-group \ parameters='{"back_log":1, "binlog_cache_size":4096}' \ region=us-east-1
Update an RDS parameter group.
[ "Update", "an", "RDS", "parameter", "group", "." ]
def update_parameter_group( name, parameters, apply_method="pending-reboot", tags=None, region=None, key=None, keyid=None, profile=None, ): """ Update an RDS parameter group. CLI Example: .. code-block:: bash salt myminion boto_rds.update_parameter_group my-param-group \ parameters='{"back_log":1, "binlog_cache_size":4096}' \ region=us-east-1 """ res = __salt__["boto_rds.parameter_group_exists"]( name, tags, region, key, keyid, profile ) if not res.get("exists"): return { "exists": bool(res), "message": "RDS parameter group {} does not exist.".format(name), } param_list = [] for key, value in parameters.items(): item = odict.OrderedDict() item.update({"ParameterName": key}) item.update({"ApplyMethod": apply_method}) if type(value) is bool: item.update({"ParameterValue": "on" if value else "off"}) else: item.update({"ParameterValue": str(value)}) param_list.append(item) if not param_list: return {"results": False} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn: return {"results": bool(conn)} res = conn.modify_db_parameter_group( DBParameterGroupName=name, Parameters=param_list ) return {"results": bool(res)} except ClientError as e: return {"error": __utils__["boto3.get_error"](e)}
[ "def", "update_parameter_group", "(", "name", ",", "parameters", ",", "apply_method", "=", "\"pending-reboot\"", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", "...
https://github.com/saltstack/salt/blob/fae5bc757ad0f1716483ce7ae180b451545c2058/salt/modules/boto_rds.py#L592-L647
frappe/erpnext
9d36e30ef7043b391b5ed2523b8288bf46c45d18
erpnext/hr/doctype/employee_checkin/employee_checkin.py
python
add_log_based_on_employee_field
(employee_field_value, timestamp, device_id=None, log_type=None, skip_auto_attendance=0, employee_fieldname='attendance_device_id')
return doc
Finds the relevant Employee using the employee field value and creates a Employee Checkin. :param employee_field_value: The value to look for in employee field. :param timestamp: The timestamp of the Log. Currently expected in the following format as string: '2019-05-08 10:48:08.000000' :param device_id: (optional)Location / Device ID. A short string is expected. :param log_type: (optional)Direction of the Punch if available (IN/OUT). :param skip_auto_attendance: (optional)Skip auto attendance field will be set for this log(0/1). :param employee_fieldname: (Default: attendance_device_id)Name of the field in Employee DocType based on which employee lookup will happen.
Finds the relevant Employee using the employee field value and creates a Employee Checkin.
[ "Finds", "the", "relevant", "Employee", "using", "the", "employee", "field", "value", "and", "creates", "a", "Employee", "Checkin", "." ]
def add_log_based_on_employee_field(employee_field_value, timestamp, device_id=None, log_type=None, skip_auto_attendance=0, employee_fieldname='attendance_device_id'): """Finds the relevant Employee using the employee field value and creates a Employee Checkin. :param employee_field_value: The value to look for in employee field. :param timestamp: The timestamp of the Log. Currently expected in the following format as string: '2019-05-08 10:48:08.000000' :param device_id: (optional)Location / Device ID. A short string is expected. :param log_type: (optional)Direction of the Punch if available (IN/OUT). :param skip_auto_attendance: (optional)Skip auto attendance field will be set for this log(0/1). :param employee_fieldname: (Default: attendance_device_id)Name of the field in Employee DocType based on which employee lookup will happen. """ if not employee_field_value or not timestamp: frappe.throw(_("'employee_field_value' and 'timestamp' are required.")) employee = frappe.db.get_values("Employee", {employee_fieldname: employee_field_value}, ["name", "employee_name", employee_fieldname], as_dict=True) if employee: employee = employee[0] else: frappe.throw(_("No Employee found for the given employee field value. '{}': {}").format(employee_fieldname,employee_field_value)) doc = frappe.new_doc("Employee Checkin") doc.employee = employee.name doc.employee_name = employee.employee_name doc.time = timestamp doc.device_id = device_id doc.log_type = log_type if cint(skip_auto_attendance) == 1: doc.skip_auto_attendance = '1' doc.insert() return doc
[ "def", "add_log_based_on_employee_field", "(", "employee_field_value", ",", "timestamp", ",", "device_id", "=", "None", ",", "log_type", "=", "None", ",", "skip_auto_attendance", "=", "0", ",", "employee_fieldname", "=", "'attendance_device_id'", ")", ":", "if", "no...
https://github.com/frappe/erpnext/blob/9d36e30ef7043b391b5ed2523b8288bf46c45d18/erpnext/hr/doctype/employee_checkin/employee_checkin.py#L47-L76
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/utils/dataset.py
python
TransformDataset.__getitem__
(self, idx)
return self.transform(self.data[idx])
[] operator.
[] operator.
[ "[]", "operator", "." ]
def __getitem__(self, idx): """[] operator.""" return self.transform(self.data[idx])
[ "def", "__getitem__", "(", "self", ",", "idx", ")", ":", "return", "self", ".", "transform", "(", "self", ".", "data", "[", "idx", "]", ")" ]
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/utils/dataset.py#L31-L33
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/plugins/admin/__init__.py
python
AdminPlugin.onLoadConfig
(self)
Load plugin configuration.
Load plugin configuration.
[ "Load", "plugin", "configuration", "." ]
def onLoadConfig(self): """ Load plugin configuration. """ self.load_config_warn_reasons() self.load_config_messages() self.load_config_warn() try: self._noreason_level = self.console.getGroupLevel(self.config.get('settings', 'noreason_level')) self.debug('loaded settings/noreason_level: %s' % self._noreason_level) except NoOptionError: self.warning('could not find settings/noreason_level in config file, ' 'using default: %s' % self._noreason_level) except KeyError, e: self.error('could not load settings/noreason_level config value: %s' % e) self.debug('using default value (%s) for settings/noreason_level' % self._noreason_level) try: self._long_tempban_level = self.console.getGroupLevel(self.config.get('settings', 'long_tempban_level')) self.debug('loaded settings/long_tempban_level: %s' % self._long_tempban_level) except NoOptionError: self.warning('could not find settings/long_tempban_level in config file, ' 'using default: %s' % self._long_tempban_level) except KeyError, e: self.error('could not load settings/long_tempban_level config value: %s' % e) self.debug('using default value (%s) for settings/long_tempban_level' % self._long_tempban_level) try: self._long_tempban_max_duration = self.config.getDuration('settings', 'long_tempban_max_duration') self.debug('loaded settings/long_tempban_max_duration: %s' % self._long_tempban_level) except NoOptionError: self.warning('could not find settings/long_tempban_max_duration in config file, ' 'using default: %s' % self._long_tempban_max_duration) try: self._hidecmd_level = self.console.getGroupLevel(self.config.get('settings', 'hidecmd_level')) self.debug('loaded settings/hidecmd_level: %s' % self._hidecmd_level) except NoOptionError: self.warning('could not find settings/hidecmd_level in config file, ' 'using default: %s' % self._hidecmd_level) except KeyError, e: self.error('could not load settings/hidecmd_level config value: %s' % e) self.debug('using default value (%s) for settings/hidecmd_level' % self._hidecmd_level) try: self._admins_level = self.console.getGroupLevel(self.config.get('settings', 'admins_level')) self.debug('loaded settings/admins_level: %s' % self._admins_level) except NoOptionError: self.warning('could not find settings/admins_level in config file, ' 'using default: %s' % self._admins_level) except KeyError, e: self.error('could not load settings/admins_level config value: %s' % e) self.debug('using default value (%s) for settings/admins_level' % self._admins_level) try: self._announce_registration = self.config.getboolean('settings', 'announce_registration') self.debug('loaded settings/announce_registration: %s' % self._announce_registration) except NoOptionError: self.warning('could not find settings/announce_registration in config file, ' 'using default: %s' % self._announce_registration) except ValueError, e: self.error('could not load settings/announce_registration config value: %s' % e) self.debug('using default value (%s) for settings/announce_registration' % self._announce_registration) try: # be sure to clamp at 59 seconds else the cronjob won't work properly past_bans_check_rate = self.config.getint('settings', 'past_bans_check_rate') if past_bans_check_rate > 59: past_bans_check_rate = 59 self._past_bans_check_rate = past_bans_check_rate self.debug('loaded settings/past_bans_check_rate: %s' % self._past_bans_check_rate) except NoOptionError: self.warning('could not find settings/past_bans_check_rate in config file, ' 'using default: %s' % self._past_bans_check_rate) except ValueError, e: self.error('could not load settings/past_bans_check_rate config value: %s' % e) self.debug('using default value (%s) for settings/past_bans_check_rate' % self._past_bans_check_rate)
[ "def", "onLoadConfig", "(", "self", ")", ":", "self", ".", "load_config_warn_reasons", "(", ")", "self", ".", "load_config_messages", "(", ")", "self", ".", "load_config_warn", "(", ")", "try", ":", "self", ".", "_noreason_level", "=", "self", ".", "console"...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/plugins/admin/__init__.py#L141-L218
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/xml/sax/_exceptions.py
python
SAXParseException.getColumnNumber
(self)
return self._colnum
The column number of the end of the text where the exception occurred.
The column number of the end of the text where the exception occurred.
[ "The", "column", "number", "of", "the", "end", "of", "the", "text", "where", "the", "exception", "occurred", "." ]
def getColumnNumber(self): """The column number of the end of the text where the exception occurred.""" return self._colnum
[ "def", "getColumnNumber", "(", "self", ")", ":", "return", "self", ".", "_colnum" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/xml/sax/_exceptions.py#L72-L75
vaab/gitchangelog
95fe8d5bd171db29922b40d9d3a13dab5af094c0
src/gitchangelog/gitchangelog.py
python
GitRepos.tags
(self, contains=None)
return sorted([self.commit(tag) for tag in tags if tag != ''], key=lambda x: int(x.committer_date_timestamp))
String list of repository's tag names Current tag order is committer date timestamp of tagged commit. No firm reason for that, and it could change in future version.
String list of repository's tag names
[ "String", "list", "of", "repository", "s", "tag", "names" ]
def tags(self, contains=None): """String list of repository's tag names Current tag order is committer date timestamp of tagged commit. No firm reason for that, and it could change in future version. """ if contains: tags = self.git.tag(contains=contains).split("\n") else: tags = self.git.tag().split("\n") ## Should we use new version name sorting ? refering to : ## ``git tags --sort -v:refname`` in git version >2.0. ## Sorting and reversing with command line is not available on ## git version <2.0 return sorted([self.commit(tag) for tag in tags if tag != ''], key=lambda x: int(x.committer_date_timestamp))
[ "def", "tags", "(", "self", ",", "contains", "=", "None", ")", ":", "if", "contains", ":", "tags", "=", "self", ".", "git", ".", "tag", "(", "contains", "=", "contains", ")", ".", "split", "(", "\"\\n\"", ")", "else", ":", "tags", "=", "self", "....
https://github.com/vaab/gitchangelog/blob/95fe8d5bd171db29922b40d9d3a13dab5af094c0/src/gitchangelog/gitchangelog.py#L1177-L1193
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/camera/v4l2/mjpeg.py
python
MjpegManager.isCameraOpened
(self)
return self._streamer is not None
[]
def isCameraOpened(self): return self._streamer is not None
[ "def", "isCameraOpened", "(", "self", ")", ":", "return", "self", ".", "_streamer", "is", "not", "None" ]
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/camera/v4l2/mjpeg.py#L154-L155
PyCQA/pylint
3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb
pylint/checkers/refactoring/refactoring_checker.py
python
RefactoringChecker._check_unnecessary_dict_index_lookup
( self, node: Union[nodes.For, nodes.Comprehension] )
Add message when accessing dict values by index lookup.
Add message when accessing dict values by index lookup.
[ "Add", "message", "when", "accessing", "dict", "values", "by", "index", "lookup", "." ]
def _check_unnecessary_dict_index_lookup( self, node: Union[nodes.For, nodes.Comprehension] ) -> None: """Add message when accessing dict values by index lookup.""" # Verify that we have an .items() call and # that the object which is iterated is used as a subscript in the # body of the for. # Is it a proper items call? if ( isinstance(node.iter, nodes.Call) and isinstance(node.iter.func, nodes.Attribute) and node.iter.func.attrname == "items" ): inferred = utils.safe_infer(node.iter.func) if not isinstance(inferred, astroid.BoundMethod): return iterating_object_name = node.iter.func.expr.as_string() # Verify that the body of the for loop uses a subscript # with the object that was iterated. This uses some heuristics # in order to make sure that the same object is used in the # for body. children = ( node.body if isinstance(node, nodes.For) else node.parent.get_children() ) for child in children: for subscript in child.nodes_of_class(nodes.Subscript): if not isinstance(subscript.value, (nodes.Name, nodes.Attribute)): continue value = subscript.slice if isinstance(node, nodes.For) and ( isinstance(subscript.parent, nodes.Assign) and subscript in subscript.parent.targets or isinstance(subscript.parent, nodes.AugAssign) and subscript == subscript.parent.target ): # Ignore this subscript if it is the target of an assignment # Early termination; after reassignment dict index lookup will be necessary return if isinstance(subscript.parent, nodes.Delete): # Ignore this subscript if it's used with the delete keyword return # Case where .items is assigned to k,v (i.e., for k, v in d.items()) if isinstance(value, nodes.Name): if ( not isinstance(node.target, nodes.Tuple) # Ignore 1-tuples: for k, in d.items() or len(node.target.elts) < 2 or value.name != node.target.elts[0].name or iterating_object_name != subscript.value.as_string() ): continue if ( isinstance(node, nodes.For) and value.lookup(value.name)[1][-1].lineno > node.lineno ): # Ignore this subscript if it has been redefined after # the for loop. This checks for the line number using .lookup() # to get the line number where the iterating object was last # defined and compare that to the for loop's line number continue self.add_message( "unnecessary-dict-index-lookup", node=subscript, args=(node.target.elts[1].as_string()), ) # Case where .items is assigned to single var (i.e., for item in d.items()) elif isinstance(value, nodes.Subscript): if ( not isinstance(node.target, nodes.AssignName) or node.target.name != value.value.name or iterating_object_name != subscript.value.as_string() ): continue if ( isinstance(node, nodes.For) and value.value.lookup(value.value.name)[1][-1].lineno > node.lineno ): # Ignore this subscript if it has been redefined after # the for loop. This checks for the line number using .lookup() # to get the line number where the iterating object was last # defined and compare that to the for loop's line number continue # check if subscripted by 0 (key) inferred = utils.safe_infer(value.slice) if not isinstance(inferred, nodes.Const) or inferred.value != 0: continue self.add_message( "unnecessary-dict-index-lookup", node=subscript, args=("1".join(value.as_string().rsplit("0", maxsplit=1)),), )
[ "def", "_check_unnecessary_dict_index_lookup", "(", "self", ",", "node", ":", "Union", "[", "nodes", ".", "For", ",", "nodes", ".", "Comprehension", "]", ")", "->", "None", ":", "# Verify that we have an .items() call and", "# that the object which is iterated is used as ...
https://github.com/PyCQA/pylint/blob/3fc855f9d0fa8e6410be5a23cf954ffd5471b4eb/pylint/checkers/refactoring/refactoring_checker.py#L1851-L1952
mne-tools/mne-python
f90b303ce66a8415e64edd4605b09ac0179c1ebf
mne/io/base.py
python
_index_as_time
(index, sfreq, first_samp=0, use_first_samp=False)
return times / sfreq
Convert indices to time. Parameters ---------- index : list-like | int List of ints or int representing points in time. use_first_samp : boolean If True, the time returned is relative to the session onset, else relative to the recording onset. Returns ------- times : ndarray Times corresponding to the index supplied.
Convert indices to time.
[ "Convert", "indices", "to", "time", "." ]
def _index_as_time(index, sfreq, first_samp=0, use_first_samp=False): """Convert indices to time. Parameters ---------- index : list-like | int List of ints or int representing points in time. use_first_samp : boolean If True, the time returned is relative to the session onset, else relative to the recording onset. Returns ------- times : ndarray Times corresponding to the index supplied. """ times = np.atleast_1d(index) + (first_samp if use_first_samp else 0) return times / sfreq
[ "def", "_index_as_time", "(", "index", ",", "sfreq", ",", "first_samp", "=", "0", ",", "use_first_samp", "=", "False", ")", ":", "times", "=", "np", ".", "atleast_1d", "(", "index", ")", "+", "(", "first_samp", "if", "use_first_samp", "else", "0", ")", ...
https://github.com/mne-tools/mne-python/blob/f90b303ce66a8415e64edd4605b09ac0179c1ebf/mne/io/base.py#L1993-L2010
nyu-mll/multiNLI
c4078cad9f9b5d06a672f2edb69bde007a3567a9
python/util/blocks.py
python
last_output
(output, true_length)
return last_output
To get the last hidden layer form a dynamically unrolled RNN. Input of shape (batch_size, max_seq_length, hidden_dim). true_length: Tensor of shape (batch_size). Such a tensor is given by the length() function. Output of shape (batch_size, hidden_dim).
To get the last hidden layer form a dynamically unrolled RNN. Input of shape (batch_size, max_seq_length, hidden_dim).
[ "To", "get", "the", "last", "hidden", "layer", "form", "a", "dynamically", "unrolled", "RNN", ".", "Input", "of", "shape", "(", "batch_size", "max_seq_length", "hidden_dim", ")", "." ]
def last_output(output, true_length): """ To get the last hidden layer form a dynamically unrolled RNN. Input of shape (batch_size, max_seq_length, hidden_dim). true_length: Tensor of shape (batch_size). Such a tensor is given by the length() function. Output of shape (batch_size, hidden_dim). """ max_length = int(output.get_shape()[1]) length_mask = tf.expand_dims(tf.one_hot(true_length-1, max_length, on_value=1., off_value=0.), -1) last_output = tf.reduce_sum(tf.multiply(output, length_mask), 1) return last_output
[ "def", "last_output", "(", "output", ",", "true_length", ")", ":", "max_length", "=", "int", "(", "output", ".", "get_shape", "(", ")", "[", "1", "]", ")", "length_mask", "=", "tf", ".", "expand_dims", "(", "tf", ".", "one_hot", "(", "true_length", "-"...
https://github.com/nyu-mll/multiNLI/blob/c4078cad9f9b5d06a672f2edb69bde007a3567a9/python/util/blocks.py#L60-L71
rdegges/simpleq
53c16578124b28f469afe53771154b730d3a88c2
simpleq/queues.py
python
Queue.add_job
(self, job)
Add a new job to the queue. This will serialize the desired code, and dump it into this SQS queue to be processed. :param obj job: The Job to enqueue.
Add a new job to the queue.
[ "Add", "a", "new", "job", "to", "the", "queue", "." ]
def add_job(self, job): """ Add a new job to the queue. This will serialize the desired code, and dump it into this SQS queue to be processed. :param obj job: The Job to enqueue. """ self.queue.write(job.message)
[ "def", "add_job", "(", "self", ",", "job", ")", ":", "self", ".", "queue", ".", "write", "(", "job", ".", "message", ")" ]
https://github.com/rdegges/simpleq/blob/53c16578124b28f469afe53771154b730d3a88c2/simpleq/queues.py#L106-L115
microsoft/botbuilder-python
3d410365461dc434df59bdfeaa2f16d28d9df868
libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py
python
DialogContext.emit_event
( self, name: str, value: object = None, bubble: bool = True, from_leaf: bool = False, )
Searches for a dialog with a given ID. Emits a named event for the current dialog, or someone who started it, to handle. :param name: Name of the event to raise. :param value: Value to send along with the event. :param bubble: Flag to control whether the event should be bubbled to its parent if not handled locally. Defaults to a value of `True`. :param from_leaf: Whether the event is emitted from a leaf node. :param cancellationToken: The cancellation token. :return: True if the event was handled.
Searches for a dialog with a given ID. Emits a named event for the current dialog, or someone who started it, to handle. :param name: Name of the event to raise. :param value: Value to send along with the event. :param bubble: Flag to control whether the event should be bubbled to its parent if not handled locally. Defaults to a value of `True`. :param from_leaf: Whether the event is emitted from a leaf node. :param cancellationToken: The cancellation token. :return: True if the event was handled.
[ "Searches", "for", "a", "dialog", "with", "a", "given", "ID", ".", "Emits", "a", "named", "event", "for", "the", "current", "dialog", "or", "someone", "who", "started", "it", "to", "handle", ".", ":", "param", "name", ":", "Name", "of", "the", "event",...
async def emit_event( self, name: str, value: object = None, bubble: bool = True, from_leaf: bool = False, ) -> bool: """ Searches for a dialog with a given ID. Emits a named event for the current dialog, or someone who started it, to handle. :param name: Name of the event to raise. :param value: Value to send along with the event. :param bubble: Flag to control whether the event should be bubbled to its parent if not handled locally. Defaults to a value of `True`. :param from_leaf: Whether the event is emitted from a leaf node. :param cancellationToken: The cancellation token. :return: True if the event was handled. """ try: # Initialize event dialog_event = DialogEvent(bubble=bubble, name=name, value=value,) dialog_context = self # Find starting dialog if from_leaf: while True: child_dc = dialog_context.child if child_dc: dialog_context = child_dc else: break # Dispatch to active dialog first instance = dialog_context.active_dialog if instance: dialog = await dialog_context.find_dialog(instance.id) if dialog: return await dialog.on_dialog_event(dialog_context, dialog_event) return False except Exception as err: self.__set_exception_context_data(err) raise
[ "async", "def", "emit_event", "(", "self", ",", "name", ":", "str", ",", "value", ":", "object", "=", "None", ",", "bubble", ":", "bool", "=", "True", ",", "from_leaf", ":", "bool", "=", "False", ",", ")", "->", "bool", ":", "try", ":", "# Initiali...
https://github.com/microsoft/botbuilder-python/blob/3d410365461dc434df59bdfeaa2f16d28d9df868/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_context.py#L343-L389
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/content/instrumentvalidation.py
python
InstrumentValidation.isValidationInProgress
(self)
return down_from <= today <= down_to
Checks if the date is beteween a validation period
Checks if the date is beteween a validation period
[ "Checks", "if", "the", "date", "is", "beteween", "a", "validation", "period" ]
def isValidationInProgress(self): """Checks if the date is beteween a validation period """ today = DateTime() down_from = self.getDownFrom() down_to = self.getDownTo() return down_from <= today <= down_to
[ "def", "isValidationInProgress", "(", "self", ")", ":", "today", "=", "DateTime", "(", ")", "down_from", "=", "self", ".", "getDownFrom", "(", ")", "down_to", "=", "self", ".", "getDownTo", "(", ")", "return", "down_from", "<=", "today", "<=", "down_to" ]
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/content/instrumentvalidation.py#L166-L173
deepmipt/DeepPavlov
08555428388fed3c7b036c0a82a70a25efcabcff
deeppavlov/models/ranking/matching_models/dam_utils/operations.py
python
mask
(row_lengths, col_lengths, max_row_length, max_col_length)
return tf.einsum('bik,bjk->bij', row_mask, col_mask)
Return a mask tensor representing the first N positions of each row and each column. Args: row_lengths: a tensor with shape [batch] col_lengths: a tensor with shape [batch] Returns: a mask tensor with shape [batch, max_row_length, max_col_length] Raises:
Return a mask tensor representing the first N positions of each row and each column.
[ "Return", "a", "mask", "tensor", "representing", "the", "first", "N", "positions", "of", "each", "row", "and", "each", "column", "." ]
def mask(row_lengths, col_lengths, max_row_length, max_col_length): '''Return a mask tensor representing the first N positions of each row and each column. Args: row_lengths: a tensor with shape [batch] col_lengths: a tensor with shape [batch] Returns: a mask tensor with shape [batch, max_row_length, max_col_length] Raises: ''' row_mask = tf.sequence_mask(row_lengths, max_row_length) # bool, [batch, max_row_len] col_mask = tf.sequence_mask(col_lengths, max_col_length) # bool, [batch, max_col_len] row_mask = tf.cast(tf.expand_dims(row_mask, -1), tf.float32) col_mask = tf.cast(tf.expand_dims(col_mask, -1), tf.float32) return tf.einsum('bik,bjk->bij', row_mask, col_mask)
[ "def", "mask", "(", "row_lengths", ",", "col_lengths", ",", "max_row_length", ",", "max_col_length", ")", ":", "row_mask", "=", "tf", ".", "sequence_mask", "(", "row_lengths", ",", "max_row_length", ")", "# bool, [batch, max_row_len]", "col_mask", "=", "tf", ".", ...
https://github.com/deepmipt/DeepPavlov/blob/08555428388fed3c7b036c0a82a70a25efcabcff/deeppavlov/models/ranking/matching_models/dam_utils/operations.py#L367-L385
aws-samples/machine-learning-samples
025bd6d97a9f45813aad38cc2734252103ba3a93
cost-based-ml/cost_based_ml.py
python
plot_threshold_costs
(threshold_costs, best_threshold, lowest_cost)
[]
def plot_threshold_costs(threshold_costs, best_threshold, lowest_cost): plt.figure() thresholds = list(zip(*threshold_costs)[0]) costs = list(zip(*threshold_costs)[1]) plt.plot(thresholds, costs, c='red', label='cost') mean = np.mean(costs) plt.axis([0, 1, 0, mean*3]) plt.plot([0, 1], [lowest_cost, lowest_cost], 'k-', label='lowest cost') plt.plot([best_threshold, best_threshold], [0, lowest_cost], 'k-') plt.legend() plt.title('Threshold cost') plt.xlabel('score threshold') plt.ylabel('cost') plt.draw()
[ "def", "plot_threshold_costs", "(", "threshold_costs", ",", "best_threshold", ",", "lowest_cost", ")", ":", "plt", ".", "figure", "(", ")", "thresholds", "=", "list", "(", "zip", "(", "*", "threshold_costs", ")", "[", "0", "]", ")", "costs", "=", "list", ...
https://github.com/aws-samples/machine-learning-samples/blob/025bd6d97a9f45813aad38cc2734252103ba3a93/cost-based-ml/cost_based_ml.py#L105-L121
Theano/Theano
8fd9203edfeecebced9344b0c70193be292a9ade
theano/tensor/subtensor.py
python
Subtensor.collapse
(idxs, cond)
return ret
Parameters ---------- idxs : a list of indices or slices. cond : a callable that returns a bool Returns ------- list idxs, with the slices flattened out into a list. If cond is true for an entry, does not flatten it.
Parameters ---------- idxs : a list of indices or slices. cond : a callable that returns a bool
[ "Parameters", "----------", "idxs", ":", "a", "list", "of", "indices", "or", "slices", ".", "cond", ":", "a", "callable", "that", "returns", "a", "bool" ]
def collapse(idxs, cond): """ Parameters ---------- idxs : a list of indices or slices. cond : a callable that returns a bool Returns ------- list idxs, with the slices flattened out into a list. If cond is true for an entry, does not flatten it. """ ret = [] def helper(entry): if cond(entry): ret.append(entry) elif isinstance(entry, slice): helper(entry.start) helper(entry.stop) helper(entry.step) for idx in idxs: helper(idx) return ret
[ "def", "collapse", "(", "idxs", ",", "cond", ")", ":", "ret", "=", "[", "]", "def", "helper", "(", "entry", ")", ":", "if", "cond", "(", "entry", ")", ":", "ret", ".", "append", "(", "entry", ")", "elif", "isinstance", "(", "entry", ",", "slice",...
https://github.com/Theano/Theano/blob/8fd9203edfeecebced9344b0c70193be292a9ade/theano/tensor/subtensor.py#L299-L326
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_group.py
python
Utils.create_tmpfile_copy
(inc_file)
return tmpfile
create a temporary copy of a file
create a temporary copy of a file
[ "create", "a", "temporary", "copy", "of", "a", "file" ]
def create_tmpfile_copy(inc_file): '''create a temporary copy of a file''' tmpfile = Utils.create_tmpfile('lib_openshift-') Utils._write(tmpfile, open(inc_file).read()) # Cleanup the tmpfile atexit.register(Utils.cleanup, [tmpfile]) return tmpfile
[ "def", "create_tmpfile_copy", "(", "inc_file", ")", ":", "tmpfile", "=", "Utils", ".", "create_tmpfile", "(", "'lib_openshift-'", ")", "Utils", ".", "_write", "(", "tmpfile", ",", "open", "(", "inc_file", ")", ".", "read", "(", ")", ")", "# Cleanup the tmpfi...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_adm_policy_group.py#L1199-L1207
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListItemAttr.GetFooterBackgroundColour
(self)
return self._footerColBack
Returns the currently set background colour for a footer item.
Returns the currently set background colour for a footer item.
[ "Returns", "the", "currently", "set", "background", "colour", "for", "a", "footer", "item", "." ]
def GetFooterBackgroundColour(self): """ Returns the currently set background colour for a footer item. """ return self._footerColBack
[ "def", "GetFooterBackgroundColour", "(", "self", ")", ":", "return", "self", ".", "_footerColBack" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L1320-L1323
home-assistant/core
265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1
homeassistant/components/picnic/coordinator.py
python
PicnicUpdateCoordinator._get_last_order
(self)
return last_order
Get data of the last order from the list of deliveries.
Get data of the last order from the list of deliveries.
[ "Get", "data", "of", "the", "last", "order", "from", "the", "list", "of", "deliveries", "." ]
def _get_last_order(self) -> dict: """Get data of the last order from the list of deliveries.""" # Get the deliveries deliveries = self.picnic_api_client.get_deliveries(summary=True) # Determine the last order and return an empty dict if there is none try: last_order = copy.deepcopy(deliveries[0]) except KeyError: return {} # Get the position details if the order is not delivered yet delivery_position = {} if not last_order.get("delivery_time"): try: delivery_position = self.picnic_api_client.get_delivery_position( last_order["delivery_id"] ) except ValueError: # No information yet can mean an empty response pass # Determine the ETA, if available, the one from the delivery position API is more precise # but it's only available shortly before the actual delivery. last_order["eta"] = delivery_position.get( "eta_window", last_order.get("eta2", {}) ) # Determine the total price by adding up the total price of all sub-orders total_price = 0 for order in last_order.get("orders", []): total_price += order.get("total_price", 0) # Sanitise the object last_order["total_price"] = total_price last_order.setdefault("delivery_time", {}) if "eta2" in last_order: del last_order["eta2"] # Make a copy because some references are local return last_order
[ "def", "_get_last_order", "(", "self", ")", "->", "dict", ":", "# Get the deliveries", "deliveries", "=", "self", ".", "picnic_api_client", ".", "get_deliveries", "(", "summary", "=", "True", ")", "# Determine the last order and return an empty dict if there is none", "tr...
https://github.com/home-assistant/core/blob/265ebd17a3f17ed8dc1e9bdede03ac8e323f1ab1/homeassistant/components/picnic/coordinator.py#L101-L141
netzob/netzob
49ee3e5e7d6dce67496afd5a75827a78be0c9f70
netzob/src/netzob/Model/Vocabulary/Types/TypeConverter.py
python
TypeConverter.convert
(data, sourceType, destinationType, src_unitSize=None, src_endianness=AbstractType.defaultEndianness(), src_sign=AbstractType.defaultSign(), dst_unitSize=None, dst_endianness=AbstractType.defaultEndianness(), dst_sign=AbstractType.defaultSign())
Encode data provided as a sourceType to a destinationType. To convert an ASCII to its binary (bitarray) representation >>> from netzob.all import * >>> data = "That's an helloworld!" >>> bin = TypeConverter.convert(data, ASCII, BitArray) >>> print(bin) bitarray('010101000110100001100001011101000010011101110011001000000110000101101110001000000110100001100101011011000110110001101111011101110110111101110010011011000110010000100001') >>> data == TypeConverter.convert(bin, BitArray, ASCII) True To convert a raw data to its decimal representation and then to its ASCII representation >>> data = b'\\x23' >>> decData = TypeConverter.convert(data, Raw, Integer) >>> print(decData) 35 >>> print(TypeConverter.convert(decData, Integer, ASCII)) # Conversion to and from Integer detects the output unitsize depending on the input: >>> TypeConverter.convert(b'\\x0b\\x00', Raw, Integer) 2816 >>> TypeConverter.convert(11, Integer, Raw) b'\\x0b' >>> TypeConverter.convert(b'\\xa0\\x0b', Raw, Integer, dst_sign=AbstractType.SIGN_SIGNED) -24565 >>> TypeConverter.convert(-24565, Integer, Raw, src_sign=AbstractType.SIGN_SIGNED) b'\\xa0\\x0b' >>> TypeConverter.convert(0, Integer, Raw) b'\\x00' >>> TypeConverter.convert(b'\\x00\\x00\\x00', Raw, Integer) Traceback (most recent call last): ... TypeError: Unsupported autodetected Integer target UnitSize. Valid UnitSizes are 8, 16, 32 and 64 bits. You can also play with the unitSize to convert multiple ascii in a single high value decimal >>> TypeConverter.convert("5", ASCII, Integer) 53 >>> print(TypeConverter.convert("zoby", ASCII, Integer)) 2054120057 >>> print(TypeConverter.convert("zoby", ASCII, Integer, dst_unitSize=AbstractType.UNITSIZE_32)) 2054120057 It also works for 'semantic' data like IPv4s >>> TypeConverter.convert("192.168.0.10", IPv4, Integer, dst_sign=AbstractType.SIGN_UNSIGNED) 3232235530 >>> TypeConverter.convert("127.0.0.1", IPv4, BitArray) bitarray('01111111000000000000000000000001') >>> TypeConverter.convert(167815360, Integer, IPv4, src_unitSize=AbstractType.UNITSIZE_32, src_sign=AbstractType.SIGN_UNSIGNED) IPAddress('10.0.168.192') To check Integer conversion consistency >>> f = Field(b'some') >>> v = f.domain.currentValue.tobytes() >>> try: ... v_hex = v.hex() ... except AttributeError: ... import codecs # Python <= 3.4: 'bytes' object has no attribute 'hex' ... v_hex = codecs.encode(v, 'hex_codec').decode('ascii') >>> '0x'+v_hex == hex(TypeConverter.convert(f.domain.currentValue, BitArray, Integer)) True :param sourceType: the data source type :type sourceType: :class:`type` :param destinationType: the destination type :type destinationType: :class:`type` :keyword src_unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_* :type src_unitSize: str :keyword src_endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE :type src_endianness: str :keyword src_sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED :type src_sign: str :keyword dst_unitSize: the unitsize of the expected result. Values must be one of AbstractType.UNITSIZE_* :type dst_unitSize: str :keyword dst_endianness: the endianness of the expected result. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE :type dst_endianness: str :keyword dst_sign: the sign of the expected result. Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED :type dst_sign: str :raise: TypeError if parameter not valid
Encode data provided as a sourceType to a destinationType.
[ "Encode", "data", "provided", "as", "a", "sourceType", "to", "a", "destinationType", "." ]
def convert(data, sourceType, destinationType, src_unitSize=None, src_endianness=AbstractType.defaultEndianness(), src_sign=AbstractType.defaultSign(), dst_unitSize=None, dst_endianness=AbstractType.defaultEndianness(), dst_sign=AbstractType.defaultSign()): """Encode data provided as a sourceType to a destinationType. To convert an ASCII to its binary (bitarray) representation >>> from netzob.all import * >>> data = "That's an helloworld!" >>> bin = TypeConverter.convert(data, ASCII, BitArray) >>> print(bin) bitarray('010101000110100001100001011101000010011101110011001000000110000101101110001000000110100001100101011011000110110001101111011101110110111101110010011011000110010000100001') >>> data == TypeConverter.convert(bin, BitArray, ASCII) True To convert a raw data to its decimal representation and then to its ASCII representation >>> data = b'\\x23' >>> decData = TypeConverter.convert(data, Raw, Integer) >>> print(decData) 35 >>> print(TypeConverter.convert(decData, Integer, ASCII)) # Conversion to and from Integer detects the output unitsize depending on the input: >>> TypeConverter.convert(b'\\x0b\\x00', Raw, Integer) 2816 >>> TypeConverter.convert(11, Integer, Raw) b'\\x0b' >>> TypeConverter.convert(b'\\xa0\\x0b', Raw, Integer, dst_sign=AbstractType.SIGN_SIGNED) -24565 >>> TypeConverter.convert(-24565, Integer, Raw, src_sign=AbstractType.SIGN_SIGNED) b'\\xa0\\x0b' >>> TypeConverter.convert(0, Integer, Raw) b'\\x00' >>> TypeConverter.convert(b'\\x00\\x00\\x00', Raw, Integer) Traceback (most recent call last): ... TypeError: Unsupported autodetected Integer target UnitSize. Valid UnitSizes are 8, 16, 32 and 64 bits. You can also play with the unitSize to convert multiple ascii in a single high value decimal >>> TypeConverter.convert("5", ASCII, Integer) 53 >>> print(TypeConverter.convert("zoby", ASCII, Integer)) 2054120057 >>> print(TypeConverter.convert("zoby", ASCII, Integer, dst_unitSize=AbstractType.UNITSIZE_32)) 2054120057 It also works for 'semantic' data like IPv4s >>> TypeConverter.convert("192.168.0.10", IPv4, Integer, dst_sign=AbstractType.SIGN_UNSIGNED) 3232235530 >>> TypeConverter.convert("127.0.0.1", IPv4, BitArray) bitarray('01111111000000000000000000000001') >>> TypeConverter.convert(167815360, Integer, IPv4, src_unitSize=AbstractType.UNITSIZE_32, src_sign=AbstractType.SIGN_UNSIGNED) IPAddress('10.0.168.192') To check Integer conversion consistency >>> f = Field(b'some') >>> v = f.domain.currentValue.tobytes() >>> try: ... v_hex = v.hex() ... except AttributeError: ... import codecs # Python <= 3.4: 'bytes' object has no attribute 'hex' ... v_hex = codecs.encode(v, 'hex_codec').decode('ascii') >>> '0x'+v_hex == hex(TypeConverter.convert(f.domain.currentValue, BitArray, Integer)) True :param sourceType: the data source type :type sourceType: :class:`type` :param destinationType: the destination type :type destinationType: :class:`type` :keyword src_unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_* :type src_unitSize: str :keyword src_endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE :type src_endianness: str :keyword src_sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED :type src_sign: str :keyword dst_unitSize: the unitsize of the expected result. Values must be one of AbstractType.UNITSIZE_* :type dst_unitSize: str :keyword dst_endianness: the endianness of the expected result. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE :type dst_endianness: str :keyword dst_sign: the sign of the expected result. Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED :type dst_sign: str :raise: TypeError if parameter not valid """ # Use defaultUnitSize for all types except Integer if dst_unitSize is None and destinationType is not Integer: dst_unitSize = AbstractType.defaultUnitSize() if src_unitSize is None and sourceType is not Integer: src_unitSize = AbstractType.defaultUnitSize() # is the two formats supported ? if sourceType not in TypeConverter.supportedTypes(): raise TypeError( "The source type ({0}) is not supported".format(sourceType)) if destinationType not in TypeConverter.supportedTypes(): raise TypeError("The destination type ({0}) is not supported". format(destinationType)) if data is None: raise TypeError("Data cannot be None") # Do we have a specific source to destination encoding function if (sourceType, destinationType ) in list(TypeConverter.__directEncoding().keys()): func = TypeConverter.__directEncoding()[(sourceType, destinationType)] return func(data, src_unitSize, src_endianness, src_sign, dst_unitSize, dst_endianness, dst_sign) else: # Convert from source to raw if sourceType is not Raw: if sourceType is Integer and src_unitSize is None: src_unitSize = Integer.checkUnitSizeForValue(data,src_sign) binData = sourceType.decode( data, unitSize=src_unitSize, endianness=src_endianness, sign=src_sign) else: binData = data # Convert from raw to Destination if destinationType is not Raw: if destinationType is Integer and dst_unitSize is None: nbUnits = len(binData) if nbUnits == 8: dst_unitSize = AbstractType.UNITSIZE_64 elif nbUnits == 4: dst_unitSize = AbstractType.UNITSIZE_32 elif nbUnits == 2: dst_unitSize = AbstractType.UNITSIZE_16 elif nbUnits == 1: dst_unitSize = AbstractType.UNITSIZE_8 else: raise TypeError("Unsupported autodetected Integer target UnitSize. Valid UnitSizes are 8, 16, 32 and 64 bits.") outputData = destinationType.encode( binData, unitSize=dst_unitSize, endianness=dst_endianness, sign=dst_sign) else: outputData = binData return outputData
[ "def", "convert", "(", "data", ",", "sourceType", ",", "destinationType", ",", "src_unitSize", "=", "None", ",", "src_endianness", "=", "AbstractType", ".", "defaultEndianness", "(", ")", ",", "src_sign", "=", "AbstractType", ".", "defaultSign", "(", ")", ",",...
https://github.com/netzob/netzob/blob/49ee3e5e7d6dce67496afd5a75827a78be0c9f70/netzob/src/netzob/Model/Vocabulary/Types/TypeConverter.py#L64-L219
jliljebl/flowblade
995313a509b80e99eb1ad550d945bdda5995093b
flowblade-trunk/Flowblade/app.py
python
display_current_sequence
()
[]
def display_current_sequence(): # Get shorter alias. player = editorstate.player player.consumer.stop() player.init_for_profile(editorstate.project.profile) player.create_sdl_consumer() player.set_tracktor_producer(editorstate.current_sequence().tractor) player.connect_and_start() updater.display_sequence_in_monitor() player.seek_frame(0) updater.repaint_tline()
[ "def", "display_current_sequence", "(", ")", ":", "# Get shorter alias.", "player", "=", "editorstate", ".", "player", "player", ".", "consumer", ".", "stop", "(", ")", "player", ".", "init_for_profile", "(", "editorstate", ".", "project", ".", "profile", ")", ...
https://github.com/jliljebl/flowblade/blob/995313a509b80e99eb1ad550d945bdda5995093b/flowblade-trunk/Flowblade/app.py#L757-L768
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/core/cache/backends/memcached.py
python
BaseMemcachedCache._get_memcache_timeout
(self, timeout)
return int(timeout)
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout.
[ "Memcached", "deals", "with", "long", "(", ">", "30", "days", ")", "timeouts", "in", "a", "special", "way", ".", "Call", "this", "function", "to", "obtain", "a", "safe", "value", "for", "your", "timeout", "." ]
def _get_memcache_timeout(self, timeout): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ timeout = timeout or self.default_timeout if timeout > 2592000: # 60*60*24*30, 30 days # See http://code.google.com/p/memcached/wiki/FAQ # "You can set expire times up to 30 days in the future. After that # memcached interprets it as a date, and will expire the item after # said date. This is a simple (but obscure) mechanic." # # This means that we have to switch to absolute timestamps. timeout += int(time.time()) return int(timeout)
[ "def", "_get_memcache_timeout", "(", "self", ",", "timeout", ")", ":", "timeout", "=", "timeout", "or", "self", ".", "default_timeout", "if", "timeout", ">", "2592000", ":", "# 60*60*24*30, 30 days", "# See http://code.google.com/p/memcached/wiki/FAQ", "# \"You can set ex...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/core/cache/backends/memcached.py#L38-L52
visionml/pytracking
3e6a8980db7a2275252abcc398ed0c2494f0ceab
pytracking/utils/params.py
python
TrackerParams.get
(self, name: str, *default)
return getattr(self, name, default[0])
Get a parameter value with the given name. If it does not exists, it return the default value given as a second argument or returns an error if no default value is given.
Get a parameter value with the given name. If it does not exists, it return the default value given as a second argument or returns an error if no default value is given.
[ "Get", "a", "parameter", "value", "with", "the", "given", "name", ".", "If", "it", "does", "not", "exists", "it", "return", "the", "default", "value", "given", "as", "a", "second", "argument", "or", "returns", "an", "error", "if", "no", "default", "value...
def get(self, name: str, *default): """Get a parameter value with the given name. If it does not exists, it return the default value given as a second argument or returns an error if no default value is given.""" if len(default) > 1: raise ValueError('Can only give one default value.') if not default: return getattr(self, name) return getattr(self, name, default[0])
[ "def", "get", "(", "self", ",", "name", ":", "str", ",", "*", "default", ")", ":", "if", "len", "(", "default", ")", ">", "1", ":", "raise", "ValueError", "(", "'Can only give one default value.'", ")", "if", "not", "default", ":", "return", "getattr", ...
https://github.com/visionml/pytracking/blob/3e6a8980db7a2275252abcc398ed0c2494f0ceab/pytracking/utils/params.py#L12-L21
LabPy/lantz
3e878e3f765a4295b0089d04e241d4beb7b8a65b
lantz/drivers/legacy/newport/powermeter1830c.py
python
powermeter1830c.go
(self)
return int(self.query('G?'))
Enable or disable the power meter from taking new measurements.
Enable or disable the power meter from taking new measurements.
[ "Enable", "or", "disable", "the", "power", "meter", "from", "taking", "new", "measurements", "." ]
def go(self): """ Enable or disable the power meter from taking new measurements. """ return int(self.query('G?'))
[ "def", "go", "(", "self", ")", ":", "return", "int", "(", "self", ".", "query", "(", "'G?'", ")", ")" ]
https://github.com/LabPy/lantz/blob/3e878e3f765a4295b0089d04e241d4beb7b8a65b/lantz/drivers/legacy/newport/powermeter1830c.py#L87-L90
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/zipfile.py
python
ZipFile._GetContents
(self)
Read the directory, making sure we close the file if the format is bad.
Read the directory, making sure we close the file if the format is bad.
[ "Read", "the", "directory", "making", "sure", "we", "close", "the", "file", "if", "the", "format", "is", "bad", "." ]
def _GetContents(self): """Read the directory, making sure we close the file if the format is bad.""" try: self._RealGetContents() except BadZipFile: if not self._filePassed: self.fp.close() self.fp = None raise
[ "def", "_GetContents", "(", "self", ")", ":", "try", ":", "self", ".", "_RealGetContents", "(", ")", "except", "BadZipFile", ":", "if", "not", "self", ".", "_filePassed", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "None",...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/zipfile.py#L753-L762
gmplot/gmplot
8654a5a370b5ec309e1282c457eaf375c3dcb4bb
gmplot/utility.py
python
_write_to_sidebar
(file, name, link=None, depth=0)
Add an item to the GitHub Wiki _Sidebar file as a link. Args: file (handle): _Sidebar file. name (str): Readable name of the item to be added. Optional: Args: link (str): Link to the item of interest. If not specified, the item name will be used as the link. depth (int): Indentation level of the given item in the _Sidebar. Defaults to 0.
Add an item to the GitHub Wiki _Sidebar file as a link.
[ "Add", "an", "item", "to", "the", "GitHub", "Wiki", "_Sidebar", "file", "as", "a", "link", "." ]
def _write_to_sidebar(file, name, link=None, depth=0): ''' Add an item to the GitHub Wiki _Sidebar file as a link. Args: file (handle): _Sidebar file. name (str): Readable name of the item to be added. Optional: Args: link (str): Link to the item of interest. If not specified, the item name will be used as the link. depth (int): Indentation level of the given item in the _Sidebar. Defaults to 0. ''' link_content = name if link is not None and name != link: link_content += '|' + link formatted_link = '[[%s]]' % link_content if depth == 0: file.write(_bookend(formatted_link, '**') + '\n') else: file.write(_INDENT * (depth - 1) + '* ' + formatted_link) file.write('\n')
[ "def", "_write_to_sidebar", "(", "file", ",", "name", ",", "link", "=", "None", ",", "depth", "=", "0", ")", ":", "link_content", "=", "name", "if", "link", "is", "not", "None", "and", "name", "!=", "link", ":", "link_content", "+=", "'|'", "+", "lin...
https://github.com/gmplot/gmplot/blob/8654a5a370b5ec309e1282c457eaf375c3dcb4bb/gmplot/utility.py#L106-L130
lvpengyuan/masktextspotter.caffe2
da99ef31f5ccb4de5248bb881d5b4a291910c8ae
lib/modeling/generate_anchors.py
python
_mkanchors
(ws, hs, x_ctr, y_ctr)
return anchors
Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows).
Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows).
[ "Given", "a", "vector", "of", "widths", "(", "ws", ")", "and", "heights", "(", "hs", ")", "around", "a", "center", "(", "x_ctr", "y_ctr", ")", "output", "a", "set", "of", "anchors", "(", "windows", ")", "." ]
def _mkanchors(ws, hs, x_ctr, y_ctr): """Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack( ( x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1) ) ) return anchors
[ "def", "_mkanchors", "(", "ws", ",", "hs", ",", "x_ctr", ",", "y_ctr", ")", ":", "ws", "=", "ws", "[", ":", ",", "np", ".", "newaxis", "]", "hs", "=", "hs", "[", ":", ",", "np", ".", "newaxis", "]", "anchors", "=", "np", ".", "hstack", "(", ...
https://github.com/lvpengyuan/masktextspotter.caffe2/blob/da99ef31f5ccb4de5248bb881d5b4a291910c8ae/lib/modeling/generate_anchors.py#L89-L103
tensorflow/datasets
2e496976d7d45550508395fb2f35cf958c8a3414
tensorflow_datasets/image/lost_and_found.py
python
LostAndFound._split_generators
(self, dl_manager)
return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ feat: path.join(dl_paths[feat], zip_file_names[feat], 'train') for feat in self.builder_config.features }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, # These kwargs will be passed to _generate_examples gen_kwargs={ feat: path.join(dl_paths[feat], zip_file_names[feat], 'test') for feat in self.builder_config.features }, ) ]
Returns SplitGenerators.
Returns SplitGenerators.
[ "Returns", "SplitGenerators", "." ]
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" base_url = 'http://www.dhbw-stuttgart.de/~sgehrig/lostAndFoundDataset/{}.zip' # For each feature, this is the name of the zipfile and # root-directory in the archive zip_file_names = { 'image_left': self.builder_config.left_image_string, 'image_right': self.builder_config.right_image_string, 'segmentation_label': 'gtCoarse', 'instance_id': 'gtCoarse', 'disparity_map': 'disparity' } download_urls = { feat: base_url.format(zip_file_names[feat]) for feat in self.builder_config.features } # Split download and extract in two functions such that mock-data can # replace the result of the download function and is still used as input to # extract. Therefore, fake_data can be compressed zip archives. dl_paths = dl_manager.extract(dl_manager.download(download_urls)) return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, # These kwargs will be passed to _generate_examples gen_kwargs={ feat: path.join(dl_paths[feat], zip_file_names[feat], 'train') for feat in self.builder_config.features }, ), tfds.core.SplitGenerator( name=tfds.Split.TEST, # These kwargs will be passed to _generate_examples gen_kwargs={ feat: path.join(dl_paths[feat], zip_file_names[feat], 'test') for feat in self.builder_config.features }, ) ]
[ "def", "_split_generators", "(", "self", ",", "dl_manager", ")", ":", "base_url", "=", "'http://www.dhbw-stuttgart.de/~sgehrig/lostAndFoundDataset/{}.zip'", "# For each feature, this is the name of the zipfile and", "# root-directory in the archive", "zip_file_names", "=", "{", "'ima...
https://github.com/tensorflow/datasets/blob/2e496976d7d45550508395fb2f35cf958c8a3414/tensorflow_datasets/image/lost_and_found.py#L162-L202
qutip/qutip
52d01da181a21b810c3407812c670f35fdc647e8
qutip/control/fidcomp.py
python
FidCompTraceDiff.get_fid_err_gradient
(self)
return self.fid_err_grad
Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array The gradients are cached in case they are requested mutliple times between control updates (although this is not typically found to happen)
Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array The gradients are cached in case they are requested mutliple times between control updates (although this is not typically found to happen)
[ "Returns", "the", "normalised", "gradient", "of", "the", "fidelity", "error", "in", "a", "(", "nTimeslots", "x", "n_ctrls", ")", "array", "The", "gradients", "are", "cached", "in", "case", "they", "are", "requested", "mutliple", "times", "between", "control", ...
def get_fid_err_gradient(self): """ Returns the normalised gradient of the fidelity error in a (nTimeslots x n_ctrls) array The gradients are cached in case they are requested mutliple times between control updates (although this is not typically found to happen) """ if not self.fid_err_grad_current: dyn = self.parent self.fid_err_grad = self.compute_fid_err_grad() self.fid_err_grad_current = True if dyn.stats is not None: dyn.stats.num_grad_computes += 1 self.grad_norm = np.sqrt(np.sum(self.fid_err_grad**2)) if self.log_level <= logging.DEBUG_INTENSE: logger.log(logging.DEBUG_INTENSE, "fidelity error gradients:\n" "{}".format(self.fid_err_grad)) if self.log_level <= logging.DEBUG: logger.debug("Gradient norm: " "{} ".format(self.grad_norm)) return self.fid_err_grad
[ "def", "get_fid_err_gradient", "(", "self", ")", ":", "if", "not", "self", ".", "fid_err_grad_current", ":", "dyn", "=", "self", ".", "parent", "self", ".", "fid_err_grad", "=", "self", ".", "compute_fid_err_grad", "(", ")", "self", ".", "fid_err_grad_current"...
https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/control/fidcomp.py#L605-L629
matplotlib/matplotlib
8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322
lib/matplotlib/font_manager.py
python
FontManager.get_font_names
(self)
return list(set([font.name for font in self.ttflist]))
Return the list of available fonts.
Return the list of available fonts.
[ "Return", "the", "list", "of", "available", "fonts", "." ]
def get_font_names(self): """Return the list of available fonts.""" return list(set([font.name for font in self.ttflist]))
[ "def", "get_font_names", "(", "self", ")", ":", "return", "list", "(", "set", "(", "[", "font", ".", "name", "for", "font", "in", "self", ".", "ttflist", "]", ")", ")" ]
https://github.com/matplotlib/matplotlib/blob/8d7a2b9d2a38f01ee0d6802dd4f9e98aec812322/lib/matplotlib/font_manager.py#L1334-L1336
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
web2py/venv/lib/python2.7/encodings/zlib_codec.py
python
zlib_decode
(input,errors='strict')
return (output, len(input))
Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
Decodes the object input and returns a tuple (output object, length consumed).
[ "Decodes", "the", "object", "input", "and", "returns", "a", "tuple", "(", "output", "object", "length", "consumed", ")", "." ]
def zlib_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = zlib.decompress(input) return (output, len(input))
[ "def", "zlib_decode", "(", "input", ",", "errors", "=", "'strict'", ")", ":", "assert", "errors", "==", "'strict'", "output", "=", "zlib", ".", "decompress", "(", "input", ")", "return", "(", "output", ",", "len", "(", "input", ")", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/web2py/venv/lib/python2.7/encodings/zlib_codec.py#L28-L44
EnableSecurity/sipvicious
89228319d0652f3bdd920d1d4ff97b4791f0bb28
sipvicious/libs/svhelper.py
python
numToDottedQuad
(n)
return socket.inet_ntoa(struct.pack('!L', n))
convert long int to dotted quad string
convert long int to dotted quad string
[ "convert", "long", "int", "to", "dotted", "quad", "string" ]
def numToDottedQuad(n): "convert long int to dotted quad string" return socket.inet_ntoa(struct.pack('!L', n))
[ "def", "numToDottedQuad", "(", "n", ")", ":", "return", "socket", ".", "inet_ntoa", "(", "struct", ".", "pack", "(", "'!L'", ",", "n", ")", ")" ]
https://github.com/EnableSecurity/sipvicious/blob/89228319d0652f3bdd920d1d4ff97b4791f0bb28/sipvicious/libs/svhelper.py#L692-L694
tao12345666333/tornado-zh
e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c
tornado/tcpclient.py
python
_Connector.split
(addrinfo)
return primary, secondary
Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families).
Partition the ``addrinfo`` list by address family.
[ "Partition", "the", "addrinfo", "list", "by", "address", "family", "." ]
def split(addrinfo): """Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """ primary = [] secondary = [] primary_af = addrinfo[0][0] for af, addr in addrinfo: if af == primary_af: primary.append((af, addr)) else: secondary.append((af, addr)) return primary, secondary
[ "def", "split", "(", "addrinfo", ")", ":", "primary", "=", "[", "]", "secondary", "=", "[", "]", "primary_af", "=", "addrinfo", "[", "0", "]", "[", "0", "]", "for", "af", ",", "addr", "in", "addrinfo", ":", "if", "af", "==", "primary_af", ":", "p...
https://github.com/tao12345666333/tornado-zh/blob/e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c/tornado/tcpclient.py#L61-L78
richardaecn/class-balanced-loss
1d7857208a2abc03d84e35a9d5383af8225d4b4d
tpu/models/experimental/inception/inception_v2.py
python
InputPipeline.input_fn
(self, params)
return images, labels
Input function which provides a single batch for train or eval. Args: params: `dict` of parameters passed from the `TPUEstimator`. `params['batch_size']` is always provided and should be used as the effective batch size. Returns: A (images, labels) tuple of `Tensor`s for a batch of samples.
Input function which provides a single batch for train or eval.
[ "Input", "function", "which", "provides", "a", "single", "batch", "for", "train", "or", "eval", "." ]
def input_fn(self, params): """Input function which provides a single batch for train or eval. Args: params: `dict` of parameters passed from the `TPUEstimator`. `params['batch_size']` is always provided and should be used as the effective batch size. Returns: A (images, labels) tuple of `Tensor`s for a batch of samples. """ batch_size = params['batch_size'] if FLAGS.use_data == 'real': file_pattern = os.path.join( self.data_dir, 'train-*' if self.is_training else 'validation-*') dataset = tf.data.Dataset.list_files(file_pattern, shuffle=self.is_training) if self.is_training: dataset = dataset.repeat() def prefetch_dataset(filename): dataset = tf.data.TFRecordDataset( filename, buffer_size=FLAGS.prefetch_dataset_buffer_size) return dataset dataset = dataset.apply( tf.contrib.data.parallel_interleave( prefetch_dataset, cycle_length=FLAGS.num_files_infeed, sloppy=True)) if FLAGS.followup_shuffle_buffer_size > 0: dataset = dataset.shuffle( buffer_size=FLAGS.followup_shuffle_buffer_size) dataset = dataset.map( self.dataset_parser, num_parallel_calls=FLAGS.num_parallel_calls) dataset = dataset.prefetch(batch_size) dataset = dataset.apply( tf.contrib.data.batch_and_drop_remainder(batch_size)) dataset = dataset.prefetch(2) # Prefetch overlaps in-feed with training images, labels = dataset.make_one_shot_iterator().get_next() else: images = tf.random_uniform( [batch_size, FLAGS.height, FLAGS.width, 3], minval=-1, maxval=1) labels = tf.random_uniform( [batch_size], minval=0, maxval=999, dtype=tf.int32) images = tensor_transform_fn(images, params['output_perm']) return images, labels
[ "def", "input_fn", "(", "self", ",", "params", ")", ":", "batch_size", "=", "params", "[", "'batch_size'", "]", "if", "FLAGS", ".", "use_data", "==", "'real'", ":", "file_pattern", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_dir", ",",...
https://github.com/richardaecn/class-balanced-loss/blob/1d7857208a2abc03d84e35a9d5383af8225d4b4d/tpu/models/experimental/inception/inception_v2.py#L332-L388
google/ml-fairness-gym
5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9
agents/allocation_agents.py
python
MLEGreedyAgent._construct_approx_fi_table
(self, n_bins, rates, n_resource)
return fi
Constructs a n_bins by n_resource+1 matrix of f_i values. Args: n_bins: int number of bins. rates: rate for each bin. n_resource: int number of resources available to allocate. Returns: np.ndarray of f_i(v_i) for every allocation, bin pair.
Constructs a n_bins by n_resource+1 matrix of f_i values.
[ "Constructs", "a", "n_bins", "by", "n_resource", "+", "1", "matrix", "of", "f_i", "values", "." ]
def _construct_approx_fi_table(self, n_bins, rates, n_resource): """Constructs a n_bins by n_resource+1 matrix of f_i values. Args: n_bins: int number of bins. rates: rate for each bin. n_resource: int number of resources available to allocate. Returns: np.ndarray of f_i(v_i) for every allocation, bin pair. """ c_values = np.array( range(1, self.params.poisson_truncation_val), dtype=float).reshape( (self.params.poisson_truncation_val - 1, 1)) c_values_with0 = np.array( range(self.params.poisson_truncation_val), dtype=float).reshape( (self.params.poisson_truncation_val, 1)) alloc_vals = np.array( range(1, n_resource), dtype=float).reshape((n_resource - 1, 1)) poissons = stats.poisson(mu=np.array(rates)) pmf_values = poissons.pmf(c_values_with0) minimums = np.minimum(alloc_vals.T, c_values) mins_over_c = np.divide(minimums, c_values) # defining 0/0 to be 1, can change to np.zeros if 0/0 should be zero. mins_over_c = np.concatenate((np.ones((1, n_resource - 1)), mins_over_c), axis=0) # can also switch the order of these concatenates depending on if min(v,c)/c # where v=0, c=0 should be 0 or one. mins_over_c = np.concatenate((np.zeros( (self.params.poisson_truncation_val, 1)), mins_over_c), axis=1) fi = np.matmul(pmf_values.T, mins_over_c) return fi
[ "def", "_construct_approx_fi_table", "(", "self", ",", "n_bins", ",", "rates", ",", "n_resource", ")", ":", "c_values", "=", "np", ".", "array", "(", "range", "(", "1", ",", "self", ".", "params", ".", "poisson_truncation_val", ")", ",", "dtype", "=", "f...
https://github.com/google/ml-fairness-gym/blob/5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9/agents/allocation_agents.py#L512-L545
replit-archive/empythoned
977ec10ced29a3541a4973dc2b59910805695752
dist/lib/python2.7/distutils/ccompiler.py
python
CCompiler.add_runtime_library_dir
(self, dir)
Add 'dir' to the list of directories that will be searched for shared libraries at runtime.
Add 'dir' to the list of directories that will be searched for shared libraries at runtime.
[ "Add", "dir", "to", "the", "list", "of", "directories", "that", "will", "be", "searched", "for", "shared", "libraries", "at", "runtime", "." ]
def add_runtime_library_dir(self, dir): """Add 'dir' to the list of directories that will be searched for shared libraries at runtime. """ self.runtime_library_dirs.append(dir)
[ "def", "add_runtime_library_dir", "(", "self", ",", "dir", ")", ":", "self", ".", "runtime_library_dirs", ".", "append", "(", "dir", ")" ]
https://github.com/replit-archive/empythoned/blob/977ec10ced29a3541a4973dc2b59910805695752/dist/lib/python2.7/distutils/ccompiler.py#L337-L341
d2l-ai/d2l-zh
1c2e25a557db446b5691c18e595e5664cc254730
d2l/mxnet.py
python
load_array
(data_arrays, batch_size, is_train=True)
return gluon.data.DataLoader(dataset, batch_size, shuffle=is_train)
构造一个Gluon数据迭代器 Defined in :numref:`sec_linear_concise`
构造一个Gluon数据迭代器
[ "构造一个Gluon数据迭代器" ]
def load_array(data_arrays, batch_size, is_train=True): """构造一个Gluon数据迭代器 Defined in :numref:`sec_linear_concise`""" dataset = gluon.data.ArrayDataset(*data_arrays) return gluon.data.DataLoader(dataset, batch_size, shuffle=is_train)
[ "def", "load_array", "(", "data_arrays", ",", "batch_size", ",", "is_train", "=", "True", ")", ":", "dataset", "=", "gluon", ".", "data", ".", "ArrayDataset", "(", "*", "data_arrays", ")", "return", "gluon", ".", "data", ".", "DataLoader", "(", "dataset", ...
https://github.com/d2l-ai/d2l-zh/blob/1c2e25a557db446b5691c18e595e5664cc254730/d2l/mxnet.py#L144-L149
rossant/galry
6201fa32fb5c9ef3cea700cc22caf52fb69ebe31
galry/processors/navigation_processor.py
python
NavigationEventProcessor.process_zoom_event
(self, parameter)
[]
def process_zoom_event(self, parameter): self.zoom(parameter) self.parent.block_refresh = False # Block momentum when zooming. self.momentum = False self.set_cursor('MagnifyingGlassCursor') self.transform_view()
[ "def", "process_zoom_event", "(", "self", ",", "parameter", ")", ":", "self", ".", "zoom", "(", "parameter", ")", "self", ".", "parent", ".", "block_refresh", "=", "False", "# Block momentum when zooming.", "self", ".", "momentum", "=", "False", "self", ".", ...
https://github.com/rossant/galry/blob/6201fa32fb5c9ef3cea700cc22caf52fb69ebe31/galry/processors/navigation_processor.py#L133-L139
TeamMsgExtractor/msg-extractor
8a3a0255a7306bdb8073bd8f222d3be5c688080a
extract_msg/appointment.py
python
Appointment.resourceAttendees
(self)
return self._ensureSetNamed('_resourceAttendees', '0008')
Returns the resource attendees of the meeting.
Returns the resource attendees of the meeting.
[ "Returns", "the", "resource", "attendees", "of", "the", "meeting", "." ]
def resourceAttendees(self): """ Returns the resource attendees of the meeting. """ return self._ensureSetNamed('_resourceAttendees', '0008')
[ "def", "resourceAttendees", "(", "self", ")", ":", "return", "self", ".", "_ensureSetNamed", "(", "'_resourceAttendees'", ",", "'0008'", ")" ]
https://github.com/TeamMsgExtractor/msg-extractor/blob/8a3a0255a7306bdb8073bd8f222d3be5c688080a/extract_msg/appointment.py#L54-L58
timbrel/GitSavvy
c0a627c30da79cb10a5a33f30d92d177f78da0ab
core/git_command.py
python
_GitCommand.repo_path
(self)
return self.get_repo_path()
Return the absolute path to the git repo that contains the file that this view interacts with. Like `file_path`, this can be overridden by setting the view's `git_savvy.repo_path` setting.
Return the absolute path to the git repo that contains the file that this view interacts with. Like `file_path`, this can be overridden by setting the view's `git_savvy.repo_path` setting.
[ "Return", "the", "absolute", "path", "to", "the", "git", "repo", "that", "contains", "the", "file", "that", "this", "view", "interacts", "with", ".", "Like", "file_path", "this", "can", "be", "overridden", "by", "setting", "the", "view", "s", "git_savvy", ...
def repo_path(self): # type: () -> str """ Return the absolute path to the git repo that contains the file that this view interacts with. Like `file_path`, this can be overridden by setting the view's `git_savvy.repo_path` setting. """ return self.get_repo_path()
[ "def", "repo_path", "(", "self", ")", ":", "# type: () -> str", "return", "self", ".", "get_repo_path", "(", ")" ]
https://github.com/timbrel/GitSavvy/blob/c0a627c30da79cb10a5a33f30d92d177f78da0ab/core/git_command.py#L503-L510
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/setuptools/pep425tags.py
python
get_flag
(var, fallback, expected=True, warn=True)
return val == expected
Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.
Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.
[ "Use", "a", "fallback", "method", "for", "determining", "SOABI", "flags", "if", "the", "needed", "config", "var", "is", "unset", "or", "unavailable", "." ]
def get_flag(var, fallback, expected=True, warn=True): """Use a fallback method for determining SOABI flags if the needed config var is unset or unavailable.""" val = get_config_var(var) if val is None: if warn: log.debug("Config variable '%s' is unset, Python ABI tag may " "be incorrect", var) return fallback() return val == expected
[ "def", "get_flag", "(", "var", ",", "fallback", ",", "expected", "=", "True", ",", "warn", "=", "True", ")", ":", "val", "=", "get_config_var", "(", "var", ")", "if", "val", "is", "None", ":", "if", "warn", ":", "log", ".", "debug", "(", "\"Config ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/setuptools/pep425tags.py#L67-L76
okigan/awscurl
ea2a9b192e80053a4edf7dbfe7b390e249a92527
awscurl/utils.py
python
sha256_hash_for_binary_data
(val)
return hashlib.sha256(val).hexdigest()
Sha256 hash of binary data.
Sha256 hash of binary data.
[ "Sha256", "hash", "of", "binary", "data", "." ]
def sha256_hash_for_binary_data(val): """ Sha256 hash of binary data. """ return hashlib.sha256(val).hexdigest()
[ "def", "sha256_hash_for_binary_data", "(", "val", ")", ":", "return", "hashlib", ".", "sha256", "(", "val", ")", ".", "hexdigest", "(", ")" ]
https://github.com/okigan/awscurl/blob/ea2a9b192e80053a4edf7dbfe7b390e249a92527/awscurl/utils.py#L16-L20
xonsh/xonsh
b76d6f994f22a4078f602f8b386f4ec280c8461f
xonsh/jupyter_shell.py
python
StdJupyterRedirectBuf.fileno
(self)
return self.redirect.fileno()
Returns the file descriptor of the std buffer.
Returns the file descriptor of the std buffer.
[ "Returns", "the", "file", "descriptor", "of", "the", "std", "buffer", "." ]
def fileno(self): """Returns the file descriptor of the std buffer.""" return self.redirect.fileno()
[ "def", "fileno", "(", "self", ")", ":", "return", "self", ".", "redirect", ".", "fileno", "(", ")" ]
https://github.com/xonsh/xonsh/blob/b76d6f994f22a4078f602f8b386f4ec280c8461f/xonsh/jupyter_shell.py#L17-L19
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/venv/lib/python2.7/site-packages/pkg_resources/__init__.py
python
ZipManifests.build
(cls, path)
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows.
Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects.
[ "Build", "a", "dictionary", "similar", "to", "the", "zipimport", "directory", "caches", "except", "instead", "of", "tuples", "store", "ZipInfo", "objects", "." ]
def build(cls, path): """ Build a dictionary similar to the zipimport directory caches, except instead of tuples, store ZipInfo objects. Use a platform-specific path separator (os.sep) for the path keys for compatibility with pypy on Windows. """ with ContextualZipFile(path) as zfile: items = ( ( name.replace('/', os.sep), zfile.getinfo(name), ) for name in zfile.namelist() ) return dict(items)
[ "def", "build", "(", "cls", ",", "path", ")", ":", "with", "ContextualZipFile", "(", "path", ")", "as", "zfile", ":", "items", "=", "(", "(", "name", ".", "replace", "(", "'/'", ",", "os", ".", "sep", ")", ",", "zfile", ".", "getinfo", "(", "name...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/venv/lib/python2.7/site-packages/pkg_resources/__init__.py#L1719-L1735
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/jinja2/compiler.py
python
FrameIdentifierVisitor.visit_For
(self, node)
Visiting stops at for blocks. However the block sequence is visited as part of the outer scope.
Visiting stops at for blocks. However the block sequence is visited as part of the outer scope.
[ "Visiting", "stops", "at", "for", "blocks", ".", "However", "the", "block", "sequence", "is", "visited", "as", "part", "of", "the", "outer", "scope", "." ]
def visit_For(self, node): """Visiting stops at for blocks. However the block sequence is visited as part of the outer scope. """ self.visit(node.iter)
[ "def", "visit_For", "(", "self", ",", "node", ")", ":", "self", ".", "visit", "(", "node", ".", "iter", ")" ]
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/jinja2/compiler.py#L338-L342
junsukchoe/ADL
dab2e78163bd96970ec9ae41de62835332dbf4fe
tensorpack/dataflow/common.py
python
MapData.__init__
(self, ds, func)
Args: ds (DataFlow): input DataFlow func (datapoint -> datapoint | None): takes a datapoint and returns a new datapoint. Return None to discard/skip this datapoint.
Args: ds (DataFlow): input DataFlow func (datapoint -> datapoint | None): takes a datapoint and returns a new datapoint. Return None to discard/skip this datapoint.
[ "Args", ":", "ds", "(", "DataFlow", ")", ":", "input", "DataFlow", "func", "(", "datapoint", "-", ">", "datapoint", "|", "None", ")", ":", "takes", "a", "datapoint", "and", "returns", "a", "new", "datapoint", ".", "Return", "None", "to", "discard", "/"...
def __init__(self, ds, func): """ Args: ds (DataFlow): input DataFlow func (datapoint -> datapoint | None): takes a datapoint and returns a new datapoint. Return None to discard/skip this datapoint. """ super(MapData, self).__init__(ds) self.func = func
[ "def", "__init__", "(", "self", ",", "ds", ",", "func", ")", ":", "super", "(", "MapData", ",", "self", ")", ".", "__init__", "(", "ds", ")", "self", ".", "func", "=", "func" ]
https://github.com/junsukchoe/ADL/blob/dab2e78163bd96970ec9ae41de62835332dbf4fe/tensorpack/dataflow/common.py#L304-L312
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/iam/connection.py
python
IAMConnection.get_all_users
(self, path_prefix='/', marker=None, max_items=None)
return self.get_response('ListUsers', params, list_marker='Users')
List the users that have the specified path prefix. :type path_prefix: string :param path_prefix: If provided, only users whose paths match the provided prefix will be returned. :type marker: string :param marker: Use this only when paginating results and only in follow-up request after you've received a response where the results are truncated. Set this to the value of the Marker element in the response you just received. :type max_items: int :param max_items: Use this only when paginating results to indicate the maximum number of groups you want in the response.
List the users that have the specified path prefix.
[ "List", "the", "users", "that", "have", "the", "specified", "path", "prefix", "." ]
def get_all_users(self, path_prefix='/', marker=None, max_items=None): """ List the users that have the specified path prefix. :type path_prefix: string :param path_prefix: If provided, only users whose paths match the provided prefix will be returned. :type marker: string :param marker: Use this only when paginating results and only in follow-up request after you've received a response where the results are truncated. Set this to the value of the Marker element in the response you just received. :type max_items: int :param max_items: Use this only when paginating results to indicate the maximum number of groups you want in the response. """ params = {'PathPrefix': path_prefix} if marker: params['Marker'] = marker if max_items: params['MaxItems'] = max_items return self.get_response('ListUsers', params, list_marker='Users')
[ "def", "get_all_users", "(", "self", ",", "path_prefix", "=", "'/'", ",", "marker", "=", "None", ",", "max_items", "=", "None", ")", ":", "params", "=", "{", "'PathPrefix'", ":", "path_prefix", "}", "if", "marker", ":", "params", "[", "'Marker'", "]", ...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/iam/connection.py#L314-L337
realpython/book2-exercises
cde325eac8e6d8cff2316601c2e5b36bb46af7d0
py2manager/gluon/contrib/pysimplesoap/simplexml.py
python
SimpleXMLElement.add_comment
(self, data)
Add an xml comment to this child
Add an xml comment to this child
[ "Add", "an", "xml", "comment", "to", "this", "child" ]
def add_comment(self, data): """Add an xml comment to this child""" comment = self.__document.createComment(data) self._element.appendChild(comment)
[ "def", "add_comment", "(", "self", ",", "data", ")", ":", "comment", "=", "self", ".", "__document", ".", "createComment", "(", "data", ")", "self", ".", "_element", ".", "appendChild", "(", "comment", ")" ]
https://github.com/realpython/book2-exercises/blob/cde325eac8e6d8cff2316601c2e5b36bb46af7d0/py2manager/gluon/contrib/pysimplesoap/simplexml.py#L108-L111
Antergos/Cnchi
13ac2209da9432d453e0097cf48a107640b563a9
src/pacman/pac.py
python
Pac.remove
(self, pkg_names, options=None)
return self.finalize_transaction(transaction)
Removes a list of package names
Removes a list of package names
[ "Removes", "a", "list", "of", "package", "names" ]
def remove(self, pkg_names, options=None): """ Removes a list of package names """ if not options: options = {} # Prepare target list targets = [] database = self.handle.get_localdb() for pkg_name in pkg_names: pkg = database.get_pkg(pkg_name) if pkg is None: logging.error("Target %s not found", pkg_name) return False targets.append(pkg) transaction = self.init_transaction(options) if transaction is None: logging.error("Can't init transaction") return False for pkg in targets: logging.debug( "Adding package '%s' to remove transaction", pkg.name) transaction.remove_pkg(pkg) return self.finalize_transaction(transaction)
[ "def", "remove", "(", "self", ",", "pkg_names", ",", "options", "=", "None", ")", ":", "if", "not", "options", ":", "options", "=", "{", "}", "# Prepare target list", "targets", "=", "[", "]", "database", "=", "self", ".", "handle", ".", "get_localdb", ...
https://github.com/Antergos/Cnchi/blob/13ac2209da9432d453e0097cf48a107640b563a9/src/pacman/pac.py#L206-L233
moodoki/semantic_image_inpainting
c9201b0707b0d200c2bdb89ca23af078cb9aa153
src/tools.py
python
binarizeMask
(mask, dtype=np.float32)
return bmask
Helper function, ensures mask is 0/1 or 0/255 and single channel. If dtype specified as float32 (default), output mask will be 0, 1 if required dtype is uint8, output mask will be 0, 255 Args: mask:. dtype:.
Helper function, ensures mask is 0/1 or 0/255 and single channel.
[ "Helper", "function", "ensures", "mask", "is", "0", "/", "1", "or", "0", "/", "255", "and", "single", "channel", "." ]
def binarizeMask(mask, dtype=np.float32): """Helper function, ensures mask is 0/1 or 0/255 and single channel. If dtype specified as float32 (default), output mask will be 0, 1 if required dtype is uint8, output mask will be 0, 255 Args: mask:. dtype:. """ assert(np.dtype(dtype) == np.float32 or np.dtype(dtype) == np.uint8) bmask = np.array(mask, dtype=np.float32) bmask[bmask>0] = 1.0 bmask[bmask<=0] = 0 if dtype == np.uint8: bmask = np.array(bmask*255, dtype=np.uint8) return bmask
[ "def", "binarizeMask", "(", "mask", ",", "dtype", "=", "np", ".", "float32", ")", ":", "assert", "(", "np", ".", "dtype", "(", "dtype", ")", "==", "np", ".", "float32", "or", "np", ".", "dtype", "(", "dtype", ")", "==", "np", ".", "uint8", ")", ...
https://github.com/moodoki/semantic_image_inpainting/blob/c9201b0707b0d200c2bdb89ca23af078cb9aa153/src/tools.py#L32-L48
ianwhale/nsga-net
0ee6225c4ad3afabe5f5e8fd6dcb6dfffb1faf2d
models/macro_decoder.py
python
ChannelBasedDecoder.__init__
(self, list_genome, channels, repeats=None)
Constructor. :param list_genome: list, genome describing the connections in a network. :param channels: list, list of tuples describing the channel size changes. :param repeats: None | list, list of integers describing how many times to repeat each phase.
Constructor. :param list_genome: list, genome describing the connections in a network. :param channels: list, list of tuples describing the channel size changes. :param repeats: None | list, list of integers describing how many times to repeat each phase.
[ "Constructor", ".", ":", "param", "list_genome", ":", "list", "genome", "describing", "the", "connections", "in", "a", "network", ".", ":", "param", "channels", ":", "list", "list", "of", "tuples", "describing", "the", "channel", "size", "changes", ".", ":",...
def __init__(self, list_genome, channels, repeats=None): """ Constructor. :param list_genome: list, genome describing the connections in a network. :param channels: list, list of tuples describing the channel size changes. :param repeats: None | list, list of integers describing how many times to repeat each phase. """ super().__init__(list_genome) self._model = None # First, we remove all inactive phases. self._genome = self.get_effective_genome(list_genome) self._channels = channels[:len(self._genome)] # Use the provided repeats list, or a list of all ones (only repeat each phase once). if repeats is not None: # First select only the repeats that are active in the list_genome. active_repeats = [] for idx, gene in enumerate(list_genome): if phase_active(gene): active_repeats.append(repeats[idx]) self.adjust_for_repeats(active_repeats) else: # Each phase only repeated once. self._repeats = [1 for _ in self._genome] # If we had no active nodes, our model is just the identity, and we stop constructing. if not self._genome: self._model = Identity()
[ "def", "__init__", "(", "self", ",", "list_genome", ",", "channels", ",", "repeats", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", "list_genome", ")", "self", ".", "_model", "=", "None", "# First, we remove all inactive phases.", "self", "....
https://github.com/ianwhale/nsga-net/blob/0ee6225c4ad3afabe5f5e8fd6dcb6dfffb1faf2d/models/macro_decoder.py#L32-L62
naftaliharris/tauthon
5587ceec329b75f7caf6d65a036db61ac1bae214
Lib/lib-tk/turtle.py
python
RawTurtle.tracer
(self, flag=None, delay=None)
return self.screen.tracer(flag, delay)
Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a Turtle instance named turtle): >>> turtle.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... turtle.fd(dist) ... turtle.rt(90) ... dist += 2
Turns turtle animation on/off and set delay for update drawings.
[ "Turns", "turtle", "animation", "on", "/", "off", "and", "set", "delay", "for", "update", "drawings", "." ]
def tracer(self, flag=None, delay=None): """Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a Turtle instance named turtle): >>> turtle.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... turtle.fd(dist) ... turtle.rt(90) ... dist += 2 """ return self.screen.tracer(flag, delay)
[ "def", "tracer", "(", "self", ",", "flag", "=", "None", ",", "delay", "=", "None", ")", ":", "return", "self", ".", "screen", ".", "tracer", "(", "flag", ",", "delay", ")" ]
https://github.com/naftaliharris/tauthon/blob/5587ceec329b75f7caf6d65a036db61ac1bae214/Lib/lib-tk/turtle.py#L2576-L2595
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/plugins/attack/db/sqlmap/thirdparty/chardet/codingstatemachine.py
python
CodingStateMachine.get_coding_state_machine
(self)
return self._mModel['name']
[]
def get_coding_state_machine(self): return self._mModel['name']
[ "def", "get_coding_state_machine", "(", "self", ")", ":", "return", "self", ".", "_mModel", "[", "'name'", "]" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/plugins/attack/db/sqlmap/thirdparty/chardet/codingstatemachine.py#L60-L61
bitprophet/ssh
e8bdad4c82a50158a749233dca58c29e47c60b76
ssh/transport.py
python
Transport.send_ignore
(self, bytes=None)
Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls. @param bytes: the number of random bytes to send in the payload of the ignored packet -- defaults to a random number from 10 to 41. @type bytes: int
Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls.
[ "Send", "a", "junk", "packet", "across", "the", "encrypted", "link", ".", "This", "is", "sometimes", "used", "to", "add", "noise", "to", "a", "connection", "to", "confuse", "would", "-", "be", "attackers", ".", "It", "can", "also", "be", "used", "as", ...
def send_ignore(self, bytes=None): """ Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls. @param bytes: the number of random bytes to send in the payload of the ignored packet -- defaults to a random number from 10 to 41. @type bytes: int """ m = Message() m.add_byte(chr(MSG_IGNORE)) if bytes is None: bytes = (ord(rng.read(1)) % 32) + 10 m.add_bytes(rng.read(bytes)) self._send_user_message(m)
[ "def", "send_ignore", "(", "self", ",", "bytes", "=", "None", ")", ":", "m", "=", "Message", "(", ")", "m", ".", "add_byte", "(", "chr", "(", "MSG_IGNORE", ")", ")", "if", "bytes", "is", "None", ":", "bytes", "=", "(", "ord", "(", "rng", ".", "...
https://github.com/bitprophet/ssh/blob/e8bdad4c82a50158a749233dca58c29e47c60b76/ssh/transport.py#L847-L863
QUANTAXIS/QUANTAXIS
d6eccb97c8385854aa596d6ba8d70ec0655519ff
QUANTAXIS/QAData/QADataStruct.py
python
QA_DataStruct_Future_day.tradetime
(self)
返回交易所日历下的日期 Returns: [type] -- [description]
返回交易所日历下的日期
[ "返回交易所日历下的日期" ]
def tradetime(self): """返回交易所日历下的日期 Returns: [type] -- [description] """ try: return self.date except: return None
[ "def", "tradetime", "(", "self", ")", ":", "try", ":", "return", "self", ".", "date", "except", ":", "return", "None" ]
https://github.com/QUANTAXIS/QUANTAXIS/blob/d6eccb97c8385854aa596d6ba8d70ec0655519ff/QUANTAXIS/QAData/QADataStruct.py#L599-L609
pybrain/pybrain
dcdf32ba1805490cefbc0bdeb227260d304fdb42
pybrain/tools/datasettools.py
python
convertSequenceToTimeWindows
(DSseq, NewClass, winsize)
return DSwin
Converts a sequential classification dataset into time windows of fixed length. Assumes the correct class is given at the last timestep of each sequence. Incomplete windows at the sequence end are pruned. No overlap between windows. :arg DSseq: the sequential data set to cut up :arg winsize: size of the data window :arg NewClass: class of the windowed data set to be returned (gets initialised with indim*winsize, outdim)
Converts a sequential classification dataset into time windows of fixed length. Assumes the correct class is given at the last timestep of each sequence. Incomplete windows at the sequence end are pruned. No overlap between windows.
[ "Converts", "a", "sequential", "classification", "dataset", "into", "time", "windows", "of", "fixed", "length", ".", "Assumes", "the", "correct", "class", "is", "given", "at", "the", "last", "timestep", "of", "each", "sequence", ".", "Incomplete", "windows", "...
def convertSequenceToTimeWindows(DSseq, NewClass, winsize): """ Converts a sequential classification dataset into time windows of fixed length. Assumes the correct class is given at the last timestep of each sequence. Incomplete windows at the sequence end are pruned. No overlap between windows. :arg DSseq: the sequential data set to cut up :arg winsize: size of the data window :arg NewClass: class of the windowed data set to be returned (gets initialised with indim*winsize, outdim)""" assert isinstance(DSseq, SequentialDataSet) #assert isinstance(DSwin, SupervisedDataSet) DSwin = NewClass(DSseq.indim * winsize, DSseq.outdim) nsamples = 0 nseqs = 0 si = r_[DSseq['sequence_index'].flatten(), DSseq.endmarker['sequence_index']] for i in range(DSseq.getNumSequences()): # get one sequence as arrays input = DSseq['input'][si[i]:si[i + 1], :] target = DSseq['target'][si[i]:si[i + 1], :] nseqs += 1 # cut this sequence into windows, assuming class is given at the last step of each sequence for k in range(winsize, input.shape[0], winsize): inp_win = input[k - winsize:k, :] tar_win = target[k - 1, :] DSwin.addSample(inp_win.flatten(), tar_win.flatten()) nsamples += 1 ##print("added sample %d from sequence %d: %d - %d" %( nsamples, nseqs, k-winsize, k-1)) print(("samples in original dataset: ", len(DSseq))) print(("window size * nsamples = ", winsize * nsamples)) print(("total data points in original data: ", len(DSseq) * DSseq.indim)) print(("total data points in windowed dataset: ", len(DSwin) * DSwin.indim)) return DSwin
[ "def", "convertSequenceToTimeWindows", "(", "DSseq", ",", "NewClass", ",", "winsize", ")", ":", "assert", "isinstance", "(", "DSseq", ",", "SequentialDataSet", ")", "#assert isinstance(DSwin, SupervisedDataSet)", "DSwin", "=", "NewClass", "(", "DSseq", ".", "indim", ...
https://github.com/pybrain/pybrain/blob/dcdf32ba1805490cefbc0bdeb227260d304fdb42/pybrain/tools/datasettools.py#L11-L42
rsalmei/alive-progress
767445917e7cb384981c0dc29b3b3204384353b1
alive_progress/styles/exhibit.py
python
exhibit_bar
(bar, fps)
[]
def exhibit_bar(bar, fps): total = int(fps * 5) while True: # standard use cases, increment till completion, underflow and overflow. for s, t in (0, total), (0, int(total * .5)), (int(total * .5), int(total + 1)): for pos in range(s, t): percent = pos / total yield bar(percent), percent # generates a small pause in movement between cases, based on the fps. percent = t / total for _ in range(int(fps * 2)): yield bar.end(percent), percent # advanced use cases, which do not go always forward. factor = random.random() + 1 # a number between 1.0 and 2.0. for percent in (1. - x * factor / total for x in range(total)): yield bar(percent), percent # generates a small giggle, like a real gauge. measure, giggle = random.random(), lambda: (random.random() - .5) * .2 for _ in range(int(fps * 2)): percent = measure + giggle() yield bar(percent), percent # gradually comes to a full stop. for t in range(int(fps * 5)): # smoother stabilization. percent = measure + giggle() / 1.04 ** t yield bar(percent), percent # enjoy the full stop for a while. for t in range(int(fps * 2)): yield bar(measure), measure
[ "def", "exhibit_bar", "(", "bar", ",", "fps", ")", ":", "total", "=", "int", "(", "fps", "*", "5", ")", "while", "True", ":", "# standard use cases, increment till completion, underflow and overflow.", "for", "s", ",", "t", "in", "(", "0", ",", "total", ")",...
https://github.com/rsalmei/alive-progress/blob/767445917e7cb384981c0dc29b3b3204384353b1/alive_progress/styles/exhibit.py#L220-L248
bridgecrewio/checkov
f4f8caead6aa2f1824ae1cc88cd1816b12211629
checkov/arm/base_resource_value_check.py
python
BaseResourceValueCheck.get_inspected_key
(self)
:return: JSONPath syntax path of the checked attribute
:return: JSONPath syntax path of the checked attribute
[ ":", "return", ":", "JSONPath", "syntax", "path", "of", "the", "checked", "attribute" ]
def get_inspected_key(self) -> str: """ :return: JSONPath syntax path of the checked attribute """ raise NotImplementedError()
[ "def", "get_inspected_key", "(", "self", ")", "->", "str", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/bridgecrewio/checkov/blob/f4f8caead6aa2f1824ae1cc88cd1816b12211629/checkov/arm/base_resource_value_check.py#L54-L58
aiidateam/aiida-core
c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2
aiida/schedulers/plugins/lsf.py
python
LsfScheduler._parse_submit_output
(self, retval, stdout, stderr)
Parse the output of the submit command, as returned by executing the command returned by _get_submit_command command. To be implemented by the plugin. Return a string with the JobID.
Parse the output of the submit command, as returned by executing the command returned by _get_submit_command command.
[ "Parse", "the", "output", "of", "the", "submit", "command", "as", "returned", "by", "executing", "the", "command", "returned", "by", "_get_submit_command", "command", "." ]
def _parse_submit_output(self, retval, stdout, stderr): """ Parse the output of the submit command, as returned by executing the command returned by _get_submit_command command. To be implemented by the plugin. Return a string with the JobID. """ if retval != 0: self.logger.error(f'Error in _parse_submit_output: retval={retval}; stdout={stdout}; stderr={stderr}') raise SchedulerError(f'Error during submission, retval={retval}\nstdout={stdout}\nstderr={stderr}') try: transport_string = f' for {self.transport}' except SchedulerError: transport_string = '' if stderr.strip(): self.logger.warning(f'in _parse_submit_output{transport_string}: there was some text in stderr: {stderr}') try: return stdout.strip().split('Job <')[1].split('>')[0] except IndexError as exc: raise SchedulerParsingError(f'Cannot parse submission output: `{stdout}`') from exc
[ "def", "_parse_submit_output", "(", "self", ",", "retval", ",", "stdout", ",", "stderr", ")", ":", "if", "retval", "!=", "0", ":", "self", ".", "logger", ".", "error", "(", "f'Error in _parse_submit_output: retval={retval}; stdout={stdout}; stderr={stderr}'", ")", "...
https://github.com/aiidateam/aiida-core/blob/c743a335480f8bb3a5e4ebd2463a31f9f3b9f9b2/aiida/schedulers/plugins/lsf.py#L650-L674
scanny/python-pptx
71d1ca0b2b3b9178d64cdab565e8503a25a54e0b
pptx/opc/serialized.py
python
_PhysPkgReader.__contains__
(self, item)
Must be implemented by each subclass.
Must be implemented by each subclass.
[ "Must", "be", "implemented", "by", "each", "subclass", "." ]
def __contains__(self, item): """Must be implemented by each subclass.""" raise NotImplementedError( # pragma: no cover "`%s` must implement `.__contains__()`" % type(self).__name__ )
[ "def", "__contains__", "(", "self", ",", "item", ")", ":", "raise", "NotImplementedError", "(", "# pragma: no cover", "\"`%s` must implement `.__contains__()`\"", "%", "type", "(", "self", ")", ".", "__name__", ")" ]
https://github.com/scanny/python-pptx/blob/71d1ca0b2b3b9178d64cdab565e8503a25a54e0b/pptx/opc/serialized.py#L114-L118
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/drawreport/descendtree.py
python
TitleC.calc_title
(self, family_id)
Calculate the title of the report
Calculate the title of the report
[ "Calculate", "the", "title", "of", "the", "report" ]
def calc_title(self, family_id): """Calculate the title of the report""" family = self.database.get_family_from_gramps_id(family_id) kids = [self.database.get_person_from_handle(kid.ref) for kid in family.get_child_ref_list()] #ok we have the children. Make a title off of them # Translators: needed for Arabic, ignore otherwise cousin_names = self._(', ').join(self._get_names(kids, self._nd)) self.text = self._( "Cousin Chart for %(names)s") % {'names' : cousin_names} self.set_box_height_width()
[ "def", "calc_title", "(", "self", ",", "family_id", ")", ":", "family", "=", "self", ".", "database", ".", "get_family_from_gramps_id", "(", "family_id", ")", "kids", "=", "[", "self", ".", "database", ".", "get_person_from_handle", "(", "kid", ".", "ref", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/drawreport/descendtree.py#L348-L363
kwotsin/mimicry
70ce919b0684b14af264881cc6acf4eccaff42b2
examples/ssgan_tutorial.py
python
SSGANGenerator.train_step
(self, real_batch, netD, optG, log_data, device=None, global_step=None, **kwargs)
return log_data
Train step function.
Train step function.
[ "Train", "step", "function", "." ]
def train_step(self, real_batch, netD, optG, log_data, device=None, global_step=None, **kwargs): """ Train step function. """ self.zero_grad() # Get only batch size from real batch batch_size = real_batch[0].shape[0] # Produce fake images and logits fake_images = self.generate_images(num_images=batch_size, device=device) output, _ = netD(fake_images) # Compute GAN loss, upright images only. errG = self.compute_gan_loss(output) # Compute SS loss, rotates the images. -- only for fake images! errG_SS = netD.compute_ss_loss(images=fake_images, scale=self.ss_loss_scale) # Backprop and update gradients errG_total = errG + errG_SS errG_total.backward() optG.step() # Log statistics log_data.add_metric('errG', errG, group='loss') log_data.add_metric('errG_SS', errG_SS, group='loss_SS') return log_data
[ "def", "train_step", "(", "self", ",", "real_batch", ",", "netD", ",", "optG", ",", "log_data", ",", "device", "=", "None", ",", "global_step", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "zero_grad", "(", ")", "# Get only batch size fro...
https://github.com/kwotsin/mimicry/blob/70ce919b0684b14af264881cc6acf4eccaff42b2/examples/ssgan_tutorial.py#L62-L99
googlefonts/nototools
903a218f62256a286cde48c76b3051703f8a1de5
nototools/unicode_data.py
python
_load_emoji_sequence_data
()
Ensure the emoji sequence data is initialized.
Ensure the emoji sequence data is initialized.
[ "Ensure", "the", "emoji", "sequence", "data", "is", "initialized", "." ]
def _load_emoji_sequence_data(): """Ensure the emoji sequence data is initialized.""" global _emoji_sequence_data, _emoji_non_vs_to_canonical if _emoji_sequence_data is not None: return _emoji_sequence_data = {} _emoji_non_vs_to_canonical = {} def add_data(data): for k, t in data.items(): if k in _emoji_sequence_data: print("already have data for sequence:", seq_to_string(k), t) _emoji_sequence_data[k] = t if EMOJI_VS in k: _emoji_non_vs_to_canonical[strip_emoji_vs(k)] = k for datafile in ["emoji-zwj-sequences.txt", "emoji-sequences.txt"]: add_data(_read_emoji_data_file(datafile)) add_data(_read_emoji_data(_LEGACY_ANDROID_SEQUENCES.splitlines())) _load_unicode_data_txt() # ensure character_names_data is populated _load_emoji_data() # ensure presentation_default_text is populated _load_emoji_group_data() # ensure group data is populated # Get names for single emoji from the test data. We will prefer these over # those in UnicodeData (e.g. prefer "one o'clock" to "clock face one oclock"), # and if they're not in UnicodeData these are proposed new emoji. for seq, (_, _, _, emoji_name) in _emoji_group_data.items(): non_vs_seq = strip_emoji_vs(seq) if len(non_vs_seq) > 1: continue cp = non_vs_seq[0] # If it's not in character names data, it's a proposed emoji. if cp not in _character_names_data: # use 'ignore' to strip curly quotes etc if they exist, unicode # character names are ASCII, and it's probably best to keep it that way. cp_name = emoji_name.encode("ascii", "ignore").upper() _character_names_data[cp] = cp_name is_default_text_presentation = cp in _presentation_default_text if is_default_text_presentation: seq = (cp, EMOJI_VS) emoji_age = age(cp) if emoji_age is not None: emoji_age = float(emoji_age) emoji_age = PROPOSED_EMOJI_AGE current_data = _emoji_sequence_data.get(seq) or ( emoji_name, emoji_age, "Emoji_Single_Sequence", ) if is_default_text_presentation: emoji_name = "(emoji) " + emoji_name _emoji_sequence_data[seq] = (emoji_name, current_data[1], current_data[2]) # Fill in sequences of single emoji, handling non-canonical to canonical also. for k in _emoji: non_vs_seq = (k,) is_default_text_presentation = k in _presentation_default_text if is_default_text_presentation: canonical_seq = (k, EMOJI_VS) _emoji_non_vs_to_canonical[non_vs_seq] = canonical_seq else: canonical_seq = non_vs_seq if canonical_seq in _emoji_sequence_data: # Prefer names we have where they exist emoji_name, emoji_age, seq_type = _emoji_sequence_data[canonical_seq] else: emoji_name = name(k, "unnamed").lower() if name == "unnamed": continue emoji_age = age(k) seq_type = "Emoji_Single_Sequence" if is_default_text_presentation and not emoji_name.startswith("(emoji) "): emoji_name = "(emoji) " + emoji_name _emoji_sequence_data[canonical_seq] = (emoji_name, emoji_age, seq_type)
[ "def", "_load_emoji_sequence_data", "(", ")", ":", "global", "_emoji_sequence_data", ",", "_emoji_non_vs_to_canonical", "if", "_emoji_sequence_data", "is", "not", "None", ":", "return", "_emoji_sequence_data", "=", "{", "}", "_emoji_non_vs_to_canonical", "=", "{", "}", ...
https://github.com/googlefonts/nototools/blob/903a218f62256a286cde48c76b3051703f8a1de5/nototools/unicode_data.py#L1150-L1236
carnal0wnage/weirdAAL
c14e36d7bb82447f38a43da203f4bc29429f4cf4
libs/aws/sql.py
python
search_list_awskeys_in_database
(db_name, AWSKeyID)
Function to query for all AWSKeys in the database
Function to query for all AWSKeys in the database
[ "Function", "to", "query", "for", "all", "AWSKeys", "in", "the", "database" ]
def search_list_awskeys_in_database(db_name, AWSKeyID): ''' Function to query for all AWSKeys in the database ''' with sqlite3.connect(db_name) as db: cursor = db.cursor() cursor.execute("""SELECT DISTINCT AWSKeyID,target from recon""") results = cursor.fetchall() return results
[ "def", "search_list_awskeys_in_database", "(", "db_name", ",", "AWSKeyID", ")", ":", "with", "sqlite3", ".", "connect", "(", "db_name", ")", "as", "db", ":", "cursor", "=", "db", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"\"\"SELECT DISTINCT ...
https://github.com/carnal0wnage/weirdAAL/blob/c14e36d7bb82447f38a43da203f4bc29429f4cf4/libs/aws/sql.py#L129-L137
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/scipy/constants/constants.py
python
C2F
(C)
return 1.8 * _np.asanyarray(C) + 32
Convert Celsius to Fahrenheit Parameters ---------- C : array_like Celsius temperature(s) to be converted. Returns ------- F : float or array of floats Equivalent Fahrenheit temperature(s). See also -------- convert_temperature Notes ----- Computes ``F = 1.8 * C + 32``. Examples -------- >>> from scipy.constants import C2F >>> C2F(np.array([-40, 40.0])) array([ -40., 104.])
Convert Celsius to Fahrenheit
[ "Convert", "Celsius", "to", "Fahrenheit" ]
def C2F(C): """ Convert Celsius to Fahrenheit Parameters ---------- C : array_like Celsius temperature(s) to be converted. Returns ------- F : float or array of floats Equivalent Fahrenheit temperature(s). See also -------- convert_temperature Notes ----- Computes ``F = 1.8 * C + 32``. Examples -------- >>> from scipy.constants import C2F >>> C2F(np.array([-40, 40.0])) array([ -40., 104.]) """ return 1.8 * _np.asanyarray(C) + 32
[ "def", "C2F", "(", "C", ")", ":", "return", "1.8", "*", "_np", ".", "asanyarray", "(", "C", ")", "+", "32" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/scipy/constants/constants.py#L357-L386
khanhnamle1994/natural-language-processing
01d450d5ac002b0156ef4cf93a07cb508c1bcdc5
assignment1/.env/lib/python2.7/site-packages/IPython/core/history.py
python
HistoryAccessor.__init__
(self, profile='default', hist_file=u'', **traits)
Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~IPython.config.loader.Config` Config object. hist_file can also be set through this.
Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~IPython.config.loader.Config` Config object. hist_file can also be set through this.
[ "Create", "a", "new", "history", "accessor", ".", "Parameters", "----------", "profile", ":", "str", "The", "name", "of", "the", "profile", "from", "which", "to", "open", "history", ".", "hist_file", ":", "str", "Path", "to", "an", "SQLite", "history", "da...
def __init__(self, profile='default', hist_file=u'', **traits): """Create a new history accessor. Parameters ---------- profile : str The name of the profile from which to open history. hist_file : str Path to an SQLite history database stored by IPython. If specified, hist_file overrides profile. config : :class:`~IPython.config.loader.Config` Config object. hist_file can also be set through this. """ # We need a pointer back to the shell for various tasks. super(HistoryAccessor, self).__init__(**traits) # defer setting hist_file from kwarg until after init, # otherwise the default kwarg value would clobber any value # set by config if hist_file: self.hist_file = hist_file if self.hist_file == u'': # No one has set the hist_file, yet. self.hist_file = self._get_hist_file_name(profile) if sqlite3 is None and self.enabled: warn("IPython History requires SQLite, your history will not be saved") self.enabled = False self.init_db()
[ "def", "__init__", "(", "self", ",", "profile", "=", "'default'", ",", "hist_file", "=", "u''", ",", "*", "*", "traits", ")", ":", "# We need a pointer back to the shell for various tasks.", "super", "(", "HistoryAccessor", ",", "self", ")", ".", "__init__", "("...
https://github.com/khanhnamle1994/natural-language-processing/blob/01d450d5ac002b0156ef4cf93a07cb508c1bcdc5/assignment1/.env/lib/python2.7/site-packages/IPython/core/history.py#L155-L184
beer-garden/beer-garden
7b1b7dd64ab1f19f370451c9438362d11f3a06e4
src/app/beer_garden/local_plugins/manager.py
python
PluginManager.stop_all
(self)
return self._stop_multiple(self._runners)
Stop all known runners.
Stop all known runners.
[ "Stop", "all", "known", "runners", "." ]
def stop_all(self) -> None: """Stop all known runners.""" return self._stop_multiple(self._runners)
[ "def", "stop_all", "(", "self", ")", "->", "None", ":", "return", "self", ".", "_stop_multiple", "(", "self", ".", "_runners", ")" ]
https://github.com/beer-garden/beer-garden/blob/7b1b7dd64ab1f19f370451c9438362d11f3a06e4/src/app/beer_garden/local_plugins/manager.py#L383-L385
trakt/Plex-Trakt-Scrobbler
aeb0bfbe62fad4b06c164f1b95581da7f35dce0b
Trakttv.bundle/Contents/Libraries/Windows/i386/vc14/ucs2/cryptography/hazmat/backends/openssl/encode_asn1.py
python
_encode_ocsp_nocheck
(backend, ext)
return _encode_asn1_str_gc(backend, b"\x05\x00", 2)
The OCSP No Check extension is defined as a null ASN.1 value embedded in an ASN.1 string.
The OCSP No Check extension is defined as a null ASN.1 value embedded in an ASN.1 string.
[ "The", "OCSP", "No", "Check", "extension", "is", "defined", "as", "a", "null", "ASN", ".", "1", "value", "embedded", "in", "an", "ASN", ".", "1", "string", "." ]
def _encode_ocsp_nocheck(backend, ext): """ The OCSP No Check extension is defined as a null ASN.1 value embedded in an ASN.1 string. """ return _encode_asn1_str_gc(backend, b"\x05\x00", 2)
[ "def", "_encode_ocsp_nocheck", "(", "backend", ",", "ext", ")", ":", "return", "_encode_asn1_str_gc", "(", "backend", ",", "b\"\\x05\\x00\"", ",", "2", ")" ]
https://github.com/trakt/Plex-Trakt-Scrobbler/blob/aeb0bfbe62fad4b06c164f1b95581da7f35dce0b/Trakttv.bundle/Contents/Libraries/Windows/i386/vc14/ucs2/cryptography/hazmat/backends/openssl/encode_asn1.py#L244-L249
jcrist/skein
69699eaf0d03228076448524b6212b6d0b646a85
skein/kv.py
python
_value_owner_pair
(kv)
return ValueOwnerPair(kv.value, (_container_instance_to_string(kv.owner) if kv.HasField("owner") else None))
Build a ValueOwnerPair from a KeyValue object
Build a ValueOwnerPair from a KeyValue object
[ "Build", "a", "ValueOwnerPair", "from", "a", "KeyValue", "object" ]
def _value_owner_pair(kv): """Build a ValueOwnerPair from a KeyValue object""" return ValueOwnerPair(kv.value, (_container_instance_to_string(kv.owner) if kv.HasField("owner") else None))
[ "def", "_value_owner_pair", "(", "kv", ")", ":", "return", "ValueOwnerPair", "(", "kv", ".", "value", ",", "(", "_container_instance_to_string", "(", "kv", ".", "owner", ")", "if", "kv", ".", "HasField", "(", "\"owner\"", ")", "else", "None", ")", ")" ]
https://github.com/jcrist/skein/blob/69699eaf0d03228076448524b6212b6d0b646a85/skein/kv.py#L210-L213
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/mixins/xc16.py
python
Xc16Compiler.__init__
(self)
[]
def __init__(self) -> None: if not self.is_cross: raise EnvironmentException('xc16 supports only cross-compilation.') self.id = 'xc16' # Assembly self.can_compile_suffixes.add('s') default_warn_args = [] # type: T.List[str] self.warn_args = {'0': [], '1': default_warn_args, '2': default_warn_args + [], '3': default_warn_args + []}
[ "def", "__init__", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "is_cross", ":", "raise", "EnvironmentException", "(", "'xc16 supports only cross-compilation.'", ")", "self", ".", "id", "=", "'xc16'", "# Assembly", "self", ".", "can_compile_suf...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/xc16.py#L58-L68
FederatedAI/FATE
32540492623568ecd1afcb367360133616e02fa3
python/federatedml/secureprotol/spdz/utils/naming.py
python
NamingService.set_instance
(cls, instance)
return prev
[]
def set_instance(cls, instance): prev = cls.__instance cls.__instance = instance return prev
[ "def", "set_instance", "(", "cls", ",", "instance", ")", ":", "prev", "=", "cls", ".", "__instance", "cls", ".", "__instance", "=", "instance", "return", "prev" ]
https://github.com/FederatedAI/FATE/blob/32540492623568ecd1afcb367360133616e02fa3/python/federatedml/secureprotol/spdz/utils/naming.py#L29-L32
aliyun/aliyun-openapi-python-sdk
bda53176cc9cf07605b1cf769f0df444cca626a0
aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/__init__.py
python
disable_warnings
(category=exceptions.HTTPWarning)
Helper for quickly disabling all urllib3 warnings.
Helper for quickly disabling all urllib3 warnings.
[ "Helper", "for", "quickly", "disabling", "all", "urllib3", "warnings", "." ]
def disable_warnings(category=exceptions.HTTPWarning): """ Helper for quickly disabling all urllib3 warnings. """ warnings.simplefilter('ignore', category)
[ "def", "disable_warnings", "(", "category", "=", "exceptions", ".", "HTTPWarning", ")", ":", "warnings", ".", "simplefilter", "(", "'ignore'", ",", "category", ")" ]
https://github.com/aliyun/aliyun-openapi-python-sdk/blob/bda53176cc9cf07605b1cf769f0df444cca626a0/aliyun-python-sdk-core/aliyunsdkcore/vendored/requests/packages/urllib3/__init__.py#L93-L97
mdiazcl/fuzzbunch-debian
2b76c2249ade83a389ae3badb12a1bd09901fd2c
windows/Resources/Python/Core/Lib/distutils/text_file.py
python
TextFile.unreadline
(self, line)
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.
[ "Push", "line", "(", "a", "string", ")", "onto", "an", "internal", "buffer", "that", "will", "be", "checked", "by", "future", "readline", "()", "calls", ".", "Handy", "for", "implementing", "a", "parser", "with", "line", "-", "at", "-", "a", "-", "time...
def unreadline(self, line): """Push 'line' (a string) onto an internal buffer that will be checked by future 'readline()' calls. Handy for implementing a parser with line-at-a-time lookahead.""" self.linebuf.append(line)
[ "def", "unreadline", "(", "self", ",", "line", ")", ":", "self", ".", "linebuf", ".", "append", "(", "line", ")" ]
https://github.com/mdiazcl/fuzzbunch-debian/blob/2b76c2249ade83a389ae3badb12a1bd09901fd2c/windows/Resources/Python/Core/Lib/distutils/text_file.py#L226-L230
JaniceWuo/MovieRecommend
4c86db64ca45598917d304f535413df3bc9fea65
movierecommend/venv1/Lib/site-packages/django/template/base.py
python
VariableNode.__init__
(self, filter_expression)
[]
def __init__(self, filter_expression): self.filter_expression = filter_expression
[ "def", "__init__", "(", "self", ",", "filter_expression", ")", ":", "self", ".", "filter_expression", "=", "filter_expression" ]
https://github.com/JaniceWuo/MovieRecommend/blob/4c86db64ca45598917d304f535413df3bc9fea65/movierecommend/venv1/Lib/site-packages/django/template/base.py#L1032-L1033
openai/kubernetes-ec2-autoscaler
1d4d1314e9ee2cb2ae0e17b8b8d8d7845fe8b168
autoscaler/kube.py
python
KubeNode.can_fit
(self, resources)
return left.possible
[]
def can_fit(self, resources): assert isinstance(resources, KubeResource) left = self.capacity - (self.used_capacity + resources) return left.possible
[ "def", "can_fit", "(", "self", ",", "resources", ")", ":", "assert", "isinstance", "(", "resources", ",", "KubeResource", ")", "left", "=", "self", ".", "capacity", "-", "(", "self", ".", "used_capacity", "+", "resources", ")", "return", "left", ".", "po...
https://github.com/openai/kubernetes-ec2-autoscaler/blob/1d4d1314e9ee2cb2ae0e17b8b8d8d7845fe8b168/autoscaler/kube.py#L283-L286
alandmoore/wcgbrowser
14fb69df878154271d15ca4429b350f72d1813cf
browser.py
python
get_ip
()
return s.getsockname()[0]
Get the local routing IP. Liberally borrowed from https://stackoverflow.com/a/25850698/1454109
Get the local routing IP.
[ "Get", "the", "local", "routing", "IP", "." ]
def get_ip(): """Get the local routing IP. Liberally borrowed from https://stackoverflow.com/a/25850698/1454109 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('1.1.1.1', 1)) # IP used is kind of irrelevant except OSError: return '' return s.getsockname()[0]
[ "def", "get_ip", "(", ")", ":", "s", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "try", ":", "s", ".", "connect", "(", "(", "'1.1.1.1'", ",", "1", ")", ")", "# IP used is kind of irrelevant", "exc...
https://github.com/alandmoore/wcgbrowser/blob/14fb69df878154271d15ca4429b350f72d1813cf/browser.py#L171-L182
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/site-packages/setuptools/dist.py
python
Distribution._set_global_opts_from_features
(self)
Add --with-X/--without-X options based on optional features
Add --with-X/--without-X options based on optional features
[ "Add", "--", "with", "-", "X", "/", "--", "without", "-", "X", "options", "based", "on", "optional", "features" ]
def _set_global_opts_from_features(self): """Add --with-X/--without-X options based on optional features""" go = [] no = self.negative_opt.copy() for name, feature in self.features.items(): self._set_feature(name, None) feature.validate(self) if feature.optional: descr = feature.description incdef = ' (default)' excdef = '' if not feature.include_by_default(): excdef, incdef = incdef, excdef go.append(('with-' + name, None, 'include ' + descr + incdef)) go.append(('without-' + name, None, 'exclude ' + descr + excdef)) no['without-' + name] = 'with-' + name self.global_options = self.feature_options = go + self.global_options self.negative_opt = self.feature_negopt = no
[ "def", "_set_global_opts_from_features", "(", "self", ")", ":", "go", "=", "[", "]", "no", "=", "self", ".", "negative_opt", ".", "copy", "(", ")", "for", "name", ",", "feature", "in", "self", ".", "features", ".", "items", "(", ")", ":", "self", "."...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/site-packages/setuptools/dist.py#L445-L467
Karmenzind/fp-server
931fca8fab9d7397c52cf9e76a76b1c60e190403
src/core/web.py
python
WebHandler.do_failed
(self, code=400, msg='error', data={})
for failed event
for failed event
[ "for", "failed", "event" ]
def do_failed(self, code=400, msg='error', data={}): """ for failed event """ result = { 'code': code, 'msg': msg, 'data': self._to_representation(data) } self.set_status(200, 'OK') self.do_finish(result)
[ "def", "do_failed", "(", "self", ",", "code", "=", "400", ",", "msg", "=", "'error'", ",", "data", "=", "{", "}", ")", ":", "result", "=", "{", "'code'", ":", "code", ",", "'msg'", ":", "msg", ",", "'data'", ":", "self", ".", "_to_representation", ...
https://github.com/Karmenzind/fp-server/blob/931fca8fab9d7397c52cf9e76a76b1c60e190403/src/core/web.py#L114-L123
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/build.py
python
CustomTargetIndex.get_link_deps_mapping
(self, prefix: str, environment: environment.Environment)
return self.target.get_link_deps_mapping(prefix, environment)
[]
def get_link_deps_mapping(self, prefix: str, environment: environment.Environment) -> T.Mapping[str, str]: return self.target.get_link_deps_mapping(prefix, environment)
[ "def", "get_link_deps_mapping", "(", "self", ",", "prefix", ":", "str", ",", "environment", ":", "environment", ".", "Environment", ")", "->", "T", ".", "Mapping", "[", "str", ",", "str", "]", ":", "return", "self", ".", "target", ".", "get_link_deps_mappi...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/build.py#L2752-L2753
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_serviceaccount_secret.py
python
OCServiceAccountSecret.exists
(self, in_secret)
return True
verifies if secret exists in the service account
verifies if secret exists in the service account
[ "verifies", "if", "secret", "exists", "in", "the", "service", "account" ]
def exists(self, in_secret): ''' verifies if secret exists in the service account ''' result = self.service_account.find_secret(in_secret) if not result: return False return True
[ "def", "exists", "(", "self", ",", "in_secret", ")", ":", "result", "=", "self", ".", "service_account", ".", "find_secret", "(", "in_secret", ")", "if", "not", "result", ":", "return", "False", "return", "True" ]
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_openshift/library/oc_serviceaccount_secret.py#L1611-L1616
smartbgp/yabgp
f073633a813899cd9b413bc28ea2f7737deee141
yabgp/message/attribute/extcommunity.py
python
ExtCommunity.parse
(cls, value)
return ext_community
Each Extended Community is encoded as an 8-octet quantity, as follows: - Type Field : 1 or 2 octets - Value Field : Remaining octets 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type high | Type low(*) | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Value | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Parse Extended Community attributes. :param value : value
Each Extended Community is encoded as an 8-octet quantity, as follows: - Type Field : 1 or 2 octets - Value Field : Remaining octets 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type high | Type low(*) | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Value | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Parse Extended Community attributes. :param value : value
[ "Each", "Extended", "Community", "is", "encoded", "as", "an", "8", "-", "octet", "quantity", "as", "follows", ":", "-", "Type", "Field", ":", "1", "or", "2", "octets", "-", "Value", "Field", ":", "Remaining", "octets", "0", "1", "2", "3", "0", "1", ...
def parse(cls, value): """ Each Extended Community is encoded as an 8-octet quantity, as follows: - Type Field : 1 or 2 octets - Value Field : Remaining octets 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Type high | Type low(*) | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Value | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Parse Extended Community attributes. :param value : value """ # devide every ext community if len(value) % 8 != 0: raise excep.UpdateMessageError( sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=value) ext_community = [] while value: comm_type, subtype = struct.unpack('!BB', value[0:2]) value_tmp = value[2:8] comm_code = comm_type * 256 + subtype # Route Target if comm_code == bgp_cons.BGP_EXT_COM_RT_0: # Route Target, Format AS(2bytes):AN(4bytes) asn, an = struct.unpack('!HI', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) elif comm_code == bgp_cons.BGP_EXT_COM_RT_1: # Route Target,Format IPv4 address(4bytes):AN(2bytes) ipv4 = str(netaddr.IPAddress(struct.unpack('!I', value_tmp[0:4])[0])) an = struct.unpack('!H', value_tmp[4:])[0] ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], ipv4, an)) elif comm_code == bgp_cons.BGP_EXT_COM_RT_2: # Route Target,Format AS(4bytes):AN(2bytes) asn, an = struct.unpack('!IH', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) # Route Origin elif comm_code == bgp_cons.BGP_EXT_COM_RO_0: # Route Origin,Format AS(2bytes):AN(4bytes) asn, an = struct.unpack('!HI', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) elif comm_code == bgp_cons.BGP_EXT_COM_RO_1: # Route Origin,Format IP address:AN(2bytes) ipv4 = str(netaddr.IPAddress(struct.unpack('!I', value_tmp[0:4])[0])) an = struct.unpack('!H', value_tmp[4:])[0] ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], ipv4, an)) elif comm_code == bgp_cons.BGP_EXT_COM_RO_2: # Route Origin,Format AS(2bytes):AN(4bytes) asn, an = struct.unpack('!IH', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) # BGP Flow spec elif comm_code == bgp_cons.BGP_EXT_REDIRECT_NH: ipv4 = str(netaddr.IPAddress(int(binascii.b2a_hex(value_tmp[0:4]), 16))) copy_flag = struct.unpack('!H', value_tmp[4:])[0] ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], ipv4, copy_flag)) elif comm_code == bgp_cons.BGP_EXT_TRA_RATE: asn, rate = struct.unpack('!Hf', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, int(rate))) elif comm_code == bgp_cons.BGP_EXT_TRA_ACTION: bit_value = parse_bit(ord(value_tmp[-1])) ext_community.append( '%s:S:%s,T:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], bit_value['6'], bit_value['7'])) elif comm_code == bgp_cons.BGP_EXT_REDIRECT_VRF: asn, an = struct.unpack('!HI', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) elif comm_code == bgp_cons.BGP_EXT_TRA_MARK: mark = ord(value_tmp[-1:]) ext_community.append('%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], mark)) # Transitive Opaque elif comm_code == bgp_cons.BGP_EXT_COM_ENCAP: ext_community.append( '%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], struct.unpack('!I', value_tmp[2:])[0])) elif comm_code == bgp_cons.BGP_EXT_COM_COLOR: ext_community.append('%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], struct.unpack('!I', value_tmp[2:])[0])) # EVPN elif comm_code == bgp_cons.BGP_EXT_COM_EVPN_ES_IMPORT: mac = str(netaddr.EUI(int(binascii.b2a_hex(value_tmp), 16))) ext_community.append('%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], mac)) elif comm_code == bgp_cons.BGP_EXT_COM_EVPN_MAC_MOBIL: flag = ord(value_tmp[0:1]) seq = struct.unpack('!I', value_tmp[2:])[0] ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], flag, seq)) elif comm_code == bgp_cons.BGP_EXT_COM_EVPN_ESI_MPLS_LABEL: flag = ord(value_tmp[0:1]) label = struct.unpack('!L', b'\00' + value_tmp[3:])[0] label >>= 4 ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], flag, label)) elif comm_code == bgp_cons.BGP_EXT_COM_EVPN_ROUTE_MAC: ext_community.append('%s:%s' % ( bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], str(netaddr.EUI(int(binascii.b2a_hex(value_tmp), 16))))) # BGP link bandwith elif comm_code == bgp_cons.BGP_EXT_COM_LINK_BW: asn, an = struct.unpack('!HI', value_tmp) ext_community.append('%s:%s:%s' % (bgp_cons.BGP_EXT_COM_STR_DICT[comm_code], asn, an)) else: ext_community.append([bgp_cons.BGP_EXT_COM_UNKNOW, repr(value_tmp)]) LOG.warn('unknow bgp extended community, type=%s, value=%s', comm_code, repr(value_tmp)) value = value[8:] return ext_community
[ "def", "parse", "(", "cls", ",", "value", ")", ":", "# devide every ext community", "if", "len", "(", "value", ")", "%", "8", "!=", "0", ":", "raise", "excep", ".", "UpdateMessageError", "(", "sub_error", "=", "bgp_cons", ".", "ERR_MSG_UPDATE_ATTR_LEN", ",",...
https://github.com/smartbgp/yabgp/blob/f073633a813899cd9b413bc28ea2f7737deee141/yabgp/message/attribute/extcommunity.py#L56-L173
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/external/py2cs.py
python
truncate
(s, n)
return s if len(s) <= n else s[: n - 3] + '...'
Return s truncated to n characters.
Return s truncated to n characters.
[ "Return", "s", "truncated", "to", "n", "characters", "." ]
def truncate(s, n): '''Return s truncated to n characters.''' return s if len(s) <= n else s[: n - 3] + '...'
[ "def", "truncate", "(", "s", ",", "n", ")", ":", "return", "s", "if", "len", "(", "s", ")", "<=", "n", "else", "s", "[", ":", "n", "-", "3", "]", "+", "'...'" ]
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/external/py2cs.py#L193-L195