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
ironport/shrapnel
9496a64c46271b0c5cef0feb8f2cdf33cb752bb6
coro/ssh/keys/openssh_key_storage.py
python
OpenSSH_Key_Storage.load_public_keys
(self, username=None, public_key_filename=None)
return result
load_public_keys(self, username=None, public_key_filename=None) -> [key_obj, ...] Loads the public keys with the given filename. Defaults to $HOME/.ssh/id_dsa.pub Returns a list of SSH_Public_Private_Key object. Returns an empty list if the key is not available.
load_public_keys(self, username=None, public_key_filename=None) -> [key_obj, ...] Loads the public keys with the given filename. Defaults to $HOME/.ssh/id_dsa.pub Returns a list of SSH_Public_Private_Key object. Returns an empty list if the key is not available.
[ "load_public_keys", "(", "self", "username", "=", "None", "public_key_filename", "=", "None", ")", "-", ">", "[", "key_obj", "...", "]", "Loads", "the", "public", "keys", "with", "the", "given", "filename", ".", "Defaults", "to", "$HOME", "/", ".", "ssh", ...
def load_public_keys(self, username=None, public_key_filename=None): """load_public_keys(self, username=None, public_key_filename=None) -> [key_obj, ...] Loads the public keys with the given filename. Defaults to $HOME/.ssh/id_dsa.pub Returns a list of SSH_Public_Private_Key object. Returns an empty list if the key is not available. """ public_key_filenames = self.get_public_key_filenames(username, public_key_filename) result = [] for filename in public_key_filenames: try: data = open(filename).read() except IOError: pass else: result.append(self.parse_public_key(data)) return result
[ "def", "load_public_keys", "(", "self", ",", "username", "=", "None", ",", "public_key_filename", "=", "None", ")", ":", "public_key_filenames", "=", "self", ".", "get_public_key_filenames", "(", "username", ",", "public_key_filename", ")", "result", "=", "[", "...
https://github.com/ironport/shrapnel/blob/9496a64c46271b0c5cef0feb8f2cdf33cb752bb6/coro/ssh/keys/openssh_key_storage.py#L159-L175
AstroPrint/AstroBox
e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75
src/astroprint/plugin/services/system.py
python
SystemService.connectionCommand
(self, data, sendResponse)
[]
def connectionCommand(self, data, sendResponse): # valid_commands = { # "connect": ["autoconnect"], # "disconnect": [], # "reconnect": [] # } command = data['command'] pm = printerManager() if command in ["connect", "reconnect"]: s = settings() #driver = None port = None baudrate = None options = pm.getConnectionOptions() if "port" in data: port = data["port"] if port not in options["ports"]: if port is None: port = "None" sendResponse("invalid_port_" + port,True) return if "baudrate" in data and data['baudrate']: baudrate = int(data["baudrate"]) if baudrate: baudrates = options["baudrates"] if baudrates and baudrate not in baudrates: sendResponse("invalid_baudrate_" + baudrate,True) return else: sendResponse("baudrate_null",True) return if "save" in data and data["save"]: s.set(["serial", "port"], port) s.setInt(["serial", "baudrate"], baudrate) if "autoconnect" in data: s.setBoolean(["serial", "autoconnect"], data["autoconnect"]) s.save() if command == "connect": pm.connect(port, baudrate) elif command == "reconnect": pm.reConnect(port, baudrate) elif command == "disconnect": pm.disconnect() sendResponse({'success':'no error'})
[ "def", "connectionCommand", "(", "self", ",", "data", ",", "sendResponse", ")", ":", "# valid_commands = {", "# \t\"connect\": [\"autoconnect\"],", "# \t\"disconnect\": [],", "# \t\"reconnect\": []", "# }", "command", "=", "data", "[", "'command'", "]", "pm", "=", "prin...
https://github.com/AstroPrint/AstroBox/blob/e7e3b8a7d33ea85fcb6b2696869c0d719ceb8b75/src/astroprint/plugin/services/system.py#L138-L195
poodarchu/Det3D
01258d8cb26656c5b950f8d41f9dcc1dd62a391e
det3d/visualization/show_lidar_vtk.py
python
VtkPointCloud.clearPoints
(self)
[]
def clearPoints(self): self.vtkPoints = vtk.vtkPoints() self.vtkCells = vtk.vtkCellArray() self.vtkDepth = vtk.vtkDoubleArray() self.vtkDepth.SetName("DepthArray") self.vtkPolyData.SetPoints(self.vtkPoints) self.vtkPolyData.SetVerts(self.vtkCells) self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth) self.vtkPolyData.GetPointData().SetActiveScalars("DepthArray")
[ "def", "clearPoints", "(", "self", ")", ":", "self", ".", "vtkPoints", "=", "vtk", ".", "vtkPoints", "(", ")", "self", ".", "vtkCells", "=", "vtk", ".", "vtkCellArray", "(", ")", "self", ".", "vtkDepth", "=", "vtk", ".", "vtkDoubleArray", "(", ")", "...
https://github.com/poodarchu/Det3D/blob/01258d8cb26656c5b950f8d41f9dcc1dd62a391e/det3d/visualization/show_lidar_vtk.py#L59-L67
huggingface/transformers
623b4f7c63f60cce917677ee704d6c93ee960b4b
examples/research_projects/longform-qa/eli5_utils.py
python
train_qa_retriever
(qar_model, qar_tokenizer, qar_train_dset, qar_valid_dset, qar_args)
[]
def train_qa_retriever(qar_model, qar_tokenizer, qar_train_dset, qar_valid_dset, qar_args): qar_optimizer = AdamW(qar_model.parameters(), lr=qar_args.learning_rate, eps=1e-8) qar_scheduler = get_linear_schedule_with_warmup( qar_optimizer, num_warmup_steps=100, num_training_steps=(qar_args.num_epochs + 1) * math.ceil(len(qar_train_dset) / qar_args.batch_size), ) for e in range(qar_args.num_epochs): train_qa_retriever_epoch(qar_model, qar_train_dset, qar_tokenizer, qar_optimizer, qar_scheduler, qar_args, e) m_save_dict = { "model": qar_model.state_dict(), "optimizer": qar_optimizer.state_dict(), "scheduler": qar_scheduler.state_dict(), } print("Saving model {}".format(qar_args.model_save_name)) torch.save(m_save_dict, "{}_{}.pth".format(qar_args.model_save_name, e)) eval_loss = evaluate_qa_retriever(qar_model, qar_valid_dset, qar_tokenizer, qar_args) print("Evaluation loss epoch {:4d}: {:.3f}".format(e, eval_loss))
[ "def", "train_qa_retriever", "(", "qar_model", ",", "qar_tokenizer", ",", "qar_train_dset", ",", "qar_valid_dset", ",", "qar_args", ")", ":", "qar_optimizer", "=", "AdamW", "(", "qar_model", ".", "parameters", "(", ")", ",", "lr", "=", "qar_args", ".", "learni...
https://github.com/huggingface/transformers/blob/623b4f7c63f60cce917677ee704d6c93ee960b4b/examples/research_projects/longform-qa/eli5_utils.py#L318-L335
cea-hpc/clustershell
c421133ed4baa69e35ff76c476d4097201485344
lib/ClusterShell/Worker/EngineClient.py
python
EngineClientStream.writable
(self)
return self.evmask & E_WRITE
Return whether the stream is setup as writable.
Return whether the stream is setup as writable.
[ "Return", "whether", "the", "stream", "is", "setup", "as", "writable", "." ]
def writable(self): """Return whether the stream is setup as writable.""" return self.evmask & E_WRITE
[ "def", "writable", "(", "self", ")", ":", "return", "self", ".", "evmask", "&", "E_WRITE" ]
https://github.com/cea-hpc/clustershell/blob/c421133ed4baa69e35ff76c476d4097201485344/lib/ClusterShell/Worker/EngineClient.py#L125-L127
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventDetails.sso_remove_cert_details
(cls, val)
return cls('sso_remove_cert_details', val)
Create an instance of this class set to the ``sso_remove_cert_details`` tag with value ``val``. :param SsoRemoveCertDetails val: :rtype: EventDetails
Create an instance of this class set to the ``sso_remove_cert_details`` tag with value ``val``.
[ "Create", "an", "instance", "of", "this", "class", "set", "to", "the", "sso_remove_cert_details", "tag", "with", "value", "val", "." ]
def sso_remove_cert_details(cls, val): """ Create an instance of this class set to the ``sso_remove_cert_details`` tag with value ``val``. :param SsoRemoveCertDetails val: :rtype: EventDetails """ return cls('sso_remove_cert_details', val)
[ "def", "sso_remove_cert_details", "(", "cls", ",", "val", ")", ":", "return", "cls", "(", "'sso_remove_cert_details'", ",", "val", ")" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L11845-L11853
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/cookies.py
python
RequestsCookieJar._find
(self, name, domain=None, path=None)
Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value
Requests uses this method internally to get cookie values.
[ "Requests", "uses", "this", "method", "internally", "to", "get", "cookie", "values", "." ]
def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ for cookie in iter(self): if cookie.name == name: if domain is None or cookie.domain == domain: if path is None or cookie.path == path: return cookie.value raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
[ "def", "_find", "(", "self", ",", "name", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "if", "cookie", ".", "name", "==", "name", ":", "if", "domain", "is", "None", "or", ...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/requests/cookies.py#L356-L374
wistbean/fxxkpython
88e16d79d8dd37236ba6ecd0d0ff11d63143968c
vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distro.py
python
os_release_attr
(attribute)
return _distro.os_release_attr(attribute)
Return a single named information item from the os-release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items.
Return a single named information item from the os-release file data source of the current OS distribution.
[ "Return", "a", "single", "named", "information", "item", "from", "the", "os", "-", "release", "file", "data", "source", "of", "the", "current", "OS", "distribution", "." ]
def os_release_attr(attribute): """ Return a single named information item from the os-release file data source of the current OS distribution. Parameters: * ``attribute`` (string): Key of the information item. Returns: * (string): Value of the information item, if the item exists. The empty string, if the item does not exist. See `os-release file`_ for details about these information items. """ return _distro.os_release_attr(attribute)
[ "def", "os_release_attr", "(", "attribute", ")", ":", "return", "_distro", ".", "os_release_attr", "(", "attribute", ")" ]
https://github.com/wistbean/fxxkpython/blob/88e16d79d8dd37236ba6ecd0d0ff11d63143968c/vip/qyxuan/projects/Snake/venv/lib/python3.6/site-packages/pip-19.0.3-py3.6.egg/pip/_vendor/distro.py#L464-L480
zotroneneis/magical_universe
365308fb83042a4e3f0302e3da242a9703f30b73
code_per_day/day_12_to_15.py
python
Pupil.befriend
(self, person)
Adds another person to your list of friends
Adds another person to your list of friends
[ "Adds", "another", "person", "to", "your", "list", "of", "friends" ]
def befriend(self, person): """Adds another person to your list of friends""" self._friends.append(person) print(f"{person.name} is now your friend!")
[ "def", "befriend", "(", "self", ",", "person", ")", ":", "self", ".", "_friends", ".", "append", "(", "person", ")", "print", "(", "f\"{person.name} is now your friend!\"", ")" ]
https://github.com/zotroneneis/magical_universe/blob/365308fb83042a4e3f0302e3da242a9703f30b73/code_per_day/day_12_to_15.py#L185-L188
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/ssl.py
python
SSLSocket.recv
(self, buflen=1024, flags=0)
[]
def recv(self, buflen=1024, flags=0): self._checkClosed() if self._sslobj: if flags != 0: raise ValueError( "non-zero flags not allowed in calls to recv() on %s" % self.__class__) return self.read(buflen) else: return self._sock.recv(buflen, flags)
[ "def", "recv", "(", "self", ",", "buflen", "=", "1024", ",", "flags", "=", "0", ")", ":", "self", ".", "_checkClosed", "(", ")", "if", "self", ".", "_sslobj", ":", "if", "flags", "!=", "0", ":", "raise", "ValueError", "(", "\"non-zero flags not allowed...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/ssl.py#L707-L716
hzy46/Deep-Learning-21-Examples
15c2d9edccad090cd67b033f24a43c544e5cba3e
chapter_5/research/object_detection/utils/per_image_evaluation.py
python
PerImageEvaluation._compute_tp_fp
(self, detected_boxes, detected_scores, detected_class_labels, groundtruth_boxes, groundtruth_class_labels, groundtruth_is_difficult_lists)
return result_scores, result_tp_fp_labels
Labels true/false positives of detections of an image across all classes. Args: detected_boxes: A float numpy array of shape [N, 4], representing N regions of detected object regions. Each row is of the format [y_min, x_min, y_max, x_max] detected_scores: A float numpy array of shape [N, 1], representing the confidence scores of the detected N object instances. detected_class_labels: A integer numpy array of shape [N, 1], repreneting the class labels of the detected N object instances. groundtruth_boxes: A float numpy array of shape [M, 4], representing M regions of object instances in ground truth groundtruth_class_labels: An integer numpy array of shape [M, 1], representing M class labels of object instances in ground truth groundtruth_is_difficult_lists: A boolean numpy array of length M denoting whether a ground truth box is a difficult instance or not Returns: result_scores: A list of float numpy arrays. Each numpy array is of shape [K, 1], representing K scores detected with object class label c result_tp_fp_labels: A list of boolean numpy array. Each numpy array is of shape [K, 1], representing K True/False positive label of object instances detected with class label c
Labels true/false positives of detections of an image across all classes.
[ "Labels", "true", "/", "false", "positives", "of", "detections", "of", "an", "image", "across", "all", "classes", "." ]
def _compute_tp_fp(self, detected_boxes, detected_scores, detected_class_labels, groundtruth_boxes, groundtruth_class_labels, groundtruth_is_difficult_lists): """Labels true/false positives of detections of an image across all classes. Args: detected_boxes: A float numpy array of shape [N, 4], representing N regions of detected object regions. Each row is of the format [y_min, x_min, y_max, x_max] detected_scores: A float numpy array of shape [N, 1], representing the confidence scores of the detected N object instances. detected_class_labels: A integer numpy array of shape [N, 1], repreneting the class labels of the detected N object instances. groundtruth_boxes: A float numpy array of shape [M, 4], representing M regions of object instances in ground truth groundtruth_class_labels: An integer numpy array of shape [M, 1], representing M class labels of object instances in ground truth groundtruth_is_difficult_lists: A boolean numpy array of length M denoting whether a ground truth box is a difficult instance or not Returns: result_scores: A list of float numpy arrays. Each numpy array is of shape [K, 1], representing K scores detected with object class label c result_tp_fp_labels: A list of boolean numpy array. Each numpy array is of shape [K, 1], representing K True/False positive label of object instances detected with class label c """ result_scores = [] result_tp_fp_labels = [] for i in range(self.num_groundtruth_classes): gt_boxes_at_ith_class = groundtruth_boxes[(groundtruth_class_labels == i ), :] groundtruth_is_difficult_list_at_ith_class = ( groundtruth_is_difficult_lists[groundtruth_class_labels == i]) detected_boxes_at_ith_class = detected_boxes[(detected_class_labels == i ), :] detected_scores_at_ith_class = detected_scores[detected_class_labels == i] scores, tp_fp_labels = self._compute_tp_fp_for_single_class( detected_boxes_at_ith_class, detected_scores_at_ith_class, gt_boxes_at_ith_class, groundtruth_is_difficult_list_at_ith_class) result_scores.append(scores) result_tp_fp_labels.append(tp_fp_labels) return result_scores, result_tp_fp_labels
[ "def", "_compute_tp_fp", "(", "self", ",", "detected_boxes", ",", "detected_scores", ",", "detected_class_labels", ",", "groundtruth_boxes", ",", "groundtruth_class_labels", ",", "groundtruth_is_difficult_lists", ")", ":", "result_scores", "=", "[", "]", "result_tp_fp_lab...
https://github.com/hzy46/Deep-Learning-21-Examples/blob/15c2d9edccad090cd67b033f24a43c544e5cba3e/chapter_5/research/object_detection/utils/per_image_evaluation.py#L158-L201
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/ultimatelistctrl.py
python
UltimateListHeaderData.SetToolTip
(self, tip)
Sets the header/footer item tooltip. :param `tip`: the new header/footer tooltip.
Sets the header/footer item tooltip.
[ "Sets", "the", "header", "/", "footer", "item", "tooltip", "." ]
def SetToolTip(self, tip): """ Sets the header/footer item tooltip. :param `tip`: the new header/footer tooltip. """ self._tip = tip
[ "def", "SetToolTip", "(", "self", ",", "tip", ")", ":", "self", ".", "_tip", "=", "tip" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/ultimatelistctrl.py#L3245-L3252
IJDykeman/wangTiles
7c1ee2095ebdf7f72bce07d94c6484915d5cae8b
experimental_code/tiles_3d/venv/lib/python2.7/site-packages/setuptools/depends.py
python
_iter_code
(code)
Yield '(op,arg)' pair for each operation in code object 'code
Yield '(op,arg)' pair for each operation in code object 'code
[ "Yield", "(", "op", "arg", ")", "pair", "for", "each", "operation", "in", "code", "object", "code" ]
def _iter_code(code): """Yield '(op,arg)' pair for each operation in code object 'code'""" from array import array from dis import HAVE_ARGUMENT, EXTENDED_ARG bytes = array('b',code.co_code) eof = len(code.co_code) ptr = 0 extended_arg = 0 while ptr<eof: op = bytes[ptr] if op>=HAVE_ARGUMENT: arg = bytes[ptr+1] + bytes[ptr+2]*256 + extended_arg ptr += 3 if op==EXTENDED_ARG: extended_arg = arg * long_type(65536) continue else: arg = None ptr += 1 yield op,arg
[ "def", "_iter_code", "(", "code", ")", ":", "from", "array", "import", "array", "from", "dis", "import", "HAVE_ARGUMENT", ",", "EXTENDED_ARG", "bytes", "=", "array", "(", "'b'", ",", "code", ".", "co_code", ")", "eof", "=", "len", "(", "code", ".", "co...
https://github.com/IJDykeman/wangTiles/blob/7c1ee2095ebdf7f72bce07d94c6484915d5cae8b/experimental_code/tiles_3d/venv/lib/python2.7/site-packages/setuptools/depends.py#L83-L113
CacheBrowser/cachebrowser
4bf1d58e5c82a0dbaa878f7725c830d472f5326e
cachebrowser/pipes/scrambler.py
python
ScramblerAPI.set_settings
(self, context, request)
[]
def set_settings(self, context, request): if 'enabled' in request.params: self.scrambler.enabled = bool(request.params['enabled']) if 'overhead' in request.params: self.scrambler.overhead = int(request.params['overhead']) if 'drops' in request.params: self.scrambler.drop_ads = bool(request.params['drops']) if 'decoys' in request.params: self.scrambler.send_decoys = bool(request.params['decoys']) request.reply({ 'result': 'success' })
[ "def", "set_settings", "(", "self", ",", "context", ",", "request", ")", ":", "if", "'enabled'", "in", "request", ".", "params", ":", "self", ".", "scrambler", ".", "enabled", "=", "bool", "(", "request", ".", "params", "[", "'enabled'", "]", ")", "if"...
https://github.com/CacheBrowser/cachebrowser/blob/4bf1d58e5c82a0dbaa878f7725c830d472f5326e/cachebrowser/pipes/scrambler.py#L223-L234
google/youtube-8m
e6f6bf682d20bb21904ea9c081c15e070809d914
average_precision_calculator.py
python
AveragePrecisionCalculator.__init__
(self, top_n=None)
Construct an AveragePrecisionCalculator to calculate average precision. This class is used to calculate the average precision for a single label. Args: top_n: A positive Integer specifying the average precision at n, or None to use all provided data points. Raises: ValueError: An error occurred when the top_n is not a positive integer.
Construct an AveragePrecisionCalculator to calculate average precision.
[ "Construct", "an", "AveragePrecisionCalculator", "to", "calculate", "average", "precision", "." ]
def __init__(self, top_n=None): """Construct an AveragePrecisionCalculator to calculate average precision. This class is used to calculate the average precision for a single label. Args: top_n: A positive Integer specifying the average precision at n, or None to use all provided data points. Raises: ValueError: An error occurred when the top_n is not a positive integer. """ if not ((isinstance(top_n, int) and top_n >= 0) or top_n is None): raise ValueError("top_n must be a positive integer or None.") self._top_n = top_n # average precision at n self._total_positives = 0 # total number of positives have seen self._heap = []
[ "def", "__init__", "(", "self", ",", "top_n", "=", "None", ")", ":", "if", "not", "(", "(", "isinstance", "(", "top_n", ",", "int", ")", "and", "top_n", ">=", "0", ")", "or", "top_n", "is", "None", ")", ":", "raise", "ValueError", "(", "\"top_n mus...
https://github.com/google/youtube-8m/blob/e6f6bf682d20bb21904ea9c081c15e070809d914/average_precision_calculator.py#L63-L80
twilio/stashboard
3e4b18a8168c102d1e1d7f88fec22bcbfc530d23
stashboard/contrib/httplib2/__init__.py
python
Http.request
(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None)
return (response, content)
Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The 'body' is the entity body to be sent with the request. It is a string object. Any extra headers that are to be sent with the request should be provided in the 'headers' dictionary. The maximum number of redirect to follow before raising an exception is 'redirections. The default is 5. The return value is a tuple of (response, content), the first being and instance of the 'Response' class, the second being a string that contains the response entity body.
Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
[ "Performs", "a", "single", "HTTP", "request", ".", "The", "uri", "is", "the", "URI", "of", "the", "HTTP", "resource", "and", "can", "begin", "with", "either", "http", "or", "https", ".", "The", "value", "of", "uri", "must", "be", "an", "absolute", "URI...
def request(self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None): """ Performs a single HTTP request. The 'uri' is the URI of the HTTP resource and can begin with either 'http' or 'https'. The value of 'uri' must be an absolute URI. The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc. There is no restriction on the methods allowed. The 'body' is the entity body to be sent with the request. It is a string object. Any extra headers that are to be sent with the request should be provided in the 'headers' dictionary. The maximum number of redirect to follow before raising an exception is 'redirections. The default is 5. The return value is a tuple of (response, content), the first being and instance of the 'Response' class, the second being a string that contains the response entity body. """ try: if headers is None: headers = {} else: headers = self._normalize_headers(headers) if not headers.has_key('user-agent'): headers['user-agent'] = "Python-httplib2/%s" % __version__ uri = iri2uri(uri) (scheme, authority, request_uri, defrag_uri) = urlnorm(uri) domain_port = authority.split(":")[0:2] if len(domain_port) == 2 and domain_port[1] == '443' and scheme == 'http': scheme = 'https' authority = domain_port[0] conn_key = scheme+":"+authority if conn_key in self.connections: conn = self.connections[conn_key] else: if not connection_type: connection_type = (scheme == 'https') and HTTPSConnectionWithTimeout or HTTPConnectionWithTimeout certs = list(self.certificates.iter(authority)) if scheme == 'https' and certs: conn = self.connections[conn_key] = connection_type(authority, key_file=certs[0][0], cert_file=certs[0][1], timeout=self.timeout, proxy_info=self.proxy_info) else: conn = self.connections[conn_key] = connection_type(authority, timeout=self.timeout, proxy_info=self.proxy_info) conn.set_debuglevel(debuglevel) if 'range' not in headers and 'accept-encoding' not in headers: headers['accept-encoding'] = 'gzip, deflate' info = email.Message.Message() cached_value = None if self.cache: cachekey = defrag_uri cached_value = self.cache.get(cachekey) if cached_value: # info = email.message_from_string(cached_value) # # Need to replace the line above with the kludge below # to fix the non-existent bug not fixed in this # bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html try: info, content = cached_value.split('\r\n\r\n', 1) feedparser = email.FeedParser.FeedParser() feedparser.feed(info) info = feedparser.close() feedparser._parse = None except IndexError: self.cache.delete(cachekey) cachekey = None cached_value = None else: cachekey = None if method in self.optimistic_concurrency_methods and self.cache and info.has_key('etag') and not self.ignore_etag and 'if-match' not in headers: # http://www.w3.org/1999/04/Editing/ headers['if-match'] = info['etag'] if method not in ["GET", "HEAD"] and self.cache and cachekey: # RFC 2616 Section 13.10 self.cache.delete(cachekey) # Check the vary header in the cache to see if this request # matches what varies in the cache. if method in ['GET', 'HEAD'] and 'vary' in info: vary = info['vary'] vary_headers = vary.lower().replace(' ', '').split(',') for header in vary_headers: key = '-varied-%s' % header value = info[key] if headers.get(header, None) != value: cached_value = None break if cached_value and method in ["GET", "HEAD"] and self.cache and 'range' not in headers: if info.has_key('-x-permanent-redirect-url'): # Should cached permanent redirects be counted in our redirection count? For now, yes. if redirections <= 0: raise RedirectLimit("Redirected more times than rediection_limit allows.", {}, "") (response, new_content) = self.request(info['-x-permanent-redirect-url'], "GET", headers = headers, redirections = redirections - 1) response.previous = Response(info) response.previous.fromcache = True else: # Determine our course of action: # Is the cached entry fresh or stale? # Has the client requested a non-cached response? # # There seems to be three possible answers: # 1. [FRESH] Return the cache entry w/o doing a GET # 2. [STALE] Do the GET (but add in cache validators if available) # 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request entry_disposition = _entry_disposition(info, headers) if entry_disposition == "FRESH": if not cached_value: info['status'] = '504' content = "" response = Response(info) if cached_value: response.fromcache = True return (response, content) if entry_disposition == "STALE": if info.has_key('etag') and not self.ignore_etag and not 'if-none-match' in headers: headers['if-none-match'] = info['etag'] if info.has_key('last-modified') and not 'last-modified' in headers: headers['if-modified-since'] = info['last-modified'] elif entry_disposition == "TRANSPARENT": pass (response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) if response.status == 304 and method == "GET": # Rewrite the cache entry with the new end-to-end headers # Take all headers that are in response # and overwrite their values in info. # unless they are hop-by-hop, or are listed in the connection header. for key in _get_end2end_headers(response): info[key] = response[key] merged_response = Response(info) if hasattr(response, "_stale_digest"): merged_response._stale_digest = response._stale_digest _updateCache(headers, merged_response, content, self.cache, cachekey) response = merged_response response.status = 200 response.fromcache = True elif response.status == 200: content = new_content else: self.cache.delete(cachekey) content = new_content else: cc = _parse_cache_control(headers) if cc.has_key('only-if-cached'): info['status'] = '504' response = Response(info) content = "" else: (response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey) except Exception, e: if self.force_exception_to_status_code: if isinstance(e, HttpLib2ErrorWithResponse): response = e.response content = e.content response.status = 500 response.reason = str(e) elif isinstance(e, socket.timeout): content = "Request Timeout" response = Response( { "content-type": "text/plain", "status": "408", "content-length": len(content) }) response.reason = "Request Timeout" else: content = str(e) response = Response( { "content-type": "text/plain", "status": "400", "content-length": len(content) }) response.reason = "Bad Request" else: raise return (response, content)
[ "def", "request", "(", "self", ",", "uri", ",", "method", "=", "\"GET\"", ",", "body", "=", "None", ",", "headers", "=", "None", ",", "redirections", "=", "DEFAULT_MAX_REDIRECTS", ",", "connection_type", "=", "None", ")", ":", "try", ":", "if", "headers"...
https://github.com/twilio/stashboard/blob/3e4b18a8168c102d1e1d7f88fec22bcbfc530d23/stashboard/contrib/httplib2/__init__.py#L1037-L1230
CIRCL/AIL-framework
9c561d482705095f734d4d87fce6b6ab203d7c90
bin/lib/Decoded.py
python
get_decoded_domain_item
(sha1_string)
Retun all domain of a given decoded item. :param sha1_string: sha1_string
Retun all domain of a given decoded item.
[ "Retun", "all", "domain", "of", "a", "given", "decoded", "item", "." ]
def get_decoded_domain_item(sha1_string): ''' Retun all domain of a given decoded item. :param sha1_string: sha1_string ''' res = r_serv_metadata.smembers('domain_hash:{}'.format(sha1_string)) if res: return list(res) else: return []
[ "def", "get_decoded_domain_item", "(", "sha1_string", ")", ":", "res", "=", "r_serv_metadata", ".", "smembers", "(", "'domain_hash:{}'", ".", "format", "(", "sha1_string", ")", ")", "if", "res", ":", "return", "list", "(", "res", ")", "else", ":", "return", ...
https://github.com/CIRCL/AIL-framework/blob/9c561d482705095f734d4d87fce6b6ab203d7c90/bin/lib/Decoded.py#L169-L179
bikalims/bika.lims
35e4bbdb5a3912cae0b5eb13e51097c8b0486349
bika/lims/browser/analysisrequest/invoice.py
python
InvoiceView.__call__
(self)
return self.template()
[]
def __call__(self): context = self.context workflow = getToolByName(context, 'portal_workflow') # Collect related data and objects invoice = context.getInvoice() sample = context.getSample() samplePoint = sample.getSamplePoint() reviewState = workflow.getInfoFor(context, 'review_state') # Collection invoice information if invoice: self.invoiceId = invoice.getId() else: self.invoiceId = _('Proforma (Not yet invoiced)') # Collect verified invoice information verified = reviewState in VERIFIED_STATES if verified: self.verifiedBy = context.getVerifier() self.verified = verified self.request['verified'] = verified # Collect published date self.datePublished = \ self.ulocalized_time(getTransitionDate(context, 'publish'), long_format=1) # Collect received date dateReceived = context.getDateReceived() if dateReceived is not None: dateReceived = self.ulocalized_time(dateReceived, long_format=1) self.dateReceived = dateReceived # Collect general information self.reviewState = reviewState contact = context.getContact() self.contact = contact.Title() if contact else "" self.clientOrderNumber = context.getClientOrderNumber() self.clientReference = context.getClientReference() self.clientSampleId = sample.getClientSampleID() self.sampleType = sample.getSampleType().Title() self.samplePoint = samplePoint and samplePoint.Title() self.requestId = context.getRequestID() self.headers = [ {'title': 'Invoice ID', 'value': self.invoiceId}, {'title': 'Client Reference', 'value': self.clientReference }, {'title': 'Sample Type', 'value': self.sampleType}, {'title': 'Request ID', 'value': self.requestId}, {'title': 'Date Received', 'value': self.dateReceived}, ] if not isAttributeHidden('AnalysisRequest', 'ClientOrderNumber'): self.headers.append({'title': 'Client Sample Id', 'value': self.clientOrderNumber}) if not isAttributeHidden('AnalysisRequest', 'SamplePoint'): self.headers.append( {'title': 'Sample Point', 'value': self.samplePoint}) if self.verified: self.headers.append( {'title': 'Verified By', 'value': self.verifiedBy}) if self.datePublished: self.headers.append( {'title': 'datePublished', 'value': self.datePublished}) analyses = [] profiles = [] # Retrieve required data from analyses collection all_analyses, all_profiles, analyses_from_profiles = context.getServicesAndProfiles() # Relating category with solo analysis for analysis in all_analyses: service = analysis.getService() categoryName = service.getCategory().Title() # Find the category try: category = ( o for o in analyses if o['name'] == categoryName ).next() except: category = {'name': categoryName, 'analyses': []} analyses.append(category) # Append the analysis to the category category['analyses'].append({ 'title': analysis.Title(), 'price': analysis.getPrice(), 'priceVat': "%.2f" % analysis.getVATAmount(), 'priceTotal': "%.2f" % analysis.getTotalPrice(), }) # Relating analysis services with their profiles # We'll take the analysis contained on each profile for profile in all_profiles: # If profile's checkbox "Use Analysis Profile Price" is enabled, only the profile price will be displayed. # Otherwise each analysis will display its own price. pservices = [] if profile.getUseAnalysisProfilePrice(): # We have to use the profiles price only for pservice in profile.getService(): pservices.append({ 'title': pservice.Title(), 'price': None, 'priceVat': None, 'priceTotal': None, }) profiles.append({'name': profile.title, 'price': profile.getAnalysisProfilePrice(), 'priceVat': profile.getVATAmount(), 'priceTotal': profile.getTotalPrice(), 'analyses': pservices}) else: # We need the analyses prices instead of profile price for pservice in profile.getService(): # We want the analysis instead of the service, because we want the price for the client # (for instance the bulk price) panalysis = self._getAnalysisForProfileService(pservice.getKeyword(), analyses_from_profiles) if panalysis == 0: continue else: pservices.append({ 'title': pservice.Title(), 'price': panalysis.getPrice(), 'priceVat': "%.2f" % panalysis.getVATAmount(), 'priceTotal': "%.2f" % panalysis.getTotalPrice(), }) profiles.append({'name': profile.title, 'price': None, 'priceVat': None, 'priceTotal': None, 'analyses': pservices}) self.analyses = analyses self.profiles = profiles # Get subtotals self.subtotal = context.getSubtotal() self.subtotalVATAmount = "%.2f" % context.getSubtotalVATAmount() self.subtotalTotalPrice = "%.2f" % context.getSubtotalTotalPrice() # Get totals self.memberDiscount = Decimal(context.getDefaultMemberDiscount()) self.discountAmount = context.getDiscountAmount() self.VATAmount = "%.2f" % context.getVATAmount() self.totalPrice = "%.2f" % context.getTotalPrice() # Render the template return self.template()
[ "def", "__call__", "(", "self", ")", ":", "context", "=", "self", ".", "context", "workflow", "=", "getToolByName", "(", "context", ",", "'portal_workflow'", ")", "# Collect related data and objects", "invoice", "=", "context", ".", "getInvoice", "(", ")", "samp...
https://github.com/bikalims/bika.lims/blob/35e4bbdb5a3912cae0b5eb13e51097c8b0486349/bika/lims/browser/analysisrequest/invoice.py#L41-L175
mrDoctorWho/vk4xmpp
e8f25a16832adb6b93fe8b50afdc9547e429389b
library/xmpp/dispatcher.py
python
Dispatcher.SendAndCallForResponse
(self, stanza, func, args={})
Put stanza on the wire and call back when recipient replies. Additional callback arguments can be specified in args.
Put stanza on the wire and call back when recipient replies. Additional callback arguments can be specified in args.
[ "Put", "stanza", "on", "the", "wire", "and", "call", "back", "when", "recipient", "replies", ".", "Additional", "callback", "arguments", "can", "be", "specified", "in", "args", "." ]
def SendAndCallForResponse(self, stanza, func, args={}): """ Put stanza on the wire and call back when recipient replies. Additional callback arguments can be specified in args. """ self._expected[self.send(stanza)] = (func, args)
[ "def", "SendAndCallForResponse", "(", "self", ",", "stanza", ",", "func", ",", "args", "=", "{", "}", ")", ":", "self", ".", "_expected", "[", "self", ".", "send", "(", "stanza", ")", "]", "=", "(", "func", ",", "args", ")" ]
https://github.com/mrDoctorWho/vk4xmpp/blob/e8f25a16832adb6b93fe8b50afdc9547e429389b/library/xmpp/dispatcher.py#L440-L445
kiibohd/kll
b6d997b810006326d31fc570c89d396fd0b70569
kll/common/parse.py
python
Make.unseqString
(token)
return token[1:-1]
Converts a raw sequence string to a Python string 'this string' -> this string
Converts a raw sequence string to a Python string
[ "Converts", "a", "raw", "sequence", "string", "to", "a", "Python", "string" ]
def unseqString(token): ''' Converts a raw sequence string to a Python string 'this string' -> this string ''' return token[1:-1]
[ "def", "unseqString", "(", "token", ")", ":", "return", "token", "[", "1", ":", "-", "1", "]" ]
https://github.com/kiibohd/kll/blob/b6d997b810006326d31fc570c89d396fd0b70569/kll/common/parse.py#L465-L471
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_project.py
python
OpenShiftCLI.openshift_cmd
(self, cmd, oadm=False, output=False, output_type='json', input_data=None)
return rval
Base command for oc
Base command for oc
[ "Base", "command", "for", "oc" ]
def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [self.oc_binary] if oadm: cmds.append('adm') cmds.extend(cmd) if self.all_namespaces: cmds.extend(['--all-namespaces']) elif self.namespace is not None and self.namespace.lower() not in ['none', 'emtpy']: # E501 cmds.extend(['-n', self.namespace]) if self.verbose: print(' '.join(cmds)) try: returncode, stdout, stderr = self._run(cmds, input_data) except OSError as ex: returncode, stdout, stderr = 1, '', 'Failed to execute {}: {}'.format(subprocess.list2cmdline(cmds), ex) rval = {"returncode": returncode, "cmd": ' '.join(cmds)} if output_type == 'json': rval['results'] = {} if output and stdout: try: rval['results'] = json.loads(stdout) except ValueError as verr: if "No JSON object could be decoded" in verr.args: rval['err'] = verr.args elif output_type == 'raw': rval['results'] = stdout if output else '' if self.verbose: print("STDOUT: {0}".format(stdout)) print("STDERR: {0}".format(stderr)) if 'err' in rval or returncode != 0: rval.update({"stderr": stderr, "stdout": stdout}) return rval
[ "def", "openshift_cmd", "(", "self", ",", "cmd", ",", "oadm", "=", "False", ",", "output", "=", "False", ",", "output_type", "=", "'json'", ",", "input_data", "=", "None", ")", ":", "cmds", "=", "[", "self", ".", "oc_binary", "]", "if", "oadm", ":", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.10.0-0.29.0/roles/lib_openshift/library/oc_project.py#L1121-L1165
quic/aimet
dae9bae9a77ca719aa7553fefde4768270fc3518
TrainingExtensions/torch/src/python/aimet_torch/meta/old_connectedgraph.py
python
get_module_name
(xname)
return '.'.join(module_name_parts)
Parses the xname for named operations.
Parses the xname for named operations.
[ "Parses", "the", "xname", "for", "named", "operations", "." ]
def get_module_name(xname): """ Parses the xname for named operations.""" # e.g. VGG / Sequential[features] / Conv2d[0] / Conv_33 xparts = xname.split('/') module_name_parts = [] for part in xparts[:-1]: bracket_pos = part.find('[') if bracket_pos < 0: module_name_parts.append(part) else: var_name = part[bracket_pos + 1:-1] module_name_parts.append(var_name) return '.'.join(module_name_parts)
[ "def", "get_module_name", "(", "xname", ")", ":", "# e.g. VGG / Sequential[features] / Conv2d[0] / Conv_33", "xparts", "=", "xname", ".", "split", "(", "'/'", ")", "module_name_parts", "=", "[", "]", "for", "part", "in", "xparts", "[", ":", "-", "1", "]", ":",...
https://github.com/quic/aimet/blob/dae9bae9a77ca719aa7553fefde4768270fc3518/TrainingExtensions/torch/src/python/aimet_torch/meta/old_connectedgraph.py#L618-L631
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/db/generic.py
python
DbGeneric.get_summary
(self)
return { _("Number of people"): self.get_number_of_people(), _("Number of families"): self.get_number_of_families(), _("Number of sources"): self.get_number_of_sources(), _("Number of citations"): self.get_number_of_citations(), _("Number of events"): self.get_number_of_events(), _("Number of media"): self.get_number_of_media(), _("Number of places"): self.get_number_of_places(), _("Number of repositories"): self.get_number_of_repositories(), _("Number of notes"): self.get_number_of_notes(), _("Number of tags"): self.get_number_of_tags(), _("Schema version"): ".".join([str(v) for v in self.VERSION]), }
Returns dictionary of summary item. Should include, if possible: _("Number of people") _("Version") _("Data version")
Returns dictionary of summary item. Should include, if possible:
[ "Returns", "dictionary", "of", "summary", "item", ".", "Should", "include", "if", "possible", ":" ]
def get_summary(self): """ Returns dictionary of summary item. Should include, if possible: _("Number of people") _("Version") _("Data version") """ return { _("Number of people"): self.get_number_of_people(), _("Number of families"): self.get_number_of_families(), _("Number of sources"): self.get_number_of_sources(), _("Number of citations"): self.get_number_of_citations(), _("Number of events"): self.get_number_of_events(), _("Number of media"): self.get_number_of_media(), _("Number of places"): self.get_number_of_places(), _("Number of repositories"): self.get_number_of_repositories(), _("Number of notes"): self.get_number_of_notes(), _("Number of tags"): self.get_number_of_tags(), _("Schema version"): ".".join([str(v) for v in self.VERSION]), }
[ "def", "get_summary", "(", "self", ")", ":", "return", "{", "_", "(", "\"Number of people\"", ")", ":", "self", ".", "get_number_of_people", "(", ")", ",", "_", "(", "\"Number of families\"", ")", ":", "self", ".", "get_number_of_families", "(", ")", ",", ...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/db/generic.py#L2406-L2427
spotify/cstar
6172580a3ceba091f9599df355c267f9ce22a99a
cstar/topology.py
python
Topology.get_down
(self)
return Topology(node for node in self if not node.is_up)
Returns a set of all nodes that are down in this topology
Returns a set of all nodes that are down in this topology
[ "Returns", "a", "set", "of", "all", "nodes", "that", "are", "down", "in", "this", "topology" ]
def get_down(self): """Returns a set of all nodes that are down in this topology""" return Topology(node for node in self if not node.is_up)
[ "def", "get_down", "(", "self", ")", ":", "return", "Topology", "(", "node", "for", "node", "in", "self", "if", "not", "node", ".", "is_up", ")" ]
https://github.com/spotify/cstar/blob/6172580a3ceba091f9599df355c267f9ce22a99a/cstar/topology.py#L99-L101
tao12345666333/tornado-zh
e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c
tornado/iostream.py
python
BaseIOStream.read_until_regex
(self, regex, callback=None, max_bytes=None)
return future
Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted.
Asynchronously read until we have matched the given regex.
[ "Asynchronously", "read", "until", "we", "have", "matched", "the", "given", "regex", "." ]
def read_until_regex(self, regex, callback=None, max_bytes=None): """Asynchronously read until we have matched the given regex. The result includes the data that matches the regex and anything that came before it. If a callback is given, it will be run with the data as an argument; if not, this method returns a `.Future`. If ``max_bytes`` is not None, the connection will be closed if more than ``max_bytes`` bytes have been read and the regex is not satisfied. .. versionchanged:: 4.0 Added the ``max_bytes`` argument. The ``callback`` argument is now optional and a `.Future` will be returned if it is omitted. """ future = self._set_read_callback(callback) self._read_regex = re.compile(regex) self._read_max_bytes = max_bytes try: self._try_inline_read() except UnsatisfiableReadError as e: # Handle this the same way as in _handle_events. gen_log.info("Unsatisfiable read, closing connection: %s" % e) self.close(exc_info=True) return future except: if future is not None: # Ensure that the future doesn't log an error because its # failure was never examined. future.add_done_callback(lambda f: f.exception()) raise return future
[ "def", "read_until_regex", "(", "self", ",", "regex", ",", "callback", "=", "None", ",", "max_bytes", "=", "None", ")", ":", "future", "=", "self", ".", "_set_read_callback", "(", "callback", ")", "self", ".", "_read_regex", "=", "re", ".", "compile", "(...
https://github.com/tao12345666333/tornado-zh/blob/e9e8519beb147d9e1290f6a4fa7d61123d1ecb1c/tornado/iostream.py#L229-L261
benelot/pybullet-gym
bc68201c8101c4e30dde95f425647a0709ee2f29
pybulletgym/envs/mujoco/scenes/scene_bases.py
python
Scene.episode_restart
(self, bullet_client)
This function gets overridden by specific scene, to reset specific objects into their start positions
This function gets overridden by specific scene, to reset specific objects into their start positions
[ "This", "function", "gets", "overridden", "by", "specific", "scene", "to", "reset", "specific", "objects", "into", "their", "start", "positions" ]
def episode_restart(self, bullet_client): "This function gets overridden by specific scene, to reset specific objects into their start positions" self.cpp_world.clean_everything()
[ "def", "episode_restart", "(", "self", ",", "bullet_client", ")", ":", "self", ".", "cpp_world", ".", "clean_everything", "(", ")" ]
https://github.com/benelot/pybullet-gym/blob/bc68201c8101c4e30dde95f425647a0709ee2f29/pybulletgym/envs/mujoco/scenes/scene_bases.py#L43-L45
pazz/alot
52f11f089df19cf336ad0983368e880dc5364149
alot/db/utils.py
python
_decrypted_message_from_message
(original_bytes, m, session_keys=None)
return m
Detect and decrypt OpenPGP encrypted data in an email object. If this succeeds, any mime messages found in the recovered plaintext message are added to the returned message object. :param original_bytes: the original top-level mail raw bytes, containing the segments against which signatures will be verified. Necessary because parsing and re-serialising a Message isn't byte-perfect, which interferes with signature validation. :type original_bytes: bytes :param m: an email object :param session_keys: a list OpenPGP session keys :returns: :class:`email.message.Message` possibly augmented with decrypted data
Detect and decrypt OpenPGP encrypted data in an email object. If this succeeds, any mime messages found in the recovered plaintext message are added to the returned message object.
[ "Detect", "and", "decrypt", "OpenPGP", "encrypted", "data", "in", "an", "email", "object", ".", "If", "this", "succeeds", "any", "mime", "messages", "found", "in", "the", "recovered", "plaintext", "message", "are", "added", "to", "the", "returned", "message", ...
def _decrypted_message_from_message(original_bytes, m, session_keys=None): '''Detect and decrypt OpenPGP encrypted data in an email object. If this succeeds, any mime messages found in the recovered plaintext message are added to the returned message object. :param original_bytes: the original top-level mail raw bytes, containing the segments against which signatures will be verified. Necessary because parsing and re-serialising a Message isn't byte-perfect, which interferes with signature validation. :type original_bytes: bytes :param m: an email object :param session_keys: a list OpenPGP session keys :returns: :class:`email.message.Message` possibly augmented with decrypted data ''' # make sure no one smuggles a token in (data from m is untrusted) del m[X_SIGNATURE_VALID_HEADER] del m[X_SIGNATURE_MESSAGE_HEADER] if m.is_multipart(): p = get_params(m) # handle OpenPGP signed data if (m.get_content_subtype() == 'signed' and p.get('protocol') == _APP_PGP_SIG): _handle_signatures(original_bytes, m, m, p) # handle OpenPGP encrypted data elif (m.get_content_subtype() == 'encrypted' and p.get('protocol') == _APP_PGP_ENC and 'Version: 1' in m.get_payload(0).get_payload()): _handle_encrypted(m, m, session_keys) # It is also possible to put either of the abov into a multipart/mixed # segment elif m.get_content_subtype() == 'mixed': sub = m.get_payload(0) if sub.is_multipart(): p = get_params(sub) if (sub.get_content_subtype() == 'signed' and p.get('protocol') == _APP_PGP_SIG): _handle_signatures(original_bytes, m, sub, p) elif (sub.get_content_subtype() == 'encrypted' and p.get('protocol') == _APP_PGP_ENC): _handle_encrypted(m, sub, session_keys) return m
[ "def", "_decrypted_message_from_message", "(", "original_bytes", ",", "m", ",", "session_keys", "=", "None", ")", ":", "# make sure no one smuggles a token in (data from m is untrusted)", "del", "m", "[", "X_SIGNATURE_VALID_HEADER", "]", "del", "m", "[", "X_SIGNATURE_MESSAG...
https://github.com/pazz/alot/blob/52f11f089df19cf336ad0983368e880dc5364149/alot/db/utils.py#L251-L299
OWASP/Nettacker
0b79a5b4fc8762199e85dd086554d585e62c314a
core/load_modules.py
python
load_all_profiles
(limit=-1)
return profiles
load all available profiles Returns: an array of all profile names
load all available profiles
[ "load", "all", "available", "profiles" ]
def load_all_profiles(limit=-1): """ load all available profiles Returns: an array of all profile names """ from core.utility import sort_dictonary all_modules_with_details = load_all_modules(limit=limit, full_details=True) profiles = {} if '...' in all_modules_with_details: del all_modules_with_details['...'] del all_modules_with_details['all'] for key in all_modules_with_details: for tag in all_modules_with_details[key]['profiles']: if tag not in profiles: profiles[tag] = [] profiles[tag].append(key) else: profiles[tag].append(key) if len(profiles) == limit: profiles = sort_dictonary(profiles) profiles['...'] = [] profiles['all'] = [] return profiles profiles = sort_dictonary(profiles) profiles['all'] = [] return profiles
[ "def", "load_all_profiles", "(", "limit", "=", "-", "1", ")", ":", "from", "core", ".", "utility", "import", "sort_dictonary", "all_modules_with_details", "=", "load_all_modules", "(", "limit", "=", "limit", ",", "full_details", "=", "True", ")", "profiles", "...
https://github.com/OWASP/Nettacker/blob/0b79a5b4fc8762199e85dd086554d585e62c314a/core/load_modules.py#L302-L329
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/core/series.py
python
Series.__array__
(self, result=None)
return self.get_values()
the array interface, return my values
the array interface, return my values
[ "the", "array", "interface", "return", "my", "values" ]
def __array__(self, result=None): """ the array interface, return my values """ return self.get_values()
[ "def", "__array__", "(", "self", ",", "result", "=", "None", ")", ":", "return", "self", ".", "get_values", "(", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/core/series.py#L471-L475
TesterlifeRaymond/doraemon
d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333
venv/lib/python3.6/site-packages/pip/utils/__init__.py
python
read_text_file
(filename)
return data
Return the contents of *filename*. Try to decode the file contents with utf-8, the preferred system encoding (e.g., cp1252 on some Windows machines), and latin1, in that order. Decoding a byte string with latin1 will never raise an error. In the worst case, the returned string will contain some garbage characters.
Return the contents of *filename*.
[ "Return", "the", "contents", "of", "*", "filename", "*", "." ]
def read_text_file(filename): """Return the contents of *filename*. Try to decode the file contents with utf-8, the preferred system encoding (e.g., cp1252 on some Windows machines), and latin1, in that order. Decoding a byte string with latin1 will never raise an error. In the worst case, the returned string will contain some garbage characters. """ with open(filename, 'rb') as fp: data = fp.read() encodings = ['utf-8', locale.getpreferredencoding(False), 'latin1'] for enc in encodings: try: data = data.decode(enc) except UnicodeDecodeError: continue break assert type(data) != bytes # Latin1 should have worked. return data
[ "def", "read_text_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fp", ":", "data", "=", "fp", ".", "read", "(", ")", "encodings", "=", "[", "'utf-8'", ",", "locale", ".", "getpreferredencoding", "(", "False"...
https://github.com/TesterlifeRaymond/doraemon/blob/d5cb6e34bd5f2aa97273ce0c0c9303e32beaa333/venv/lib/python3.6/site-packages/pip/utils/__init__.py#L722-L743
edfungus/Crouton
ada98b3930192938a48909072b45cb84b945f875
clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py
python
assert_fingerprint
(cert, fingerprint)
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
Checks if given fingerprint matches the supplied certificate.
[ "Checks", "if", "given", "fingerprint", "matches", "the", "supplied", "certificate", "." ]
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ # Maps the length of a digest to a possible hash function producing # this digest. hashfunc_map = { 16: md5, 20: sha1, 32: sha256, } fingerprint = fingerprint.replace(':', '').lower() digest_length, odd = divmod(len(fingerprint), 2) if odd or digest_length not in hashfunc_map: raise SSLError('Fingerprint is of invalid length.') # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) hashfunc = hashfunc_map[digest_length] cert_digest = hashfunc(cert).digest() if not cert_digest == fingerprint_bytes: raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".' .format(hexlify(fingerprint_bytes), hexlify(cert_digest)))
[ "def", "assert_fingerprint", "(", "cert", ",", "fingerprint", ")", ":", "# Maps the length of a digest to a possible hash function producing", "# this digest.", "hashfunc_map", "=", "{", "16", ":", "md5", ",", "20", ":", "sha1", ",", "32", ":", "sha256", ",", "}", ...
https://github.com/edfungus/Crouton/blob/ada98b3930192938a48909072b45cb84b945f875/clients/esp8266_clients/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py#L105-L139
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/rfc822.py
python
AddrlistClass.getphraselist
(self)
return plist
Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space.
Parse a sequence of RFC 2822 phrases.
[ "Parse", "a", "sequence", "of", "RFC", "2822", "phrases", "." ]
def getphraselist(self): """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. """ plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] in self.phraseends: break else: plist.append(self.getatom(self.phraseends)) return plist
[ "def", "getphraselist", "(", "self", ")", ":", "plist", "=", "[", "]", "while", "self", ".", "pos", "<", "len", "(", "self", ".", "field", ")", ":", "if", "self", ".", "field", "[", "self", ".", "pos", "]", "in", "self", ".", "LWS", ":", "self"...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/bin/x86/Debug/Lib/rfc822.py#L747-L768
HaoZhang95/Python24
b897224b8a0e6a5734f408df8c24846a98c553bf
00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/distlib/manifest.py
python
Manifest.clear
(self)
Clear all collected files.
Clear all collected files.
[ "Clear", "all", "collected", "files", "." ]
def clear(self): """Clear all collected files.""" self.files = set() self.allfiles = []
[ "def", "clear", "(", "self", ")", ":", "self", ".", "files", "=", "set", "(", ")", "self", ".", "allfiles", "=", "[", "]" ]
https://github.com/HaoZhang95/Python24/blob/b897224b8a0e6a5734f408df8c24846a98c553bf/00Python/venv/Lib/site-packages/pip-10.0.1-py3.7.egg/pip/_vendor/distlib/manifest.py#L125-L128
barseghyanartur/django-fobi
a998feae007d7fe3637429a80e42952ec7cda79f
src/fobi/base.py
python
BaseIntegrationPluginRegistry.get
(self, integrate_with, uid, default=None)
return item
Get the given entry from the registry. :param str integrate_with: :param str uid: :param mixed default: :return mixed.
Get the given entry from the registry.
[ "Get", "the", "given", "entry", "from", "the", "registry", "." ]
def get(self, integrate_with, uid, default=None): """Get the given entry from the registry. :param str integrate_with: :param str uid: :param mixed default: :return mixed. """ item = self._registry[integrate_with].get(uid, default) if not item: err_msg = self.plugin_not_found_error_message.format( uid, self.__class__ ) if self.fail_on_missing_plugin: logger.error(err_msg) raise self.plugin_not_found_exception_cls(err_msg) else: logger.debug(err_msg) return item
[ "def", "get", "(", "self", ",", "integrate_with", ",", "uid", ",", "default", "=", "None", ")", ":", "item", "=", "self", ".", "_registry", "[", "integrate_with", "]", ".", "get", "(", "uid", ",", "default", ")", "if", "not", "item", ":", "err_msg", ...
https://github.com/barseghyanartur/django-fobi/blob/a998feae007d7fe3637429a80e42952ec7cda79f/src/fobi/base.py#L2504-L2524
citronneur/rdpy
cef16a9f64d836a3221a344ca7d571644280d829
rdpy/protocol/rdp/t125/per.py
python
readChoice
(s)
return choice.value
@summary: read per choice format @param s: Stream @return: int that represent choice
[]
def readChoice(s): """ @summary: read per choice format @param s: Stream @return: int that represent choice """ choice = UInt8() s.readType(choice) return choice.value
[ "def", "readChoice", "(", "s", ")", ":", "choice", "=", "UInt8", "(", ")", "s", ".", "readType", "(", "choice", ")", "return", "choice", ".", "value" ]
https://github.com/citronneur/rdpy/blob/cef16a9f64d836a3221a344ca7d571644280d829/rdpy/protocol/rdp/t125/per.py#L56-L64
Epistimio/orion
732e739d99561020dbe620760acf062ade746006
src/orion/client/__init__.py
python
create_experiment
(name, **config)
return build_experiment(name, **config)
Build an experiment to be executable This function is deprecated and will be removed in v0.3.0. Use `build_experiment` instead.
Build an experiment to be executable
[ "Build", "an", "experiment", "to", "be", "executable" ]
def create_experiment(name, **config): """Build an experiment to be executable This function is deprecated and will be removed in v0.3.0. Use `build_experiment` instead. """ return build_experiment(name, **config)
[ "def", "create_experiment", "(", "name", ",", "*", "*", "config", ")", ":", "return", "build_experiment", "(", "name", ",", "*", "*", "config", ")" ]
https://github.com/Epistimio/orion/blob/732e739d99561020dbe620760acf062ade746006/src/orion/client/__init__.py#L38-L44
limodou/uliweb
8bc827fa6bf7bf58aa8136b6c920fe2650c52422
uliweb/lib/werkzeug/formparser.py
python
parse_multipart_headers
(iterable)
return Headers(result)
Parses multipart headers from an iterable that yields lines (including the trailing newline symbol). The iterable has to be newline terminated. The iterable will stop at the line where the headers ended so it can be further consumed. :param iterable: iterable of strings that are newline terminated
Parses multipart headers from an iterable that yields lines (including the trailing newline symbol). The iterable has to be newline terminated.
[ "Parses", "multipart", "headers", "from", "an", "iterable", "that", "yields", "lines", "(", "including", "the", "trailing", "newline", "symbol", ")", ".", "The", "iterable", "has", "to", "be", "newline", "terminated", "." ]
def parse_multipart_headers(iterable): """Parses multipart headers from an iterable that yields lines (including the trailing newline symbol). The iterable has to be newline terminated. The iterable will stop at the line where the headers ended so it can be further consumed. :param iterable: iterable of strings that are newline terminated """ result = [] for line in iterable: line = to_native(line) line, line_terminated = _line_parse(line) if not line_terminated: raise ValueError('unexpected end of line in multipart header') if not line: break elif line[0] in ' \t' and result: key, value = result[-1] result[-1] = (key, value + '\n ' + line[1:]) else: parts = line.split(':', 1) if len(parts) == 2: result.append((parts[0].strip(), parts[1].strip())) # we link the list to the headers, no need to create a copy, the # list was not shared anyways. return Headers(result)
[ "def", "parse_multipart_headers", "(", "iterable", ")", ":", "result", "=", "[", "]", "for", "line", "in", "iterable", ":", "line", "=", "to_native", "(", "line", ")", "line", ",", "line_terminated", "=", "_line_parse", "(", "line", ")", "if", "not", "li...
https://github.com/limodou/uliweb/blob/8bc827fa6bf7bf58aa8136b6c920fe2650c52422/uliweb/lib/werkzeug/formparser.py#L245-L272
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gui/widgets/selectionwidget.py
python
SelectionWidget.select
(self, region)
Highlights the given region in the image.
Highlights the given region in the image.
[ "Highlights", "the", "given", "region", "in", "the", "image", "." ]
def select(self, region): """ Highlights the given region in the image. """ self.current = region if self.current is not None: self.selection = self.current.coords() self.image.queue_draw()
[ "def", "select", "(", "self", ",", "region", ")", ":", "self", ".", "current", "=", "region", "if", "self", ".", "current", "is", "not", "None", ":", "self", ".", "selection", "=", "self", ".", "current", ".", "coords", "(", ")", "self", ".", "imag...
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gui/widgets/selectionwidget.py#L415-L422
kubernetes-client/python
47b9da9de2d02b2b7a34fbe05afb44afd130d73a
kubernetes/client/models/v1_bound_object_reference.py
python
V1BoundObjectReference.name
(self, name)
Sets the name of this V1BoundObjectReference. Name of the referent. # noqa: E501 :param name: The name of this V1BoundObjectReference. # noqa: E501 :type: str
Sets the name of this V1BoundObjectReference.
[ "Sets", "the", "name", "of", "this", "V1BoundObjectReference", "." ]
def name(self, name): """Sets the name of this V1BoundObjectReference. Name of the referent. # noqa: E501 :param name: The name of this V1BoundObjectReference. # noqa: E501 :type: str """ self._name = name
[ "def", "name", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name" ]
https://github.com/kubernetes-client/python/blob/47b9da9de2d02b2b7a34fbe05afb44afd130d73a/kubernetes/client/models/v1_bound_object_reference.py#L128-L137
riga/tfdeploy
22aea652fe12f081be43414e0f1f76c7d9aaf53c
tfdeploy.py
python
SplitV
(a, splits, axis)
return tuple(np.split(np.copy(a), np.cumsum(splits), axis=axis))
Split op with multiple split sizes.
Split op with multiple split sizes.
[ "Split", "op", "with", "multiple", "split", "sizes", "." ]
def SplitV(a, splits, axis): """ Split op with multiple split sizes. """ return tuple(np.split(np.copy(a), np.cumsum(splits), axis=axis))
[ "def", "SplitV", "(", "a", ",", "splits", ",", "axis", ")", ":", "return", "tuple", "(", "np", ".", "split", "(", "np", ".", "copy", "(", "a", ")", ",", "np", ".", "cumsum", "(", "splits", ")", ",", "axis", "=", "axis", ")", ")" ]
https://github.com/riga/tfdeploy/blob/22aea652fe12f081be43414e0f1f76c7d9aaf53c/tfdeploy.py#L1175-L1179
DataDog/dd-agent
526559be731b6e47b12d7aa8b6d45cb8d9ac4d68
utils/jmx.py
python
jmx_command
(args, agent_config, redirect_std_streams=False)
Run JMXFetch with the given command if it is valid (and print user-friendly info if it's not)
Run JMXFetch with the given command if it is valid (and print user-friendly info if it's not)
[ "Run", "JMXFetch", "with", "the", "given", "command", "if", "it", "is", "valid", "(", "and", "print", "user", "-", "friendly", "info", "if", "it", "s", "not", ")" ]
def jmx_command(args, agent_config, redirect_std_streams=False): """ Run JMXFetch with the given command if it is valid (and print user-friendly info if it's not) """ from jmxfetch import JMX_LIST_COMMANDS, JMXFetch if len(args) < 1 or args[0] not in JMX_LIST_COMMANDS.keys(): print "#" * 80 print "JMX tool to be used to help configuring your JMX checks." print "See http://docs.datadoghq.com/integrations/java/ for more information" print "#" * 80 print "\n" print "You have to specify one of the following commands:" for command, desc in JMX_LIST_COMMANDS.iteritems(): print " - %s [OPTIONAL: LIST OF CHECKS]: %s" % (command, desc) print "Example: sudo /etc/init.d/datadog-agent jmx list_matching_attributes tomcat jmx solr" print "\n" else: jmx_command = args[0] checks_list = args[1:] confd_directory = get_confd_path() jmx_process = JMXFetch(confd_directory, agent_config) jmx_process.configure(jmx_command) should_run = jmx_process.should_run() if should_run: jmx_process.run(jmx_command, checks_list, reporter="console", redirect_std_streams=redirect_std_streams) else: print "Couldn't find any valid JMX configuration in your conf.d directory: %s" % confd_directory print "Have you enabled any JMX check ?" print "If you think it's not normal please get in touch with Datadog Support"
[ "def", "jmx_command", "(", "args", ",", "agent_config", ",", "redirect_std_streams", "=", "False", ")", ":", "from", "jmxfetch", "import", "JMX_LIST_COMMANDS", ",", "JMXFetch", "if", "len", "(", "args", ")", "<", "1", "or", "args", "[", "0", "]", "not", ...
https://github.com/DataDog/dd-agent/blob/526559be731b6e47b12d7aa8b6d45cb8d9ac4d68/utils/jmx.py#L26-L57
jamespacileo/django-pure-pagination
4e5febe5f6df7fda8488b77fd827b8547d436f26
pure_pagination/paginator.py
python
Page._other_page_querystring
(self, page_number)
return 'page=%s' % page_number
Returns a query string for the given page, preserving any GET parameters present.
Returns a query string for the given page, preserving any GET parameters present.
[ "Returns", "a", "query", "string", "for", "the", "given", "page", "preserving", "any", "GET", "parameters", "present", "." ]
def _other_page_querystring(self, page_number): """ Returns a query string for the given page, preserving any GET parameters present. """ if self.paginator.request: self.base_queryset['page'] = page_number return self.base_queryset.urlencode() # raise Warning("You must supply Paginator() with the request object for a proper querystring.") return 'page=%s' % page_number
[ "def", "_other_page_querystring", "(", "self", ",", "page_number", ")", ":", "if", "self", ".", "paginator", ".", "request", ":", "self", ".", "base_queryset", "[", "'page'", "]", "=", "page_number", "return", "self", ".", "base_queryset", ".", "urlencode", ...
https://github.com/jamespacileo/django-pure-pagination/blob/4e5febe5f6df7fda8488b77fd827b8547d436f26/pure_pagination/paginator.py#L199-L209
twrecked/hass-aarlo
c00cc750912449dab97b46e060fe52e34e9ca73b
custom_components/aarlo/media_player.py
python
ArloMediaPlayer.state
(self)
return self._state
Return the state of the device.
Return the state of the device.
[ "Return", "the", "state", "of", "the", "device", "." ]
def state(self): """Return the state of the device.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
https://github.com/twrecked/hass-aarlo/blob/c00cc750912449dab97b46e060fe52e34e9ca73b/custom_components/aarlo/media_player.py#L143-L145
zenodo/zenodo
3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5
zenodo/modules/deposit/api.py
python
ZenodoDeposit._create_inclusion_requests
(comms, record)
Create inclusion requests for communities. :param comms: Community IDs for which the inclusion requests might should be created (if they don't exist already). :type comms: list of str :param record: Record corresponding to this deposit. :type record: `invenio_records.api.Record`
Create inclusion requests for communities.
[ "Create", "inclusion", "requests", "for", "communities", "." ]
def _create_inclusion_requests(comms, record): """Create inclusion requests for communities. :param comms: Community IDs for which the inclusion requests might should be created (if they don't exist already). :type comms: list of str :param record: Record corresponding to this deposit. :type record: `invenio_records.api.Record` """ for comm_id in comms: comm_api = ZenodoCommunity(comm_id) # Check if InclusionRequest exists for any version already pending_irs = comm_api.get_comm_irs(record) if pending_irs.count() == 0 and not comm_api.has_record(record): comm = Community.get(comm_id) notify = comm_id not in \ current_app.config['ZENODO_COMMUNITIES_NOTIFY_DISABLED'] InclusionRequest.create(comm, record, notify=notify)
[ "def", "_create_inclusion_requests", "(", "comms", ",", "record", ")", ":", "for", "comm_id", "in", "comms", ":", "comm_api", "=", "ZenodoCommunity", "(", "comm_id", ")", "# Check if InclusionRequest exists for any version already", "pending_irs", "=", "comm_api", ".", ...
https://github.com/zenodo/zenodo/blob/3c45e52a742ad5a0a7788a67b02fbbc15ab4d8d5/zenodo/modules/deposit/api.py#L156-L174
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/categories/baseclasses.py
python
Category.objects
(self)
return self.args[1]
Returns the class of objects of this category. Examples ======== >>> from sympy.categories import Object, Category >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> K = Category("K", FiniteSet(A, B)) >>> K.objects Class({Object("A"), Object("B")})
Returns the class of objects of this category.
[ "Returns", "the", "class", "of", "objects", "of", "this", "category", "." ]
def objects(self): """ Returns the class of objects of this category. Examples ======== >>> from sympy.categories import Object, Category >>> from sympy import FiniteSet >>> A = Object("A") >>> B = Object("B") >>> K = Category("K", FiniteSet(A, B)) >>> K.objects Class({Object("A"), Object("B")}) """ return self.args[1]
[ "def", "objects", "(", "self", ")", ":", "return", "self", ".", "args", "[", "1", "]" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/sympy/categories/baseclasses.py#L475-L491
PaddlePaddle/PARL
5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96
examples/PPO/mujoco_model.py
python
Actor.forward
(self, obs)
return mean, self.log_std
Forward pass for policy network Args: obs (np.array): current observation
Forward pass for policy network
[ "Forward", "pass", "for", "policy", "network" ]
def forward(self, obs): """ Forward pass for policy network Args: obs (np.array): current observation """ x = paddle.tanh(self.fc1(obs)) x = paddle.tanh(self.fc2(x)) mean = self.fc_mean(x) return mean, self.log_std
[ "def", "forward", "(", "self", ",", "obs", ")", ":", "x", "=", "paddle", ".", "tanh", "(", "self", ".", "fc1", "(", "obs", ")", ")", "x", "=", "paddle", ".", "tanh", "(", "self", ".", "fc2", "(", "x", ")", ")", "mean", "=", "self", ".", "fc...
https://github.com/PaddlePaddle/PARL/blob/5fb7a5d2b5d0f0dac57fdf4acb9e79485c7efa96/examples/PPO/mujoco_model.py#L69-L79
leo-editor/leo-editor
383d6776d135ef17d73d935a2f0ecb3ac0e99494
leo/plugins/obsolete/tkGui.py
python
tkinterListBoxDialog.createFrame
(self)
Create the essentials of a listBoxDialog frame Subclasses will add buttons to self.buttonFrame
Create the essentials of a listBoxDialog frame
[ "Create", "the", "essentials", "of", "a", "listBoxDialog", "frame" ]
def createFrame(self): """Create the essentials of a listBoxDialog frame Subclasses will add buttons to self.buttonFrame""" if g.app.unitTesting: return self.outerFrame = f = Tk.Frame(self.frame) f.pack(expand=1,fill="both") if self.label: labf = Tk.Frame(f) labf.pack(pady=2) lab = Tk.Label(labf,text=self.label) lab.pack() f2 = Tk.Frame(f) f2.pack(expand=1,fill="both") self.box = box = Tk.Listbox(f2,height=20,width=30) box.pack(side="left",expand=1,fill="both") bar = Tk.Scrollbar(f2) bar.pack(side="left", fill="y") bar.config(command=box.yview) box.config(yscrollcommand=bar.set)
[ "def", "createFrame", "(", "self", ")", ":", "if", "g", ".", "app", ".", "unitTesting", ":", "return", "self", ".", "outerFrame", "=", "f", "=", "Tk", ".", "Frame", "(", "self", ".", "frame", ")", "f", ".", "pack", "(", "expand", "=", "1", ",", ...
https://github.com/leo-editor/leo-editor/blob/383d6776d135ef17d73d935a2f0ecb3ac0e99494/leo/plugins/obsolete/tkGui.py#L2340-L2367
espnet/espnet
ea411f3f627b8f101c211e107d0ff7053344ac80
espnet/scheduler/scheduler.py
python
register_scheduler
(cls)
return cls
Register scheduler.
Register scheduler.
[ "Register", "scheduler", "." ]
def register_scheduler(cls): """Register scheduler.""" SCHEDULER_DICT[cls.alias] = cls.__module__ + ":" + cls.__name__ return cls
[ "def", "register_scheduler", "(", "cls", ")", ":", "SCHEDULER_DICT", "[", "cls", ".", "alias", "]", "=", "cls", ".", "__module__", "+", "\":\"", "+", "cls", ".", "__name__", "return", "cls" ]
https://github.com/espnet/espnet/blob/ea411f3f627b8f101c211e107d0ff7053344ac80/espnet/scheduler/scheduler.py#L83-L86
tomplus/kubernetes_asyncio
f028cc793e3a2c519be6a52a49fb77ff0b014c9b
kubernetes_asyncio/client/models/v1beta1_custom_resource_definition_version.py
python
V1beta1CustomResourceDefinitionVersion.__init__
(self, additional_printer_columns=None, deprecated=None, deprecation_warning=None, name=None, schema=None, served=None, storage=None, subresources=None, local_vars_configuration=None)
V1beta1CustomResourceDefinitionVersion - a model defined in OpenAPI
V1beta1CustomResourceDefinitionVersion - a model defined in OpenAPI
[ "V1beta1CustomResourceDefinitionVersion", "-", "a", "model", "defined", "in", "OpenAPI" ]
def __init__(self, additional_printer_columns=None, deprecated=None, deprecation_warning=None, name=None, schema=None, served=None, storage=None, subresources=None, local_vars_configuration=None): # noqa: E501 """V1beta1CustomResourceDefinitionVersion - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._additional_printer_columns = None self._deprecated = None self._deprecation_warning = None self._name = None self._schema = None self._served = None self._storage = None self._subresources = None self.discriminator = None if additional_printer_columns is not None: self.additional_printer_columns = additional_printer_columns if deprecated is not None: self.deprecated = deprecated if deprecation_warning is not None: self.deprecation_warning = deprecation_warning self.name = name if schema is not None: self.schema = schema self.served = served self.storage = storage if subresources is not None: self.subresources = subresources
[ "def", "__init__", "(", "self", ",", "additional_printer_columns", "=", "None", ",", "deprecated", "=", "None", ",", "deprecation_warning", "=", "None", ",", "name", "=", "None", ",", "schema", "=", "None", ",", "served", "=", "None", ",", "storage", "=", ...
https://github.com/tomplus/kubernetes_asyncio/blob/f028cc793e3a2c519be6a52a49fb77ff0b014c9b/kubernetes_asyncio/client/models/v1beta1_custom_resource_definition_version.py#L57-L85
tp4a/teleport
1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad
server/www/packages/packages-darwin/x64/ldap3/extend/novell/endTransaction.py
python
EndTransaction.config
(self)
[]
def config(self): self.request_name = '2.16.840.1.113719.1.27.103.2' self.response_name = '2.16.840.1.113719.1.27.103.2' self.request_value = EndGroupTypeRequestValue() self.asn1_spec = EndGroupTypeResponseValue()
[ "def", "config", "(", "self", ")", ":", "self", ".", "request_name", "=", "'2.16.840.1.113719.1.27.103.2'", "self", ".", "response_name", "=", "'2.16.840.1.113719.1.27.103.2'", "self", ".", "request_value", "=", "EndGroupTypeRequestValue", "(", ")", "self", ".", "as...
https://github.com/tp4a/teleport/blob/1fafd34f1f775d2cf80ea4af6e44468d8e0b24ad/server/www/packages/packages-darwin/x64/ldap3/extend/novell/endTransaction.py#L32-L36
stoq/stoq
c26991644d1affcf96bc2e0a0434796cabdf8448
stoq/lib/gui/slaves/paymentslave.py
python
PaymentListSlave.create_payments
(self)
return payments
Commit the payments on the list to the database
Commit the payments on the list to the database
[ "Commit", "the", "payments", "on", "the", "list", "to", "the", "database" ]
def create_payments(self): """Commit the payments on the list to the database""" if not self.is_payment_list_valid(): return [] payments = [] for p in self.payment_list: due_date = localdatetime(p.due_date.year, p.due_date.month, p.due_date.day) try: # When creating temporary identifiers, we should use negative # values, but we need to get the next negative value before # creating the payment, otherwise there may be a conflict in the # database, since the payment identifier for the other branch # may already exist if self.temporary_identifiers: tmp_identifier = Payment.get_temporary_identifier(self.method.store) else: tmp_identifier = None payment = self.method.create_payment( payment_type=self.payment_type, payment_group=self.group, branch=self.branch, station=api.get_current_station(self.branch.store), value=p.value, due_date=due_date, description=p.description, payment_number=p.payment_number) if tmp_identifier: payment.identifier = tmp_identifier except PaymentMethodError as err: warning(str(err)) return if p.bank_account: # Add the bank_account into the payment, if any. bank_account = payment.check_data.bank_account bank_account.bank_number = p.bank_account.bank_number bank_account.bank_branch = p.bank_account.bank_branch bank_account.bank_account = p.bank_account.bank_account payments.append(payment) return payments
[ "def", "create_payments", "(", "self", ")", ":", "if", "not", "self", ".", "is_payment_list_valid", "(", ")", ":", "return", "[", "]", "payments", "=", "[", "]", "for", "p", "in", "self", ".", "payment_list", ":", "due_date", "=", "localdatetime", "(", ...
https://github.com/stoq/stoq/blob/c26991644d1affcf96bc2e0a0434796cabdf8448/stoq/lib/gui/slaves/paymentslave.py#L381-L420
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/webbrowser.py
python
get
(using=None)
Return a browser launcher instance appropriate for the environment.
Return a browser launcher instance appropriate for the environment.
[ "Return", "a", "browser", "launcher", "instance", "appropriate", "for", "the", "environment", "." ]
def get(using=None): """Return a browser launcher instance appropriate for the environment.""" if _tryorder is None: with _lock: if _tryorder is None: register_standard_browsers() if using is not None: alternatives = [using] else: alternatives = _tryorder for browser in alternatives: if '%s' in browser: # User gave us a command line, split it into name and args browser = shlex.split(browser) if browser[-1] == '&': return BackgroundBrowser(browser[:-1]) else: return GenericBrowser(browser) else: # User gave us a browser name or path. try: command = _browsers[browser.lower()] except KeyError: command = _synthesize(browser) if command[1] is not None: return command[1] elif command[0] is not None: return command[0]() raise Error("could not locate runnable browser")
[ "def", "get", "(", "using", "=", "None", ")", ":", "if", "_tryorder", "is", "None", ":", "with", "_lock", ":", "if", "_tryorder", "is", "None", ":", "register_standard_browsers", "(", ")", "if", "using", "is", "not", "None", ":", "alternatives", "=", "...
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/webbrowser.py#L37-L65
wwqgtxx/wwqLyParse
33136508e52821babd9294fdecffbdf02d73a6fc
wwqLyParse/lib/aiohttp_lib/aiohttp/connector.py
python
TCPConnector.family
(self)
return self._family
Socket family like AF_INET.
Socket family like AF_INET.
[ "Socket", "family", "like", "AF_INET", "." ]
def family(self) -> int: """Socket family like AF_INET.""" return self._family
[ "def", "family", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_family" ]
https://github.com/wwqgtxx/wwqLyParse/blob/33136508e52821babd9294fdecffbdf02d73a6fc/wwqLyParse/lib/aiohttp_lib/aiohttp/connector.py#L730-L732
wxWidgets/Phoenix
b2199e299a6ca6d866aa6f3d0888499136ead9d6
wx/lib/agw/aui/tabart.py
python
AuiSimpleTabArt.SetAGWFlags
(self, agwFlags)
Sets the tab art flags. :param integer `agwFlags`: a combination of the following values: ==================================== ================================== Flag name Description ==================================== ================================== ``AUI_NB_TOP`` With this style, tabs are drawn along the top of the notebook ``AUI_NB_LEFT`` With this style, tabs are drawn along the left of the notebook. Not implemented yet. ``AUI_NB_RIGHT`` With this style, tabs are drawn along the right of the notebook. Not implemented yet. ``AUI_NB_BOTTOM`` With this style, tabs are drawn along the bottom of the notebook ``AUI_NB_TAB_SPLIT`` Allows the tab control to be split by dragging a tab ``AUI_NB_TAB_MOVE`` Allows a tab to be moved horizontally by dragging ``AUI_NB_TAB_EXTERNAL_MOVE`` Allows a tab to be moved to another tab control ``AUI_NB_TAB_FIXED_WIDTH`` With this style, all tabs have the same width ``AUI_NB_SCROLL_BUTTONS`` With this style, left and right scroll buttons are displayed ``AUI_NB_WINDOWLIST_BUTTON`` With this style, a drop-down list of windows is available ``AUI_NB_CLOSE_BUTTON`` With this style, a close button is available on the tab bar ``AUI_NB_CLOSE_ON_ACTIVE_TAB`` With this style, a close button is available on the active tab ``AUI_NB_CLOSE_ON_ALL_TABS`` With this style, a close button is available on all tabs ``AUI_NB_MIDDLE_CLICK_CLOSE`` Allows to close :class:`~wx.lib.agw.aui.auibook.AuiNotebook` tabs by mouse middle button click ``AUI_NB_SUB_NOTEBOOK`` This style is used by :class:`~wx.lib.agw.aui.framemanager.AuiManager` to create automatic AuiNotebooks ``AUI_NB_HIDE_ON_SINGLE_TAB`` Hides the tab window if only one tab is present ``AUI_NB_SMART_TABS`` Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows ``AUI_NB_USE_IMAGES_DROPDOWN`` Uses images on dropdown window list menu instead of check items ``AUI_NB_CLOSE_ON_TAB_LEFT`` Draws the tab close button on the left instead of on the right (a la Camino browser) ``AUI_NB_TAB_FLOAT`` Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages ``AUI_NB_DRAW_DND_TAB`` Draws an image representation of a tab while dragging (on by default) ``AUI_NB_ORDER_BY_ACCESS`` Tab navigation order by last access time for the tabs ``AUI_NB_NO_TAB_FOCUS`` Don't draw tab focus rectangle ==================================== ==================================
Sets the tab art flags.
[ "Sets", "the", "tab", "art", "flags", "." ]
def SetAGWFlags(self, agwFlags): """ Sets the tab art flags. :param integer `agwFlags`: a combination of the following values: ==================================== ================================== Flag name Description ==================================== ================================== ``AUI_NB_TOP`` With this style, tabs are drawn along the top of the notebook ``AUI_NB_LEFT`` With this style, tabs are drawn along the left of the notebook. Not implemented yet. ``AUI_NB_RIGHT`` With this style, tabs are drawn along the right of the notebook. Not implemented yet. ``AUI_NB_BOTTOM`` With this style, tabs are drawn along the bottom of the notebook ``AUI_NB_TAB_SPLIT`` Allows the tab control to be split by dragging a tab ``AUI_NB_TAB_MOVE`` Allows a tab to be moved horizontally by dragging ``AUI_NB_TAB_EXTERNAL_MOVE`` Allows a tab to be moved to another tab control ``AUI_NB_TAB_FIXED_WIDTH`` With this style, all tabs have the same width ``AUI_NB_SCROLL_BUTTONS`` With this style, left and right scroll buttons are displayed ``AUI_NB_WINDOWLIST_BUTTON`` With this style, a drop-down list of windows is available ``AUI_NB_CLOSE_BUTTON`` With this style, a close button is available on the tab bar ``AUI_NB_CLOSE_ON_ACTIVE_TAB`` With this style, a close button is available on the active tab ``AUI_NB_CLOSE_ON_ALL_TABS`` With this style, a close button is available on all tabs ``AUI_NB_MIDDLE_CLICK_CLOSE`` Allows to close :class:`~wx.lib.agw.aui.auibook.AuiNotebook` tabs by mouse middle button click ``AUI_NB_SUB_NOTEBOOK`` This style is used by :class:`~wx.lib.agw.aui.framemanager.AuiManager` to create automatic AuiNotebooks ``AUI_NB_HIDE_ON_SINGLE_TAB`` Hides the tab window if only one tab is present ``AUI_NB_SMART_TABS`` Use Smart Tabbing, like ``Alt`` + ``Tab`` on Windows ``AUI_NB_USE_IMAGES_DROPDOWN`` Uses images on dropdown window list menu instead of check items ``AUI_NB_CLOSE_ON_TAB_LEFT`` Draws the tab close button on the left instead of on the right (a la Camino browser) ``AUI_NB_TAB_FLOAT`` Allows the floating of single tabs. Known limitation: when the notebook is more or less full screen, tabs cannot be dragged far enough outside of the notebook to become floating pages ``AUI_NB_DRAW_DND_TAB`` Draws an image representation of a tab while dragging (on by default) ``AUI_NB_ORDER_BY_ACCESS`` Tab navigation order by last access time for the tabs ``AUI_NB_NO_TAB_FOCUS`` Don't draw tab focus rectangle ==================================== ================================== """ self._agwFlags = agwFlags
[ "def", "SetAGWFlags", "(", "self", ",", "agwFlags", ")", ":", "self", ".", "_agwFlags", "=", "agwFlags" ]
https://github.com/wxWidgets/Phoenix/blob/b2199e299a6ca6d866aa6f3d0888499136ead9d6/wx/lib/agw/aui/tabart.py#L1042-L1079
magenta/magenta
be6558f1a06984faff6d6949234f5fe9ad0ffdb5
magenta/models/sketch_rnn/rnn.py
python
HyperLSTMCell.hyper_norm
(self, layer, scope='hyper', use_bias=True)
return result
[]
def hyper_norm(self, layer, scope='hyper', use_bias=True): num_units = self.num_units embedding_size = self.hyper_embedding_size # recurrent batch norm init trick (https://arxiv.org/abs/1603.09025). init_gamma = 0.10 # cooijmans' da man. with tf.variable_scope(scope): zw = super_linear( self.hyper_output, embedding_size, init_w='constant', weight_start=0.00, use_bias=True, bias_start=1.0, scope='zw') alpha = super_linear( zw, num_units, init_w='constant', weight_start=init_gamma / embedding_size, use_bias=False, scope='alpha') result = tf.multiply(alpha, layer) if use_bias: zb = super_linear( self.hyper_output, embedding_size, init_w='gaussian', weight_start=0.01, use_bias=False, bias_start=0.0, scope='zb') beta = super_linear( zb, num_units, init_w='constant', weight_start=0.00, use_bias=False, scope='beta') result += beta return result
[ "def", "hyper_norm", "(", "self", ",", "layer", ",", "scope", "=", "'hyper'", ",", "use_bias", "=", "True", ")", ":", "num_units", "=", "self", ".", "num_units", "embedding_size", "=", "self", ".", "hyper_embedding_size", "# recurrent batch norm init trick (https:...
https://github.com/magenta/magenta/blob/be6558f1a06984faff6d6949234f5fe9ad0ffdb5/magenta/models/sketch_rnn/rnn.py#L377-L416
collinsctk/PyQYT
7af3673955f94ff1b2df2f94220cd2dab2e252af
ExtentionPackages/paramiko/transport.py
python
Transport.atfork
(self)
Terminate this Transport without closing the session. On posix systems, if a Transport is open during process forking, both parent and child will share the underlying socket, but only one process can use the connection (without corrupting the session). Use this method to clean up a Transport object without disrupting the other process. .. versionadded:: 1.5.3
Terminate this Transport without closing the session. On posix systems, if a Transport is open during process forking, both parent and child will share the underlying socket, but only one process can use the connection (without corrupting the session). Use this method to clean up a Transport object without disrupting the other process.
[ "Terminate", "this", "Transport", "without", "closing", "the", "session", ".", "On", "posix", "systems", "if", "a", "Transport", "is", "open", "during", "process", "forking", "both", "parent", "and", "child", "will", "share", "the", "underlying", "socket", "bu...
def atfork(self): """ Terminate this Transport without closing the session. On posix systems, if a Transport is open during process forking, both parent and child will share the underlying socket, but only one process can use the connection (without corrupting the session). Use this method to clean up a Transport object without disrupting the other process. .. versionadded:: 1.5.3 """ self.sock.close() self.close()
[ "def", "atfork", "(", "self", ")", ":", "self", ".", "sock", ".", "close", "(", ")", "self", ".", "close", "(", ")" ]
https://github.com/collinsctk/PyQYT/blob/7af3673955f94ff1b2df2f94220cd2dab2e252af/ExtentionPackages/paramiko/transport.py#L414-L425
hydroshare/hydroshare
7ba563b55412f283047fb3ef6da367d41dec58c6
hs_core/serialization.py
python
GenericResourceMeta.include_resource_file
(resource_filename)
return True
:param resource_filename: Name of resource filename. :return: True if resource_filename should be included.
:param resource_filename: Name of resource filename. :return: True if resource_filename should be included.
[ ":", "param", "resource_filename", ":", "Name", "of", "resource", "filename", ".", ":", "return", ":", "True", "if", "resource_filename", "should", "be", "included", "." ]
def include_resource_file(resource_filename): """ :param resource_filename: Name of resource filename. :return: True if resource_filename should be included. """ return True
[ "def", "include_resource_file", "(", "resource_filename", ")", ":", "return", "True" ]
https://github.com/hydroshare/hydroshare/blob/7ba563b55412f283047fb3ef6da367d41dec58c6/hs_core/serialization.py#L247-L252
rwth-i6/returnn
f2d718a197a280b0d5f0fd91a7fcb8658560dddb
returnn/tf/util/basic.py
python
directed
(x, direction)
If direction == 1 or direction is None, returns just x. If direction == -1, returns reversed(x). :param tf.Tensor x: :param int|None direction: -1 or 1 (or None) :rtype: tf.Tensor
If direction == 1 or direction is None, returns just x. If direction == -1, returns reversed(x).
[ "If", "direction", "==", "1", "or", "direction", "is", "None", "returns", "just", "x", ".", "If", "direction", "==", "-", "1", "returns", "reversed", "(", "x", ")", "." ]
def directed(x, direction): """ If direction == 1 or direction is None, returns just x. If direction == -1, returns reversed(x). :param tf.Tensor x: :param int|None direction: -1 or 1 (or None) :rtype: tf.Tensor """ if direction == 1 or direction is None: return x if direction == -1: return reversed(x) raise ValueError("invalid direction: %r" % direction)
[ "def", "directed", "(", "x", ",", "direction", ")", ":", "if", "direction", "==", "1", "or", "direction", "is", "None", ":", "return", "x", "if", "direction", "==", "-", "1", ":", "return", "reversed", "(", "x", ")", "raise", "ValueError", "(", "\"in...
https://github.com/rwth-i6/returnn/blob/f2d718a197a280b0d5f0fd91a7fcb8658560dddb/returnn/tf/util/basic.py#L1869-L1882
statsmodels/statsmodels
debbe7ea6ba28fe5bdb78f09f8cac694bef98722
statsmodels/tsa/regime_switching/markov_regression.py
python
MarkovRegression._em_variance
(self, result, endog, exog, betas, tmp=None)
return variance
EM step for variances
EM step for variances
[ "EM", "step", "for", "variances" ]
def _em_variance(self, result, endog, exog, betas, tmp=None): """ EM step for variances """ k_exog = 0 if exog is None else exog.shape[1] if self.switching_variance: variance = np.zeros(self.k_regimes) for i in range(self.k_regimes): if k_exog > 0: resid = endog - np.dot(exog, betas[i]) else: resid = endog variance[i] = ( np.sum(resid**2 * result.smoothed_marginal_probabilities[i]) / np.sum(result.smoothed_marginal_probabilities[i])) else: variance = 0 if tmp is None: tmp = np.sqrt(result.smoothed_marginal_probabilities) for i in range(self.k_regimes): tmp_endog = tmp[i] * endog if k_exog > 0: tmp_exog = tmp[i][:, np.newaxis] * exog resid = tmp_endog - np.dot(tmp_exog, betas[i]) else: resid = tmp_endog variance += np.sum(resid**2) variance /= self.nobs return variance
[ "def", "_em_variance", "(", "self", ",", "result", ",", "endog", ",", "exog", ",", "betas", ",", "tmp", "=", "None", ")", ":", "k_exog", "=", "0", "if", "exog", "is", "None", "else", "exog", ".", "shape", "[", "1", "]", "if", "self", ".", "switch...
https://github.com/statsmodels/statsmodels/blob/debbe7ea6ba28fe5bdb78f09f8cac694bef98722/statsmodels/tsa/regime_switching/markov_regression.py#L254-L284
catalyst-cooperative/pudl
40d176313e60dfa9d2481f63842ed23f08f1ad5f
src/pudl/helpers.py
python
fix_eia_na
(df)
return df.replace( to_replace=[ r'^\.$', # Nothing but a decimal point r'^\s*$', # The empty string and entirely whitespace strings ], value=np.nan, regex=True )
Replace common ill-posed EIA NA spreadsheet values with np.nan. Currently replaces empty string, single decimal points with no numbers, and any single whitespace character with np.nan. Args: df (pandas.DataFrame): The DataFrame to clean. Returns: pandas.DataFrame: The cleaned DataFrame.
Replace common ill-posed EIA NA spreadsheet values with np.nan.
[ "Replace", "common", "ill", "-", "posed", "EIA", "NA", "spreadsheet", "values", "with", "np", ".", "nan", "." ]
def fix_eia_na(df): """ Replace common ill-posed EIA NA spreadsheet values with np.nan. Currently replaces empty string, single decimal points with no numbers, and any single whitespace character with np.nan. Args: df (pandas.DataFrame): The DataFrame to clean. Returns: pandas.DataFrame: The cleaned DataFrame. """ return df.replace( to_replace=[ r'^\.$', # Nothing but a decimal point r'^\s*$', # The empty string and entirely whitespace strings ], value=np.nan, regex=True )
[ "def", "fix_eia_na", "(", "df", ")", ":", "return", "df", ".", "replace", "(", "to_replace", "=", "[", "r'^\\.$'", ",", "# Nothing but a decimal point", "r'^\\s*$'", ",", "# The empty string and entirely whitespace strings", "]", ",", "value", "=", "np", ".", "nan...
https://github.com/catalyst-cooperative/pudl/blob/40d176313e60dfa9d2481f63842ed23f08f1ad5f/src/pudl/helpers.py#L806-L827
NervanaSystems/neon
8c3fb8a93b4a89303467b25817c60536542d08bd
neon/backends/backend.py
python
OpTreeNode.__new__
(cls, *args)
return tuple.__new__(cls, args)
[]
def __new__(cls, *args): return tuple.__new__(cls, args)
[ "def", "__new__", "(", "cls", ",", "*", "args", ")", ":", "return", "tuple", ".", "__new__", "(", "cls", ",", "args", ")" ]
https://github.com/NervanaSystems/neon/blob/8c3fb8a93b4a89303467b25817c60536542d08bd/neon/backends/backend.py#L1690-L1691
ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework
cb692f527e4e819b6c228187c5702d990a180043
external/Scripting Engine/Xenotix Python Scripting Engine/Lib/traceback.py
python
print_exception
(etype, value, tb, limit=None, file=None)
Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error.
Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
[ "Print", "exception", "up", "to", "limit", "stack", "trace", "entries", "from", "tb", "to", "file", "." ]
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error. """ if file is None: file = sys.stderr if tb: _print(file, 'Traceback (most recent call last):') print_tb(tb, limit, file) lines = format_exception_only(etype, value) for line in lines: _print(file, line, '')
[ "def", "print_exception", "(", "etype", ",", "value", ",", "tb", ",", "limit", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "if", "tb", ":", "_print", "(", "file", ",", "'Tra...
https://github.com/ajinabraham/OWASP-Xenotix-XSS-Exploit-Framework/blob/cb692f527e4e819b6c228187c5702d990a180043/external/Scripting Engine/Xenotix Python Scripting Engine/Lib/traceback.py#L110-L128
duo-labs/secret-bridge
772e7531357719459e69ca6ef4aa889dc2d4d684
models/monitors/pagination.py
python
paginate
(poll_func, event_offset=0)
return events
Paginates through the available events returned from calls to poll_func, returning the gathered events. If no existing event_offset is provided, this will only fetch the latest page. Events are returned newest to oldest. Arguments: poll_func {func} -- A function which fetches a list of `github.Event` Keyword Arguments: event_offset {int} -- The latest event ID retrieved (default: {0}) Returns: list(github.Event) -- A list of new events
Paginates through the available events returned from calls to poll_func, returning the gathered events.
[ "Paginates", "through", "the", "available", "events", "returned", "from", "calls", "to", "poll_func", "returning", "the", "gathered", "events", "." ]
def paginate(poll_func, event_offset=0): """Paginates through the available events returned from calls to poll_func, returning the gathered events. If no existing event_offset is provided, this will only fetch the latest page. Events are returned newest to oldest. Arguments: poll_func {func} -- A function which fetches a list of `github.Event` Keyword Arguments: event_offset {int} -- The latest event ID retrieved (default: {0}) Returns: list(github.Event) -- A list of new events """ events = [] for idx, event in enumerate(poll_func()): # If we've reached our offset, break out of the loop if int(event.id) <= event_offset: break events.append(event) # If we don't have a current offset, we only want to grab one page # so we can short-circuit at the fixed page size of 30 items if not event_offset and idx == PAGE_SIZE: break return events
[ "def", "paginate", "(", "poll_func", ",", "event_offset", "=", "0", ")", ":", "events", "=", "[", "]", "for", "idx", ",", "event", "in", "enumerate", "(", "poll_func", "(", ")", ")", ":", "# If we've reached our offset, break out of the loop", "if", "int", "...
https://github.com/duo-labs/secret-bridge/blob/772e7531357719459e69ca6ef4aa889dc2d4d684/models/monitors/pagination.py#L6-L34
samuelclay/NewsBlur
2c45209df01a1566ea105e04d499367f32ac9ad2
apps/social/tasks.py
python
SyncFacebookFriends
(user_id)
[]
def SyncFacebookFriends(user_id): social_services = MSocialServices.objects.get(user_id=user_id) social_services.sync_facebook_friends()
[ "def", "SyncFacebookFriends", "(", "user_id", ")", ":", "social_services", "=", "MSocialServices", ".", "objects", ".", "get", "(", "user_id", "=", "user_id", ")", "social_services", ".", "sync_facebook_friends", "(", ")" ]
https://github.com/samuelclay/NewsBlur/blob/2c45209df01a1566ea105e04d499367f32ac9ad2/apps/social/tasks.py#L47-L49
mpi4py/mpi4py
8a5e5adf8f41e4e7cc134a8f2574aeb95a7e8dac
src/mpi4py/util/dtlib.py
python
to_numpy_dtype
(datatype)
Convert MPI datatype to NumPy datatype.
Convert MPI datatype to NumPy datatype.
[ "Convert", "MPI", "datatype", "to", "NumPy", "datatype", "." ]
def to_numpy_dtype(datatype): """Convert MPI datatype to NumPy datatype.""" def mpi2npy(datatype, count): dtype = to_numpy_dtype(datatype) return dtype if count == 1 else (dtype, count) def np_dtype(spec): try: return _np_dtype(spec) except NameError: # pragma: no cover return spec if datatype == MPI.DATATYPE_NULL: raise ValueError("cannot convert null MPI datatype to NumPy") combiner = datatype.combiner # predefined datatype if combiner == MPI.COMBINER_NAMED: typecode = _get_typecode(datatype) if typecode is not None: return np_dtype(typecode) raise ValueError("cannot convert MPI datatype to NumPy") # user-defined datatype basetype, _, info = datatype.decode() datatypes = [basetype] try: # duplicated datatype if combiner == MPI.COMBINER_DUP: return to_numpy_dtype(basetype) # contiguous datatype if combiner == MPI.COMBINER_CONTIGUOUS: dtype = to_numpy_dtype(basetype) count = info['count'] return np_dtype((dtype, (count,))) # subarray datatype if combiner == MPI.COMBINER_SUBARRAY: dtype = to_numpy_dtype(basetype) sizes = info['sizes'] subsizes = info['subsizes'] starts = info['starts'] order = info['order'] assert subsizes == sizes assert min(starts) == max(starts) == 0 if order == MPI.ORDER_FORTRAN: sizes = sizes[::-1] return np_dtype((dtype, tuple(sizes))) # struct datatype aligned = True if combiner == MPI.COMBINER_RESIZED: if basetype.combiner == MPI.COMBINER_STRUCT: aligned = _is_aligned(basetype, info['extent']) combiner = MPI.COMBINER_STRUCT _, _, info = basetype.decode() datatypes.pop().Free() if combiner == MPI.COMBINER_STRUCT: datatypes = info['datatypes'] blocklengths = info['blocklengths'] displacements = info['displacements'] names = [f'f{i}' for i in range(len(datatypes))] formats = list(map(mpi2npy, datatypes, blocklengths)) offsets = displacements itemsize = datatype.extent aligned &= all(map(_is_aligned, datatypes, offsets)) return np_dtype( { 'names': names, 'formats': formats, 'offsets': offsets, 'itemsize': itemsize, 'aligned': aligned, } ) # vector datatype combiner_vector = ( MPI.COMBINER_VECTOR, MPI.COMBINER_HVECTOR, ) if combiner in combiner_vector: dtype = to_numpy_dtype(basetype) count = info['count'] blocklength = info['blocklength'] stride = info['stride'] if combiner == MPI.COMBINER_VECTOR: stride *= basetype.extent aligned = _is_aligned(basetype) if combiner == MPI.COMBINER_HVECTOR: stride = stride if count > 1 else 0 aligned = _is_aligned(basetype, stride) names = [f'f{i}' for i in range(count)] formats = [(dtype, (blocklength,))] * count offsets = [stride * i for i in range(count)] itemsize = datatype.extent return np_dtype( { 'names': names, 'formats': formats, 'offsets': offsets, 'itemsize': itemsize, 'aligned': aligned, } ) # indexed datatype combiner_indexed = ( MPI.COMBINER_INDEXED, MPI.COMBINER_HINDEXED, MPI.COMBINER_INDEXED_BLOCK, MPI.COMBINER_HINDEXED_BLOCK, ) if combiner in combiner_indexed: dtype = to_numpy_dtype(basetype) stride = 1 aligned = _is_aligned(basetype) displacements = info['displacements'] if combiner in combiner_indexed[:2]: blocklengths = info['blocklengths'] if combiner in combiner_indexed[2:]: blocklengths = [info['blocklength']] * len(displacements) if combiner in combiner_indexed[0::2]: stride = basetype.extent if combiner in combiner_indexed[1::2]: aligned &= all(_is_aligned(basetype, d) for d in displacements) names = [f'f{i}' for i in range(len(displacements))] formats = [(dtype, (blen,)) for blen in blocklengths] offsets = [disp * stride for disp in displacements] return np_dtype( { 'names': names, 'formats': formats, 'offsets': offsets, 'aligned': aligned, } ) # Fortran 90 datatype combiner_f90 = ( MPI.COMBINER_F90_INTEGER, MPI.COMBINER_F90_REAL, MPI.COMBINER_F90_COMPLEX, ) if combiner in combiner_f90: datatypes.pop() typesize = datatype.Get_size() typecode = 'ifc'[combiner_f90.index(combiner)] return np_dtype(f'{typecode}{typesize}') raise ValueError("cannot convert MPI datatype to NumPy") finally: for _tp in datatypes: if not _tp.is_predefined: _tp.Free()
[ "def", "to_numpy_dtype", "(", "datatype", ")", ":", "def", "mpi2npy", "(", "datatype", ",", "count", ")", ":", "dtype", "=", "to_numpy_dtype", "(", "datatype", ")", "return", "dtype", "if", "count", "==", "1", "else", "(", "dtype", ",", "count", ")", "...
https://github.com/mpi4py/mpi4py/blob/8a5e5adf8f41e4e7cc134a8f2574aeb95a7e8dac/src/mpi4py/util/dtlib.py#L170-L327
fortharris/Pcode
147962d160a834c219e12cb456abc130826468e4
rope/refactor/importutils/importinfo.py
python
EmptyImport.is_empty
(self)
return True
[]
def is_empty(self): return True
[ "def", "is_empty", "(", "self", ")", ":", "return", "True" ]
https://github.com/fortharris/Pcode/blob/147962d160a834c219e12cb456abc130826468e4/rope/refactor/importutils/importinfo.py#L190-L191
PowerScript/KatanaFramework
0f6ad90a88de865d58ec26941cb4460501e75496
lib/future/src/future/backports/email/generator.py
python
Generator.flatten
(self, msg, unixfrom=False, linesep=None)
r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy.
r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created.
[ "r", "Print", "the", "message", "object", "tree", "rooted", "at", "msg", "to", "the", "output", "file", "specified", "when", "the", "Generator", "instance", "was", "created", "." ]
def flatten(self, msg, unixfrom=False, linesep=None): r"""Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. linesep specifies the characters used to indicate a new line in the output. The default value is determined by the policy. """ # We use the _XXX constants for operating on data that comes directly # from the msg, and _encoded_XXX constants for operating on data that # has already been converted (to bytes in the BytesGenerator) and # inserted into a temporary buffer. policy = msg.policy if self.policy is None else self.policy if linesep is not None: policy = policy.clone(linesep=linesep) if self.maxheaderlen is not None: policy = policy.clone(max_line_length=self.maxheaderlen) self._NL = policy.linesep self._encoded_NL = self._encode(self._NL) self._EMPTY = '' self._encoded_EMTPY = self._encode('') # Because we use clone (below) when we recursively process message # subparts, and because clone uses the computed policy (not None), # submessages will automatically get set to the computed policy when # they are processed by this code. old_gen_policy = self.policy old_msg_policy = msg.policy try: self.policy = policy msg.policy = policy if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) self.write(ufrom + self._NL) self._write(msg) finally: self.policy = old_gen_policy msg.policy = old_msg_policy
[ "def", "flatten", "(", "self", ",", "msg", ",", "unixfrom", "=", "False", ",", "linesep", "=", "None", ")", ":", "# We use the _XXX constants for operating on data that comes directly", "# from the msg, and _encoded_XXX constants for operating on data that", "# has already been c...
https://github.com/PowerScript/KatanaFramework/blob/0f6ad90a88de865d58ec26941cb4460501e75496/lib/future/src/future/backports/email/generator.py#L76-L121
mcneel/rhinoscriptsyntax
c49bd0bf24c2513bdcb84d1bf307144489600fd9
Scripts/rhinoscript/curve.py
python
PointInPlanarClosedCurve
(point, curve, plane=None, tolerance=None)
return 2
Determines if a point is inside of a closed curve, on a closed curve, or outside of a closed curve Parameters: point (point|guid): text point curve (guid): identifier of a curve object plane (plane, optional): plane containing the closed curve and point. If omitted, the currently active construction plane is used tolerance (number, optional) it omitted, the document abosulte tolerance is used Returns: number: number identifying the result if successful 0 = point is outside of the curve 1 = point is inside of the curve 2 = point in on the curve Example: import rhinoscriptsyntax as rs curve = rs.GetObject("Select a planar, closed curve", rs.filter.curve) if rs.IsCurveClosed(curve) and rs.IsCurvePlanar(curve): point = rs.GetPoint("Pick a point") if point: result = rs.PointInPlanarClosedCurve(point, curve) if result==0: print "The point is outside of the closed curve." elif result==1: print "The point is inside of the closed curve." else: print "The point is on the closed curve." See Also: PlanarClosedCurveContainment PlanarCurveCollision
Determines if a point is inside of a closed curve, on a closed curve, or outside of a closed curve Parameters: point (point|guid): text point curve (guid): identifier of a curve object plane (plane, optional): plane containing the closed curve and point. If omitted, the currently active construction plane is used tolerance (number, optional) it omitted, the document abosulte tolerance is used Returns: number: number identifying the result if successful 0 = point is outside of the curve 1 = point is inside of the curve 2 = point in on the curve Example: import rhinoscriptsyntax as rs curve = rs.GetObject("Select a planar, closed curve", rs.filter.curve) if rs.IsCurveClosed(curve) and rs.IsCurvePlanar(curve): point = rs.GetPoint("Pick a point") if point: result = rs.PointInPlanarClosedCurve(point, curve) if result==0: print "The point is outside of the closed curve." elif result==1: print "The point is inside of the closed curve." else: print "The point is on the closed curve." See Also: PlanarClosedCurveContainment PlanarCurveCollision
[ "Determines", "if", "a", "point", "is", "inside", "of", "a", "closed", "curve", "on", "a", "closed", "curve", "or", "outside", "of", "a", "closed", "curve", "Parameters", ":", "point", "(", "point|guid", ")", ":", "text", "point", "curve", "(", "guid", ...
def PointInPlanarClosedCurve(point, curve, plane=None, tolerance=None): """Determines if a point is inside of a closed curve, on a closed curve, or outside of a closed curve Parameters: point (point|guid): text point curve (guid): identifier of a curve object plane (plane, optional): plane containing the closed curve and point. If omitted, the currently active construction plane is used tolerance (number, optional) it omitted, the document abosulte tolerance is used Returns: number: number identifying the result if successful 0 = point is outside of the curve 1 = point is inside of the curve 2 = point in on the curve Example: import rhinoscriptsyntax as rs curve = rs.GetObject("Select a planar, closed curve", rs.filter.curve) if rs.IsCurveClosed(curve) and rs.IsCurvePlanar(curve): point = rs.GetPoint("Pick a point") if point: result = rs.PointInPlanarClosedCurve(point, curve) if result==0: print "The point is outside of the closed curve." elif result==1: print "The point is inside of the closed curve." else: print "The point is on the closed curve." See Also: PlanarClosedCurveContainment PlanarCurveCollision """ point = rhutil.coerce3dpoint(point, True) curve = rhutil.coercecurve(curve, -1, True) if tolerance is None or tolerance<=0: tolerance = scriptcontext.doc.ModelAbsoluteTolerance if plane: plane = rhutil.coerceplane(plane) else: plane = scriptcontext.doc.Views.ActiveView.ActiveViewport.ConstructionPlane() rc = curve.Contains(point, plane, tolerance) if rc==Rhino.Geometry.PointContainment.Unset: raise Exception("Curve.Contains returned Unset") if rc==Rhino.Geometry.PointContainment.Outside: return 0 if rc==Rhino.Geometry.PointContainment.Inside: return 1 return 2
[ "def", "PointInPlanarClosedCurve", "(", "point", ",", "curve", ",", "plane", "=", "None", ",", "tolerance", "=", "None", ")", ":", "point", "=", "rhutil", ".", "coerce3dpoint", "(", "point", ",", "True", ")", "curve", "=", "rhutil", ".", "coercecurve", "...
https://github.com/mcneel/rhinoscriptsyntax/blob/c49bd0bf24c2513bdcb84d1bf307144489600fd9/Scripts/rhinoscript/curve.py#L3485-L3525
asyml/texar
a23f021dae289a3d768dc099b220952111da04fd
texar/tf/modules/decoders/tf_helpers.py
python
TrainingHelper.next_inputs
(self, time, outputs, state, name=None, **unused_kwargs)
Gets the inputs for next step.
Gets the inputs for next step.
[ "Gets", "the", "inputs", "for", "next", "step", "." ]
def next_inputs(self, time, outputs, state, name=None, **unused_kwargs): """Gets the inputs for next step.""" with ops.name_scope(name, "TrainingHelperNextInputs", [time, outputs, state]): next_time = time + 1 finished = (next_time >= self._sequence_length) all_finished = math_ops.reduce_all(finished) def read_from_ta(inp): return inp.read(next_time) next_inputs = control_flow_ops.cond( all_finished, lambda: self._zero_inputs, lambda: nest.map_structure(read_from_ta, self._input_tas)) return (finished, next_inputs, state)
[ "def", "next_inputs", "(", "self", ",", "time", ",", "outputs", ",", "state", ",", "name", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "\"TrainingHelperNextInputs\"", ",", "[", "time", ",", ...
https://github.com/asyml/texar/blob/a23f021dae289a3d768dc099b220952111da04fd/texar/tf/modules/decoders/tf_helpers.py#L253-L267
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_route.py
python
Yedit.remove_entry
(data, key, index=None, value=None, sep='.')
remove data at location key
remove data at location key
[ "remove", "data", "at", "location", "key" ]
def remove_entry(data, key, index=None, value=None, sep='.'): ''' remove data at location key ''' if key == '' and isinstance(data, dict): if value is not None: data.pop(value) elif index is not None: raise YeditException("remove_entry for a dictionary does not have an index {}".format(index)) else: data.clear() return True elif key == '' and isinstance(data, list): ind = None if value is not None: try: ind = data.index(value) except ValueError: return False elif index is not None: ind = index else: del data[:] if ind is not None: data.pop(ind) return True if not (key and Yedit.valid_key(key, sep)) and \ isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key and isinstance(data, dict): data = data.get(dict_key) elif (arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1): data = data[int(arr_ind)] else: return None # process last index for remove # expected list entry if key_indexes[-1][0]: if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501 del data[int(key_indexes[-1][0])] return True # expected dict entry elif key_indexes[-1][1]: if isinstance(data, dict): del data[key_indexes[-1][1]] return True
[ "def", "remove_entry", "(", "data", ",", "key", ",", "index", "=", "None", ",", "value", "=", "None", ",", "sep", "=", "'.'", ")", ":", "if", "key", "==", "''", "and", "isinstance", "(", "data", ",", "dict", ")", ":", "if", "value", "is", "not", ...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.11.28-1/roles/lib_openshift/library/oc_route.py#L264-L318
google/rekall
55d1925f2df9759a989b35271b4fa48fc54a1c86
rekall-core/rekall/plugins/windows/dns.py
python
WinDNSCache.locate_cache_hashtable
(self)
return self._locate_heap(task, vad)
Finds the DNS cache hashtable. The dns cache runs inside one of the svchost.exe processes and is implemented via the dnsrslvr.dll service. We therefore first search for the correct VAD region for this DLL. We then find the private heap that belongs to the resolver.
Finds the DNS cache hashtable.
[ "Finds", "the", "DNS", "cache", "hashtable", "." ]
def locate_cache_hashtable(self): """Finds the DNS cache hashtable. The dns cache runs inside one of the svchost.exe processes and is implemented via the dnsrslvr.dll service. We therefore first search for the correct VAD region for this DLL. We then find the private heap that belongs to the resolver. """ vad, task = self._find_svchost_vad() if task is None: raise RuntimeError("Unable to find svchost.exe for dnsrslvr.dll.") # Switch to the svchost process context now. self.cc.SwitchProcessContext(task) # Load the profile for dnsrslvr and add the new types. dnsrslvr_mod = self.session.address_resolver.GetModuleByName("dnsrslvr") if not dnsrslvr_mod: raise RuntimeError("Unable to find dnsrslvr.dll.") self.profile = InitializedDNSTypes(dnsrslvr_mod.profile) hash_table = self.session.address_resolver.get_constant_object( "dnsrslvr!g_HashTable", "Pointer", target_args=dict( target="Array", target_args=dict( count=self.session.address_resolver.get_constant_object( "dnsrslvr!g_HashTableSize", "unsigned int").v(), target="Pointer", target_args=dict( target="DNS_HASHTABLE_ENTRY" ) ) ) ) if hash_table: return hash_table.deref() ntdll_mod = self.session.address_resolver.GetModuleByName("ntdll") self.heap_profile = ntdll_mod.profile # First try to locate the hash table using the index, then fallback to # using scanning techniques: if not self.plugin_args.no_index: hash_table = self._locate_heap_using_index(task) if hash_table: return hash_table return self._locate_heap(task, vad)
[ "def", "locate_cache_hashtable", "(", "self", ")", ":", "vad", ",", "task", "=", "self", ".", "_find_svchost_vad", "(", ")", "if", "task", "is", "None", ":", "raise", "RuntimeError", "(", "\"Unable to find svchost.exe for dnsrslvr.dll.\"", ")", "# Switch to the svch...
https://github.com/google/rekall/blob/55d1925f2df9759a989b35271b4fa48fc54a1c86/rekall-core/rekall/plugins/windows/dns.py#L313-L363
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py
python
Misc.selection_own_get
(self, **kw)
Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).
Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).
[ "Return", "owner", "of", "X", "selection", ".", "The", "following", "keyword", "parameter", "can", "be", "provided", ":", "selection", "-", "name", "of", "the", "selection", "(", "default", "PRIMARY", ")", "type", "-", "type", "of", "the", "selection", "("...
def selection_own_get(self, **kw): """Return owner of X selection. The following keyword parameter can be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" if 'displayof' not in kw: kw['displayof'] = self._w name = self.tk.call(('selection', 'own') + self._options(kw)) if not name: return None else: return self._nametowidget(name)
[ "def", "selection_own_get", "(", "self", ",", "*", "*", "kw", ")", ":", "if", "'displayof'", "not", "in", "kw", ":", "kw", "[", "'displayof'", "]", "=", "self", ".", "_w", "name", "=", "self", ".", "tk", ".", "call", "(", "(", "'selection'", ",", ...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/lib-tk/Tkinter.py#L734-L747
pillone/usntssearch
24b5e5bc4b6af2589d95121c4d523dc58cb34273
NZBmegasearch/werkzeug/http.py
python
parse_if_range_header
(value)
return IfRange(unquote_etag(value)[0])
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7
Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object.
[ "Parses", "an", "if", "-", "range", "header", "which", "can", "be", "an", "etag", "or", "a", "date", ".", "Returns", "a", ":", "class", ":", "~werkzeug", ".", "datastructures", ".", "IfRange", "object", "." ]
def parse_if_range_header(value): """Parses an if-range header which can be an etag or a date. Returns a :class:`~werkzeug.datastructures.IfRange` object. .. versionadded:: 0.7 """ if not value: return IfRange() date = parse_date(value) if date is not None: return IfRange(date=date) # drop weakness information return IfRange(unquote_etag(value)[0])
[ "def", "parse_if_range_header", "(", "value", ")", ":", "if", "not", "value", ":", "return", "IfRange", "(", ")", "date", "=", "parse_date", "(", "value", ")", "if", "date", "is", "not", "None", ":", "return", "IfRange", "(", "date", "=", "date", ")", ...
https://github.com/pillone/usntssearch/blob/24b5e5bc4b6af2589d95121c4d523dc58cb34273/NZBmegasearch/werkzeug/http.py#L390-L402
weilanhanf/daily_fresh_demo
6220804724c2aeaa69e00860d0c5a17d2bd895b2
apps/df_user/views.py
python
info
(request)
return render(request, 'df_user/user_center_info.html', context)
[]
def info(request): # 用户中心 username = request.session.get('user_name') user = UserInfo.objects.filter(uname=username).first() browser_goods = GoodsBrowser.objects.filter(user=user).order_by("-browser_time") goods_list = [] if browser_goods: goods_list = [browser_good.good for browser_good in browser_goods] # 从浏览商品记录中取出浏览商品 explain = '最近浏览' else: explain = '无最近浏览' context = { 'title': '用户中心', 'page_name': 1, 'user_phone': user.uphone, 'user_address': user.uaddress, 'user_name': username, 'goods_list': goods_list, 'explain': explain, } return render(request, 'df_user/user_center_info.html', context)
[ "def", "info", "(", "request", ")", ":", "# 用户中心", "username", "=", "request", ".", "session", ".", "get", "(", "'user_name'", ")", "user", "=", "UserInfo", ".", "objects", ".", "filter", "(", "uname", "=", "username", ")", ".", "first", "(", ")", "b...
https://github.com/weilanhanf/daily_fresh_demo/blob/6220804724c2aeaa69e00860d0c5a17d2bd895b2/apps/df_user/views.py#L108-L128
riptideio/pymodbus
c5772b35ae3f29d1947f3ab453d8d00df846459f
pymodbus/device.py
python
ModbusDeviceIdentification.__iter__
(self)
return iteritems(self.__data)
Iterater over the device information :returns: An iterator of the device information
Iterater over the device information
[ "Iterater", "over", "the", "device", "information" ]
def __iter__(self): ''' Iterater over the device information :returns: An iterator of the device information ''' return iteritems(self.__data)
[ "def", "__iter__", "(", "self", ")", ":", "return", "iteritems", "(", "self", ".", "__data", ")" ]
https://github.com/riptideio/pymodbus/blob/c5772b35ae3f29d1947f3ab453d8d00df846459f/pymodbus/device.py#L226-L231
NifTK/NiftyNet
935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0
niftynet/contrib/csv_reader/sampler_resize_v2_csv.py
python
zoom_3d
(image, ratio, interp_order)
return np.concatenate(output, axis=-2)
Taking 5D image as input, and zoom each 3D slice independently
Taking 5D image as input, and zoom each 3D slice independently
[ "Taking", "5D", "image", "as", "input", "and", "zoom", "each", "3D", "slice", "independently" ]
def zoom_3d(image, ratio, interp_order): """ Taking 5D image as input, and zoom each 3D slice independently """ assert image.ndim == 5, "input images should be 5D array" output = [] for time_pt in range(image.shape[3]): output_mod = [] for mod in range(image.shape[4]): zoomed = scipy.ndimage.zoom( image[..., time_pt, mod], ratio[:3], order=interp_order) output_mod.append(zoomed[..., np.newaxis, np.newaxis]) output.append(np.concatenate(output_mod, axis=-1)) return np.concatenate(output, axis=-2)
[ "def", "zoom_3d", "(", "image", ",", "ratio", ",", "interp_order", ")", ":", "assert", "image", ".", "ndim", "==", "5", ",", "\"input images should be 5D array\"", "output", "=", "[", "]", "for", "time_pt", "in", "range", "(", "image", ".", "shape", "[", ...
https://github.com/NifTK/NiftyNet/blob/935bf4334cd00fa9f9d50f6a95ddcbfdde4031e0/niftynet/contrib/csv_reader/sampler_resize_v2_csv.py#L120-L133
astropy/astroquery
11c9c83fa8e5f948822f8f73c854ec4b72043016
astroquery/gaia/core.py
python
GaiaClass.__checkCoordInput
(self, value, msg)
[]
def __checkCoordInput(self, value, msg): if not (isinstance(value, str) or isinstance(value, commons.CoordClasses)): raise ValueError(f"{msg} must be either a string or astropy.coordinates")
[ "def", "__checkCoordInput", "(", "self", ",", "value", ",", "msg", ")", ":", "if", "not", "(", "isinstance", "(", "value", ",", "str", ")", "or", "isinstance", "(", "value", ",", "commons", ".", "CoordClasses", ")", ")", ":", "raise", "ValueError", "("...
https://github.com/astropy/astroquery/blob/11c9c83fa8e5f948822f8f73c854ec4b72043016/astroquery/gaia/core.py#L701-L704
facebookresearch/detectron2
cb92ae1763cd7d3777c243f07749574cdaec6cb8
detectron2/data/datasets/coco_panoptic.py
python
merge_to_panoptic
(detection_dicts, sem_seg_dicts)
return results
Create dataset dicts for panoptic segmentation, by merging two dicts using "file_name" field to match their entries. Args: detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. sem_seg_dicts (list[dict]): lists of dicts for semantic segmentation. Returns: list[dict] (one per input image): Each dict contains all (key, value) pairs from dicts in both detection_dicts and sem_seg_dicts that correspond to the same image. The function assumes that the same key in different dicts has the same value.
Create dataset dicts for panoptic segmentation, by merging two dicts using "file_name" field to match their entries.
[ "Create", "dataset", "dicts", "for", "panoptic", "segmentation", "by", "merging", "two", "dicts", "using", "file_name", "field", "to", "match", "their", "entries", "." ]
def merge_to_panoptic(detection_dicts, sem_seg_dicts): """ Create dataset dicts for panoptic segmentation, by merging two dicts using "file_name" field to match their entries. Args: detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. sem_seg_dicts (list[dict]): lists of dicts for semantic segmentation. Returns: list[dict] (one per input image): Each dict contains all (key, value) pairs from dicts in both detection_dicts and sem_seg_dicts that correspond to the same image. The function assumes that the same key in different dicts has the same value. """ results = [] sem_seg_file_to_entry = {x["file_name"]: x for x in sem_seg_dicts} assert len(sem_seg_file_to_entry) > 0 for det_dict in detection_dicts: dic = copy.copy(det_dict) dic.update(sem_seg_file_to_entry[dic["file_name"]]) results.append(dic) return results
[ "def", "merge_to_panoptic", "(", "detection_dicts", ",", "sem_seg_dicts", ")", ":", "results", "=", "[", "]", "sem_seg_file_to_entry", "=", "{", "x", "[", "\"file_name\"", "]", ":", "x", "for", "x", "in", "sem_seg_dicts", "}", "assert", "len", "(", "sem_seg_...
https://github.com/facebookresearch/detectron2/blob/cb92ae1763cd7d3777c243f07749574cdaec6cb8/detectron2/data/datasets/coco_panoptic.py#L168-L190
crossbario/crossbar
ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64
crossbar/edge/worker/xbrmm.py
python
MarketplaceController._process_block
(self, w3, block_number, Events)
return cnt
:param w3: :param block_number: :param Events: :return:
[]
def _process_block(self, w3, block_number, Events): """ :param w3: :param block_number: :param Events: :return: """ cnt = 0 # filter by block, and XBR contract addresses # FIXME: potentially add filters for global data or market specific data for the markets started in this worker filter_params = { 'address': [ xbr.xbrtoken.address, xbr.xbrnetwork.address, xbr.xbrcatalog.address, xbr.xbrmarket.address, xbr.xbrchannel.address ], 'fromBlock': block_number, 'toBlock': block_number, } result = w3.eth.getLogs(filter_params) if result: for evt in result: receipt = w3.eth.getTransactionReceipt(evt['transactionHash']) for Event, handler in Events: # FIXME: MismatchedABI pops up .. we silence this with errors=web3.logs.DISCARD if hasattr(web3, 'logs') and web3.logs: all_res = Event().processReceipt(receipt, errors=web3.logs.DISCARD) else: all_res = Event().processReceipt(receipt) for res in all_res: self.log.info('{handler} processing block {block_number} / txn {txn} with args {args}', handler=hl(handler.__name__), block_number=hlid(block_number), txn=hlid('0x' + binascii.b2a_hex(evt['transactionHash']).decode()), args=hlval(res.args)) handler(res.transactionHash, res.blockHash, res.args) cnt += 1 with self._db.begin(write=True) as txn: block = cfxdb.xbr.block.Block() block.timestamp = np.datetime64(time_ns(), 'ns') block.block_number = block_number # FIXME # block.block_hash = bytes() block.cnt_events = cnt self._xbr.blocks[txn, pack_uint256(block_number)] = block if cnt: self.log.info('Processed blockchain block {block_number}: processed {cnt} XBR events.', block_number=hlid(block_number), cnt=hlid(cnt)) else: self.log.info('Processed blockchain block {block_number}: no XBR events found!', block_number=hlid(block_number)) return cnt
[ "def", "_process_block", "(", "self", ",", "w3", ",", "block_number", ",", "Events", ")", ":", "cnt", "=", "0", "# filter by block, and XBR contract addresses", "# FIXME: potentially add filters for global data or market specific data for the markets started in this worker", "filte...
https://github.com/crossbario/crossbar/blob/ed350b7ba1c8421f3640b9c2e94a21ed4cfdff64/crossbar/edge/worker/xbrmm.py#L772-L829
wbond/package_control
cfaaeb57612023e3679ecb7f8cd7ceac9f57990d
package_control/automatic_upgrader.py
python
AutomaticUpgrader.upgrade_packages
(self)
Upgrades all packages that are not currently upgraded to the lastest version. Also renames any installed packages to their new names.
Upgrades all packages that are not currently upgraded to the lastest version. Also renames any installed packages to their new names.
[ "Upgrades", "all", "packages", "that", "are", "not", "currently", "upgraded", "to", "the", "lastest", "version", ".", "Also", "renames", "any", "installed", "packages", "to", "their", "new", "names", "." ]
def upgrade_packages(self): """ Upgrades all packages that are not currently upgraded to the lastest version. Also renames any installed packages to their new names. """ if not self.auto_upgrade: return self.package_renamer.rename_packages(self.installer) package_list = self.installer.make_package_list( [ 'install', 'reinstall', 'downgrade', 'overwrite', 'none' ], ignore_packages=self.auto_upgrade_ignore ) if USE_QUICK_PANEL_ITEM: package_list = [info.trigger for info in package_list] else: package_list = [info[0] for info in package_list] # If Package Control is being upgraded, just do that and restart if 'Package Control' in package_list: if self.last_run: def reset_last_run(): # Re-save the last run time so it runs again after PC has # been updated self.save_last_run(self.last_run) sublime.set_timeout(reset_last_run, 1) package_list = ['Package Control'] if not package_list: console_write( u''' No updated packages ''' ) return console_write( u''' Installing %s upgrades ''', len(package_list) ) disabled_packages = [] # Disabling a package means changing settings, which can only be done # in the main thread. We then then wait a bit and continue with the # upgrades. def disable_packages(): disabled_packages.extend(self.installer.disable_packages(package_list, 'upgrade')) sublime.set_timeout(disable_packages, 1) # Wait so that the ignored packages can be "unloaded" time.sleep(0.7) for package_name in package_list: if self.installer.manager.install_package(package_name): if package_name in disabled_packages: # We use a functools.partial to generate the on-complete callback in # order to bind the current value of the parameters, unlike lambdas. on_complete = functools.partial(self.installer.reenable_package, package_name, 'upgrade') sublime.set_timeout(on_complete, 700) version = self.installer.manager.get_version(package_name) console_write( u''' Upgraded %s to %s ''', (package_name, version) )
[ "def", "upgrade_packages", "(", "self", ")", ":", "if", "not", "self", ".", "auto_upgrade", ":", "return", "self", ".", "package_renamer", ".", "rename_packages", "(", "self", ".", "installer", ")", "package_list", "=", "self", ".", "installer", ".", "make_p...
https://github.com/wbond/package_control/blob/cfaaeb57612023e3679ecb7f8cd7ceac9f57990d/package_control/automatic_upgrader.py#L260-L339
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/contrib/formtools/wizard/legacy.py
python
FormWizard.render_revalidation_failure
(self, request, step, form)
return self.render(form, request, step)
Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation.
Hook for rendering a template if final revalidation failed.
[ "Hook", "for", "rendering", "a", "template", "if", "final", "revalidation", "failed", "." ]
def render_revalidation_failure(self, request, step, form): """ Hook for rendering a template if final revalidation failed. It is highly unlikely that this point would ever be reached, but See the comment in __call__() for an explanation. """ return self.render(form, request, step)
[ "def", "render_revalidation_failure", "(", "self", ",", "request", ",", "step", ",", "form", ")", ":", "return", "self", ".", "render", "(", "form", ",", "request", ",", "step", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/contrib/formtools/wizard/legacy.py#L161-L168
rytilahti/python-miio
b6e53dd16fac77915426e7592e2528b78ef65190
miio/airfilter_util.py
python
FilterTypeUtil.determine_filter_type
( self, rfid_tag: Optional[str], product_id: Optional[str] )
return ft
Determine Xiaomi air filter type based on its product ID. :param rfid_tag: RFID tag value :param product_id: Product ID such as "0:0:30:33"
Determine Xiaomi air filter type based on its product ID.
[ "Determine", "Xiaomi", "air", "filter", "type", "based", "on", "its", "product", "ID", "." ]
def determine_filter_type( self, rfid_tag: Optional[str], product_id: Optional[str] ) -> Optional[FilterType]: """Determine Xiaomi air filter type based on its product ID. :param rfid_tag: RFID tag value :param product_id: Product ID such as "0:0:30:33" """ if rfid_tag is None: return None if rfid_tag == "0:0:0:0:0:0:0": return FilterType.Unknown if product_id is None: return FilterType.Regular ft = self._filter_type_cache.get(product_id) if ft is None: for filter_re, filter_type in FILTER_TYPE_RE: if filter_re.match(product_id): ft = self._filter_type_cache[product_id] = filter_type break return ft
[ "def", "determine_filter_type", "(", "self", ",", "rfid_tag", ":", "Optional", "[", "str", "]", ",", "product_id", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "FilterType", "]", ":", "if", "rfid_tag", "is", "None", ":", "return", "None"...
https://github.com/rytilahti/python-miio/blob/b6e53dd16fac77915426e7592e2528b78ef65190/miio/airfilter_util.py#L25-L46
aimagelab/meshed-memory-transformer
e0fe3fae68091970407e82e5b907cbc423f25df2
data/vocab.py
python
FastText.__init__
(self, language="en", **kwargs)
[]
def __init__(self, language="en", **kwargs): url = self.url_base.format(language) name = os.path.basename(url) super(FastText, self).__init__(name, url=url, **kwargs)
[ "def", "__init__", "(", "self", ",", "language", "=", "\"en\"", ",", "*", "*", "kwargs", ")", ":", "url", "=", "self", ".", "url_base", ".", "format", "(", "language", ")", "name", "=", "os", ".", "path", ".", "basename", "(", "url", ")", "super", ...
https://github.com/aimagelab/meshed-memory-transformer/blob/e0fe3fae68091970407e82e5b907cbc423f25df2/data/vocab.py#L315-L318
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_objectvalidator.py
python
main
()
ansible oc module for validating OpenShift objects
ansible oc module for validating OpenShift objects
[ "ansible", "oc", "module", "for", "validating", "OpenShift", "objects" ]
def main(): ''' ansible oc module for validating OpenShift objects ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), ), supports_check_mode=False, ) rval = OCObjectValidator.run_ansible(module.params) if 'failed' in rval: module.fail_json(**rval) module.exit_json(**rval)
[ "def", "main", "(", ")", ":", "module", "=", "AnsibleModule", "(", "argument_spec", "=", "dict", "(", "kubeconfig", "=", "dict", "(", "default", "=", "'/etc/origin/master/admin.kubeconfig'", ",", "type", "=", "'str'", ")", ",", ")", ",", "supports_check_mode",...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.40/roles/lib_vendored_deps/library/oc_objectvalidator.py#L1508-L1525
qutip/qutip
52d01da181a21b810c3407812c670f35fdc647e8
qutip/ipynbtools.py
python
parallel_map
(task, values, task_args=None, task_kwargs=None, client=None, view=None, progress_bar=None, show_scheduling=False, **kwargs)
return [ar.get() for ar in ar_list]
Call the function ``task`` for each value in ``values`` using a cluster of IPython engines. The function ``task`` should have the signature ``task(value, *args, **kwargs)``. The ``client`` and ``view`` are the IPython.parallel client and load-balanced view that will be used in the parfor execution. If these are ``None``, new instances will be created. Parameters ---------- task: a Python function The function that is to be called for each value in ``task_vec``. values: array / list The list or array of values for which the ``task`` function is to be evaluated. task_args: list / dictionary The optional additional argument to the ``task`` function. task_kwargs: list / dictionary The optional additional keyword argument to the ``task`` function. client: IPython.parallel.Client The IPython.parallel Client instance that will be used in the parfor execution. view: a IPython.parallel.Client view The view that is to be used in scheduling the tasks on the IPython cluster. Preferably a load-balanced view, which is obtained from the IPython.parallel.Client instance client by calling, view = client.load_balanced_view(). show_scheduling: bool {False, True}, default False Display a graph showing how the tasks (the evaluation of ``task`` for for the value in ``task_vec1``) was scheduled on the IPython engine cluster. show_progressbar: bool {False, True}, default False Display a HTML-based progress bar during the execution of the parfor loop. Returns -------- result : list The result list contains the value of ``task(value, task_args, task_kwargs)`` for each value in ``values``.
Call the function ``task`` for each value in ``values`` using a cluster of IPython engines. The function ``task`` should have the signature ``task(value, *args, **kwargs)``.
[ "Call", "the", "function", "task", "for", "each", "value", "in", "values", "using", "a", "cluster", "of", "IPython", "engines", ".", "The", "function", "task", "should", "have", "the", "signature", "task", "(", "value", "*", "args", "**", "kwargs", ")", ...
def parallel_map(task, values, task_args=None, task_kwargs=None, client=None, view=None, progress_bar=None, show_scheduling=False, **kwargs): """ Call the function ``task`` for each value in ``values`` using a cluster of IPython engines. The function ``task`` should have the signature ``task(value, *args, **kwargs)``. The ``client`` and ``view`` are the IPython.parallel client and load-balanced view that will be used in the parfor execution. If these are ``None``, new instances will be created. Parameters ---------- task: a Python function The function that is to be called for each value in ``task_vec``. values: array / list The list or array of values for which the ``task`` function is to be evaluated. task_args: list / dictionary The optional additional argument to the ``task`` function. task_kwargs: list / dictionary The optional additional keyword argument to the ``task`` function. client: IPython.parallel.Client The IPython.parallel Client instance that will be used in the parfor execution. view: a IPython.parallel.Client view The view that is to be used in scheduling the tasks on the IPython cluster. Preferably a load-balanced view, which is obtained from the IPython.parallel.Client instance client by calling, view = client.load_balanced_view(). show_scheduling: bool {False, True}, default False Display a graph showing how the tasks (the evaluation of ``task`` for for the value in ``task_vec1``) was scheduled on the IPython engine cluster. show_progressbar: bool {False, True}, default False Display a HTML-based progress bar during the execution of the parfor loop. Returns -------- result : list The result list contains the value of ``task(value, task_args, task_kwargs)`` for each value in ``values``. """ submitted = datetime.datetime.now() if task_args is None: task_args = tuple() if task_kwargs is None: task_kwargs = {} if client is None: client = Client() # make sure qutip is available at engines dview = client[:] dview.block = True dview.execute("from qutip import *") if view is None: view = client.load_balanced_view() ar_list = [view.apply_async(task, value, *task_args, **task_kwargs) for value in values] if progress_bar is None: view.wait(ar_list) else: if progress_bar is True: progress_bar = HTMLProgressBar() n = len(ar_list) progress_bar.start(n) while True: n_finished = sum([ar.progress for ar in ar_list]) progress_bar.update(n_finished) if view.wait(ar_list, timeout=0.5): progress_bar.update(n) break progress_bar.finished() if show_scheduling: metadata = [[ar.engine_id, (ar.started - submitted).total_seconds(), (ar.completed - submitted).total_seconds()] for ar in ar_list] _visualize_parfor_data(metadata) return [ar.get() for ar in ar_list]
[ "def", "parallel_map", "(", "task", ",", "values", ",", "task_args", "=", "None", ",", "task_kwargs", "=", "None", ",", "client", "=", "None", ",", "view", "=", "None", ",", "progress_bar", "=", "None", ",", "show_scheduling", "=", "False", ",", "*", "...
https://github.com/qutip/qutip/blob/52d01da181a21b810c3407812c670f35fdc647e8/qutip/ipynbtools.py#L239-L340
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/box/unselected/_marker.py
python
Marker.__init__
(self, arg=None, color=None, opacity=None, size=None, **kwargs)
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.box.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. Returns ------- Marker
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.box.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists.
[ "Construct", "a", "new", "Marker", "object", "Parameters", "----------", "arg", "dict", "of", "properties", "compatible", "with", "this", "constructor", "or", "an", "instance", "of", ":", "class", ":", "plotly", ".", "graph_objs", ".", "box", ".", "unselected"...
def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.box.unselected.Marker` color Sets the marker color of unselected points, applied only when a selection exists. opacity Sets the marker opacity of unselected points, applied only when a selection exists. size Sets the marker size of unselected points, applied only when a selection exists. Returns ------- Marker """ super(Marker, self).__init__("marker") if "_parent" in kwargs: self._parent = kwargs["_parent"] return # Validate arg # ------------ if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError( """\ The first argument to the plotly.graph_objs.box.unselected.Marker constructor must be a dict or an instance of :class:`plotly.graph_objs.box.unselected.Marker`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) # Populate data dict with properties # ---------------------------------- _v = arg.pop("color", None) _v = color if color is not None else _v if _v is not None: self["color"] = _v _v = arg.pop("opacity", None) _v = opacity if opacity is not None else _v if _v is not None: self["opacity"] = _v _v = arg.pop("size", None) _v = size if size is not None else _v if _v is not None: self["size"] = _v # Process unknown kwargs # ---------------------- self._process_kwargs(**dict(arg, **kwargs)) # Reset skip_invalid # ------------------ self._skip_invalid = False
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "opacity", "=", "None", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Marker", ",", "self", ")", ".", "__init__", "(", "\"marke...
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/box/unselected/_marker.py#L131-L203
kelvinguu/neural-editor
3390140cb727b8c44092398fa68ceb0231b28e8b
textmorph/edit_model/editor.py
python
Editor.edit
(self, examples, max_seq_length=35, beam_size=5, batch_size=256)
return beam_list, edit_traces
Performs edits on a batch of source sentences. Args: examples (list[EditExample]) max_seq_length (int): max # timesteps to generate for beam_size (int): for beam decoding batch_size (int): max number of examples to pass into the RNN decoder at a time. The total # examples decoded in parallel = batch_size / beam_size. Returns: beam_list (list[list[list[unicode]]]): a batch of beams. edit_traces (list[EditTrace])
Performs edits on a batch of source sentences.
[ "Performs", "edits", "on", "a", "batch", "of", "source", "sentences", "." ]
def edit(self, examples, max_seq_length=35, beam_size=5, batch_size=256): """Performs edits on a batch of source sentences. Args: examples (list[EditExample]) max_seq_length (int): max # timesteps to generate for beam_size (int): for beam decoding batch_size (int): max number of examples to pass into the RNN decoder at a time. The total # examples decoded in parallel = batch_size / beam_size. Returns: beam_list (list[list[list[unicode]]]): a batch of beams. edit_traces (list[EditTrace]) """ beam_list = [] edit_traces = [] for batch in chunks(examples, batch_size / beam_size): beams, traces = self._edit_batch(batch, max_seq_length, beam_size) beam_list.extend(beams) edit_traces.extend(traces) return beam_list, edit_traces
[ "def", "edit", "(", "self", ",", "examples", ",", "max_seq_length", "=", "35", ",", "beam_size", "=", "5", ",", "batch_size", "=", "256", ")", ":", "beam_list", "=", "[", "]", "edit_traces", "=", "[", "]", "for", "batch", "in", "chunks", "(", "exampl...
https://github.com/kelvinguu/neural-editor/blob/3390140cb727b8c44092398fa68ceb0231b28e8b/textmorph/edit_model/editor.py#L133-L153
ansible/ansible-modules-core
00911a75ad6635834b6d28eef41f197b2f73c381
cloud/amazon/rds_param_group.py
python
set_parameter
(param, value, immediate)
Allows setting parameters with 10M = 10* 1024 * 1024 and so on.
Allows setting parameters with 10M = 10* 1024 * 1024 and so on.
[ "Allows", "setting", "parameters", "with", "10M", "=", "10", "*", "1024", "*", "1024", "and", "so", "on", "." ]
def set_parameter(param, value, immediate): """ Allows setting parameters with 10M = 10* 1024 * 1024 and so on. """ converted_value = value if param.type == 'string': converted_value = str(value) elif param.type == 'integer': if isinstance(value, basestring): try: for modifier in INT_MODIFIERS.keys(): if value.endswith(modifier): converted_value = int(value[:-1]) * INT_MODIFIERS[modifier] converted_value = int(converted_value) except ValueError: # may be based on a variable (ie. {foo*3/4}) so # just pass it on through to boto converted_value = str(value) elif isinstance(value, bool): converted_value = 1 if value else 0 else: converted_value = int(value) elif param.type == 'boolean': if isinstance(value, basestring): converted_value = value in TRUE_VALUES else: converted_value = bool(value) param.value = converted_value param.apply(immediate)
[ "def", "set_parameter", "(", "param", ",", "value", ",", "immediate", ")", ":", "converted_value", "=", "value", "if", "param", ".", "type", "==", "'string'", ":", "converted_value", "=", "str", "(", "value", ")", "elif", "param", ".", "type", "==", "'in...
https://github.com/ansible/ansible-modules-core/blob/00911a75ad6635834b6d28eef41f197b2f73c381/cloud/amazon/rds_param_group.py#L148-L180
osmr/imgclsmob
f2993d3ce73a2f7ddba05da3891defb08547d504
gluon/gluoncv2/models/resattnet.py
python
resattnet236
(**kwargs)
return get_resattnet(blocks=236, model_name="resattnet236", **kwargs)
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters.
ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
[ "ResAttNet", "-", "236", "model", "from", "Residual", "Attention", "Network", "for", "Image", "Classification", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1704", ".", "06904", "." ]
def resattnet236(**kwargs): """ ResAttNet-236 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in which to load the pretrained weights. root : str, default '~/.mxnet/models' Location for keeping the model parameters. """ return get_resattnet(blocks=236, model_name="resattnet236", **kwargs)
[ "def", "resattnet236", "(", "*", "*", "kwargs", ")", ":", "return", "get_resattnet", "(", "blocks", "=", "236", ",", "model_name", "=", "\"resattnet236\"", ",", "*", "*", "kwargs", ")" ]
https://github.com/osmr/imgclsmob/blob/f2993d3ce73a2f7ddba05da3891defb08547d504/gluon/gluoncv2/models/resattnet.py#L696-L709
sqall01/alertR
e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13
sensorClientExecuter/lib/client/serverCommunication.py
python
ServerCommunication._handler_profile_change
(self, incomingMessage: Dict[str, Any])
return False
Internal function that handles received profile change messages (for nodes of type alert). :param incomingMessage: :return:
Internal function that handles received profile change messages (for nodes of type alert).
[ "Internal", "function", "that", "handles", "received", "profile", "change", "messages", "(", "for", "nodes", "of", "type", "alert", ")", "." ]
def _handler_profile_change(self, incomingMessage: Dict[str, Any]) -> bool: """ Internal function that handles received profile change messages (for nodes of type alert). :param incomingMessage: :return: """ logging.debug("[%s]: Received profile change to '%s'." % (self._log_tag, incomingMessage["payload"]["name"])) try: msg_time = incomingMessage["msgTime"] profile = ManagerObjProfile() profile.profileId = incomingMessage["payload"]["profileId"] profile.name = incomingMessage["payload"]["name"] except Exception: logging.exception("[%s]: Received profile change invalid." % self._log_tag) return False # handle received state change if self._event_handler.profile_change(msg_time, profile): return True return False
[ "def", "_handler_profile_change", "(", "self", ",", "incomingMessage", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "bool", ":", "logging", ".", "debug", "(", "\"[%s]: Received profile change to '%s'.\"", "%", "(", "self", ".", "_log_tag", ",", "incomi...
https://github.com/sqall01/alertR/blob/e1d1a83e54f876cc4cd7bd87387e05cb75d4dc13/sensorClientExecuter/lib/client/serverCommunication.py#L138-L164
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/pickle.py
python
_Unpickler.load_dup
(self)
[]
def load_dup(self): self.append(self.stack[-1])
[ "def", "load_dup", "(", "self", ")", ":", "self", ".", "append", "(", "self", ".", "stack", "[", "-", "1", "]", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/pickle.py#L1190-L1191
1040003585/WebScrapingWithPython
a770fa5b03894076c8c9539b1ffff34424ffc016
portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py
python
with_metaclass
(meta, *bases)
return type.__new__(metaclass, 'temporary_class', (), {})
Create a base class with a metaclass.
Create a base class with a metaclass.
[ "Create", "a", "base", "class", "with", "a", "metaclass", "." ]
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a dummy", "# metaclass for one level of class instantiation that replaces itself with", "# the actual metaclass.", "class", "metaclass", "(", "meta", ")...
https://github.com/1040003585/WebScrapingWithPython/blob/a770fa5b03894076c8c9539b1ffff34424ffc016/portia_examle/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/packages/six.py#L800-L809
LumaPictures/pymel
fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72
pymel/tools/mel2py/melparse.py
python
find_num_leading_space
(text)
return i
Given a text block consisting of multiple lines, find the number of characters in the longest common whitespace that appears at the start of every non-empty line
Given a text block consisting of multiple lines, find the number of characters in the longest common whitespace that appears at the start of every non-empty line
[ "Given", "a", "text", "block", "consisting", "of", "multiple", "lines", "find", "the", "number", "of", "characters", "in", "the", "longest", "common", "whitespace", "that", "appears", "at", "the", "start", "of", "every", "non", "-", "empty", "line" ]
def find_num_leading_space(text): '''Given a text block consisting of multiple lines, find the number of characters in the longest common whitespace that appears at the start of every non-empty line''' lines = text.split('\n') nonEmptyLines = [l for l in lines if l.strip()] if not nonEmptyLines: return 0 first = nonEmptyLines[0] rest = nonEmptyLines[1:] for i, char in enumerate(first): if char not in ' \t': break for line in rest: if line[i] != char: break return i
[ "def", "find_num_leading_space", "(", "text", ")", ":", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "nonEmptyLines", "=", "[", "l", "for", "l", "in", "lines", "if", "l", ".", "strip", "(", ")", "]", "if", "not", "nonEmptyLines", ":", "retu...
https://github.com/LumaPictures/pymel/blob/fa88a3f4fa18e09bb8aa9bdf4dab53d984bada72/pymel/tools/mel2py/melparse.py#L573-L591
pyro-ppl/numpyro
6a0856b7cda82fc255e23adc797bb79f5b7fc904
numpyro/distributions/kl.py
python
kl_divergence
(p, q)
r""" Compute Kullback-Leibler divergence :math:`KL(p \| q)` between two distributions.
r""" Compute Kullback-Leibler divergence :math:`KL(p \| q)` between two distributions.
[ "r", "Compute", "Kullback", "-", "Leibler", "divergence", ":", "math", ":", "KL", "(", "p", "\\", "|", "q", ")", "between", "two", "distributions", "." ]
def kl_divergence(p, q): r""" Compute Kullback-Leibler divergence :math:`KL(p \| q)` between two distributions. """ raise NotImplementedError
[ "def", "kl_divergence", "(", "p", ",", "q", ")", ":", "raise", "NotImplementedError" ]
https://github.com/pyro-ppl/numpyro/blob/6a0856b7cda82fc255e23adc797bb79f5b7fc904/numpyro/distributions/kl.py#L45-L49
werner-duvaud/muzero-general
23a1f6910e97d78475ccd29576cdd107c5afefd2
games/breakout.py
python
Game.step
(self, action)
return observation, reward, done
Apply action to the game. Args: action : action of the action_space to take. Returns: The new observation, the reward and a boolean if the game has ended.
Apply action to the game. Args: action : action of the action_space to take.
[ "Apply", "action", "to", "the", "game", ".", "Args", ":", "action", ":", "action", "of", "the", "action_space", "to", "take", "." ]
def step(self, action): """ Apply action to the game. Args: action : action of the action_space to take. Returns: The new observation, the reward and a boolean if the game has ended. """ observation, reward, done, _ = self.env.step(action) observation = cv2.resize(observation, (96, 96), interpolation=cv2.INTER_AREA) observation = numpy.asarray(observation, dtype="float32") / 255.0 observation = numpy.moveaxis(observation, -1, 0) return observation, reward, done
[ "def", "step", "(", "self", ",", "action", ")", ":", "observation", ",", "reward", ",", "done", ",", "_", "=", "self", ".", "env", ".", "step", "(", "action", ")", "observation", "=", "cv2", ".", "resize", "(", "observation", ",", "(", "96", ",", ...
https://github.com/werner-duvaud/muzero-general/blob/23a1f6910e97d78475ccd29576cdd107c5afefd2/games/breakout.py#L145-L159
dansanderson/picotool
d8c51e58416f8010dc8c0fba3df5f0424b5bb852
pico8/tool.py
python
luafind
(args)
return 0
Looks for Lua code lines that match a pattern in one or more carts. Args: args: The argparser parsed args object. Returns: 0 on success, 1 on failure.
Looks for Lua code lines that match a pattern in one or more carts.
[ "Looks", "for", "Lua", "code", "lines", "that", "match", "a", "pattern", "in", "one", "or", "more", "carts", "." ]
def luafind(args): """Looks for Lua code lines that match a pattern in one or more carts. Args: args: The argparser parsed args object. Returns: 0 on success, 1 on failure. """ # (The first argument is the pattern, but it's stored in args.filename.) filenames = list(args.filename) if len(filenames) < 2: util.error( 'Usage: p8tool luafind <pattern> <filename> [<filename>...]\n') return 1 pattern = re.compile(filenames.pop(0)) # TODO: Tell the Lua class not to bother parsing, since we only need the # token stream to get the lines of code. for fname, g in _games_for_filenames(filenames): line_count = 0 for line in g.lua.to_lines(): line_count += 1 if pattern.search(line) is None: continue if args.listfiles: util.write(fname + '\n') break util.write('{}:{}:{}'.format( fname, line_count, _as_friendly_string(line))) return 0
[ "def", "luafind", "(", "args", ")", ":", "# (The first argument is the pattern, but it's stored in args.filename.)", "filenames", "=", "list", "(", "args", ".", "filename", ")", "if", "len", "(", "filenames", ")", "<", "2", ":", "util", ".", "error", "(", "'Usag...
https://github.com/dansanderson/picotool/blob/d8c51e58416f8010dc8c0fba3df5f0424b5bb852/pico8/tool.py#L372-L403
boto/boto
b2a6f08122b2f1b89888d2848e730893595cd001
boto/cloudtrail/layer1.py
python
CloudTrailConnection.update_trail
(self, name, s3_bucket_name=None, s3_key_prefix=None, sns_topic_name=None, include_global_service_events=None, cloud_watch_logs_log_group_arn=None, cloud_watch_logs_role_arn=None)
return self.make_request(action='UpdateTrail', body=json.dumps(params))
From the command line, use `update-subscription`. Updates the settings that specify delivery of log files. Changes to a trail do not require stopping the CloudTrail service. Use this action to designate an existing bucket for log delivery. If the existing bucket has previously been a target for CloudTrail log files, an IAM policy exists for the bucket. :type name: string :param name: Specifies the name of the trail. :type s3_bucket_name: string :param s3_bucket_name: Specifies the name of the Amazon S3 bucket designated for publishing log files. :type s3_key_prefix: string :param s3_key_prefix: Specifies the Amazon S3 key prefix that precedes the name of the bucket you have designated for log file delivery. :type sns_topic_name: string :param sns_topic_name: Specifies the name of the Amazon SNS topic defined for notification of log file delivery. :type include_global_service_events: boolean :param include_global_service_events: Specifies whether the trail is publishing events from global services such as IAM to the log files. :type cloud_watch_logs_log_group_arn: string :param cloud_watch_logs_log_group_arn: Specifies a log group name using an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail logs will be delivered. Not required unless you specify CloudWatchLogsRoleArn. :type cloud_watch_logs_role_arn: string :param cloud_watch_logs_role_arn: Specifies the role for the CloudWatch Logs endpoint to assume to write to a users log group.
From the command line, use `update-subscription`.
[ "From", "the", "command", "line", "use", "update", "-", "subscription", "." ]
def update_trail(self, name, s3_bucket_name=None, s3_key_prefix=None, sns_topic_name=None, include_global_service_events=None, cloud_watch_logs_log_group_arn=None, cloud_watch_logs_role_arn=None): """ From the command line, use `update-subscription`. Updates the settings that specify delivery of log files. Changes to a trail do not require stopping the CloudTrail service. Use this action to designate an existing bucket for log delivery. If the existing bucket has previously been a target for CloudTrail log files, an IAM policy exists for the bucket. :type name: string :param name: Specifies the name of the trail. :type s3_bucket_name: string :param s3_bucket_name: Specifies the name of the Amazon S3 bucket designated for publishing log files. :type s3_key_prefix: string :param s3_key_prefix: Specifies the Amazon S3 key prefix that precedes the name of the bucket you have designated for log file delivery. :type sns_topic_name: string :param sns_topic_name: Specifies the name of the Amazon SNS topic defined for notification of log file delivery. :type include_global_service_events: boolean :param include_global_service_events: Specifies whether the trail is publishing events from global services such as IAM to the log files. :type cloud_watch_logs_log_group_arn: string :param cloud_watch_logs_log_group_arn: Specifies a log group name using an Amazon Resource Name (ARN), a unique identifier that represents the log group to which CloudTrail logs will be delivered. Not required unless you specify CloudWatchLogsRoleArn. :type cloud_watch_logs_role_arn: string :param cloud_watch_logs_role_arn: Specifies the role for the CloudWatch Logs endpoint to assume to write to a users log group. """ params = {'Name': name, } if s3_bucket_name is not None: params['S3BucketName'] = s3_bucket_name if s3_key_prefix is not None: params['S3KeyPrefix'] = s3_key_prefix if sns_topic_name is not None: params['SnsTopicName'] = sns_topic_name if include_global_service_events is not None: params['IncludeGlobalServiceEvents'] = include_global_service_events if cloud_watch_logs_log_group_arn is not None: params['CloudWatchLogsLogGroupArn'] = cloud_watch_logs_log_group_arn if cloud_watch_logs_role_arn is not None: params['CloudWatchLogsRoleArn'] = cloud_watch_logs_role_arn return self.make_request(action='UpdateTrail', body=json.dumps(params))
[ "def", "update_trail", "(", "self", ",", "name", ",", "s3_bucket_name", "=", "None", ",", "s3_key_prefix", "=", "None", ",", "sns_topic_name", "=", "None", ",", "include_global_service_events", "=", "None", ",", "cloud_watch_logs_log_group_arn", "=", "None", ",", ...
https://github.com/boto/boto/blob/b2a6f08122b2f1b89888d2848e730893595cd001/boto/cloudtrail/layer1.py#L291-L350
1012598167/flask_mongodb_game
60c7e0351586656ec38f851592886338e50b4110
python_flask/venv/Lib/site-packages/flask/config.py
python
Config.from_envvar
(self, variable_name, silent=False)
return self.from_pyfile(rv, silent=silent)
Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: bool. ``True`` if able to load config, ``False`` otherwise.
Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code::
[ "Loads", "a", "configuration", "from", "an", "environment", "variable", "pointing", "to", "a", "configuration", "file", ".", "This", "is", "basically", "just", "a", "shortcut", "with", "nicer", "error", "messages", "for", "this", "line", "of", "code", "::" ]
def from_envvar(self, variable_name, silent=False): """Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to ``True`` if you want silent failure for missing files. :return: bool. ``True`` if able to load config, ``False`` otherwise. """ rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError( "The environment variable %r is not set " "and as such configuration could not be " "loaded. Set this variable and make it " "point to a configuration file" % variable_name ) return self.from_pyfile(rv, silent=silent)
[ "def", "from_envvar", "(", "self", ",", "variable_name", ",", "silent", "=", "False", ")", ":", "rv", "=", "os", ".", "environ", ".", "get", "(", "variable_name", ")", "if", "not", "rv", ":", "if", "silent", ":", "return", "False", "raise", "RuntimeErr...
https://github.com/1012598167/flask_mongodb_game/blob/60c7e0351586656ec38f851592886338e50b4110/python_flask/venv/Lib/site-packages/flask/config.py#L89-L111
zulip/zulip
19f891968de50d43920af63526c823bdd233cdee
zerver/webhooks/freshdesk/view.py
python
format_freshdesk_property_change_message
(ticket: TicketDict, event_info: List[str])
return content
Freshdesk will only tell us the first event to match our webhook configuration, so if we change multiple properties, we only get the before and after data for the first one.
Freshdesk will only tell us the first event to match our webhook configuration, so if we change multiple properties, we only get the before and after data for the first one.
[ "Freshdesk", "will", "only", "tell", "us", "the", "first", "event", "to", "match", "our", "webhook", "configuration", "so", "if", "we", "change", "multiple", "properties", "we", "only", "get", "the", "before", "and", "after", "data", "for", "the", "first", ...
def format_freshdesk_property_change_message(ticket: TicketDict, event_info: List[str]) -> str: """Freshdesk will only tell us the first event to match our webhook configuration, so if we change multiple properties, we only get the before and after data for the first one. """ content = PROPERTY_CHANGE_TEMPLATE.format( name=ticket.requester_name, email=ticket.requester_email, ticket_id=ticket.id, ticket_url=ticket.url, property_name=event_info[0].capitalize(), old=event_info[1], new=event_info[2], ) return content
[ "def", "format_freshdesk_property_change_message", "(", "ticket", ":", "TicketDict", ",", "event_info", ":", "List", "[", "str", "]", ")", "->", "str", ":", "content", "=", "PROPERTY_CHANGE_TEMPLATE", ".", "format", "(", "name", "=", "ticket", ".", "requester_na...
https://github.com/zulip/zulip/blob/19f891968de50d43920af63526c823bdd233cdee/zerver/webhooks/freshdesk/view.py#L110-L125
yt-project/yt
dc7b24f9b266703db4c843e329c6c8644d47b824
yt/fields/field_exceptions.py
python
NeedsProperty.__init__
(self, missing_properties)
[]
def __init__(self, missing_properties): self.missing_properties = missing_properties
[ "def", "__init__", "(", "self", ",", "missing_properties", ")", ":", "self", ".", "missing_properties", "=", "missing_properties" ]
https://github.com/yt-project/yt/blob/dc7b24f9b266703db4c843e329c6c8644d47b824/yt/fields/field_exceptions.py#L29-L30