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
sequence
function
stringlengths
18
4.83M
function_tokens
sequence
url
stringlengths
83
304
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/plugins/drawreport/fanchart.py
python
FanChart.get_max_width_for_circles
(self, rad1, rad2, max_centering_proportion)
return sin(acos(rmid/rad2)) * rad2 * 2
r""" (the "r" in the above line is to keep pylint happy) __ /__\ <- compute the line width which is drawable between 2 circles. / _ \ max_centering_proportion : 0, touching the circle1, 1, | |_| | touching the circle2, 0.5 : middle between the 2 circles | | \ / \__/ basically, max_centering_proportion is max_centering_proportion/nb_lines
r""" (the "r" in the above line is to keep pylint happy) __ /__\ <- compute the line width which is drawable between 2 circles. / _ \ max_centering_proportion : 0, touching the circle1, 1, | |_| | touching the circle2, 0.5 : middle between the 2 circles | | \ / \__/ basically, max_centering_proportion is max_centering_proportion/nb_lines
[ "r", "(", "the", "r", "in", "the", "above", "line", "is", "to", "keep", "pylint", "happy", ")", "__", "/", "__", "\\", "<", "-", "compute", "the", "line", "width", "which", "is", "drawable", "between", "2", "circles", ".", "/", "_", "\\", "max_centering_proportion", ":", "0", "touching", "the", "circle1", "1", "|", "|_|", "|", "touching", "the", "circle2", "0", ".", "5", ":", "middle", "between", "the", "2", "circles", "|", "|", "\\", "/", "\\", "__", "/", "basically", "max_centering_proportion", "is", "max_centering_proportion", "/", "nb_lines" ]
def get_max_width_for_circles(self, rad1, rad2, max_centering_proportion): r""" (the "r" in the above line is to keep pylint happy) __ /__\ <- compute the line width which is drawable between 2 circles. / _ \ max_centering_proportion : 0, touching the circle1, 1, | |_| | touching the circle2, 0.5 : middle between the 2 circles | | \ / \__/ basically, max_centering_proportion is max_centering_proportion/nb_lines """ # radius at the center of the 2 circles rmid = rad2 - (rad2-rad1)*max_centering_proportion return sin(acos(rmid/rad2)) * rad2 * 2
[ "def", "get_max_width_for_circles", "(", "self", ",", "rad1", ",", "rad2", ",", "max_centering_proportion", ")", ":", "# radius at the center of the 2 circles", "rmid", "=", "rad2", "-", "(", "rad2", "-", "rad1", ")", "*", "max_centering_proportion", "return", "sin", "(", "acos", "(", "rmid", "/", "rad2", ")", ")", "*", "rad2", "*", "2" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/plugins/drawreport/fanchart.py#L398-L413
saleguas/context_menu
2cbc68071251bdc19d1c98ea00264a4842349c61
context_menu/linux_menus.py
python
NautilusMenu.__init__
(self, name: str, sub_items: list, type: str)
Items required are the name of the top menu, the sub items, and the type.
Items required are the name of the top menu, the sub items, and the type.
[ "Items", "required", "are", "the", "name", "of", "the", "top", "menu", "the", "sub", "items", "and", "the", "type", "." ]
def __init__(self, name: str, sub_items: list, type: str): ''' Items required are the name of the top menu, the sub items, and the type. ''' self.name = name self.sub_items = sub_items self.type = type self.counter = 0 # Create all the necessary lists that will be used later on self.commands = [] self.script_dirs = [] self.funcs = [] self.imports = []
[ "def", "__init__", "(", "self", ",", "name", ":", "str", ",", "sub_items", ":", "list", ",", "type", ":", "str", ")", ":", "self", ".", "name", "=", "name", "self", ".", "sub_items", "=", "sub_items", "self", ".", "type", "=", "type", "self", ".", "counter", "=", "0", "# Create all the necessary lists that will be used later on", "self", ".", "commands", "=", "[", "]", "self", ".", "script_dirs", "=", "[", "]", "self", ".", "funcs", "=", "[", "]", "self", ".", "imports", "=", "[", "]" ]
https://github.com/saleguas/context_menu/blob/2cbc68071251bdc19d1c98ea00264a4842349c61/context_menu/linux_menus.py#L152-L165
AITTSMD/MTCNN-Tensorflow
3b3934d38f8d34287cc933a581537a1acfd0bb60
prepare_data/data_utils.py
python
read_annotation
(base_dir, label_path)
return data
read label file :param dir: path :return:
read label file :param dir: path :return:
[ "read", "label", "file", ":", "param", "dir", ":", "path", ":", "return", ":" ]
def read_annotation(base_dir, label_path): """ read label file :param dir: path :return: """ data = dict() images = [] bboxes = [] labelfile = open(label_path, 'r') while True: # image path imagepath = labelfile.readline().strip('\n') if not imagepath: break imagepath = base_dir + '/WIDER_train/images/' + imagepath images.append(imagepath) # face numbers nums = labelfile.readline().strip('\n') # im = cv2.imread(imagepath) # h, w, c = im.shape one_image_bboxes = [] for i in range(int(nums)): # text = '' # text = text + imagepath bb_info = labelfile.readline().strip('\n').split(' ') # only need x, y, w, h face_box = [float(bb_info[i]) for i in range(4)] # text = text + ' ' + str(face_box[0] / w) + ' ' + str(face_box[1] / h) xmin = face_box[0] ymin = face_box[1] xmax = xmin + face_box[2] ymax = ymin + face_box[3] # text = text + ' ' + str(xmax / w) + ' ' + str(ymax / h) one_image_bboxes.append([xmin, ymin, xmax, ymax]) # f.write(text + '\n') bboxes.append(one_image_bboxes) data['images'] = images#all images data['bboxes'] = bboxes#all image bboxes # f.close() return data
[ "def", "read_annotation", "(", "base_dir", ",", "label_path", ")", ":", "data", "=", "dict", "(", ")", "images", "=", "[", "]", "bboxes", "=", "[", "]", "labelfile", "=", "open", "(", "label_path", ",", "'r'", ")", "while", "True", ":", "# image path", "imagepath", "=", "labelfile", ".", "readline", "(", ")", ".", "strip", "(", "'\\n'", ")", "if", "not", "imagepath", ":", "break", "imagepath", "=", "base_dir", "+", "'/WIDER_train/images/'", "+", "imagepath", "images", ".", "append", "(", "imagepath", ")", "# face numbers", "nums", "=", "labelfile", ".", "readline", "(", ")", ".", "strip", "(", "'\\n'", ")", "# im = cv2.imread(imagepath)", "# h, w, c = im.shape", "one_image_bboxes", "=", "[", "]", "for", "i", "in", "range", "(", "int", "(", "nums", ")", ")", ":", "# text = ''", "# text = text + imagepath", "bb_info", "=", "labelfile", ".", "readline", "(", ")", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", "' '", ")", "# only need x, y, w, h", "face_box", "=", "[", "float", "(", "bb_info", "[", "i", "]", ")", "for", "i", "in", "range", "(", "4", ")", "]", "# text = text + ' ' + str(face_box[0] / w) + ' ' + str(face_box[1] / h)", "xmin", "=", "face_box", "[", "0", "]", "ymin", "=", "face_box", "[", "1", "]", "xmax", "=", "xmin", "+", "face_box", "[", "2", "]", "ymax", "=", "ymin", "+", "face_box", "[", "3", "]", "# text = text + ' ' + str(xmax / w) + ' ' + str(ymax / h)", "one_image_bboxes", ".", "append", "(", "[", "xmin", ",", "ymin", ",", "xmax", ",", "ymax", "]", ")", "# f.write(text + '\\n')", "bboxes", ".", "append", "(", "one_image_bboxes", ")", "data", "[", "'images'", "]", "=", "images", "#all images", "data", "[", "'bboxes'", "]", "=", "bboxes", "#all image bboxes", "# f.close()", "return", "data" ]
https://github.com/AITTSMD/MTCNN-Tensorflow/blob/3b3934d38f8d34287cc933a581537a1acfd0bb60/prepare_data/data_utils.py#L17-L59
andabi/music-source-separation
ba9aa531ccca08437f1efe5dec1871faebf5c840
mir_eval/util.py
python
filter_kwargs
(_function, *args, **kwargs)
return _function(*args, **filtered_kwargs)
Given a function and args and keyword args to pass to it, call the function but using only the keyword arguments which it accepts. This is equivalent to redefining the function with an additional \*\*kwargs to accept slop keyword args. If the target function already accepts \*\*kwargs parameters, no filtering is performed. Parameters ---------- _function : callable Function to call. Can take in any number of args or kwargs
Given a function and args and keyword args to pass to it, call the function but using only the keyword arguments which it accepts. This is equivalent to redefining the function with an additional \*\*kwargs to accept slop keyword args.
[ "Given", "a", "function", "and", "args", "and", "keyword", "args", "to", "pass", "to", "it", "call", "the", "function", "but", "using", "only", "the", "keyword", "arguments", "which", "it", "accepts", ".", "This", "is", "equivalent", "to", "redefining", "the", "function", "with", "an", "additional", "\\", "*", "\\", "*", "kwargs", "to", "accept", "slop", "keyword", "args", "." ]
def filter_kwargs(_function, *args, **kwargs): """Given a function and args and keyword args to pass to it, call the function but using only the keyword arguments which it accepts. This is equivalent to redefining the function with an additional \*\*kwargs to accept slop keyword args. If the target function already accepts \*\*kwargs parameters, no filtering is performed. Parameters ---------- _function : callable Function to call. Can take in any number of args or kwargs """ if has_kwargs(_function): return _function(*args, **kwargs) # Get the list of function arguments func_code = six.get_function_code(_function) function_args = func_code.co_varnames[:func_code.co_argcount] # Construct a dict of those kwargs which appear in the function filtered_kwargs = {} for kwarg, value in list(kwargs.items()): if kwarg in function_args: filtered_kwargs[kwarg] = value # Call the function with the supplied args and the filtered kwarg dict return _function(*args, **filtered_kwargs)
[ "def", "filter_kwargs", "(", "_function", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "has_kwargs", "(", "_function", ")", ":", "return", "_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Get the list of function arguments", "func_code", "=", "six", ".", "get_function_code", "(", "_function", ")", "function_args", "=", "func_code", ".", "co_varnames", "[", ":", "func_code", ".", "co_argcount", "]", "# Construct a dict of those kwargs which appear in the function", "filtered_kwargs", "=", "{", "}", "for", "kwarg", ",", "value", "in", "list", "(", "kwargs", ".", "items", "(", ")", ")", ":", "if", "kwarg", "in", "function_args", ":", "filtered_kwargs", "[", "kwarg", "]", "=", "value", "# Call the function with the supplied args and the filtered kwarg dict", "return", "_function", "(", "*", "args", ",", "*", "*", "filtered_kwargs", ")" ]
https://github.com/andabi/music-source-separation/blob/ba9aa531ccca08437f1efe5dec1871faebf5c840/mir_eval/util.py#L851-L879
colinskow/move37
f57afca9d15ce0233b27b2b0d6508b99b46d4c7f
rainbow_dqn/lib/doom_wrappers.py
python
ScaledFloatFrame.observation
(self, obs)
return np.array(obs).astype(np.float32) / 255.0
[]
def observation(self, obs): return np.array(obs).astype(np.float32) / 255.0
[ "def", "observation", "(", "self", ",", "obs", ")", ":", "return", "np", ".", "array", "(", "obs", ")", ".", "astype", "(", "np", ".", "float32", ")", "/", "255.0" ]
https://github.com/colinskow/move37/blob/f57afca9d15ce0233b27b2b0d6508b99b46d4c7f/rainbow_dqn/lib/doom_wrappers.py#L67-L68
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/ConfigParser.py
python
RawConfigParser.readfp
(self, fp, filename=None)
Like read() but the argument must be a file-like object. The `fp' argument must have a `readline' method. Optional second argument is the `filename', which if not given, is taken from fp.name. If fp has no `name' attribute, `<???>' is used.
Like read() but the argument must be a file-like object.
[ "Like", "read", "()", "but", "the", "argument", "must", "be", "a", "file", "-", "like", "object", "." ]
def readfp(self, fp, filename=None): """Like read() but the argument must be a file-like object. The `fp' argument must have a `readline' method. Optional second argument is the `filename', which if not given, is taken from fp.name. If fp has no `name' attribute, `<???>' is used. """ if filename is None: try: filename = fp.name except AttributeError: filename = '<???>' self._read(fp, filename)
[ "def", "readfp", "(", "self", ",", "fp", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "try", ":", "filename", "=", "fp", ".", "name", "except", "AttributeError", ":", "filename", "=", "'<???>'", "self", ".", "_read", "(", "fp", ",", "filename", ")" ]
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/ConfigParser.py#L272-L286
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/google/appengine/ext/endpoints/api_config.py
python
ApiConfigGenerator.__method_descriptor
(self, service, service_name, method_info, protorpc_method_name, protorpc_method_info)
return descriptor
Describes a method. Args: service: endpoints.Service, Implementation of the API as a service. service_name: string, Name of the service. method_info: _MethodInfo, Configuration for the method. protorpc_method_name: string, Name of the method as given in the ProtoRPC implementation. protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC description of the method. Returns: Dictionary describing the method.
Describes a method.
[ "Describes", "a", "method", "." ]
def __method_descriptor(self, service, service_name, method_info, protorpc_method_name, protorpc_method_info): """Describes a method. Args: service: endpoints.Service, Implementation of the API as a service. service_name: string, Name of the service. method_info: _MethodInfo, Configuration for the method. protorpc_method_name: string, Name of the method as given in the ProtoRPC implementation. protorpc_method_info: protorpc.remote._RemoteMethodInfo, ProtoRPC description of the method. Returns: Dictionary describing the method. """ descriptor = {} request_message_type = protorpc_method_info.remote.request_type() request_kind = self.__get_request_kind(method_info) remote_method = protorpc_method_info.remote descriptor['path'] = method_info.get_path(service.api_info) descriptor['httpMethod'] = method_info.http_method descriptor['rosyMethod'] = '%s.%s' % (service_name, protorpc_method_name) descriptor['request'] = self.__request_message_descriptor( request_kind, request_message_type, method_info.method_id(service.api_info), descriptor['path']) descriptor['response'] = self.__response_message_descriptor( remote_method.response_type(), method_info.method_id(service.api_info), method_info.cache_control) scopes = (method_info.scopes if method_info.scopes is not None else service.api_info.scopes) if scopes: descriptor['scopes'] = scopes audiences = (method_info.audiences if method_info.audiences is not None else service.api_info.audiences) if audiences: descriptor['audiences'] = audiences allowed_client_ids = (method_info.allowed_client_ids if method_info.allowed_client_ids is not None else service.api_info.allowed_client_ids) if allowed_client_ids: descriptor['clientIds'] = allowed_client_ids if remote_method.method.__doc__: descriptor['description'] = remote_method.method.__doc__ return descriptor
[ "def", "__method_descriptor", "(", "self", ",", "service", ",", "service_name", ",", "method_info", ",", "protorpc_method_name", ",", "protorpc_method_info", ")", ":", "descriptor", "=", "{", "}", "request_message_type", "=", "protorpc_method_info", ".", "remote", ".", "request_type", "(", ")", "request_kind", "=", "self", ".", "__get_request_kind", "(", "method_info", ")", "remote_method", "=", "protorpc_method_info", ".", "remote", "descriptor", "[", "'path'", "]", "=", "method_info", ".", "get_path", "(", "service", ".", "api_info", ")", "descriptor", "[", "'httpMethod'", "]", "=", "method_info", ".", "http_method", "descriptor", "[", "'rosyMethod'", "]", "=", "'%s.%s'", "%", "(", "service_name", ",", "protorpc_method_name", ")", "descriptor", "[", "'request'", "]", "=", "self", ".", "__request_message_descriptor", "(", "request_kind", ",", "request_message_type", ",", "method_info", ".", "method_id", "(", "service", ".", "api_info", ")", ",", "descriptor", "[", "'path'", "]", ")", "descriptor", "[", "'response'", "]", "=", "self", ".", "__response_message_descriptor", "(", "remote_method", ".", "response_type", "(", ")", ",", "method_info", ".", "method_id", "(", "service", ".", "api_info", ")", ",", "method_info", ".", "cache_control", ")", "scopes", "=", "(", "method_info", ".", "scopes", "if", "method_info", ".", "scopes", "is", "not", "None", "else", "service", ".", "api_info", ".", "scopes", ")", "if", "scopes", ":", "descriptor", "[", "'scopes'", "]", "=", "scopes", "audiences", "=", "(", "method_info", ".", "audiences", "if", "method_info", ".", "audiences", "is", "not", "None", "else", "service", ".", "api_info", ".", "audiences", ")", "if", "audiences", ":", "descriptor", "[", "'audiences'", "]", "=", "audiences", "allowed_client_ids", "=", "(", "method_info", ".", "allowed_client_ids", "if", "method_info", ".", "allowed_client_ids", "is", "not", "None", "else", "service", ".", "api_info", ".", "allowed_client_ids", ")", "if", "allowed_client_ids", ":", "descriptor", "[", "'clientIds'", "]", "=", "allowed_client_ids", "if", "remote_method", ".", "method", ".", "__doc__", ":", "descriptor", "[", "'description'", "]", "=", "remote_method", ".", "method", ".", "__doc__", "return", "descriptor" ]
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/google/appengine/ext/endpoints/api_config.py#L1504-L1559
Pagure/pagure
512f23f5cd1f965276969747792edeb1215cba68
pagure/lib/repo.py
python
PagureRepo.pull
(self, remote_name="origin", branch="master", force=False)
pull changes for the specified remote (defaults to origin). Code from MichaelBoselowitz at: https://github.com/MichaelBoselowitz/pygit2-examples/blob/ 68e889e50a592d30ab4105a2e7b9f28fac7324c8/examples.py#L58 licensed under the MIT license.
pull changes for the specified remote (defaults to origin).
[ "pull", "changes", "for", "the", "specified", "remote", "(", "defaults", "to", "origin", ")", "." ]
def pull(self, remote_name="origin", branch="master", force=False): """pull changes for the specified remote (defaults to origin). Code from MichaelBoselowitz at: https://github.com/MichaelBoselowitz/pygit2-examples/blob/ 68e889e50a592d30ab4105a2e7b9f28fac7324c8/examples.py#L58 licensed under the MIT license. """ for remote in self.remotes: if remote.name == remote_name: remote.fetch() remote_master_id = self.lookup_reference( "refs/remotes/origin/%s" % branch ).target if force: repo_branch = self.lookup_reference( "refs/heads/%s" % branch ) repo_branch.set_target(remote_master_id) merge_result, _ = self.merge_analysis(remote_master_id) # Up to date, do nothing if merge_result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE: return # We can just fastforward elif merge_result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD: self.checkout_tree(self.get(remote_master_id)) master_ref = self.lookup_reference( "refs/heads/%s" % branch ) master_ref.set_target(remote_master_id) self.head.set_target(remote_master_id) elif merge_result & pygit2.GIT_MERGE_ANALYSIS_NORMAL: raise pagure.exceptions.GitConflictsException( "Pulling remote changes leads to a conflict" ) else: _log.debug( "Unexpected merge result: %s" % (pygit2.GIT_MERGE_ANALYSIS_NORMAL) ) raise AssertionError("Unknown merge analysis result")
[ "def", "pull", "(", "self", ",", "remote_name", "=", "\"origin\"", ",", "branch", "=", "\"master\"", ",", "force", "=", "False", ")", ":", "for", "remote", "in", "self", ".", "remotes", ":", "if", "remote", ".", "name", "==", "remote_name", ":", "remote", ".", "fetch", "(", ")", "remote_master_id", "=", "self", ".", "lookup_reference", "(", "\"refs/remotes/origin/%s\"", "%", "branch", ")", ".", "target", "if", "force", ":", "repo_branch", "=", "self", ".", "lookup_reference", "(", "\"refs/heads/%s\"", "%", "branch", ")", "repo_branch", ".", "set_target", "(", "remote_master_id", ")", "merge_result", ",", "_", "=", "self", ".", "merge_analysis", "(", "remote_master_id", ")", "# Up to date, do nothing", "if", "merge_result", "&", "pygit2", ".", "GIT_MERGE_ANALYSIS_UP_TO_DATE", ":", "return", "# We can just fastforward", "elif", "merge_result", "&", "pygit2", ".", "GIT_MERGE_ANALYSIS_FASTFORWARD", ":", "self", ".", "checkout_tree", "(", "self", ".", "get", "(", "remote_master_id", ")", ")", "master_ref", "=", "self", ".", "lookup_reference", "(", "\"refs/heads/%s\"", "%", "branch", ")", "master_ref", ".", "set_target", "(", "remote_master_id", ")", "self", ".", "head", ".", "set_target", "(", "remote_master_id", ")", "elif", "merge_result", "&", "pygit2", ".", "GIT_MERGE_ANALYSIS_NORMAL", ":", "raise", "pagure", ".", "exceptions", ".", "GitConflictsException", "(", "\"Pulling remote changes leads to a conflict\"", ")", "else", ":", "_log", ".", "debug", "(", "\"Unexpected merge result: %s\"", "%", "(", "pygit2", ".", "GIT_MERGE_ANALYSIS_NORMAL", ")", ")", "raise", "AssertionError", "(", "\"Unknown merge analysis result\"", ")" ]
https://github.com/Pagure/pagure/blob/512f23f5cd1f965276969747792edeb1215cba68/pagure/lib/repo.py#L89-L132
carbonblack/cbapi-python
24d677ffd99aee911c2c76ecb5528e4e9320c7cc
src/cbapi/psc/alerts_query.py
python
BaseAlertSearchQuery.set_policy_names
(self, policy_names)
return self
Restricts the alerts that this query is performed on to the specified policy names. :param policy_names list: list of string policy names :return: This instance
Restricts the alerts that this query is performed on to the specified policy names.
[ "Restricts", "the", "alerts", "that", "this", "query", "is", "performed", "on", "to", "the", "specified", "policy", "names", "." ]
def set_policy_names(self, policy_names): """ Restricts the alerts that this query is performed on to the specified policy names. :param policy_names list: list of string policy names :return: This instance """ if not all(isinstance(n, str) for n in policy_names): raise ApiError("One or more invalid policy names") self._update_criteria("policy_name", policy_names) return self
[ "def", "set_policy_names", "(", "self", ",", "policy_names", ")", ":", "if", "not", "all", "(", "isinstance", "(", "n", ",", "str", ")", "for", "n", "in", "policy_names", ")", ":", "raise", "ApiError", "(", "\"One or more invalid policy names\"", ")", "self", ".", "_update_criteria", "(", "\"policy_name\"", ",", "policy_names", ")", "return", "self" ]
https://github.com/carbonblack/cbapi-python/blob/24d677ffd99aee911c2c76ecb5528e4e9320c7cc/src/cbapi/psc/alerts_query.py#L207-L218
nschloe/quadpy
c4c076d8ddfa968486a2443a95e2fb3780dcde0f
src/quadpy/t3/_xiao_gimbutas/__init__.py
python
xiao_gimbutas_11
()
return _read(this_dir / "xg11.json", source)
[]
def xiao_gimbutas_11(): return _read(this_dir / "xg11.json", source)
[ "def", "xiao_gimbutas_11", "(", ")", ":", "return", "_read", "(", "this_dir", "/", "\"xg11.json\"", ",", "source", ")" ]
https://github.com/nschloe/quadpy/blob/c4c076d8ddfa968486a2443a95e2fb3780dcde0f/src/quadpy/t3/_xiao_gimbutas/__init__.py#L64-L65
PySimpleGUI/PySimpleGUI
6c0d1fb54f493d45e90180b322fbbe70f7a5af3c
PySimpleGUI.py
python
Spin.update
(self, value=None, values=None, disabled=None, readonly=None, visible=None)
Changes some of the settings for the Spin Element. Must call `Window.Read` or `Window.Finalize` prior Note that the state can be in 3 states only.... enabled, disabled, readonly even though more combinations are available. The easy way to remember is that if you change the readonly parameter then you are enabling the element. Changes will not be visible in your window until you call window.read or window.refresh. :param value: set the current value from list of choices :type value: (Any) :param values: set available choices :type values: List[Any] :param disabled: disable. Note disabled and readonly cannot be mixed. It must be one OR the other :type disabled: (bool) :param readonly: make element readonly. Note disabled and readonly cannot be mixed. It must be one OR the other :type readonly: (bool) :param visible: control visibility of element :type visible: (bool)
Changes some of the settings for the Spin Element. Must call `Window.Read` or `Window.Finalize` prior Note that the state can be in 3 states only.... enabled, disabled, readonly even though more combinations are available. The easy way to remember is that if you change the readonly parameter then you are enabling the element. Changes will not be visible in your window until you call window.read or window.refresh. :param value: set the current value from list of choices :type value: (Any) :param values: set available choices :type values: List[Any] :param disabled: disable. Note disabled and readonly cannot be mixed. It must be one OR the other :type disabled: (bool) :param readonly: make element readonly. Note disabled and readonly cannot be mixed. It must be one OR the other :type readonly: (bool) :param visible: control visibility of element :type visible: (bool)
[ "Changes", "some", "of", "the", "settings", "for", "the", "Spin", "Element", ".", "Must", "call", "Window", ".", "Read", "or", "Window", ".", "Finalize", "prior", "Note", "that", "the", "state", "can", "be", "in", "3", "states", "only", "....", "enabled", "disabled", "readonly", "even", "though", "more", "combinations", "are", "available", ".", "The", "easy", "way", "to", "remember", "is", "that", "if", "you", "change", "the", "readonly", "parameter", "then", "you", "are", "enabling", "the", "element", ".", "Changes", "will", "not", "be", "visible", "in", "your", "window", "until", "you", "call", "window", ".", "read", "or", "window", ".", "refresh", ".", ":", "param", "value", ":", "set", "the", "current", "value", "from", "list", "of", "choices", ":", "type", "value", ":", "(", "Any", ")", ":", "param", "values", ":", "set", "available", "choices", ":", "type", "values", ":", "List", "[", "Any", "]", ":", "param", "disabled", ":", "disable", ".", "Note", "disabled", "and", "readonly", "cannot", "be", "mixed", ".", "It", "must", "be", "one", "OR", "the", "other", ":", "type", "disabled", ":", "(", "bool", ")", ":", "param", "readonly", ":", "make", "element", "readonly", ".", "Note", "disabled", "and", "readonly", "cannot", "be", "mixed", ".", "It", "must", "be", "one", "OR", "the", "other", ":", "type", "readonly", ":", "(", "bool", ")", ":", "param", "visible", ":", "control", "visibility", "of", "element", ":", "type", "visible", ":", "(", "bool", ")" ]
def update(self, value=None, values=None, disabled=None, readonly=None, visible=None): """ Changes some of the settings for the Spin Element. Must call `Window.Read` or `Window.Finalize` prior Note that the state can be in 3 states only.... enabled, disabled, readonly even though more combinations are available. The easy way to remember is that if you change the readonly parameter then you are enabling the element. Changes will not be visible in your window until you call window.read or window.refresh. :param value: set the current value from list of choices :type value: (Any) :param values: set available choices :type values: List[Any] :param disabled: disable. Note disabled and readonly cannot be mixed. It must be one OR the other :type disabled: (bool) :param readonly: make element readonly. Note disabled and readonly cannot be mixed. It must be one OR the other :type readonly: (bool) :param visible: control visibility of element :type visible: (bool) """ if not self._widget_was_created(): # if widget hasn't been created yet, then don't allow return if values != None: old_value = self.TKStringVar.get() self.Values = values self.TKSpinBox.configure(values=values) self.TKStringVar.set(old_value) if value is not None: try: self.TKStringVar.set(value) self.DefaultValue = value except: pass if readonly is True: self.Readonly = True self.TKSpinBox['state'] = 'readonly' elif readonly is False: self.Readonly = False self.TKSpinBox['state'] = 'normal' if disabled is True: self.TKSpinBox['state'] = 'disable' elif disabled is False: if self.Readonly: self.TKSpinBox['state'] = 'readonly' else: self.TKSpinBox['state'] = 'normal' if visible is False: self.TKSpinBox.pack_forget() elif visible is True: self.TKSpinBox.pack(padx=self.pad_used[0], pady=self.pad_used[1]) if visible is not None: self._visible = visible
[ "def", "update", "(", "self", ",", "value", "=", "None", ",", "values", "=", "None", ",", "disabled", "=", "None", ",", "readonly", "=", "None", ",", "visible", "=", "None", ")", ":", "if", "not", "self", ".", "_widget_was_created", "(", ")", ":", "# if widget hasn't been created yet, then don't allow", "return", "if", "values", "!=", "None", ":", "old_value", "=", "self", ".", "TKStringVar", ".", "get", "(", ")", "self", ".", "Values", "=", "values", "self", ".", "TKSpinBox", ".", "configure", "(", "values", "=", "values", ")", "self", ".", "TKStringVar", ".", "set", "(", "old_value", ")", "if", "value", "is", "not", "None", ":", "try", ":", "self", ".", "TKStringVar", ".", "set", "(", "value", ")", "self", ".", "DefaultValue", "=", "value", "except", ":", "pass", "if", "readonly", "is", "True", ":", "self", ".", "Readonly", "=", "True", "self", ".", "TKSpinBox", "[", "'state'", "]", "=", "'readonly'", "elif", "readonly", "is", "False", ":", "self", ".", "Readonly", "=", "False", "self", ".", "TKSpinBox", "[", "'state'", "]", "=", "'normal'", "if", "disabled", "is", "True", ":", "self", ".", "TKSpinBox", "[", "'state'", "]", "=", "'disable'", "elif", "disabled", "is", "False", ":", "if", "self", ".", "Readonly", ":", "self", ".", "TKSpinBox", "[", "'state'", "]", "=", "'readonly'", "else", ":", "self", ".", "TKSpinBox", "[", "'state'", "]", "=", "'normal'", "if", "visible", "is", "False", ":", "self", ".", "TKSpinBox", ".", "pack_forget", "(", ")", "elif", "visible", "is", "True", ":", "self", ".", "TKSpinBox", ".", "pack", "(", "padx", "=", "self", ".", "pad_used", "[", "0", "]", ",", "pady", "=", "self", ".", "pad_used", "[", "1", "]", ")", "if", "visible", "is", "not", "None", ":", "self", ".", "_visible", "=", "visible" ]
https://github.com/PySimpleGUI/PySimpleGUI/blob/6c0d1fb54f493d45e90180b322fbbe70f7a5af3c/PySimpleGUI.py#L2784-L2837
princewang1994/TextSnake.pytorch
b4ee996d5a4d214ed825350d6b307dd1c31faa07
demo.py
python
write_to_file
(contours, file_path)
:param contours: [[x1, y1], [x2, y2]... [xn, yn]] :param file_path: target file path
:param contours: [[x1, y1], [x2, y2]... [xn, yn]] :param file_path: target file path
[ ":", "param", "contours", ":", "[[", "x1", "y1", "]", "[", "x2", "y2", "]", "...", "[", "xn", "yn", "]]", ":", "param", "file_path", ":", "target", "file", "path" ]
def write_to_file(contours, file_path): """ :param contours: [[x1, y1], [x2, y2]... [xn, yn]] :param file_path: target file path """ # according to total-text evaluation method, output file shoud be formatted to: y0,x0, ..... yn,xn with open(file_path, 'w') as f: for cont in contours: cont = np.stack([cont[:, 1], cont[:, 0]], 1) cont = cont.flatten().astype(str).tolist() cont = ','.join(cont) f.write(cont + '\n')
[ "def", "write_to_file", "(", "contours", ",", "file_path", ")", ":", "# according to total-text evaluation method, output file shoud be formatted to: y0,x0, ..... yn,xn", "with", "open", "(", "file_path", ",", "'w'", ")", "as", "f", ":", "for", "cont", "in", "contours", ":", "cont", "=", "np", ".", "stack", "(", "[", "cont", "[", ":", ",", "1", "]", ",", "cont", "[", ":", ",", "0", "]", "]", ",", "1", ")", "cont", "=", "cont", ".", "flatten", "(", ")", ".", "astype", "(", "str", ")", ".", "tolist", "(", ")", "cont", "=", "','", ".", "join", "(", "cont", ")", "f", ".", "write", "(", "cont", "+", "'\\n'", ")" ]
https://github.com/princewang1994/TextSnake.pytorch/blob/b4ee996d5a4d214ed825350d6b307dd1c31faa07/demo.py#L18-L29
hunkim/ReinforcementZeroToAll
276e950a95c006666f1a34362dfd40ef4264ffbb
10_2_A3C_threads.py
python
pipeline
(image, new_HW=(80, 80), height_range=(35, 193), bg=(144, 72, 17))
return image
Returns a preprocessed image (1) Crop image (top and bottom) (2) Remove background & grayscale (3) Reszie to smaller image Args: image (3-D array): (H, W, C) new_HW (tuple): New image size (height, width) height_range (tuple): Height range (H_begin, H_end) else cropped bg (tuple): Background RGB Color (R, G, B) Returns: image (3-D array): (H, W, 1)
Returns a preprocessed image
[ "Returns", "a", "preprocessed", "image" ]
def pipeline(image, new_HW=(80, 80), height_range=(35, 193), bg=(144, 72, 17)): """Returns a preprocessed image (1) Crop image (top and bottom) (2) Remove background & grayscale (3) Reszie to smaller image Args: image (3-D array): (H, W, C) new_HW (tuple): New image size (height, width) height_range (tuple): Height range (H_begin, H_end) else cropped bg (tuple): Background RGB Color (R, G, B) Returns: image (3-D array): (H, W, 1) """ image = crop_image(image, height_range) image = resize_image(image, new_HW) image = kill_background_grayscale(image, bg) image = np.expand_dims(image, axis=2) return image
[ "def", "pipeline", "(", "image", ",", "new_HW", "=", "(", "80", ",", "80", ")", ",", "height_range", "=", "(", "35", ",", "193", ")", ",", "bg", "=", "(", "144", ",", "72", ",", "17", ")", ")", ":", "image", "=", "crop_image", "(", "image", ",", "height_range", ")", "image", "=", "resize_image", "(", "image", ",", "new_HW", ")", "image", "=", "kill_background_grayscale", "(", "image", ",", "bg", ")", "image", "=", "np", ".", "expand_dims", "(", "image", ",", "axis", "=", "2", ")", "return", "image" ]
https://github.com/hunkim/ReinforcementZeroToAll/blob/276e950a95c006666f1a34362dfd40ef4264ffbb/10_2_A3C_threads.py#L37-L58
napalm-automation/napalm-logs
573beee426f5f2bbbc988e432ee6b5c80457fffa
napalm_logs/transport/prometheus.py
python
PrometheusTransport.__parse_minor_major_alarm
(self, msg)
Build metrics for MINOR_ALARM_* and MAJOR_ALARM_* notifications.
Build metrics for MINOR_ALARM_* and MAJOR_ALARM_* notifications.
[ "Build", "metrics", "for", "MINOR_ALARM_", "*", "and", "MAJOR_ALARM_", "*", "notifications", "." ]
def __parse_minor_major_alarm(self, msg): ''' Build metrics for MINOR_ALARM_* and MAJOR_ALARM_* notifications. ''' error = msg['error'] if error not in self.metrics: self.metrics[error] = Counter( 'napalm_logs_{error}'.format(error=error.lower()), 'Counter for {error} notifications'.format(error=error), ['host', 'alarm_reason'], ) severity = error.split('_')[0].lower() alarm_state_metric = '{}_alarm_state'.format(severity) if alarm_state_metric not in self.metrics: self.metrics[alarm_state_metric] = Gauge( 'napalm_logs_{}'.format(alarm_state_metric), 'State of the {} system alarm. 1=SET, 0=CLEARED'.format(severity), ['host', 'alarm_reason'], ) labels = { 'host': msg['host'], 'alarm_reason': msg['yang_message']['alarms']['alarm']['additional-text'], } self.metrics[error].labels(**labels).inc() state = 1 if error == '{}_ALARM_SET'.format(severity.upper()) else 0 self.metrics[alarm_state_metric].labels(**labels).set(state)
[ "def", "__parse_minor_major_alarm", "(", "self", ",", "msg", ")", ":", "error", "=", "msg", "[", "'error'", "]", "if", "error", "not", "in", "self", ".", "metrics", ":", "self", ".", "metrics", "[", "error", "]", "=", "Counter", "(", "'napalm_logs_{error}'", ".", "format", "(", "error", "=", "error", ".", "lower", "(", ")", ")", ",", "'Counter for {error} notifications'", ".", "format", "(", "error", "=", "error", ")", ",", "[", "'host'", ",", "'alarm_reason'", "]", ",", ")", "severity", "=", "error", ".", "split", "(", "'_'", ")", "[", "0", "]", ".", "lower", "(", ")", "alarm_state_metric", "=", "'{}_alarm_state'", ".", "format", "(", "severity", ")", "if", "alarm_state_metric", "not", "in", "self", ".", "metrics", ":", "self", ".", "metrics", "[", "alarm_state_metric", "]", "=", "Gauge", "(", "'napalm_logs_{}'", ".", "format", "(", "alarm_state_metric", ")", ",", "'State of the {} system alarm. 1=SET, 0=CLEARED'", ".", "format", "(", "severity", ")", ",", "[", "'host'", ",", "'alarm_reason'", "]", ",", ")", "labels", "=", "{", "'host'", ":", "msg", "[", "'host'", "]", ",", "'alarm_reason'", ":", "msg", "[", "'yang_message'", "]", "[", "'alarms'", "]", "[", "'alarm'", "]", "[", "'additional-text'", "]", ",", "}", "self", ".", "metrics", "[", "error", "]", ".", "labels", "(", "*", "*", "labels", ")", ".", "inc", "(", ")", "state", "=", "1", "if", "error", "==", "'{}_ALARM_SET'", ".", "format", "(", "severity", ".", "upper", "(", ")", ")", "else", "0", "self", ".", "metrics", "[", "alarm_state_metric", "]", ".", "labels", "(", "*", "*", "labels", ")", ".", "set", "(", "state", ")" ]
https://github.com/napalm-automation/napalm-logs/blob/573beee426f5f2bbbc988e432ee6b5c80457fffa/napalm_logs/transport/prometheus.py#L489-L514
awslabs/aws-ec2rescue-linux
8ecf40e7ea0d2563dac057235803fca2221029d2
lib/boto3/session.py
python
Session.available_profiles
(self)
return self._session.available_profiles
The profiles available to the session credentials
The profiles available to the session credentials
[ "The", "profiles", "available", "to", "the", "session", "credentials" ]
def available_profiles(self): """ The profiles available to the session credentials """ return self._session.available_profiles
[ "def", "available_profiles", "(", "self", ")", ":", "return", "self", ".", "_session", ".", "available_profiles" ]
https://github.com/awslabs/aws-ec2rescue-linux/blob/8ecf40e7ea0d2563dac057235803fca2221029d2/lib/boto3/session.py#L110-L114
chrthomsen/pygrametl
eec60ee6c6b58c2f6be798128bebe991928fe41b
pygrametl/steps.py
python
RenamingFromToStep.__init__
(self, renaming, next=None, name=None)
Arguments: - name: A name for the Step instance. This is used when another Step (implicitly or explicitly) passes on rows. If two instanes have the same name, the name is mapped to the instance that was created the latest. Default: None - renaming: A dict with pairs (oldname, newname) which will by used by pygrametl.renamefromto to do the renaming - next: The default next step to use. This should be 1) an instance of a Step, 2) the name of a Step, or 3) None. If if is a name, the next step will be looked up dynamically each time. If it is None, no default step will exist and rows will not be passed on. Default: None - name: A name for the Step instance. This is used when another Step (implicitly or explicitly) passes on rows. If two instanes have the same name, the name is mapped to the instance that was created the latest. Default: None
Arguments:
[ "Arguments", ":" ]
def __init__(self, renaming, next=None, name=None): """Arguments: - name: A name for the Step instance. This is used when another Step (implicitly or explicitly) passes on rows. If two instanes have the same name, the name is mapped to the instance that was created the latest. Default: None - renaming: A dict with pairs (oldname, newname) which will by used by pygrametl.renamefromto to do the renaming - next: The default next step to use. This should be 1) an instance of a Step, 2) the name of a Step, or 3) None. If if is a name, the next step will be looked up dynamically each time. If it is None, no default step will exist and rows will not be passed on. Default: None - name: A name for the Step instance. This is used when another Step (implicitly or explicitly) passes on rows. If two instanes have the same name, the name is mapped to the instance that was created the latest. Default: None """ Step.__init__(self, worker=None, next=next, name=name) self.renaming = renaming
[ "def", "__init__", "(", "self", ",", "renaming", ",", "next", "=", "None", ",", "name", "=", "None", ")", ":", "Step", ".", "__init__", "(", "self", ",", "worker", "=", "None", ",", "next", "=", "next", ",", "name", "=", "name", ")", "self", ".", "renaming", "=", "renaming" ]
https://github.com/chrthomsen/pygrametl/blob/eec60ee6c6b58c2f6be798128bebe991928fe41b/pygrametl/steps.py#L326-L346
twilio/twilio-python
6e1e811ea57a1edfadd5161ace87397c563f6915
twilio/rest/api/v2010/account/call/__init__.py
python
CallInstance.annotation
(self)
return self._properties['annotation']
:returns: The annotation provided for the call :rtype: unicode
:returns: The annotation provided for the call :rtype: unicode
[ ":", "returns", ":", "The", "annotation", "provided", "for", "the", "call", ":", "rtype", ":", "unicode" ]
def annotation(self): """ :returns: The annotation provided for the call :rtype: unicode """ return self._properties['annotation']
[ "def", "annotation", "(", "self", ")", ":", "return", "self", ".", "_properties", "[", "'annotation'", "]" ]
https://github.com/twilio/twilio-python/blob/6e1e811ea57a1edfadd5161ace87397c563f6915/twilio/rest/api/v2010/account/call/__init__.py#L826-L831
lazyprogrammer/machine_learning_examples
8c022d46763ab09b4b4e0e32e8960a470093c162
rl3/a2c/atari_wrappers.py
python
NoopResetEnv.__init__
(self, env, noop_max=30)
Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0.
[ "Sample", "initial", "states", "by", "taking", "random", "number", "of", "no", "-", "ops", "on", "reset", ".", "No", "-", "op", "is", "assumed", "to", "be", "action", "0", "." ]
def __init__(self, env, noop_max=30): """Sample initial states by taking random number of no-ops on reset. No-op is assumed to be action 0. """ gym.Wrapper.__init__(self, env) self.noop_max = noop_max self.override_num_noops = None self.noop_action = 0 assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
[ "def", "__init__", "(", "self", ",", "env", ",", "noop_max", "=", "30", ")", ":", "gym", ".", "Wrapper", ".", "__init__", "(", "self", ",", "env", ")", "self", ".", "noop_max", "=", "noop_max", "self", ".", "override_num_noops", "=", "None", "self", ".", "noop_action", "=", "0", "assert", "env", ".", "unwrapped", ".", "get_action_meanings", "(", ")", "[", "0", "]", "==", "'NOOP'" ]
https://github.com/lazyprogrammer/machine_learning_examples/blob/8c022d46763ab09b4b4e0e32e8960a470093c162/rl3/a2c/atari_wrappers.py#L10-L18
nate-parrott/Flashlight
c3a7c7278a1cccf8918e7543faffc68e863ff5ab
flashlightsearchrelay/requests/cookies.py
python
RequestsCookieJar._find
(self, name, domain=None, path=None)
Requests uses this method internally to get cookie values. Takes as args name and optional domain and path. Returns a cookie.value. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies.
Requests uses this method internally to get cookie values. Takes as args name and optional domain and path. Returns a cookie.value. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies.
[ "Requests", "uses", "this", "method", "internally", "to", "get", "cookie", "values", ".", "Takes", "as", "args", "name", "and", "optional", "domain", "and", "path", ".", "Returns", "a", "cookie", ".", "value", ".", "If", "there", "are", "conflicting", "cookies", "_find", "arbitrarily", "chooses", "one", ".", "See", "_find_no_duplicates", "if", "you", "want", "an", "exception", "thrown", "if", "there", "are", "conflicting", "cookies", "." ]
def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. Takes as args name and optional domain and path. Returns a cookie.value. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies.""" 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", "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", ")", ")" ]
https://github.com/nate-parrott/Flashlight/blob/c3a7c7278a1cccf8918e7543faffc68e863ff5ab/flashlightsearchrelay/requests/cookies.py#L293-L304
thinkle/gourmet
8af29c8ded24528030e5ae2ea3461f61c1e5a575
gourmet/plugins/browse_recipes/browser.py
python
try_out
()
[]
def try_out (): import gourmet.recipeManager rb = RecipeBrowser(gourmet.recipeManager.get_recipe_manager()) vb = Gtk.VBox() vb.pack_start(rb, True, True, 0) rb.show() w = Gtk.Window() w.add(vb) w.show(); vb.show() w.set_size_request(800,500) w.connect('delete-event',Gtk.main_quit) Gtk.main()
[ "def", "try_out", "(", ")", ":", "import", "gourmet", ".", "recipeManager", "rb", "=", "RecipeBrowser", "(", "gourmet", ".", "recipeManager", ".", "get_recipe_manager", "(", ")", ")", "vb", "=", "Gtk", ".", "VBox", "(", ")", "vb", ".", "pack_start", "(", "rb", ",", "True", ",", "True", ",", "0", ")", "rb", ".", "show", "(", ")", "w", "=", "Gtk", ".", "Window", "(", ")", "w", ".", "add", "(", "vb", ")", "w", ".", "show", "(", ")", "vb", ".", "show", "(", ")", "w", ".", "set_size_request", "(", "800", ",", "500", ")", "w", ".", "connect", "(", "'delete-event'", ",", "Gtk", ".", "main_quit", ")", "Gtk", ".", "main", "(", ")" ]
https://github.com/thinkle/gourmet/blob/8af29c8ded24528030e5ae2ea3461f61c1e5a575/gourmet/plugins/browse_recipes/browser.py#L239-L250
akanimax/Variational_Discriminator_Bottleneck
26a39ddbf9ee2213dbc1b60894a9092b1a5d3710
source/generate_loss_plots.py
python
plot_loss
(*loss_vals, plot_name="Loss plot", fig_size=(17, 7), save_path=None, legends=("discriminator", "bottleneck", "generator"))
plot the discriminator loss values and save the plot if required :param loss_vals: (Variable Arg) numpy array or Sequence like for plotting values :param plot_name: Name of the plot :param fig_size: size of the generated figure (column_width, row_width) :param save_path: path to save the figure :param legends: list containing labels for loss plots' legends len(legends) == len(loss_vals) :return:
plot the discriminator loss values and save the plot if required :param loss_vals: (Variable Arg) numpy array or Sequence like for plotting values :param plot_name: Name of the plot :param fig_size: size of the generated figure (column_width, row_width) :param save_path: path to save the figure :param legends: list containing labels for loss plots' legends len(legends) == len(loss_vals) :return:
[ "plot", "the", "discriminator", "loss", "values", "and", "save", "the", "plot", "if", "required", ":", "param", "loss_vals", ":", "(", "Variable", "Arg", ")", "numpy", "array", "or", "Sequence", "like", "for", "plotting", "values", ":", "param", "plot_name", ":", "Name", "of", "the", "plot", ":", "param", "fig_size", ":", "size", "of", "the", "generated", "figure", "(", "column_width", "row_width", ")", ":", "param", "save_path", ":", "path", "to", "save", "the", "figure", ":", "param", "legends", ":", "list", "containing", "labels", "for", "loss", "plots", "legends", "len", "(", "legends", ")", "==", "len", "(", "loss_vals", ")", ":", "return", ":" ]
def plot_loss(*loss_vals, plot_name="Loss plot", fig_size=(17, 7), save_path=None, legends=("discriminator", "bottleneck", "generator")): """ plot the discriminator loss values and save the plot if required :param loss_vals: (Variable Arg) numpy array or Sequence like for plotting values :param plot_name: Name of the plot :param fig_size: size of the generated figure (column_width, row_width) :param save_path: path to save the figure :param legends: list containing labels for loss plots' legends len(legends) == len(loss_vals) :return: """ assert len(loss_vals) == len(legends), "Not enough labels for legends" plt.figure(figsize=fig_size).suptitle(plot_name) plt.grid(True, which="both") plt.ylabel("loss value") plt.xlabel("spaced iterations") plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') # plot all the provided loss values in a single plot plts = [] for loss_val in loss_vals: plts.append(plt.plot(loss_val)[0]) plt.legend(plts, legends, loc="upper right", fontsize=16) if save_path is not None: plt.savefig(save_path)
[ "def", "plot_loss", "(", "*", "loss_vals", ",", "plot_name", "=", "\"Loss plot\"", ",", "fig_size", "=", "(", "17", ",", "7", ")", ",", "save_path", "=", "None", ",", "legends", "=", "(", "\"discriminator\"", ",", "\"bottleneck\"", ",", "\"generator\"", ")", ")", ":", "assert", "len", "(", "loss_vals", ")", "==", "len", "(", "legends", ")", ",", "\"Not enough labels for legends\"", "plt", ".", "figure", "(", "figsize", "=", "fig_size", ")", ".", "suptitle", "(", "plot_name", ")", "plt", ".", "grid", "(", "True", ",", "which", "=", "\"both\"", ")", "plt", ".", "ylabel", "(", "\"loss value\"", ")", "plt", ".", "xlabel", "(", "\"spaced iterations\"", ")", "plt", ".", "axhline", "(", "y", "=", "0", ",", "color", "=", "'k'", ")", "plt", ".", "axvline", "(", "x", "=", "0", ",", "color", "=", "'k'", ")", "# plot all the provided loss values in a single plot", "plts", "=", "[", "]", "for", "loss_val", "in", "loss_vals", ":", "plts", ".", "append", "(", "plt", ".", "plot", "(", "loss_val", ")", "[", "0", "]", ")", "plt", ".", "legend", "(", "plts", ",", "legends", ",", "loc", "=", "\"upper right\"", ",", "fontsize", "=", "16", ")", "if", "save_path", "is", "not", "None", ":", "plt", ".", "savefig", "(", "save_path", ")" ]
https://github.com/akanimax/Variational_Discriminator_Bottleneck/blob/26a39ddbf9ee2213dbc1b60894a9092b1a5d3710/source/generate_loss_plots.py#L19-L50
lunixbochs/ActualVim
1f555ce719e49d6584f0e35e9f0db2f216b98fa5
lib/asyncio/sslproto.py
python
_SSLPipe.ssl_object
(self)
return self._sslobj
The internal ssl.SSLObject instance. Return None if the pipe is not wrapped.
The internal ssl.SSLObject instance.
[ "The", "internal", "ssl", ".", "SSLObject", "instance", "." ]
def ssl_object(self): """The internal ssl.SSLObject instance. Return None if the pipe is not wrapped. """ return self._sslobj
[ "def", "ssl_object", "(", "self", ")", ":", "return", "self", ".", "_sslobj" ]
https://github.com/lunixbochs/ActualVim/blob/1f555ce719e49d6584f0e35e9f0db2f216b98fa5/lib/asyncio/sslproto.py#L96-L101
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/utils/timezone.py
python
activate
(timezone)
Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. If it is a time zone name, pytz is required.
Sets the time zone for the current thread.
[ "Sets", "the", "time", "zone", "for", "the", "current", "thread", "." ]
def activate(timezone): """ Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. If it is a time zone name, pytz is required. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, six.string_types) and pytz is not None: _active.value = pytz.timezone(timezone) else: raise ValueError("Invalid timezone: %r" % timezone)
[ "def", "activate", "(", "timezone", ")", ":", "if", "isinstance", "(", "timezone", ",", "tzinfo", ")", ":", "_active", ".", "value", "=", "timezone", "elif", "isinstance", "(", "timezone", ",", "six", ".", "string_types", ")", "and", "pytz", "is", "not", "None", ":", "_active", ".", "value", "=", "pytz", ".", "timezone", "(", "timezone", ")", "else", ":", "raise", "ValueError", "(", "\"Invalid timezone: %r\"", "%", "timezone", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/utils/timezone.py#L156-L168
Edinburgh-Genome-Foundry/Flametree
a189de5d83ca1eb3526a439320e41df9e2a1162e
flametree/DiskFileManager.py
python
DiskFileManager.list_directory_content
(directory, element_type="file")
return ( [] if not os.path.exists(path) else [name for name in os.listdir(path) if filtr(os.path.join(path, name))] )
Return the list of all file or dir objects in the directory.
Return the list of all file or dir objects in the directory.
[ "Return", "the", "list", "of", "all", "file", "or", "dir", "objects", "in", "the", "directory", "." ]
def list_directory_content(directory, element_type="file"): """Return the list of all file or dir objects in the directory.""" filtr = os.path.isfile if (element_type == "file") else os.path.isdir path = directory._path return ( [] if not os.path.exists(path) else [name for name in os.listdir(path) if filtr(os.path.join(path, name))] )
[ "def", "list_directory_content", "(", "directory", ",", "element_type", "=", "\"file\"", ")", ":", "filtr", "=", "os", ".", "path", ".", "isfile", "if", "(", "element_type", "==", "\"file\"", ")", "else", "os", ".", "path", ".", "isdir", "path", "=", "directory", ".", "_path", "return", "(", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", "else", "[", "name", "for", "name", "in", "os", ".", "listdir", "(", "path", ")", "if", "filtr", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ")", "]", ")" ]
https://github.com/Edinburgh-Genome-Foundry/Flametree/blob/a189de5d83ca1eb3526a439320e41df9e2a1162e/flametree/DiskFileManager.py#L25-L33
TechXueXi/TechXueXi
8c5909fdfc35307180571338c11464e1401d37c3
SourcePackages/webserverListener.py
python
create_db
()
创建表格、插入数据
创建表格、插入数据
[ "创建表格、插入数据" ]
def create_db(): '创建表格、插入数据' # Recreate database each time for demo web_db.drop_all() web_db.create_all()
[ "def", "create_db", "(", ")", ":", "# Recreate database each time for demo", "web_db", ".", "drop_all", "(", ")", "web_db", ".", "create_all", "(", ")" ]
https://github.com/TechXueXi/TechXueXi/blob/8c5909fdfc35307180571338c11464e1401d37c3/SourcePackages/webserverListener.py#L17-L21
PyMVPA/PyMVPA
76c476b3de8264b0bb849bf226da5674d659564e
mvpa2/support/nibabel/surf.py
python
Surface.__mul__
(self, other)
return Surface(v=self._v * other, f=self.faces, check=False)
coordinate-wise scaling
coordinate-wise scaling
[ "coordinate", "-", "wise", "scaling" ]
def __mul__(self, other): '''coordinate-wise scaling''' return Surface(v=self._v * other, f=self.faces, check=False)
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "return", "Surface", "(", "v", "=", "self", ".", "_v", "*", "other", ",", "f", "=", "self", ".", "faces", ",", "check", "=", "False", ")" ]
https://github.com/PyMVPA/PyMVPA/blob/76c476b3de8264b0bb849bf226da5674d659564e/mvpa2/support/nibabel/surf.py#L995-L997
Tautulli/Tautulli
2410eb33805aaac4bd1c5dad0f71e4f15afaf742
lib/future/builtins/newnext.py
python
newnext
(iterator, default=_SENTINEL)
next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
next(iterator[, default])
[ "next", "(", "iterator", "[", "default", "]", ")" ]
def newnext(iterator, default=_SENTINEL): """ next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. """ # args = [] # if default is not _SENTINEL: # args.append(default) try: try: return iterator.__next__() except AttributeError: try: return iterator.next() except AttributeError: raise TypeError("'{0}' object is not an iterator".format( iterator.__class__.__name__)) except StopIteration as e: if default is _SENTINEL: raise e else: return default
[ "def", "newnext", "(", "iterator", ",", "default", "=", "_SENTINEL", ")", ":", "# args = []", "# if default is not _SENTINEL:", "# args.append(default)", "try", ":", "try", ":", "return", "iterator", ".", "__next__", "(", ")", "except", "AttributeError", ":", "try", ":", "return", "iterator", ".", "next", "(", ")", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"'{0}' object is not an iterator\"", ".", "format", "(", "iterator", ".", "__class__", ".", "__name__", ")", ")", "except", "StopIteration", "as", "e", ":", "if", "default", "is", "_SENTINEL", ":", "raise", "e", "else", ":", "return", "default" ]
https://github.com/Tautulli/Tautulli/blob/2410eb33805aaac4bd1c5dad0f71e4f15afaf742/lib/future/builtins/newnext.py#L43-L67
flyyufelix/cnn_finetune
cba343987d8a1dc1dfae240afa298e11898e1a3f
inception_v4.py
python
inception_v4_model
(img_rows, img_cols, color_type=1, num_classeses=None, dropout_keep_prob=0.2)
return model
Inception V4 Model for Keras Model Schema is based on https://github.com/kentsommer/keras-inceptionV4 ImageNet Pretrained Weights Theano: https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_th_dim_ordering_th_kernels.h5 TensorFlow: https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_tf_dim_ordering_tf_kernels.h5 Parameters: img_rows, img_cols - resolution of inputs channel - 1 for grayscale, 3 for color num_classes - number of class labels for our classification task
Inception V4 Model for Keras
[ "Inception", "V4", "Model", "for", "Keras" ]
def inception_v4_model(img_rows, img_cols, color_type=1, num_classeses=None, dropout_keep_prob=0.2): ''' Inception V4 Model for Keras Model Schema is based on https://github.com/kentsommer/keras-inceptionV4 ImageNet Pretrained Weights Theano: https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_th_dim_ordering_th_kernels.h5 TensorFlow: https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_tf_dim_ordering_tf_kernels.h5 Parameters: img_rows, img_cols - resolution of inputs channel - 1 for grayscale, 3 for color num_classes - number of class labels for our classification task ''' # Input Shape is 299 x 299 x 3 (tf) or 3 x 299 x 299 (th) if K.image_dim_ordering() == 'th': inputs = Input((3, 299, 299)) else: inputs = Input((299, 299, 3)) # Make inception base net = inception_v4_base(inputs) # Final pooling and prediction # 8 x 8 x 1536 net_old = AveragePooling2D((8,8), border_mode='valid')(net) # 1 x 1 x 1536 net_old = Dropout(dropout_keep_prob)(net_old) net_old = Flatten()(net_old) # 1536 predictions = Dense(output_dim=1001, activation='softmax')(net_old) model = Model(inputs, predictions, name='inception_v4') if K.image_dim_ordering() == 'th': # Use pre-trained weights for Theano backend weights_path = 'imagenet_models/inception-v4_weights_th_dim_ordering_th_kernels.h5' else: # Use pre-trained weights for Tensorflow backend weights_path = 'imagenet_models/inception-v4_weights_tf_dim_ordering_tf_kernels.h5' model.load_weights(weights_path, by_name=True) # Truncate and replace softmax layer for transfer learning # Cannot use model.layers.pop() since model is not of Sequential() type # The method below works since pre-trained weights are stored in layers but not in the model net_ft = AveragePooling2D((8,8), border_mode='valid')(net) net_ft = Dropout(dropout_keep_prob)(net_ft) net_ft = Flatten()(net_ft) predictions_ft = Dense(output_dim=num_classes, activation='softmax')(net_ft) model = Model(inputs, predictions_ft, name='inception_v4') # Learning rate is changed to 0.001 sgd = SGD(lr=1e-3, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy']) return model
[ "def", "inception_v4_model", "(", "img_rows", ",", "img_cols", ",", "color_type", "=", "1", ",", "num_classeses", "=", "None", ",", "dropout_keep_prob", "=", "0.2", ")", ":", "# Input Shape is 299 x 299 x 3 (tf) or 3 x 299 x 299 (th)", "if", "K", ".", "image_dim_ordering", "(", ")", "==", "'th'", ":", "inputs", "=", "Input", "(", "(", "3", ",", "299", ",", "299", ")", ")", "else", ":", "inputs", "=", "Input", "(", "(", "299", ",", "299", ",", "3", ")", ")", "# Make inception base", "net", "=", "inception_v4_base", "(", "inputs", ")", "# Final pooling and prediction", "# 8 x 8 x 1536", "net_old", "=", "AveragePooling2D", "(", "(", "8", ",", "8", ")", ",", "border_mode", "=", "'valid'", ")", "(", "net", ")", "# 1 x 1 x 1536", "net_old", "=", "Dropout", "(", "dropout_keep_prob", ")", "(", "net_old", ")", "net_old", "=", "Flatten", "(", ")", "(", "net_old", ")", "# 1536", "predictions", "=", "Dense", "(", "output_dim", "=", "1001", ",", "activation", "=", "'softmax'", ")", "(", "net_old", ")", "model", "=", "Model", "(", "inputs", ",", "predictions", ",", "name", "=", "'inception_v4'", ")", "if", "K", ".", "image_dim_ordering", "(", ")", "==", "'th'", ":", "# Use pre-trained weights for Theano backend", "weights_path", "=", "'imagenet_models/inception-v4_weights_th_dim_ordering_th_kernels.h5'", "else", ":", "# Use pre-trained weights for Tensorflow backend", "weights_path", "=", "'imagenet_models/inception-v4_weights_tf_dim_ordering_tf_kernels.h5'", "model", ".", "load_weights", "(", "weights_path", ",", "by_name", "=", "True", ")", "# Truncate and replace softmax layer for transfer learning", "# Cannot use model.layers.pop() since model is not of Sequential() type", "# The method below works since pre-trained weights are stored in layers but not in the model", "net_ft", "=", "AveragePooling2D", "(", "(", "8", ",", "8", ")", ",", "border_mode", "=", "'valid'", ")", "(", "net", ")", "net_ft", "=", "Dropout", "(", "dropout_keep_prob", ")", "(", "net_ft", ")", "net_ft", "=", "Flatten", "(", ")", "(", "net_ft", ")", "predictions_ft", "=", "Dense", "(", "output_dim", "=", "num_classes", ",", "activation", "=", "'softmax'", ")", "(", "net_ft", ")", "model", "=", "Model", "(", "inputs", ",", "predictions_ft", ",", "name", "=", "'inception_v4'", ")", "# Learning rate is changed to 0.001", "sgd", "=", "SGD", "(", "lr", "=", "1e-3", ",", "decay", "=", "1e-6", ",", "momentum", "=", "0.9", ",", "nesterov", "=", "True", ")", "model", ".", "compile", "(", "optimizer", "=", "sgd", ",", "loss", "=", "'categorical_crossentropy'", ",", "metrics", "=", "[", "'accuracy'", "]", ")", "return", "model" ]
https://github.com/flyyufelix/cnn_finetune/blob/cba343987d8a1dc1dfae240afa298e11898e1a3f/inception_v4.py#L203-L267
omz/PythonistaAppTemplate
f560f93f8876d82a21d108977f90583df08d55af
PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/mpmath/functions/rszeta.py
python
Rzeta_set
(ctx, s, derivatives=[0])
return rz
r""" Computes several derivatives of the auxiliary function of Riemann `R(s)`. **Definition** The function is defined by .. math :: \begin{equation} {\mathop{\mathcal R }\nolimits}(s)= \int_{0\swarrow1}\frac{x^{-s} e^{\pi i x^2}}{e^{\pi i x}- e^{-\pi i x}}\,dx \end{equation} To this function we apply the Riemann-Siegel expansion.
r""" Computes several derivatives of the auxiliary function of Riemann `R(s)`.
[ "r", "Computes", "several", "derivatives", "of", "the", "auxiliary", "function", "of", "Riemann", "R", "(", "s", ")", "." ]
def Rzeta_set(ctx, s, derivatives=[0]): r""" Computes several derivatives of the auxiliary function of Riemann `R(s)`. **Definition** The function is defined by .. math :: \begin{equation} {\mathop{\mathcal R }\nolimits}(s)= \int_{0\swarrow1}\frac{x^{-s} e^{\pi i x^2}}{e^{\pi i x}- e^{-\pi i x}}\,dx \end{equation} To this function we apply the Riemann-Siegel expansion. """ der = max(derivatives) # First we take the value of ctx.prec # During the computation we will change ctx.prec, and finally we will # restaurate the initial value wpinitial = ctx.prec # Take the real and imaginary part of s t = ctx._im(s) sigma = ctx._re(s) # Now compute several parameter that appear on the program ctx.prec = 15 a = ctx.sqrt(t/(2*ctx.pi)) # Careful asigma = ctx.power(a, sigma) # Careful # We need a simple bound A1 < asigma (see II Section 3.1 and 3.3) A1 = ctx.power(2, ctx.mag(asigma)-1) # We compute various epsilon's (see II end of Section 3.1) eps = ctx.power(2, -wpinitial) eps1 = eps/6. eps2 = eps * A1/3. # COMPUTING SOME COEFFICIENTS THAT DEPENDS # ON sigma # constant b and c (see I Theorem 2 formula (26) ) # coefficients A and B1 (see I Section 6.1 equation (50)) # here we not need high precision ctx.prec = 15 if sigma > 0: b = 2. c = math.pow(9,sigma)/4.44288 # 4.44288 =(math.sqrt(2)*math.pi) A = math.pow(9,sigma) B1 = 1 else: b = 2.25158 # math.sqrt( (3-2* math.log(2))*math.pi ) c = math.pow(2,-sigma)/4.44288 A = math.pow(2,-sigma) B1 = 1.10789 # = 2*sqrt(1-log(2)) # COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL # CORRECTION # See II Section 3.2 ctx.prec = 15 L = 1 while 3*c*ctx.gamma(L*0.5) * ctx.power(b*a,-L) >= eps2: L = L+1 L = max(2,L) # The number L has to satify some conditions. # If not RS can not compute Rzeta(s) with the prescribed precision # (see II, Section 3.2 condition (20) ) and # (II, Section 3.3 condition (22) ). Also we have added # an additional technical condition in Section 3.17 Proposition 17 if ((3*L >= 2*a*a/25.) or (3*L+2+sigma<0) or (abs(sigma)> a/2.)): #print 'Error Riemann-Siegel can not compute with such precision' ctx.prec = wpinitial raise NotImplementedError("Riemann-Siegel can not compute with such precision") # INITIALIZATION (CONTINUATION) # # eps3 is the constant defined on (II, Section 3.5 equation (27) ) # each term of the RS correction must be computed with error <= eps3 eps3 = eps2/(4*L) # eps4 is defined on (II Section 3.6 equation (30) ) # each component of the formula (II Section 3.6 equation (29) ) # must be computed with error <= eps4 eps4 = eps3/(3*L) # COMPUTING M. NUMBER OF DERIVATIVES Fp[m] TO COMPUTE M = aux_M_Fp(ctx, A, eps4, a, B1, L) Fp = {} for n in range(M, 3*L-2): Fp[n] = 0 # But I have not seen an instance of M != 3*L-3 # # DETERMINATION OF J THE NUMBER OF TERMS NEEDED # IN THE TAYLOR SERIES OF F. # See II Section 3.11 equation (49)) h1 = eps4/(632*A) h2 = ctx.pi*ctx.pi*B1*a *ctx.sqrt(3)*math.e*math.e h2 = h1 * ctx.power((h2/M**2),(M-1)/3) / M h3 = min(h1,h2) J=12 jvalue = (2*ctx.pi)**J / ctx.gamma(J+1) while jvalue > h3: J = J+1 jvalue = (2*ctx.pi)*jvalue/J # COMPUTING eps5[m] for 1 <= m <= 21 # See II Section 10 equation (43) eps5={} foreps5 = math.pi*math.pi*B1*a for m in range(0,22): aux1 = math.pow(foreps5, m/3)/(316.*A) aux2 = ctx.gamma(m+1)/ctx.gamma(m/3.0+0.5) aux2 = math.sqrt(aux2) eps5[m] = aux1*aux2*eps4 # COMPUTING wpfp # See II Section 3.13 equation (59) twenty = min(3*L-3, 21)+1 aux = 6812*J wpfp = ctx.mag(44*J) for m in range(0, twenty): wpfp = max(wpfp, ctx.mag(aux*ctx.gamma(m+1)/eps5[m])) # COMPUTING N AND p # See II Section ctx.prec = wpfp + ctx.mag(t) + 20 a = ctx.sqrt(t/(2*ctx.pi)) N = ctx.floor(a) p = 1-2*(a-N) # now we get a rounded version of p to the precision wpfp # this possibly is not necessary num = ctx.floor(p*(ctx.mpf(2)**wpfp)) difference = p * (ctx.mpf(2)**wpfp)-num if difference < 0.5: num = num else: num = num+1 p = ctx.convert(num * (ctx.mpf(2)**(-wpfp))) # COMPUTING THE COEFFICIENTS c[n] = cc[n] # We shall use the notation cc[n], since there is # a constant that is called c # See II Section 3.14 # We compute the coefficients and also save then in a # cache. The bulk of the computation is passed to # the function coef() # # eps6 is defined in II Section 3.13 equation (58) eps6 = ctx.power(2*ctx.pi, J)/(ctx.gamma(J+1)*3*J) # Now we compute the coefficients cc={} cont={} cont, pipowers = coef(ctx, J, eps6) cc = cont.copy() # we need a copy since we have Fp={} for n in range(M, 3*L-2): Fp[n] = 0 ctx.prec = wpfp for m in range(0,M+1): sumP = 0 for k in range(2*J-m-1,-1,-1): sumP = (sumP * p) + cc[k] Fp[m] = sumP # preparation of the new coefficients for k in range(0, 2*J-m-1): cc[k] = (k+1) * cc[k+1] # COMPUTING THE NUMBERS d[n,k] # See II Section 3.17 # First we compute the working precisions wpd[k] # Se II equation (92) wpd = {} d1 = max(6, ctx.mag(40*L*L)) d2 = 13+ctx.mag((1+abs(sigma))*A)-ctx.mag(eps4)-1 const = ctx.ln(8/(ctx.pi*ctx.pi*a*a*B1*B1)) /2 for n in range(0,L): d3 = ctx.mag(ctx.sqrt(ctx.gamma(n-0.5)))-ctx.floor(n*const)+d2 wpd[n] = max(d3,d1) # procedure of II Section 3.17 ctx.prec = wpd[1]+10 psigma = 1-(2*sigma) d = {} d[0,0,-2]=0; d[0,0,-1]=0; d[0,0,0]=1; d[0,0,1]=0 d[0,-1,-2]=0; d[0,-1,-1]=0; d[0,-1,0]=1; d[0,-1,1]=0 for n in range(1,L): ctx.prec = wpd[n]+10 for k in range(0,3*n//2+1): m = 3*n-2*k if (m!=0): m1 = ctx.one/m c1 = m1/4 c2 = (psigma*m1)/2 c3 = -(m+1) d[0,n,k] = c3*d[0,n-1,k-2]+c1*d[0,n-1,k]+c2*d[0,n-1,k-1] else: d[0,n,k]=0 for r in range(0,k): add = d[0,n,r]*(ctx.one*ctx.fac(2*k-2*r)/ctx.fac(k-r)) d[0,n,k] -= ((-1)**(k-r))*add d[0,n,-2]=0; d[0,n,-1]=0; d[0,n,3*n//2+1]=0 for mu in range(-2,der+1): for n in range(-2,L): for k in range(-3,max(1,3*n//2+2)): if ((mu<0)or (n<0) or(k<0)or (k>3*n//2)): d[mu,n,k] = 0 for mu in range(1,der+1): for n in range(0,L): ctx.prec = wpd[n]+10 for k in range(0,3*n//2+1): aux=(2*mu-2)*d[mu-2,n-2,k-3]+2*(sigma+n-2)*d[mu-1,n-2,k-3] d[mu,n,k] = aux - d[mu-1,n-1,k-1] # COMPUTING THE COEFFICIENTS t[k,l] # See II Section 3.9 # # computing the needed wp wptcoef = {} wpterm = {} ctx.prec = 15 c1 = ctx.mag(40*(L+2)) c2 = ctx.mag(68*(L+2)*A) c4 = ctx.mag(B1*a*math.sqrt(ctx.pi))-1 for k in range(0,L): c3 = c2 - k*c4+ctx.mag(ctx.fac(k+0.5))/2. wptcoef[k] = max(c1,c3-ctx.mag(eps4)+1)+1 +10 wpterm[k] = max(c1,ctx.mag(L+2)+c3-ctx.mag(eps3)+1)+1 +10 # check of power of pi # computing the fortcoef[mu,k,ell] fortcoef={} for mu in derivatives: for k in range(0,L): for ell in range(-2,3*k//2+1): fortcoef[mu,k,ell]=0 for mu in derivatives: for k in range(0,L): ctx.prec = wptcoef[k] for ell in range(0,3*k//2+1): fortcoef[mu,k,ell]=d[mu,k,ell]*Fp[3*k-2*ell]/pipowers[2*k-ell] fortcoef[mu,k,ell]=fortcoef[mu,k,ell]/((2*ctx.j)**ell) def trunc_a(t): wp = ctx.prec ctx.prec = wp + 2 aa = ctx.sqrt(t/(2*ctx.pi)) ctx.prec = wp return aa # computing the tcoef[chi,k,ell] tcoef={} for chi in derivatives: for k in range(0,L): for ell in range(-2,3*k//2+1): tcoef[chi,k,ell]=0 ctx.prec = wptcoef[0]+3 aa = trunc_a(t) la = -ctx.ln(aa) for chi in derivatives: for k in range(0,L): ctx.prec = wptcoef[k] for ell in range(0,3*k//2+1): tcoef[chi,k,ell] = 0 for mu in range(0, chi+1): tcoefter = ctx.binomial(chi,mu) * la**mu * \ fortcoef[chi-mu,k,ell] tcoef[chi,k,ell] += tcoefter # COMPUTING tv[k,ell] # See II Section 3.8 # Computing the powers av[k] = a**(-k) ctx.prec = wptcoef[0] + 2 # a has a good value of a. # See II Section 3.6 av = {} av[0] = 1 av[1] = av[0]/a ctx.prec = wptcoef[0] for k in range(2,L): av[k] = av[k-1] * av[1] # Computing the quotients tv = {} for chi in derivatives: for k in range(0,L): ctx.prec = wptcoef[k] for ell in range(0,3*k//2+1): tv[chi,k,ell] = tcoef[chi,k,ell]* av[k] # COMPUTING THE TERMS term[k] # See II Section 3.6 term = {} for chi in derivatives: for n in range(0,L): ctx.prec = wpterm[n] te = 0 for k in range(0, 3*n//2+1): te += tv[chi,n,k] term[chi,n] = te # COMPUTING rssum # See II Section 3.5 rssum={} ctx.prec=15 rsbound = math.sqrt(ctx.pi) * c /(b*a) ctx.prec=15 wprssum = ctx.mag(4.4*((L+3)**2)*rsbound / eps2) wprssum = max(wprssum, ctx.mag(10*(L+1))) ctx.prec = wprssum for chi in derivatives: rssum[chi] = 0 for k in range(1,L+1): rssum[chi] += term[chi,L-k] # COMPUTING S3 # See II Section 3.19 ctx.prec = 15 A2 = 2**(ctx.mag(rssum[0])) eps8 = eps/(3* A2) T = t * ctx.ln(t/(2*ctx.pi)) wps3 = 5 + ctx.mag((1+(2/eps8)*ctx.power(a,-sigma))*T) ctx.prec = wps3 tpi = t/(2*ctx.pi) arg = (t/2)*ctx.ln(tpi)-(t/2)-ctx.pi/8 U = ctx.expj(-arg) a = trunc_a(t) asigma = ctx.power(a, -sigma) S3 = ((-1)**(N-1)) * asigma * U # COMPUTING S1 the zetasum # See II Section 3.18 ctx.prec = 15 wpsum = 4 + ctx.mag((N+ctx.power(N,1-sigma))*ctx.ln(N)/eps1) ctx.prec = wpsum + 10 ''' # This can be improved S1 = {} for chi in derivatives: S1[chi] = 0 for n in range(1,int(N)+1): ln = ctx.ln(n) expn = ctx.exp(-ln*(sigma+ctx.j*t)) for chi in derivatives: term = ctx.power(-ln, chi)*expn S1[chi] += term ''' S1 = ctx._zetasum(s, 1, int(N)-1, derivatives)[0] # END OF COMPUTATION # See II Section 3.1 ctx.prec = 15 absS1 = abs(S1[der]) absS2 = abs(rssum[der] * S3) wpend = max(6, wpinitial + ctx.mag(6*(3*absS1+7*absS2))) ctx.prec = wpend rz = {} for chi in derivatives: rz[chi] = S1[chi]+rssum[chi]*S3 ctx.prec = wpinitial return rz
[ "def", "Rzeta_set", "(", "ctx", ",", "s", ",", "derivatives", "=", "[", "0", "]", ")", ":", "der", "=", "max", "(", "derivatives", ")", "# First we take the value of ctx.prec", "# During the computation we will change ctx.prec, and finally we will", "# restaurate the initial value", "wpinitial", "=", "ctx", ".", "prec", "# Take the real and imaginary part of s", "t", "=", "ctx", ".", "_im", "(", "s", ")", "sigma", "=", "ctx", ".", "_re", "(", "s", ")", "# Now compute several parameter that appear on the program", "ctx", ".", "prec", "=", "15", "a", "=", "ctx", ".", "sqrt", "(", "t", "/", "(", "2", "*", "ctx", ".", "pi", ")", ")", "# Careful", "asigma", "=", "ctx", ".", "power", "(", "a", ",", "sigma", ")", "# Careful", "# We need a simple bound A1 < asigma (see II Section 3.1 and 3.3)", "A1", "=", "ctx", ".", "power", "(", "2", ",", "ctx", ".", "mag", "(", "asigma", ")", "-", "1", ")", "# We compute various epsilon's (see II end of Section 3.1)", "eps", "=", "ctx", ".", "power", "(", "2", ",", "-", "wpinitial", ")", "eps1", "=", "eps", "/", "6.", "eps2", "=", "eps", "*", "A1", "/", "3.", "# COMPUTING SOME COEFFICIENTS THAT DEPENDS", "# ON sigma", "# constant b and c (see I Theorem 2 formula (26) )", "# coefficients A and B1 (see I Section 6.1 equation (50))", "# here we not need high precision", "ctx", ".", "prec", "=", "15", "if", "sigma", ">", "0", ":", "b", "=", "2.", "c", "=", "math", ".", "pow", "(", "9", ",", "sigma", ")", "/", "4.44288", "# 4.44288 =(math.sqrt(2)*math.pi)", "A", "=", "math", ".", "pow", "(", "9", ",", "sigma", ")", "B1", "=", "1", "else", ":", "b", "=", "2.25158", "# math.sqrt( (3-2* math.log(2))*math.pi )", "c", "=", "math", ".", "pow", "(", "2", ",", "-", "sigma", ")", "/", "4.44288", "A", "=", "math", ".", "pow", "(", "2", ",", "-", "sigma", ")", "B1", "=", "1.10789", "# = 2*sqrt(1-log(2))", "# COMPUTING L THE NUMBER OF TERMS NEEDED IN THE RIEMANN-SIEGEL", "# CORRECTION", "# See II Section 3.2", "ctx", ".", "prec", "=", "15", "L", "=", "1", "while", "3", "*", "c", "*", "ctx", ".", "gamma", "(", "L", "*", "0.5", ")", "*", "ctx", ".", "power", "(", "b", "*", "a", ",", "-", "L", ")", ">=", "eps2", ":", "L", "=", "L", "+", "1", "L", "=", "max", "(", "2", ",", "L", ")", "# The number L has to satify some conditions.", "# If not RS can not compute Rzeta(s) with the prescribed precision", "# (see II, Section 3.2 condition (20) ) and", "# (II, Section 3.3 condition (22) ). Also we have added", "# an additional technical condition in Section 3.17 Proposition 17", "if", "(", "(", "3", "*", "L", ">=", "2", "*", "a", "*", "a", "/", "25.", ")", "or", "(", "3", "*", "L", "+", "2", "+", "sigma", "<", "0", ")", "or", "(", "abs", "(", "sigma", ")", ">", "a", "/", "2.", ")", ")", ":", "#print 'Error Riemann-Siegel can not compute with such precision'", "ctx", ".", "prec", "=", "wpinitial", "raise", "NotImplementedError", "(", "\"Riemann-Siegel can not compute with such precision\"", ")", "# INITIALIZATION (CONTINUATION)", "#", "# eps3 is the constant defined on (II, Section 3.5 equation (27) )", "# each term of the RS correction must be computed with error <= eps3", "eps3", "=", "eps2", "/", "(", "4", "*", "L", ")", "# eps4 is defined on (II Section 3.6 equation (30) )", "# each component of the formula (II Section 3.6 equation (29) )", "# must be computed with error <= eps4", "eps4", "=", "eps3", "/", "(", "3", "*", "L", ")", "# COMPUTING M. NUMBER OF DERIVATIVES Fp[m] TO COMPUTE", "M", "=", "aux_M_Fp", "(", "ctx", ",", "A", ",", "eps4", ",", "a", ",", "B1", ",", "L", ")", "Fp", "=", "{", "}", "for", "n", "in", "range", "(", "M", ",", "3", "*", "L", "-", "2", ")", ":", "Fp", "[", "n", "]", "=", "0", "# But I have not seen an instance of M != 3*L-3", "#", "# DETERMINATION OF J THE NUMBER OF TERMS NEEDED", "# IN THE TAYLOR SERIES OF F.", "# See II Section 3.11 equation (49))", "h1", "=", "eps4", "/", "(", "632", "*", "A", ")", "h2", "=", "ctx", ".", "pi", "*", "ctx", ".", "pi", "*", "B1", "*", "a", "*", "ctx", ".", "sqrt", "(", "3", ")", "*", "math", ".", "e", "*", "math", ".", "e", "h2", "=", "h1", "*", "ctx", ".", "power", "(", "(", "h2", "/", "M", "**", "2", ")", ",", "(", "M", "-", "1", ")", "/", "3", ")", "/", "M", "h3", "=", "min", "(", "h1", ",", "h2", ")", "J", "=", "12", "jvalue", "=", "(", "2", "*", "ctx", ".", "pi", ")", "**", "J", "/", "ctx", ".", "gamma", "(", "J", "+", "1", ")", "while", "jvalue", ">", "h3", ":", "J", "=", "J", "+", "1", "jvalue", "=", "(", "2", "*", "ctx", ".", "pi", ")", "*", "jvalue", "/", "J", "# COMPUTING eps5[m] for 1 <= m <= 21", "# See II Section 10 equation (43)", "eps5", "=", "{", "}", "foreps5", "=", "math", ".", "pi", "*", "math", ".", "pi", "*", "B1", "*", "a", "for", "m", "in", "range", "(", "0", ",", "22", ")", ":", "aux1", "=", "math", ".", "pow", "(", "foreps5", ",", "m", "/", "3", ")", "/", "(", "316.", "*", "A", ")", "aux2", "=", "ctx", ".", "gamma", "(", "m", "+", "1", ")", "/", "ctx", ".", "gamma", "(", "m", "/", "3.0", "+", "0.5", ")", "aux2", "=", "math", ".", "sqrt", "(", "aux2", ")", "eps5", "[", "m", "]", "=", "aux1", "*", "aux2", "*", "eps4", "# COMPUTING wpfp", "# See II Section 3.13 equation (59)", "twenty", "=", "min", "(", "3", "*", "L", "-", "3", ",", "21", ")", "+", "1", "aux", "=", "6812", "*", "J", "wpfp", "=", "ctx", ".", "mag", "(", "44", "*", "J", ")", "for", "m", "in", "range", "(", "0", ",", "twenty", ")", ":", "wpfp", "=", "max", "(", "wpfp", ",", "ctx", ".", "mag", "(", "aux", "*", "ctx", ".", "gamma", "(", "m", "+", "1", ")", "/", "eps5", "[", "m", "]", ")", ")", "# COMPUTING N AND p", "# See II Section", "ctx", ".", "prec", "=", "wpfp", "+", "ctx", ".", "mag", "(", "t", ")", "+", "20", "a", "=", "ctx", ".", "sqrt", "(", "t", "/", "(", "2", "*", "ctx", ".", "pi", ")", ")", "N", "=", "ctx", ".", "floor", "(", "a", ")", "p", "=", "1", "-", "2", "*", "(", "a", "-", "N", ")", "# now we get a rounded version of p to the precision wpfp", "# this possibly is not necessary", "num", "=", "ctx", ".", "floor", "(", "p", "*", "(", "ctx", ".", "mpf", "(", "2", ")", "**", "wpfp", ")", ")", "difference", "=", "p", "*", "(", "ctx", ".", "mpf", "(", "2", ")", "**", "wpfp", ")", "-", "num", "if", "difference", "<", "0.5", ":", "num", "=", "num", "else", ":", "num", "=", "num", "+", "1", "p", "=", "ctx", ".", "convert", "(", "num", "*", "(", "ctx", ".", "mpf", "(", "2", ")", "**", "(", "-", "wpfp", ")", ")", ")", "# COMPUTING THE COEFFICIENTS c[n] = cc[n]", "# We shall use the notation cc[n], since there is", "# a constant that is called c", "# See II Section 3.14", "# We compute the coefficients and also save then in a", "# cache. The bulk of the computation is passed to", "# the function coef()", "#", "# eps6 is defined in II Section 3.13 equation (58)", "eps6", "=", "ctx", ".", "power", "(", "2", "*", "ctx", ".", "pi", ",", "J", ")", "/", "(", "ctx", ".", "gamma", "(", "J", "+", "1", ")", "*", "3", "*", "J", ")", "# Now we compute the coefficients", "cc", "=", "{", "}", "cont", "=", "{", "}", "cont", ",", "pipowers", "=", "coef", "(", "ctx", ",", "J", ",", "eps6", ")", "cc", "=", "cont", ".", "copy", "(", ")", "# we need a copy since we have", "Fp", "=", "{", "}", "for", "n", "in", "range", "(", "M", ",", "3", "*", "L", "-", "2", ")", ":", "Fp", "[", "n", "]", "=", "0", "ctx", ".", "prec", "=", "wpfp", "for", "m", "in", "range", "(", "0", ",", "M", "+", "1", ")", ":", "sumP", "=", "0", "for", "k", "in", "range", "(", "2", "*", "J", "-", "m", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "sumP", "=", "(", "sumP", "*", "p", ")", "+", "cc", "[", "k", "]", "Fp", "[", "m", "]", "=", "sumP", "# preparation of the new coefficients", "for", "k", "in", "range", "(", "0", ",", "2", "*", "J", "-", "m", "-", "1", ")", ":", "cc", "[", "k", "]", "=", "(", "k", "+", "1", ")", "*", "cc", "[", "k", "+", "1", "]", "# COMPUTING THE NUMBERS d[n,k]", "# See II Section 3.17", "# First we compute the working precisions wpd[k]", "# Se II equation (92)", "wpd", "=", "{", "}", "d1", "=", "max", "(", "6", ",", "ctx", ".", "mag", "(", "40", "*", "L", "*", "L", ")", ")", "d2", "=", "13", "+", "ctx", ".", "mag", "(", "(", "1", "+", "abs", "(", "sigma", ")", ")", "*", "A", ")", "-", "ctx", ".", "mag", "(", "eps4", ")", "-", "1", "const", "=", "ctx", ".", "ln", "(", "8", "/", "(", "ctx", ".", "pi", "*", "ctx", ".", "pi", "*", "a", "*", "a", "*", "B1", "*", "B1", ")", ")", "/", "2", "for", "n", "in", "range", "(", "0", ",", "L", ")", ":", "d3", "=", "ctx", ".", "mag", "(", "ctx", ".", "sqrt", "(", "ctx", ".", "gamma", "(", "n", "-", "0.5", ")", ")", ")", "-", "ctx", ".", "floor", "(", "n", "*", "const", ")", "+", "d2", "wpd", "[", "n", "]", "=", "max", "(", "d3", ",", "d1", ")", "# procedure of II Section 3.17", "ctx", ".", "prec", "=", "wpd", "[", "1", "]", "+", "10", "psigma", "=", "1", "-", "(", "2", "*", "sigma", ")", "d", "=", "{", "}", "d", "[", "0", ",", "0", ",", "-", "2", "]", "=", "0", "d", "[", "0", ",", "0", ",", "-", "1", "]", "=", "0", "d", "[", "0", ",", "0", ",", "0", "]", "=", "1", "d", "[", "0", ",", "0", ",", "1", "]", "=", "0", "d", "[", "0", ",", "-", "1", ",", "-", "2", "]", "=", "0", "d", "[", "0", ",", "-", "1", ",", "-", "1", "]", "=", "0", "d", "[", "0", ",", "-", "1", ",", "0", "]", "=", "1", "d", "[", "0", ",", "-", "1", ",", "1", "]", "=", "0", "for", "n", "in", "range", "(", "1", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wpd", "[", "n", "]", "+", "10", "for", "k", "in", "range", "(", "0", ",", "3", "*", "n", "//", "2", "+", "1", ")", ":", "m", "=", "3", "*", "n", "-", "2", "*", "k", "if", "(", "m", "!=", "0", ")", ":", "m1", "=", "ctx", ".", "one", "/", "m", "c1", "=", "m1", "/", "4", "c2", "=", "(", "psigma", "*", "m1", ")", "/", "2", "c3", "=", "-", "(", "m", "+", "1", ")", "d", "[", "0", ",", "n", ",", "k", "]", "=", "c3", "*", "d", "[", "0", ",", "n", "-", "1", ",", "k", "-", "2", "]", "+", "c1", "*", "d", "[", "0", ",", "n", "-", "1", ",", "k", "]", "+", "c2", "*", "d", "[", "0", ",", "n", "-", "1", ",", "k", "-", "1", "]", "else", ":", "d", "[", "0", ",", "n", ",", "k", "]", "=", "0", "for", "r", "in", "range", "(", "0", ",", "k", ")", ":", "add", "=", "d", "[", "0", ",", "n", ",", "r", "]", "*", "(", "ctx", ".", "one", "*", "ctx", ".", "fac", "(", "2", "*", "k", "-", "2", "*", "r", ")", "/", "ctx", ".", "fac", "(", "k", "-", "r", ")", ")", "d", "[", "0", ",", "n", ",", "k", "]", "-=", "(", "(", "-", "1", ")", "**", "(", "k", "-", "r", ")", ")", "*", "add", "d", "[", "0", ",", "n", ",", "-", "2", "]", "=", "0", "d", "[", "0", ",", "n", ",", "-", "1", "]", "=", "0", "d", "[", "0", ",", "n", ",", "3", "*", "n", "//", "2", "+", "1", "]", "=", "0", "for", "mu", "in", "range", "(", "-", "2", ",", "der", "+", "1", ")", ":", "for", "n", "in", "range", "(", "-", "2", ",", "L", ")", ":", "for", "k", "in", "range", "(", "-", "3", ",", "max", "(", "1", ",", "3", "*", "n", "//", "2", "+", "2", ")", ")", ":", "if", "(", "(", "mu", "<", "0", ")", "or", "(", "n", "<", "0", ")", "or", "(", "k", "<", "0", ")", "or", "(", "k", ">", "3", "*", "n", "//", "2", ")", ")", ":", "d", "[", "mu", ",", "n", ",", "k", "]", "=", "0", "for", "mu", "in", "range", "(", "1", ",", "der", "+", "1", ")", ":", "for", "n", "in", "range", "(", "0", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wpd", "[", "n", "]", "+", "10", "for", "k", "in", "range", "(", "0", ",", "3", "*", "n", "//", "2", "+", "1", ")", ":", "aux", "=", "(", "2", "*", "mu", "-", "2", ")", "*", "d", "[", "mu", "-", "2", ",", "n", "-", "2", ",", "k", "-", "3", "]", "+", "2", "*", "(", "sigma", "+", "n", "-", "2", ")", "*", "d", "[", "mu", "-", "1", ",", "n", "-", "2", ",", "k", "-", "3", "]", "d", "[", "mu", ",", "n", ",", "k", "]", "=", "aux", "-", "d", "[", "mu", "-", "1", ",", "n", "-", "1", ",", "k", "-", "1", "]", "# COMPUTING THE COEFFICIENTS t[k,l]", "# See II Section 3.9", "#", "# computing the needed wp", "wptcoef", "=", "{", "}", "wpterm", "=", "{", "}", "ctx", ".", "prec", "=", "15", "c1", "=", "ctx", ".", "mag", "(", "40", "*", "(", "L", "+", "2", ")", ")", "c2", "=", "ctx", ".", "mag", "(", "68", "*", "(", "L", "+", "2", ")", "*", "A", ")", "c4", "=", "ctx", ".", "mag", "(", "B1", "*", "a", "*", "math", ".", "sqrt", "(", "ctx", ".", "pi", ")", ")", "-", "1", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "c3", "=", "c2", "-", "k", "*", "c4", "+", "ctx", ".", "mag", "(", "ctx", ".", "fac", "(", "k", "+", "0.5", ")", ")", "/", "2.", "wptcoef", "[", "k", "]", "=", "max", "(", "c1", ",", "c3", "-", "ctx", ".", "mag", "(", "eps4", ")", "+", "1", ")", "+", "1", "+", "10", "wpterm", "[", "k", "]", "=", "max", "(", "c1", ",", "ctx", ".", "mag", "(", "L", "+", "2", ")", "+", "c3", "-", "ctx", ".", "mag", "(", "eps3", ")", "+", "1", ")", "+", "1", "+", "10", "# check of power of pi", "# computing the fortcoef[mu,k,ell]", "fortcoef", "=", "{", "}", "for", "mu", "in", "derivatives", ":", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "for", "ell", "in", "range", "(", "-", "2", ",", "3", "*", "k", "//", "2", "+", "1", ")", ":", "fortcoef", "[", "mu", ",", "k", ",", "ell", "]", "=", "0", "for", "mu", "in", "derivatives", ":", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wptcoef", "[", "k", "]", "for", "ell", "in", "range", "(", "0", ",", "3", "*", "k", "//", "2", "+", "1", ")", ":", "fortcoef", "[", "mu", ",", "k", ",", "ell", "]", "=", "d", "[", "mu", ",", "k", ",", "ell", "]", "*", "Fp", "[", "3", "*", "k", "-", "2", "*", "ell", "]", "/", "pipowers", "[", "2", "*", "k", "-", "ell", "]", "fortcoef", "[", "mu", ",", "k", ",", "ell", "]", "=", "fortcoef", "[", "mu", ",", "k", ",", "ell", "]", "/", "(", "(", "2", "*", "ctx", ".", "j", ")", "**", "ell", ")", "def", "trunc_a", "(", "t", ")", ":", "wp", "=", "ctx", ".", "prec", "ctx", ".", "prec", "=", "wp", "+", "2", "aa", "=", "ctx", ".", "sqrt", "(", "t", "/", "(", "2", "*", "ctx", ".", "pi", ")", ")", "ctx", ".", "prec", "=", "wp", "return", "aa", "# computing the tcoef[chi,k,ell]", "tcoef", "=", "{", "}", "for", "chi", "in", "derivatives", ":", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "for", "ell", "in", "range", "(", "-", "2", ",", "3", "*", "k", "//", "2", "+", "1", ")", ":", "tcoef", "[", "chi", ",", "k", ",", "ell", "]", "=", "0", "ctx", ".", "prec", "=", "wptcoef", "[", "0", "]", "+", "3", "aa", "=", "trunc_a", "(", "t", ")", "la", "=", "-", "ctx", ".", "ln", "(", "aa", ")", "for", "chi", "in", "derivatives", ":", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wptcoef", "[", "k", "]", "for", "ell", "in", "range", "(", "0", ",", "3", "*", "k", "//", "2", "+", "1", ")", ":", "tcoef", "[", "chi", ",", "k", ",", "ell", "]", "=", "0", "for", "mu", "in", "range", "(", "0", ",", "chi", "+", "1", ")", ":", "tcoefter", "=", "ctx", ".", "binomial", "(", "chi", ",", "mu", ")", "*", "la", "**", "mu", "*", "fortcoef", "[", "chi", "-", "mu", ",", "k", ",", "ell", "]", "tcoef", "[", "chi", ",", "k", ",", "ell", "]", "+=", "tcoefter", "# COMPUTING tv[k,ell]", "# See II Section 3.8", "# Computing the powers av[k] = a**(-k)", "ctx", ".", "prec", "=", "wptcoef", "[", "0", "]", "+", "2", "# a has a good value of a.", "# See II Section 3.6", "av", "=", "{", "}", "av", "[", "0", "]", "=", "1", "av", "[", "1", "]", "=", "av", "[", "0", "]", "/", "a", "ctx", ".", "prec", "=", "wptcoef", "[", "0", "]", "for", "k", "in", "range", "(", "2", ",", "L", ")", ":", "av", "[", "k", "]", "=", "av", "[", "k", "-", "1", "]", "*", "av", "[", "1", "]", "# Computing the quotients", "tv", "=", "{", "}", "for", "chi", "in", "derivatives", ":", "for", "k", "in", "range", "(", "0", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wptcoef", "[", "k", "]", "for", "ell", "in", "range", "(", "0", ",", "3", "*", "k", "//", "2", "+", "1", ")", ":", "tv", "[", "chi", ",", "k", ",", "ell", "]", "=", "tcoef", "[", "chi", ",", "k", ",", "ell", "]", "*", "av", "[", "k", "]", "# COMPUTING THE TERMS term[k]", "# See II Section 3.6", "term", "=", "{", "}", "for", "chi", "in", "derivatives", ":", "for", "n", "in", "range", "(", "0", ",", "L", ")", ":", "ctx", ".", "prec", "=", "wpterm", "[", "n", "]", "te", "=", "0", "for", "k", "in", "range", "(", "0", ",", "3", "*", "n", "//", "2", "+", "1", ")", ":", "te", "+=", "tv", "[", "chi", ",", "n", ",", "k", "]", "term", "[", "chi", ",", "n", "]", "=", "te", "# COMPUTING rssum", "# See II Section 3.5", "rssum", "=", "{", "}", "ctx", ".", "prec", "=", "15", "rsbound", "=", "math", ".", "sqrt", "(", "ctx", ".", "pi", ")", "*", "c", "/", "(", "b", "*", "a", ")", "ctx", ".", "prec", "=", "15", "wprssum", "=", "ctx", ".", "mag", "(", "4.4", "*", "(", "(", "L", "+", "3", ")", "**", "2", ")", "*", "rsbound", "/", "eps2", ")", "wprssum", "=", "max", "(", "wprssum", ",", "ctx", ".", "mag", "(", "10", "*", "(", "L", "+", "1", ")", ")", ")", "ctx", ".", "prec", "=", "wprssum", "for", "chi", "in", "derivatives", ":", "rssum", "[", "chi", "]", "=", "0", "for", "k", "in", "range", "(", "1", ",", "L", "+", "1", ")", ":", "rssum", "[", "chi", "]", "+=", "term", "[", "chi", ",", "L", "-", "k", "]", "# COMPUTING S3", "# See II Section 3.19", "ctx", ".", "prec", "=", "15", "A2", "=", "2", "**", "(", "ctx", ".", "mag", "(", "rssum", "[", "0", "]", ")", ")", "eps8", "=", "eps", "/", "(", "3", "*", "A2", ")", "T", "=", "t", "*", "ctx", ".", "ln", "(", "t", "/", "(", "2", "*", "ctx", ".", "pi", ")", ")", "wps3", "=", "5", "+", "ctx", ".", "mag", "(", "(", "1", "+", "(", "2", "/", "eps8", ")", "*", "ctx", ".", "power", "(", "a", ",", "-", "sigma", ")", ")", "*", "T", ")", "ctx", ".", "prec", "=", "wps3", "tpi", "=", "t", "/", "(", "2", "*", "ctx", ".", "pi", ")", "arg", "=", "(", "t", "/", "2", ")", "*", "ctx", ".", "ln", "(", "tpi", ")", "-", "(", "t", "/", "2", ")", "-", "ctx", ".", "pi", "/", "8", "U", "=", "ctx", ".", "expj", "(", "-", "arg", ")", "a", "=", "trunc_a", "(", "t", ")", "asigma", "=", "ctx", ".", "power", "(", "a", ",", "-", "sigma", ")", "S3", "=", "(", "(", "-", "1", ")", "**", "(", "N", "-", "1", ")", ")", "*", "asigma", "*", "U", "# COMPUTING S1 the zetasum", "# See II Section 3.18", "ctx", ".", "prec", "=", "15", "wpsum", "=", "4", "+", "ctx", ".", "mag", "(", "(", "N", "+", "ctx", ".", "power", "(", "N", ",", "1", "-", "sigma", ")", ")", "*", "ctx", ".", "ln", "(", "N", ")", "/", "eps1", ")", "ctx", ".", "prec", "=", "wpsum", "+", "10", "'''\n # This can be improved\n S1 = {}\n for chi in derivatives:\n S1[chi] = 0\n for n in range(1,int(N)+1):\n ln = ctx.ln(n)\n expn = ctx.exp(-ln*(sigma+ctx.j*t))\n for chi in derivatives:\n term = ctx.power(-ln, chi)*expn\n S1[chi] += term\n '''", "S1", "=", "ctx", ".", "_zetasum", "(", "s", ",", "1", ",", "int", "(", "N", ")", "-", "1", ",", "derivatives", ")", "[", "0", "]", "# END OF COMPUTATION", "# See II Section 3.1", "ctx", ".", "prec", "=", "15", "absS1", "=", "abs", "(", "S1", "[", "der", "]", ")", "absS2", "=", "abs", "(", "rssum", "[", "der", "]", "*", "S3", ")", "wpend", "=", "max", "(", "6", ",", "wpinitial", "+", "ctx", ".", "mag", "(", "6", "*", "(", "3", "*", "absS1", "+", "7", "*", "absS2", ")", ")", ")", "ctx", ".", "prec", "=", "wpend", "rz", "=", "{", "}", "for", "chi", "in", "derivatives", ":", "rz", "[", "chi", "]", "=", "S1", "[", "chi", "]", "+", "rssum", "[", "chi", "]", "*", "S3", "ctx", ".", "prec", "=", "wpinitial", "return", "rz" ]
https://github.com/omz/PythonistaAppTemplate/blob/f560f93f8876d82a21d108977f90583df08d55af/PythonistaAppTemplate/PythonistaKit.framework/pylib_ext/mpmath/functions/rszeta.py#L769-L1138
deepmind/dm_control
806a10e896e7c887635328bfa8352604ad0fedae
dm_control/composer/variation/rotations.py
python
QuaternionPreMultiply.__init__
(self, quat, cumulative=False)
[]
def __init__(self, quat, cumulative=False): self._quat = quat self._cumulative = cumulative
[ "def", "__init__", "(", "self", ",", "quat", ",", "cumulative", "=", "False", ")", ":", "self", ".", "_quat", "=", "quat", "self", ".", "_cumulative", "=", "cumulative" ]
https://github.com/deepmind/dm_control/blob/806a10e896e7c887635328bfa8352604ad0fedae/dm_control/composer/variation/rotations.py#L64-L66
Flolagale/mailin
fac7dcf59404691e551568f987caaaa464303b6b
python/ipaddr.py
python
_BaseNet._prefix_from_ip_string
(self, ip_str)
Turn a netmask/hostmask string into a prefix length. Args: ip_str: A netmask or hostmask, formatted as an IP address. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the input is not a netmask or hostmask.
Turn a netmask/hostmask string into a prefix length.
[ "Turn", "a", "netmask", "/", "hostmask", "string", "into", "a", "prefix", "length", "." ]
def _prefix_from_ip_string(self, ip_str): """Turn a netmask/hostmask string into a prefix length. Args: ip_str: A netmask or hostmask, formatted as an IP address. Returns: The prefix length as an integer. Raises: NetmaskValueError: If the input is not a netmask or hostmask. """ # Parse the netmask/hostmask like an IP address. try: ip_int = self._ip_int_from_string(ip_str) except AddressValueError: raise NetmaskValueError('%s is not a valid netmask' % ip_str) # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). # Note that the two ambiguous cases (all-ones and all-zeroes) are # treated as netmasks. try: return self._prefix_from_ip_int(ip_int) except NetmaskValueError: pass # Invert the bits, and try matching a /0+1+/ hostmask instead. ip_int ^= self._ALL_ONES try: return self._prefix_from_ip_int(ip_int) except NetmaskValueError: raise NetmaskValueError('%s is not a valid netmask' % ip_str)
[ "def", "_prefix_from_ip_string", "(", "self", ",", "ip_str", ")", ":", "# Parse the netmask/hostmask like an IP address.", "try", ":", "ip_int", "=", "self", ".", "_ip_int_from_string", "(", "ip_str", ")", "except", "AddressValueError", ":", "raise", "NetmaskValueError", "(", "'%s is not a valid netmask'", "%", "ip_str", ")", "# Try matching a netmask (this would be /1*0*/ as a bitwise regexp).", "# Note that the two ambiguous cases (all-ones and all-zeroes) are", "# treated as netmasks.", "try", ":", "return", "self", ".", "_prefix_from_ip_int", "(", "ip_int", ")", "except", "NetmaskValueError", ":", "pass", "# Invert the bits, and try matching a /0+1+/ hostmask instead.", "ip_int", "^=", "self", ".", "_ALL_ONES", "try", ":", "return", "self", ".", "_prefix_from_ip_int", "(", "ip_int", ")", "except", "NetmaskValueError", ":", "raise", "NetmaskValueError", "(", "'%s is not a valid netmask'", "%", "ip_str", ")" ]
https://github.com/Flolagale/mailin/blob/fac7dcf59404691e551568f987caaaa464303b6b/python/ipaddr.py#L903-L935
OpenEndedGroup/Field
4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c
Contents/lib/python/xml/dom/minidom.py
python
_write_data
(writer, data)
Writes datachars to writer.
Writes datachars to writer.
[ "Writes", "datachars", "to", "writer", "." ]
def _write_data(writer, data): "Writes datachars to writer." data = data.replace("&", "&amp;").replace("<", "&lt;") data = data.replace("\"", "&quot;").replace(">", "&gt;") writer.write(data)
[ "def", "_write_data", "(", "writer", ",", "data", ")", ":", "data", "=", "data", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", ".", "replace", "(", "\"<\"", ",", "\"&lt;\"", ")", "data", "=", "data", ".", "replace", "(", "\"\\\"\"", ",", "\"&quot;\"", ")", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", "writer", ".", "write", "(", "data", ")" ]
https://github.com/OpenEndedGroup/Field/blob/4f7c8edfb01bb0ccc927b78d3c500f018a4ae37c/Contents/lib/python/xml/dom/minidom.py#L304-L308
newfies-dialer/newfies-dialer
8168b3dd43e9f5ce73a2645b3229def1b2815d47
newfies/apirest/dnc_contact_serializers.py
python
DNCContactSerializer.get_fields
(self, *args, **kwargs)
return fields
filter survey field
filter survey field
[ "filter", "survey", "field" ]
def get_fields(self, *args, **kwargs): """filter survey field""" fields = super(DNCContactSerializer, self).get_fields(*args, **kwargs) request = self.context['request'] if request.method != 'GET' and self.init_data is not None: dnc = self.init_data.get('dnc') if dnc and dnc.find('http://') == -1: try: DNC.objects.get(pk=int(dnc)) self.init_data['dnc'] = '/rest-api/dnc-list/%s/' % dnc except: self.init_data['dnc'] = '' pass if request.method != 'GET': fields['dnc'].queryset = DNC.objects.filter(user=request.user) return fields
[ "def", "get_fields", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fields", "=", "super", "(", "DNCContactSerializer", ",", "self", ")", ".", "get_fields", "(", "*", "args", ",", "*", "*", "kwargs", ")", "request", "=", "self", ".", "context", "[", "'request'", "]", "if", "request", ".", "method", "!=", "'GET'", "and", "self", ".", "init_data", "is", "not", "None", ":", "dnc", "=", "self", ".", "init_data", ".", "get", "(", "'dnc'", ")", "if", "dnc", "and", "dnc", ".", "find", "(", "'http://'", ")", "==", "-", "1", ":", "try", ":", "DNC", ".", "objects", ".", "get", "(", "pk", "=", "int", "(", "dnc", ")", ")", "self", ".", "init_data", "[", "'dnc'", "]", "=", "'/rest-api/dnc-list/%s/'", "%", "dnc", "except", ":", "self", ".", "init_data", "[", "'dnc'", "]", "=", "''", "pass", "if", "request", ".", "method", "!=", "'GET'", ":", "fields", "[", "'dnc'", "]", ".", "queryset", "=", "DNC", ".", "objects", ".", "filter", "(", "user", "=", "request", ".", "user", ")", "return", "fields" ]
https://github.com/newfies-dialer/newfies-dialer/blob/8168b3dd43e9f5ce73a2645b3229def1b2815d47/newfies/apirest/dnc_contact_serializers.py#L82-L100
MrH0wl/Cloudmare
65e5bc9888f9d362ab2abfb103ea6c1e869d67aa
thirdparty/xlsxwriter/format.py
python
Format.set_bg_color
(self, bg_color)
Set the Format bg_color property. Args: bg_color: Background color. No default. Returns: Nothing.
Set the Format bg_color property.
[ "Set", "the", "Format", "bg_color", "property", "." ]
def set_bg_color(self, bg_color): """ Set the Format bg_color property. Args: bg_color: Background color. No default. Returns: Nothing. """ self.bg_color = self._get_color(bg_color)
[ "def", "set_bg_color", "(", "self", ",", "bg_color", ")", ":", "self", ".", "bg_color", "=", "self", ".", "_get_color", "(", "bg_color", ")" ]
https://github.com/MrH0wl/Cloudmare/blob/65e5bc9888f9d362ab2abfb103ea6c1e869d67aa/thirdparty/xlsxwriter/format.py#L441-L452
firstlookmedia/gpgsync
5575b98f4343c2928ac96a39bf8b6e9acda18763
gpgsync/common.py
python
Common.clean_keyserver
(self, keyserver)
return scheme + b'://' + domain + b':' + str(port).encode()
Convert keyserver to format: protocol://domain:port
Convert keyserver to format: protocol://domain:port
[ "Convert", "keyserver", "to", "format", ":", "protocol", ":", "//", "domain", ":", "port" ]
def clean_keyserver(self, keyserver): """ Convert keyserver to format: protocol://domain:port """ o = urlparse(keyserver) # Scheme and port scheme = o.scheme if scheme == b'hkp': port = 80 elif scheme == b'hkps': port = 443 else: scheme = b'hkp' port = 80 # Domain domain = o.netloc if domain == b'': domain = o.path.strip(b'/') # Does the domain include a port? if b':' in domain: parts = domain.split(b':') domain = parts[0] port = int(parts[1]) return scheme + b'://' + domain + b':' + str(port).encode()
[ "def", "clean_keyserver", "(", "self", ",", "keyserver", ")", ":", "o", "=", "urlparse", "(", "keyserver", ")", "# Scheme and port", "scheme", "=", "o", ".", "scheme", "if", "scheme", "==", "b'hkp'", ":", "port", "=", "80", "elif", "scheme", "==", "b'hkps'", ":", "port", "=", "443", "else", ":", "scheme", "=", "b'hkp'", "port", "=", "80", "# Domain", "domain", "=", "o", ".", "netloc", "if", "domain", "==", "b''", ":", "domain", "=", "o", ".", "path", ".", "strip", "(", "b'/'", ")", "# Does the domain include a port?", "if", "b':'", "in", "domain", ":", "parts", "=", "domain", ".", "split", "(", "b':'", ")", "domain", "=", "parts", "[", "0", "]", "port", "=", "int", "(", "parts", "[", "1", "]", ")", "return", "scheme", "+", "b'://'", "+", "domain", "+", "b':'", "+", "str", "(", "port", ")", ".", "encode", "(", ")" ]
https://github.com/firstlookmedia/gpgsync/blob/5575b98f4343c2928ac96a39bf8b6e9acda18763/gpgsync/common.py#L75-L102
Mukosame/Zooming-Slow-Mo-CVPR-2020
a053e08bb0bb5509f634b523256718f502637667
codes/models/base_model.py
python
BaseModel.resume_training
(self, resume_state)
Resume the optimizers and schedulers for training
Resume the optimizers and schedulers for training
[ "Resume", "the", "optimizers", "and", "schedulers", "for", "training" ]
def resume_training(self, resume_state): '''Resume the optimizers and schedulers for training''' resume_optimizers = resume_state['optimizers'] resume_schedulers = resume_state['schedulers'] assert len(resume_optimizers) == len( self.optimizers), 'Wrong lengths of optimizers' assert len(resume_schedulers) == len( self.schedulers), 'Wrong lengths of schedulers' for i, o in enumerate(resume_optimizers): self.optimizers[i].load_state_dict(o) for i, s in enumerate(resume_schedulers): self.schedulers[i].load_state_dict(s)
[ "def", "resume_training", "(", "self", ",", "resume_state", ")", ":", "resume_optimizers", "=", "resume_state", "[", "'optimizers'", "]", "resume_schedulers", "=", "resume_state", "[", "'schedulers'", "]", "assert", "len", "(", "resume_optimizers", ")", "==", "len", "(", "self", ".", "optimizers", ")", ",", "'Wrong lengths of optimizers'", "assert", "len", "(", "resume_schedulers", ")", "==", "len", "(", "self", ".", "schedulers", ")", ",", "'Wrong lengths of schedulers'", "for", "i", ",", "o", "in", "enumerate", "(", "resume_optimizers", ")", ":", "self", ".", "optimizers", "[", "i", "]", ".", "load_state_dict", "(", "o", ")", "for", "i", ",", "s", "in", "enumerate", "(", "resume_schedulers", ")", ":", "self", ".", "schedulers", "[", "i", "]", ".", "load_state_dict", "(", "s", ")" ]
https://github.com/Mukosame/Zooming-Slow-Mo-CVPR-2020/blob/a053e08bb0bb5509f634b523256718f502637667/codes/models/base_model.py#L117-L128
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/polys/polyutils.py
python
_sort_gens
(gens, **args)
return tuple(gens)
Sort generators in a reasonably intelligent way.
Sort generators in a reasonably intelligent way.
[ "Sort", "generators", "in", "a", "reasonably", "intelligent", "way", "." ]
def _sort_gens(gens, **args): """Sort generators in a reasonably intelligent way. """ opt = build_options(args) gens_order, wrt = {}, None if opt is not None: gens_order, wrt = {}, opt.wrt for i, gen in enumerate(opt.sort): gens_order[gen] = i + 1 def order_key(gen): gen = str(gen) if wrt is not None: try: return (-len(wrt) + wrt.index(gen), gen, 0) except ValueError: pass name, index = _re_gen.match(gen).groups() if index: index = int(index) else: index = 0 try: return ( gens_order[name], name, index) except KeyError: pass try: return (_gens_order[name], name, index) except KeyError: pass return (_max_order, name, index) try: gens = sorted(gens, key=order_key) except TypeError: # pragma: no cover pass return tuple(gens)
[ "def", "_sort_gens", "(", "gens", ",", "*", "*", "args", ")", ":", "opt", "=", "build_options", "(", "args", ")", "gens_order", ",", "wrt", "=", "{", "}", ",", "None", "if", "opt", "is", "not", "None", ":", "gens_order", ",", "wrt", "=", "{", "}", ",", "opt", ".", "wrt", "for", "i", ",", "gen", "in", "enumerate", "(", "opt", ".", "sort", ")", ":", "gens_order", "[", "gen", "]", "=", "i", "+", "1", "def", "order_key", "(", "gen", ")", ":", "gen", "=", "str", "(", "gen", ")", "if", "wrt", "is", "not", "None", ":", "try", ":", "return", "(", "-", "len", "(", "wrt", ")", "+", "wrt", ".", "index", "(", "gen", ")", ",", "gen", ",", "0", ")", "except", "ValueError", ":", "pass", "name", ",", "index", "=", "_re_gen", ".", "match", "(", "gen", ")", ".", "groups", "(", ")", "if", "index", ":", "index", "=", "int", "(", "index", ")", "else", ":", "index", "=", "0", "try", ":", "return", "(", "gens_order", "[", "name", "]", ",", "name", ",", "index", ")", "except", "KeyError", ":", "pass", "try", ":", "return", "(", "_gens_order", "[", "name", "]", ",", "name", ",", "index", ")", "except", "KeyError", ":", "pass", "return", "(", "_max_order", ",", "name", ",", "index", ")", "try", ":", "gens", "=", "sorted", "(", "gens", ",", "key", "=", "order_key", ")", "except", "TypeError", ":", "# pragma: no cover", "pass", "return", "tuple", "(", "gens", ")" ]
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/polys/polyutils.py#L31-L76
adobe/brackets-shell
c180d7ea812759ba50d25ab0685434c345343008
gyp/pylib/gyp/MSVSProject.py
python
Writer.__init__
(self, project_path, version, name, guid=None, platforms=None)
Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32']
Initializes the project.
[ "Initializes", "the", "project", "." ]
def __init__(self, project_path, version, name, guid=None, platforms=None): """Initializes the project. Args: project_path: Path to the project file. version: Format version to emit. name: Name of the project. guid: GUID to use for project, if not None. platforms: Array of string, the supported platforms. If null, ['Win32'] """ self.project_path = project_path self.version = version self.name = name self.guid = guid # Default to Win32 for platforms. if not platforms: platforms = ['Win32'] # Initialize the specifications of the various sections. self.platform_section = ['Platforms'] for platform in platforms: self.platform_section.append(['Platform', {'Name': platform}]) self.tool_files_section = ['ToolFiles'] self.configurations_section = ['Configurations'] self.files_section = ['Files'] # Keep a dict keyed on filename to speed up access. self.files_dict = dict()
[ "def", "__init__", "(", "self", ",", "project_path", ",", "version", ",", "name", ",", "guid", "=", "None", ",", "platforms", "=", "None", ")", ":", "self", ".", "project_path", "=", "project_path", "self", ".", "version", "=", "version", "self", ".", "name", "=", "name", "self", ".", "guid", "=", "guid", "# Default to Win32 for platforms.", "if", "not", "platforms", ":", "platforms", "=", "[", "'Win32'", "]", "# Initialize the specifications of the various sections.", "self", ".", "platform_section", "=", "[", "'Platforms'", "]", "for", "platform", "in", "platforms", ":", "self", ".", "platform_section", ".", "append", "(", "[", "'Platform'", ",", "{", "'Name'", ":", "platform", "}", "]", ")", "self", ".", "tool_files_section", "=", "[", "'ToolFiles'", "]", "self", ".", "configurations_section", "=", "[", "'Configurations'", "]", "self", ".", "files_section", "=", "[", "'Files'", "]", "# Keep a dict keyed on filename to speed up access.", "self", ".", "files_dict", "=", "dict", "(", ")" ]
https://github.com/adobe/brackets-shell/blob/c180d7ea812759ba50d25ab0685434c345343008/gyp/pylib/gyp/MSVSProject.py#L54-L82
odlgroup/odl
0b088df8dc4621c68b9414c3deff9127f4c4f11d
odl/space/npy_tensors.py
python
_blas_is_applicable
(*args)
Whether BLAS routines can be applied or not. BLAS routines are available for single and double precision float or complex data only. If the arrays are non-contiguous, BLAS methods are usually slower, and array-writing routines do not work at all. Hence, only contiguous arrays are allowed. Parameters ---------- x1,...,xN : `NumpyTensor` The tensors to be tested for BLAS conformity. Returns ------- blas_is_applicable : bool ``True`` if all mentioned requirements are met, ``False`` otherwise.
Whether BLAS routines can be applied or not.
[ "Whether", "BLAS", "routines", "can", "be", "applied", "or", "not", "." ]
def _blas_is_applicable(*args): """Whether BLAS routines can be applied or not. BLAS routines are available for single and double precision float or complex data only. If the arrays are non-contiguous, BLAS methods are usually slower, and array-writing routines do not work at all. Hence, only contiguous arrays are allowed. Parameters ---------- x1,...,xN : `NumpyTensor` The tensors to be tested for BLAS conformity. Returns ------- blas_is_applicable : bool ``True`` if all mentioned requirements are met, ``False`` otherwise. """ if any(x.dtype != args[0].dtype for x in args[1:]): return False elif any(x.dtype not in _BLAS_DTYPES for x in args): return False elif not (all(x.flags.f_contiguous for x in args) or all(x.flags.c_contiguous for x in args)): return False elif any(x.size > np.iinfo('int32').max for x in args): # Temporary fix for 32 bit int overflow in BLAS # TODO: use chunking instead return False else: return True
[ "def", "_blas_is_applicable", "(", "*", "args", ")", ":", "if", "any", "(", "x", ".", "dtype", "!=", "args", "[", "0", "]", ".", "dtype", "for", "x", "in", "args", "[", "1", ":", "]", ")", ":", "return", "False", "elif", "any", "(", "x", ".", "dtype", "not", "in", "_BLAS_DTYPES", "for", "x", "in", "args", ")", ":", "return", "False", "elif", "not", "(", "all", "(", "x", ".", "flags", ".", "f_contiguous", "for", "x", "in", "args", ")", "or", "all", "(", "x", ".", "flags", ".", "c_contiguous", "for", "x", "in", "args", ")", ")", ":", "return", "False", "elif", "any", "(", "x", ".", "size", ">", "np", ".", "iinfo", "(", "'int32'", ")", ".", "max", "for", "x", "in", "args", ")", ":", "# Temporary fix for 32 bit int overflow in BLAS", "# TODO: use chunking instead", "return", "False", "else", ":", "return", "True" ]
https://github.com/odlgroup/odl/blob/0b088df8dc4621c68b9414c3deff9127f4c4f11d/odl/space/npy_tensors.py#L1755-L1785
seemethere/nba_py
f1cd2b0f2702601accf21fef4b721a1564ef4705
nba_py/game.py
python
PlayByPlay.info
(self)
return _api_scrape(self.json, 0)
[]
def info(self): return _api_scrape(self.json, 0)
[ "def", "info", "(", "self", ")", ":", "return", "_api_scrape", "(", "self", ".", "json", ",", "0", ")" ]
https://github.com/seemethere/nba_py/blob/f1cd2b0f2702601accf21fef4b721a1564ef4705/nba_py/game.py#L164-L165
oracle/oci-python-sdk
3c1604e4e212008fb6718e2f68cdb5ef71fd5793
src/oci/apigateway/api_gateway_client.py
python
ApiGatewayClient.update_sdk
(self, sdk_id, update_sdk_details, **kwargs)
Updates the SDK with the given identifier. :param str sdk_id: (required) The ocid of the SDK. :param oci.apigateway.models.UpdateSdkDetails update_sdk_details: (required) The information to be updated. :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param str opc_request_id: (optional) The client request id for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/apigateway/update_sdk.py.html>`__ to see an example of how to use update_sdk API.
Updates the SDK with the given identifier.
[ "Updates", "the", "SDK", "with", "the", "given", "identifier", "." ]
def update_sdk(self, sdk_id, update_sdk_details, **kwargs): """ Updates the SDK with the given identifier. :param str sdk_id: (required) The ocid of the SDK. :param oci.apigateway.models.UpdateSdkDetails update_sdk_details: (required) The information to be updated. :param str if_match: (optional) For optimistic concurrency control. In the PUT or DELETE call for a resource, set the `if-match` parameter to the value of the etag from a previous GET or POST response for that resource. The resource will be updated or deleted only if the etag you provide matches the resource's current etag value. :param str opc_request_id: (optional) The client request id for tracing. :param obj retry_strategy: (optional) A retry strategy to apply to this specific operation/call. This will override any retry strategy set at the client-level. This should be one of the strategies available in the :py:mod:`~oci.retry` module. This operation will not retry by default, users can also use the convenient :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY` provided by the SDK to enable retries for it. The specifics of the default retry strategy are described `here <https://docs.oracle.com/en-us/iaas/tools/python/latest/sdk_behaviors/retries.html>`__. To have this operation explicitly not perform any retries, pass an instance of :py:class:`~oci.retry.NoneRetryStrategy`. :return: A :class:`~oci.response.Response` object with data of type None :rtype: :class:`~oci.response.Response` :example: Click `here <https://docs.cloud.oracle.com/en-us/iaas/tools/python-sdk-examples/latest/apigateway/update_sdk.py.html>`__ to see an example of how to use update_sdk API. """ resource_path = "/sdks/{sdkId}" method = "PUT" # Don't accept unknown kwargs expected_kwargs = [ "retry_strategy", "if_match", "opc_request_id" ] extra_kwargs = [_key for _key in six.iterkeys(kwargs) if _key not in expected_kwargs] if extra_kwargs: raise ValueError( "update_sdk got unknown kwargs: {!r}".format(extra_kwargs)) path_params = { "sdkId": sdk_id } path_params = {k: v for (k, v) in six.iteritems(path_params) if v is not missing} for (k, v) in six.iteritems(path_params): if v is None or (isinstance(v, six.string_types) and len(v.strip()) == 0): raise ValueError('Parameter {} cannot be None, whitespace or empty string'.format(k)) header_params = { "accept": "application/json", "content-type": "application/json", "if-match": kwargs.get("if_match", missing), "opc-request-id": kwargs.get("opc_request_id", missing) } header_params = {k: v for (k, v) in six.iteritems(header_params) if v is not missing and v is not None} retry_strategy = self.base_client.get_preferred_retry_strategy( operation_retry_strategy=kwargs.get('retry_strategy'), client_retry_strategy=self.retry_strategy ) if retry_strategy: if not isinstance(retry_strategy, retry.NoneRetryStrategy): self.base_client.add_opc_client_retries_header(header_params) retry_strategy.add_circuit_breaker_callback(self.circuit_breaker_callback) return retry_strategy.make_retrying_call( self.base_client.call_api, resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_sdk_details) else: return self.base_client.call_api( resource_path=resource_path, method=method, path_params=path_params, header_params=header_params, body=update_sdk_details)
[ "def", "update_sdk", "(", "self", ",", "sdk_id", ",", "update_sdk_details", ",", "*", "*", "kwargs", ")", ":", "resource_path", "=", "\"/sdks/{sdkId}\"", "method", "=", "\"PUT\"", "# Don't accept unknown kwargs", "expected_kwargs", "=", "[", "\"retry_strategy\"", ",", "\"if_match\"", ",", "\"opc_request_id\"", "]", "extra_kwargs", "=", "[", "_key", "for", "_key", "in", "six", ".", "iterkeys", "(", "kwargs", ")", "if", "_key", "not", "in", "expected_kwargs", "]", "if", "extra_kwargs", ":", "raise", "ValueError", "(", "\"update_sdk got unknown kwargs: {!r}\"", ".", "format", "(", "extra_kwargs", ")", ")", "path_params", "=", "{", "\"sdkId\"", ":", "sdk_id", "}", "path_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", "if", "v", "is", "not", "missing", "}", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "path_params", ")", ":", "if", "v", "is", "None", "or", "(", "isinstance", "(", "v", ",", "six", ".", "string_types", ")", "and", "len", "(", "v", ".", "strip", "(", ")", ")", "==", "0", ")", ":", "raise", "ValueError", "(", "'Parameter {} cannot be None, whitespace or empty string'", ".", "format", "(", "k", ")", ")", "header_params", "=", "{", "\"accept\"", ":", "\"application/json\"", ",", "\"content-type\"", ":", "\"application/json\"", ",", "\"if-match\"", ":", "kwargs", ".", "get", "(", "\"if_match\"", ",", "missing", ")", ",", "\"opc-request-id\"", ":", "kwargs", ".", "get", "(", "\"opc_request_id\"", ",", "missing", ")", "}", "header_params", "=", "{", "k", ":", "v", "for", "(", "k", ",", "v", ")", "in", "six", ".", "iteritems", "(", "header_params", ")", "if", "v", "is", "not", "missing", "and", "v", "is", "not", "None", "}", "retry_strategy", "=", "self", ".", "base_client", ".", "get_preferred_retry_strategy", "(", "operation_retry_strategy", "=", "kwargs", ".", "get", "(", "'retry_strategy'", ")", ",", "client_retry_strategy", "=", "self", ".", "retry_strategy", ")", "if", "retry_strategy", ":", "if", "not", "isinstance", "(", "retry_strategy", ",", "retry", ".", "NoneRetryStrategy", ")", ":", "self", ".", "base_client", ".", "add_opc_client_retries_header", "(", "header_params", ")", "retry_strategy", ".", "add_circuit_breaker_callback", "(", "self", ".", "circuit_breaker_callback", ")", "return", "retry_strategy", ".", "make_retrying_call", "(", "self", ".", "base_client", ".", "call_api", ",", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "body", "=", "update_sdk_details", ")", "else", ":", "return", "self", ".", "base_client", ".", "call_api", "(", "resource_path", "=", "resource_path", ",", "method", "=", "method", ",", "path_params", "=", "path_params", ",", "header_params", "=", "header_params", ",", "body", "=", "update_sdk_details", ")" ]
https://github.com/oracle/oci-python-sdk/blob/3c1604e4e212008fb6718e2f68cdb5ef71fd5793/src/oci/apigateway/api_gateway_client.py#L2034-L2123
agoragames/haigha
7b004e1c0316ec14b94fec1c54554654c38b1a25
haigha/frames/content_frame.py
python
ContentFrame.write_frame
(self, buf)
Write the frame into an existing buffer.
Write the frame into an existing buffer.
[ "Write", "the", "frame", "into", "an", "existing", "buffer", "." ]
def write_frame(self, buf): ''' Write the frame into an existing buffer. ''' writer = Writer(buf) writer.write_octet(self.type()).\ write_short(self.channel_id).\ write_long(len(self._payload)).\ write(self._payload).\ write_octet(0xce)
[ "def", "write_frame", "(", "self", ",", "buf", ")", ":", "writer", "=", "Writer", "(", "buf", ")", "writer", ".", "write_octet", "(", "self", ".", "type", "(", ")", ")", ".", "write_short", "(", "self", ".", "channel_id", ")", ".", "write_long", "(", "len", "(", "self", ".", "_payload", ")", ")", ".", "write", "(", "self", ".", "_payload", ")", ".", "write_octet", "(", "0xce", ")" ]
https://github.com/agoragames/haigha/blob/7b004e1c0316ec14b94fec1c54554654c38b1a25/haigha/frames/content_frame.py#L61-L71
nerdvegas/rez
d392c65bf63b4bca8106f938cec49144ba54e770
src/rez/packages.py
python
PackageBaseResourceWrapper.is_local
(self)
return (self.resource._repository.uid == local_repo.uid)
Returns True if the package is in the local package repository
Returns True if the package is in the local package repository
[ "Returns", "True", "if", "the", "package", "is", "in", "the", "local", "package", "repository" ]
def is_local(self): """Returns True if the package is in the local package repository""" local_repo = package_repository_manager.get_repository( self.config.local_packages_path) return (self.resource._repository.uid == local_repo.uid)
[ "def", "is_local", "(", "self", ")", ":", "local_repo", "=", "package_repository_manager", ".", "get_repository", "(", "self", ".", "config", ".", "local_packages_path", ")", "return", "(", "self", ".", "resource", ".", "_repository", ".", "uid", "==", "local_repo", ".", "uid", ")" ]
https://github.com/nerdvegas/rez/blob/d392c65bf63b4bca8106f938cec49144ba54e770/src/rez/packages.py#L120-L124
ckoepp/TwitterSearch
627b9f519d49faf6b83859717f9082b3b2622aaf
TwitterSearch/TwitterUserOrder.py
python
TwitterUserOrder.set_trim_user
(self, trim)
Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException
Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID
[ "Sets", "trim_user", "parameter", ".", "When", "set", "to", "True", "\\", "each", "tweet", "returned", "in", "a", "timeline", "will", "include", "a", "\\", "user", "object", "including", "only", "the", "status", "authors", "numerical", "ID" ]
def set_trim_user(self, trim): """ Sets 'trim_user' parameter. When set to True, \ each tweet returned in a timeline will include a \ user object including only the status authors numerical ID :param trim: Boolean triggering the usage of the parameter :raises: TwitterSearchException """ if not isinstance(trim, bool): raise TwitterSearchException(1008) self.arguments.update({'trim_user': 'true' if trim else 'false'})
[ "def", "set_trim_user", "(", "self", ",", "trim", ")", ":", "if", "not", "isinstance", "(", "trim", ",", "bool", ")", ":", "raise", "TwitterSearchException", "(", "1008", ")", "self", ".", "arguments", ".", "update", "(", "{", "'trim_user'", ":", "'true'", "if", "trim", "else", "'false'", "}", ")" ]
https://github.com/ckoepp/TwitterSearch/blob/627b9f519d49faf6b83859717f9082b3b2622aaf/TwitterSearch/TwitterUserOrder.py#L55-L66
angr/angr
4b04d56ace135018083d36d9083805be8146688b
angr/analyses/forward_analysis/visitors/function_graph.py
python
FunctionGraphVisitor.__init__
(self, func, graph=None)
[]
def __init__(self, func, graph=None): super(FunctionGraphVisitor, self).__init__() self.function = func if graph is None: self.graph = self.function.graph else: self.graph = graph self.reset()
[ "def", "__init__", "(", "self", ",", "func", ",", "graph", "=", "None", ")", ":", "super", "(", "FunctionGraphVisitor", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "function", "=", "func", "if", "graph", "is", "None", ":", "self", ".", "graph", "=", "self", ".", "function", ".", "graph", "else", ":", "self", ".", "graph", "=", "graph", "self", ".", "reset", "(", ")" ]
https://github.com/angr/angr/blob/4b04d56ace135018083d36d9083805be8146688b/angr/analyses/forward_analysis/visitors/function_graph.py#L9-L18
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
lib-python/2.7/xml/etree/ElementTree.py
python
XMLParser.doctype
(self, name, pubid, system)
This method of XMLParser is deprecated.
This method of XMLParser is deprecated.
[ "This", "method", "of", "XMLParser", "is", "deprecated", "." ]
def doctype(self, name, pubid, system): """This method of XMLParser is deprecated.""" warnings.warn( "This method of XMLParser is deprecated. Define doctype() " "method on the TreeBuilder target.", DeprecationWarning, )
[ "def", "doctype", "(", "self", ",", "name", ",", "pubid", ",", "system", ")", ":", "warnings", ".", "warn", "(", "\"This method of XMLParser is deprecated. Define doctype() \"", "\"method on the TreeBuilder target.\"", ",", "DeprecationWarning", ",", ")" ]
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/lib-python/2.7/xml/etree/ElementTree.py#L1637-L1643
HymanLiuTS/flaskTs
286648286976e85d9b9a5873632331efcafe0b21
flasky/lib/python2.7/site-packages/flask/app.py
python
Flask.log_exception
(self, exc_info)
Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8
Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`.
[ "Logs", "an", "exception", ".", "This", "is", "called", "by", ":", "meth", ":", "handle_exception", "if", "debugging", "is", "disabled", "and", "right", "before", "the", "handler", "is", "called", ".", "The", "default", "implementation", "logs", "the", "exception", "as", "error", "on", "the", ":", "attr", ":", "logger", "." ]
def log_exception(self, exc_info): """Logs an exception. This is called by :meth:`handle_exception` if debugging is disabled and right before the handler is called. The default implementation logs the exception as error on the :attr:`logger`. .. versionadded:: 0.8 """ self.logger.error('Exception on %s [%s]' % ( request.path, request.method ), exc_info=exc_info)
[ "def", "log_exception", "(", "self", ",", "exc_info", ")", ":", "self", ".", "logger", ".", "error", "(", "'Exception on %s [%s]'", "%", "(", "request", ".", "path", ",", "request", ".", "method", ")", ",", "exc_info", "=", "exc_info", ")" ]
https://github.com/HymanLiuTS/flaskTs/blob/286648286976e85d9b9a5873632331efcafe0b21/flasky/lib/python2.7/site-packages/flask/app.py#L1576-L1587
simonw/djangopeople.net
ed04d3c79d03b9c74f3e7f82b2af944e021f8e15
lib/openid/store/dumbstore.py
python
DumbStore.getAuthKey
(self)
return self.auth_key
This method returns the auth key generated by the constructor. @return: The auth key generated by the constructor. @rtype: C{str}
This method returns the auth key generated by the constructor.
[ "This", "method", "returns", "the", "auth", "key", "generated", "by", "the", "constructor", "." ]
def getAuthKey(self): """ This method returns the auth key generated by the constructor. @return: The auth key generated by the constructor. @rtype: C{str} """ return self.auth_key
[ "def", "getAuthKey", "(", "self", ")", ":", "return", "self", ".", "auth_key" ]
https://github.com/simonw/djangopeople.net/blob/ed04d3c79d03b9c74f3e7f82b2af944e021f8e15/lib/openid/store/dumbstore.py#L92-L101
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/modules/get_info.py
python
GetInfo.init_argparse
(self)
[]
def init_argparse(self): self.arg_parser = PupyArgumentParser(prog='get_info', description=self.__doc__)
[ "def", "init_argparse", "(", "self", ")", ":", "self", ".", "arg_parser", "=", "PupyArgumentParser", "(", "prog", "=", "'get_info'", ",", "description", "=", "self", ".", "__doc__", ")" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/scripts/sshbackdoors/backdoors/shell/pupy/pupy/modules/get_info.py#L8-L9
ytisf/theZoo
385eb68a35770991f34fed58f20b231e5e7a5fef
theZoo.py
python
main
()
[]
def main(): # Much much imports :) updateHandler = Updater eulaHandler = EULA() bannerHandler = muchmuchstrings.banners() db = db_handler.DBHandler() terminalHandler = Controller() def filter_array(array, colum, value): ret_array = [row for row in array if value in row[colum]] return ret_array def getArgvs(): parser = OptionParser() parser = OptionParser() parser.add_option("-f", "--filter", dest="mal_filter", default=[], help="Filter the malwares.", action="append") parser.add_option("-u", "--update", dest="update_bol", default=0, help="Updates the DB of theZoo.", action="store_true") parser.add_option("-v", "--version", dest="ver_bol", default=0, help="Shows version and licensing information.", action="store_true") parser.add_option("-w", "--license", dest="license_bol", default=0, help="Prints the GPLv3 license information.", action="store_true") (options, args) = parser.parse_args() return options # Here actually starts Main() arguments = getArgvs() # Checking for EULA Agreement a = eulaHandler.check_eula_file() if a == 0: eulaHandler.prompt_eula() # Get arguments # Check if update flag is on if arguments.update_bol == 1: a = Updater() with open('conf/db.ver', 'r') as f: a.update_db(f.readline()) sys.exit(1) # Check if version flag is on if arguments.ver_bol == 1: print(vars.maldb_banner) sys.exit(1) # Check if license flag is on if arguments.license_bol == 1: bannerHandler.print_license() sys.exit(1) if len(arguments.mal_filter) > 0: manySearch = manysearches.MuchSearch() print(vars.maldb_banner) manySearch.sort(arguments.mal_filter) sys.exit(1) # Initiate normal run. No arguments given. os.system('cls' if os.name == 'nt' else 'clear') print(vars.maldb_banner) while 1: terminalHandler.MainMenu() sys.exit(1)
[ "def", "main", "(", ")", ":", "# Much much imports :)", "updateHandler", "=", "Updater", "eulaHandler", "=", "EULA", "(", ")", "bannerHandler", "=", "muchmuchstrings", ".", "banners", "(", ")", "db", "=", "db_handler", ".", "DBHandler", "(", ")", "terminalHandler", "=", "Controller", "(", ")", "def", "filter_array", "(", "array", ",", "colum", ",", "value", ")", ":", "ret_array", "=", "[", "row", "for", "row", "in", "array", "if", "value", "in", "row", "[", "colum", "]", "]", "return", "ret_array", "def", "getArgvs", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "\"-f\"", ",", "\"--filter\"", ",", "dest", "=", "\"mal_filter\"", ",", "default", "=", "[", "]", ",", "help", "=", "\"Filter the malwares.\"", ",", "action", "=", "\"append\"", ")", "parser", ".", "add_option", "(", "\"-u\"", ",", "\"--update\"", ",", "dest", "=", "\"update_bol\"", ",", "default", "=", "0", ",", "help", "=", "\"Updates the DB of theZoo.\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_option", "(", "\"-v\"", ",", "\"--version\"", ",", "dest", "=", "\"ver_bol\"", ",", "default", "=", "0", ",", "help", "=", "\"Shows version and licensing information.\"", ",", "action", "=", "\"store_true\"", ")", "parser", ".", "add_option", "(", "\"-w\"", ",", "\"--license\"", ",", "dest", "=", "\"license_bol\"", ",", "default", "=", "0", ",", "help", "=", "\"Prints the GPLv3 license information.\"", ",", "action", "=", "\"store_true\"", ")", "(", "options", ",", "args", ")", "=", "parser", ".", "parse_args", "(", ")", "return", "options", "# Here actually starts Main()", "arguments", "=", "getArgvs", "(", ")", "# Checking for EULA Agreement", "a", "=", "eulaHandler", ".", "check_eula_file", "(", ")", "if", "a", "==", "0", ":", "eulaHandler", ".", "prompt_eula", "(", ")", "# Get arguments", "# Check if update flag is on", "if", "arguments", ".", "update_bol", "==", "1", ":", "a", "=", "Updater", "(", ")", "with", "open", "(", "'conf/db.ver'", ",", "'r'", ")", "as", "f", ":", "a", ".", "update_db", "(", "f", ".", "readline", "(", ")", ")", "sys", ".", "exit", "(", "1", ")", "# Check if version flag is on", "if", "arguments", ".", "ver_bol", "==", "1", ":", "print", "(", "vars", ".", "maldb_banner", ")", "sys", ".", "exit", "(", "1", ")", "# Check if license flag is on", "if", "arguments", ".", "license_bol", "==", "1", ":", "bannerHandler", ".", "print_license", "(", ")", "sys", ".", "exit", "(", "1", ")", "if", "len", "(", "arguments", ".", "mal_filter", ")", ">", "0", ":", "manySearch", "=", "manysearches", ".", "MuchSearch", "(", ")", "print", "(", "vars", ".", "maldb_banner", ")", "manySearch", ".", "sort", "(", "arguments", ".", "mal_filter", ")", "sys", ".", "exit", "(", "1", ")", "# Initiate normal run. No arguments given.", "os", ".", "system", "(", "'cls'", "if", "os", ".", "name", "==", "'nt'", "else", "'clear'", ")", "print", "(", "vars", ".", "maldb_banner", ")", "while", "1", ":", "terminalHandler", ".", "MainMenu", "(", ")", "sys", ".", "exit", "(", "1", ")" ]
https://github.com/ytisf/theZoo/blob/385eb68a35770991f34fed58f20b231e5e7a5fef/theZoo.py#L40-L105
PaddlePaddle/Research
2da0bd6c72d60e9df403aff23a7802779561c4a1
ST_DM/KDD2021-MSTPAC/code/ST-PAC/utils/object_transform.py
python
ObjectTransform.pickle_dumps_to_str
(cls, obj)
from object to str
from object to str
[ "from", "object", "to", "str" ]
def pickle_dumps_to_str(cls, obj): """ from object to str """ try: #return base64.encodebytes(pickle.dumps(obj)).decode() #return base64.b64encode(pickle.dumps(obj)) return base64.b64encode(pickle.dumps(obj)).decode() except pickle.PicklingError: pass
[ "def", "pickle_dumps_to_str", "(", "cls", ",", "obj", ")", ":", "try", ":", "#return base64.encodebytes(pickle.dumps(obj)).decode()", "#return base64.b64encode(pickle.dumps(obj))", "return", "base64", ".", "b64encode", "(", "pickle", ".", "dumps", "(", "obj", ")", ")", ".", "decode", "(", ")", "except", "pickle", ".", "PicklingError", ":", "pass" ]
https://github.com/PaddlePaddle/Research/blob/2da0bd6c72d60e9df403aff23a7802779561c4a1/ST_DM/KDD2021-MSTPAC/code/ST-PAC/utils/object_transform.py#L32-L41
regel/loudml
0008baef02259a8ae81dd210d3f91a51ffc9ed9f
loudml/filestorage.py
python
FileStorage.delete_model_hook
(self, model_name, hook_name)
Delete model hook
Delete model hook
[ "Delete", "model", "hook" ]
def delete_model_hook(self, model_name, hook_name): """Delete model hook""" hooks_dir = self.model_hooks_dir(model_name) hook_path = self._hook_path(hooks_dir, hook_name) try: os.unlink(hook_path) except FileNotFoundError: raise errors.NotFound("hook not found")
[ "def", "delete_model_hook", "(", "self", ",", "model_name", ",", "hook_name", ")", ":", "hooks_dir", "=", "self", ".", "model_hooks_dir", "(", "model_name", ")", "hook_path", "=", "self", ".", "_hook_path", "(", "hooks_dir", ",", "hook_name", ")", "try", ":", "os", ".", "unlink", "(", "hook_path", ")", "except", "FileNotFoundError", ":", "raise", "errors", ".", "NotFound", "(", "\"hook not found\"", ")" ]
https://github.com/regel/loudml/blob/0008baef02259a8ae81dd210d3f91a51ffc9ed9f/loudml/filestorage.py#L419-L427
glitchdotcom/WebPutty
4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7
ziplibs/werkzeug/wrappers.py
python
BaseRequest.values
(self)
return CombinedMultiDict(args)
Combined multi dict for :attr:`args` and :attr:`form`.
Combined multi dict for :attr:`args` and :attr:`form`.
[ "Combined", "multi", "dict", "for", ":", "attr", ":", "args", "and", ":", "attr", ":", "form", "." ]
def values(self): """Combined multi dict for :attr:`args` and :attr:`form`.""" args = [] for d in self.args, self.form: if not isinstance(d, MultiDict): d = MultiDict(d) args.append(d) return CombinedMultiDict(args)
[ "def", "values", "(", "self", ")", ":", "args", "=", "[", "]", "for", "d", "in", "self", ".", "args", ",", "self", ".", "form", ":", "if", "not", "isinstance", "(", "d", ",", "MultiDict", ")", ":", "d", "=", "MultiDict", "(", "d", ")", "args", ".", "append", "(", "d", ")", "return", "CombinedMultiDict", "(", "args", ")" ]
https://github.com/glitchdotcom/WebPutty/blob/4f5da5eb2b4668cbf3c15cf002feacd1d95d2ef7/ziplibs/werkzeug/wrappers.py#L380-L387
web2py/web2py
095905c4e010a1426c729483d912e270a51b7ba8
gluon/contrib/pysimplesoap/client.py
python
SoapClient.wsdl_call_get_params
(self, method, input, args, kwargs)
return (method, params)
Build params from input and args/kwargs
Build params from input and args/kwargs
[ "Build", "params", "from", "input", "and", "args", "/", "kwargs" ]
def wsdl_call_get_params(self, method, input, args, kwargs): """Build params from input and args/kwargs""" params = inputname = inputargs = None all_args = {} if input: inputname = list(input.keys())[0] inputargs = input[inputname] if input and args: # convert positional parameters to named parameters: d = {} for idx, arg in enumerate(args): key = list(inputargs.keys())[idx] if isinstance(arg, dict): if key not in arg: raise KeyError('Unhandled key %s. use client.help(method)' % key) d[key] = arg[key] else: d[key] = arg all_args.update({inputname: d}) if input and (kwargs or all_args): if kwargs: all_args.update({inputname: kwargs}) valid, errors, warnings = self.wsdl_validate_params(input, all_args) if not valid: raise ValueError('Invalid Args Structure. Errors: %s' % errors) # sort and filter parameters according to wsdl input structure tree = sort_dict(input, all_args) root = list(tree.values())[0] params = [] # make a params tuple list suitable for self.call(method, *params) for k, v in root.items(): # fix referenced namespaces as info is lost when calling call root_ns = root.namespaces[k] if not root.references[k] and isinstance(v, Struct): v.namespaces[None] = root_ns params.append((k, v)) # TODO: check style and document attributes if self.__soap_server in ('axis', ): # use the operation name method = method else: # use the message (element) name method = inputname #elif not input: #TODO: no message! (see wsmtxca.dummy) else: params = kwargs and kwargs.items() return (method, params)
[ "def", "wsdl_call_get_params", "(", "self", ",", "method", ",", "input", ",", "args", ",", "kwargs", ")", ":", "params", "=", "inputname", "=", "inputargs", "=", "None", "all_args", "=", "{", "}", "if", "input", ":", "inputname", "=", "list", "(", "input", ".", "keys", "(", ")", ")", "[", "0", "]", "inputargs", "=", "input", "[", "inputname", "]", "if", "input", "and", "args", ":", "# convert positional parameters to named parameters:", "d", "=", "{", "}", "for", "idx", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "key", "=", "list", "(", "inputargs", ".", "keys", "(", ")", ")", "[", "idx", "]", "if", "isinstance", "(", "arg", ",", "dict", ")", ":", "if", "key", "not", "in", "arg", ":", "raise", "KeyError", "(", "'Unhandled key %s. use client.help(method)'", "%", "key", ")", "d", "[", "key", "]", "=", "arg", "[", "key", "]", "else", ":", "d", "[", "key", "]", "=", "arg", "all_args", ".", "update", "(", "{", "inputname", ":", "d", "}", ")", "if", "input", "and", "(", "kwargs", "or", "all_args", ")", ":", "if", "kwargs", ":", "all_args", ".", "update", "(", "{", "inputname", ":", "kwargs", "}", ")", "valid", ",", "errors", ",", "warnings", "=", "self", ".", "wsdl_validate_params", "(", "input", ",", "all_args", ")", "if", "not", "valid", ":", "raise", "ValueError", "(", "'Invalid Args Structure. Errors: %s'", "%", "errors", ")", "# sort and filter parameters according to wsdl input structure", "tree", "=", "sort_dict", "(", "input", ",", "all_args", ")", "root", "=", "list", "(", "tree", ".", "values", "(", ")", ")", "[", "0", "]", "params", "=", "[", "]", "# make a params tuple list suitable for self.call(method, *params)", "for", "k", ",", "v", "in", "root", ".", "items", "(", ")", ":", "# fix referenced namespaces as info is lost when calling call", "root_ns", "=", "root", ".", "namespaces", "[", "k", "]", "if", "not", "root", ".", "references", "[", "k", "]", "and", "isinstance", "(", "v", ",", "Struct", ")", ":", "v", ".", "namespaces", "[", "None", "]", "=", "root_ns", "params", ".", "append", "(", "(", "k", ",", "v", ")", ")", "# TODO: check style and document attributes", "if", "self", ".", "__soap_server", "in", "(", "'axis'", ",", ")", ":", "# use the operation name", "method", "=", "method", "else", ":", "# use the message (element) name", "method", "=", "inputname", "#elif not input:", "#TODO: no message! (see wsmtxca.dummy)", "else", ":", "params", "=", "kwargs", "and", "kwargs", ".", "items", "(", ")", "return", "(", "method", ",", "params", ")" ]
https://github.com/web2py/web2py/blob/095905c4e010a1426c729483d912e270a51b7ba8/gluon/contrib/pysimplesoap/client.py#L380-L430
cheshirekow/cmake_format
eff5df1f41c665ea7cac799396042e4f406ef09a
cmakelang/genparsers.py
python
process_set_statement
(argtree, variables)
Process a set() statement, updating the variable assignments accordingly
Process a set() statement, updating the variable assignments accordingly
[ "Process", "a", "set", "()", "statement", "updating", "the", "variable", "assignments", "accordingly" ]
def process_set_statement(argtree, variables): """ Process a set() statement, updating the variable assignments accordingly """ varname = replace_varrefs(argtree.varname.spelling, variables) if not argtree.value_group: variables.pop(varname, None) return setargs = argtree.value_group.get_tokens(kind="semantic") valuestr = ";".join(arg.spelling.strip('"') for arg in setargs) variables[varname] = replace_varrefs(valuestr, variables)
[ "def", "process_set_statement", "(", "argtree", ",", "variables", ")", ":", "varname", "=", "replace_varrefs", "(", "argtree", ".", "varname", ".", "spelling", ",", "variables", ")", "if", "not", "argtree", ".", "value_group", ":", "variables", ".", "pop", "(", "varname", ",", "None", ")", "return", "setargs", "=", "argtree", ".", "value_group", ".", "get_tokens", "(", "kind", "=", "\"semantic\"", ")", "valuestr", "=", "\";\"", ".", "join", "(", "arg", ".", "spelling", ".", "strip", "(", "'\"'", ")", "for", "arg", "in", "setargs", ")", "variables", "[", "varname", "]", "=", "replace_varrefs", "(", "valuestr", ",", "variables", ")" ]
https://github.com/cheshirekow/cmake_format/blob/eff5df1f41c665ea7cac799396042e4f406ef09a/cmakelang/genparsers.py#L78-L89
CheckPointSW/Karta
b845928487b50a5b41acd532ae0399177a4356aa
src/thumbs_up/analyzers/arm.py
python
ArmAnalyzer.annotatePtr
(self, ea, code_type)
return ea + code_type
Annotate a pointer to include the code type metadata. Args: ea (int): clean effective address code_type (int): code type to be encoded in the annotation Return Value: dest address, annotated with the code type
Annotate a pointer to include the code type metadata.
[ "Annotate", "a", "pointer", "to", "include", "the", "code", "type", "metadata", "." ]
def annotatePtr(self, ea, code_type): """Annotate a pointer to include the code type metadata. Args: ea (int): clean effective address code_type (int): code type to be encoded in the annotation Return Value: dest address, annotated with the code type """ return ea + code_type
[ "def", "annotatePtr", "(", "self", ",", "ea", ",", "code_type", ")", ":", "return", "ea", "+", "code_type" ]
https://github.com/CheckPointSW/Karta/blob/b845928487b50a5b41acd532ae0399177a4356aa/src/thumbs_up/analyzers/arm.py#L143-L153
CalebBell/thermo
572a47d1b03d49fe609b8d5f826fa6a7cde00828
thermo/viscosity.py
python
ViscosityGas.calculate
(self, T, method)
return mu
r'''Method to calculate low-pressure gas viscosity at tempearture `T` with a given method. This method has no exception handling; see :obj:`T_dependent_property <thermo.utils.TDependentProperty.T_dependent_property>` for that. Parameters ---------- T : float Temperature of the gas, [K] method : str Name of the method to use Returns ------- mu : float Viscosity of the gas at T and a low pressure, [Pa*s]
r'''Method to calculate low-pressure gas viscosity at tempearture `T` with a given method.
[ "r", "Method", "to", "calculate", "low", "-", "pressure", "gas", "viscosity", "at", "tempearture", "T", "with", "a", "given", "method", "." ]
def calculate(self, T, method): r'''Method to calculate low-pressure gas viscosity at tempearture `T` with a given method. This method has no exception handling; see :obj:`T_dependent_property <thermo.utils.TDependentProperty.T_dependent_property>` for that. Parameters ---------- T : float Temperature of the gas, [K] method : str Name of the method to use Returns ------- mu : float Viscosity of the gas at T and a low pressure, [Pa*s] ''' if method == GHARAGHEIZI: mu = viscosity_gas_Gharagheizi(T, self.Tc, self.Pc, self.MW) elif method == COOLPROP: mu = CoolProp_T_dependent_property(T, self.CASRN, 'V', 'g') elif method == DIPPR_PERRY_8E: mu = EQ102(T, *self.Perrys2_312_coeffs) elif method == VDI_PPDS: mu = horner(self.VDI_PPDS_coeffs, T) elif method == YOON_THODOS: mu = Yoon_Thodos(T, self.Tc, self.Pc, self.MW) elif method == STIEL_THODOS: mu = Stiel_Thodos(T, self.Tc, self.Pc, self.MW) elif method == LUCAS_GAS: mu = Lucas_gas(T, self.Tc, self.Pc, self.Zc, self.MW, self.dipole, CASRN=self.CASRN) else: return self._base_calculate(T, method) return mu
[ "def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "if", "method", "==", "GHARAGHEIZI", ":", "mu", "=", "viscosity_gas_Gharagheizi", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "COOLPROP", ":", "mu", "=", "CoolProp_T_dependent_property", "(", "T", ",", "self", ".", "CASRN", ",", "'V'", ",", "'g'", ")", "elif", "method", "==", "DIPPR_PERRY_8E", ":", "mu", "=", "EQ102", "(", "T", ",", "*", "self", ".", "Perrys2_312_coeffs", ")", "elif", "method", "==", "VDI_PPDS", ":", "mu", "=", "horner", "(", "self", ".", "VDI_PPDS_coeffs", ",", "T", ")", "elif", "method", "==", "YOON_THODOS", ":", "mu", "=", "Yoon_Thodos", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "STIEL_THODOS", ":", "mu", "=", "Stiel_Thodos", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "MW", ")", "elif", "method", "==", "LUCAS_GAS", ":", "mu", "=", "Lucas_gas", "(", "T", ",", "self", ".", "Tc", ",", "self", ".", "Pc", ",", "self", ".", "Zc", ",", "self", ".", "MW", ",", "self", ".", "dipole", ",", "CASRN", "=", "self", ".", "CASRN", ")", "else", ":", "return", "self", ".", "_base_calculate", "(", "T", ",", "method", ")", "return", "mu" ]
https://github.com/CalebBell/thermo/blob/572a47d1b03d49fe609b8d5f826fa6a7cde00828/thermo/viscosity.py#L882-L918
alexa/alexa-skills-kit-sdk-for-python
079de73bc8b827be51ea700a3e4e19c29983a173
ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py
python
RequestVerifier._validate_cert_chain
(self, cert_chain)
Validate the certificate chain. This method checks if the passed in certificate chain is valid. A :py:class:`VerificationException` is raised if the certificate chain is not valid. The end certificate is read, using the :py:func:`cryptography.x509.load_pem_x509_certificate` method. The x509 backend is set as default to the :py:class:`cryptography.hazmat.backends.default_backend` instance. :param cert_chain: Certificate chain to be validated :type cert_chain: bytes :return: None :raises: :py:class:`VerificationException` if certificate chain is not valid
Validate the certificate chain.
[ "Validate", "the", "certificate", "chain", "." ]
def _validate_cert_chain(self, cert_chain): # type: (bytes) -> None """Validate the certificate chain. This method checks if the passed in certificate chain is valid. A :py:class:`VerificationException` is raised if the certificate chain is not valid. The end certificate is read, using the :py:func:`cryptography.x509.load_pem_x509_certificate` method. The x509 backend is set as default to the :py:class:`cryptography.hazmat.backends.default_backend` instance. :param cert_chain: Certificate chain to be validated :type cert_chain: bytes :return: None :raises: :py:class:`VerificationException` if certificate chain is not valid """ try: end_cert = None intermediate_certs = [] for type_name, headers, der_bytes in pem.unarmor( cert_chain, multiple=True): if end_cert is None: end_cert = der_bytes else: intermediate_certs.append(der_bytes) validator = CertificateValidator(end_cert, intermediate_certs) validator.validate_usage(key_usage={'digital_signature'}) except (PathError, ValidationError) as e: raise VerificationException("Certificate chain is not valid", e)
[ "def", "_validate_cert_chain", "(", "self", ",", "cert_chain", ")", ":", "# type: (bytes) -> None", "try", ":", "end_cert", "=", "None", "intermediate_certs", "=", "[", "]", "for", "type_name", ",", "headers", ",", "der_bytes", "in", "pem", ".", "unarmor", "(", "cert_chain", ",", "multiple", "=", "True", ")", ":", "if", "end_cert", "is", "None", ":", "end_cert", "=", "der_bytes", "else", ":", "intermediate_certs", ".", "append", "(", "der_bytes", ")", "validator", "=", "CertificateValidator", "(", "end_cert", ",", "intermediate_certs", ")", "validator", ".", "validate_usage", "(", "key_usage", "=", "{", "'digital_signature'", "}", ")", "except", "(", "PathError", ",", "ValidationError", ")", "as", "e", ":", "raise", "VerificationException", "(", "\"Certificate chain is not valid\"", ",", "e", ")" ]
https://github.com/alexa/alexa-skills-kit-sdk-for-python/blob/079de73bc8b827be51ea700a3e4e19c29983a173/ask-sdk-webservice-support/ask_sdk_webservice_support/verifier.py#L322-L355
snarfed/granary
ab085de2aef0cff8ac31a99b5e21443a249e8419
granary/facebook.py
python
Facebook._scraped_datetime
(tag)
Tries to parse a datetime string scraped from HTML (web or email). Examples seen in the wild: December 14 at 12:35 PM 5 July at 21:50 Args: tag: BeautifulSoup Tag
Tries to parse a datetime string scraped from HTML (web or email).
[ "Tries", "to", "parse", "a", "datetime", "string", "scraped", "from", "HTML", "(", "web", "or", "email", ")", "." ]
def _scraped_datetime(tag): """Tries to parse a datetime string scraped from HTML (web or email). Examples seen in the wild: December 14 at 12:35 PM 5 July at 21:50 Args: tag: BeautifulSoup Tag """ if not tag: return None try: # sadly using parse(fuzzy=True) here makes too many mistakes on relative # time strings seen on mbasic, eg '22 hrs [ago]', 'Yesterday at 12:34 PM' parsed = dateutil.parser.parse(tag.get_text(strip=True), default=now_fn()) return parsed.isoformat('T') except (ValueError, OverflowError): logging.debug(f"Couldn't parse datetime string {tag!r}")
[ "def", "_scraped_datetime", "(", "tag", ")", ":", "if", "not", "tag", ":", "return", "None", "try", ":", "# sadly using parse(fuzzy=True) here makes too many mistakes on relative", "# time strings seen on mbasic, eg '22 hrs [ago]', 'Yesterday at 12:34 PM'", "parsed", "=", "dateutil", ".", "parser", ".", "parse", "(", "tag", ".", "get_text", "(", "strip", "=", "True", ")", ",", "default", "=", "now_fn", "(", ")", ")", "return", "parsed", ".", "isoformat", "(", "'T'", ")", "except", "(", "ValueError", ",", "OverflowError", ")", ":", "logging", ".", "debug", "(", "f\"Couldn't parse datetime string {tag!r}\"", ")" ]
https://github.com/snarfed/granary/blob/ab085de2aef0cff8ac31a99b5e21443a249e8419/granary/facebook.py#L1754-L1773
gramps-project/gramps
04d4651a43eb210192f40a9f8c2bad8ee8fa3753
gramps/gen/lib/person.py
python
Person.get_gender
(self)
return self.__gender
Return the gender of the Person. :returns: Returns one of the following constants: - Person.MALE - Person.FEMALE - Person.UNKNOWN :rtype: int
Return the gender of the Person.
[ "Return", "the", "gender", "of", "the", "Person", "." ]
def get_gender(self): """ Return the gender of the Person. :returns: Returns one of the following constants: - Person.MALE - Person.FEMALE - Person.UNKNOWN :rtype: int """ return self.__gender
[ "def", "get_gender", "(", "self", ")", ":", "return", "self", ".", "__gender" ]
https://github.com/gramps-project/gramps/blob/04d4651a43eb210192f40a9f8c2bad8ee8fa3753/gramps/gen/lib/person.py#L654-L665
harry159821/XiamiForLinuxProject
93d75d7652548d02ba386c961bc8afb5550a530e
bs4/dammit.py
python
UnicodeDammit._sub_ms_char
(self, match)
return sub
Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.
Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.
[ "Changes", "a", "MS", "smart", "quote", "character", "to", "an", "XML", "or", "HTML", "entity", "or", "an", "ASCII", "character", "." ]
def _sub_ms_char(self, match): """Changes a MS smart quote character to an XML or HTML entity, or an ASCII character.""" orig = match.group(1) if self.smart_quotes_to == 'ascii': sub = self.MS_CHARS_TO_ASCII.get(orig).encode() else: sub = self.MS_CHARS.get(orig) if type(sub) == tuple: if self.smart_quotes_to == 'xml': sub = '&#x'.encode() + sub[1].encode() + ';'.encode() else: sub = '&'.encode() + sub[0].encode() + ';'.encode() else: sub = sub.encode() return sub
[ "def", "_sub_ms_char", "(", "self", ",", "match", ")", ":", "orig", "=", "match", ".", "group", "(", "1", ")", "if", "self", ".", "smart_quotes_to", "==", "'ascii'", ":", "sub", "=", "self", ".", "MS_CHARS_TO_ASCII", ".", "get", "(", "orig", ")", ".", "encode", "(", ")", "else", ":", "sub", "=", "self", ".", "MS_CHARS", ".", "get", "(", "orig", ")", "if", "type", "(", "sub", ")", "==", "tuple", ":", "if", "self", ".", "smart_quotes_to", "==", "'xml'", ":", "sub", "=", "'&#x'", ".", "encode", "(", ")", "+", "sub", "[", "1", "]", ".", "encode", "(", ")", "+", "';'", ".", "encode", "(", ")", "else", ":", "sub", "=", "'&'", ".", "encode", "(", ")", "+", "sub", "[", "0", "]", ".", "encode", "(", ")", "+", "';'", ".", "encode", "(", ")", "else", ":", "sub", "=", "sub", ".", "encode", "(", ")", "return", "sub" ]
https://github.com/harry159821/XiamiForLinuxProject/blob/93d75d7652548d02ba386c961bc8afb5550a530e/bs4/dammit.py#L242-L257
pyqtgraph/pyqtgraph
ac3887abfca4e529aac44f022f8e40556a2587b0
pyqtgraph/flowchart/Node.py
python
Node.update
(self, signal=True)
Collect all input values, attempt to process new output values, and propagate downstream. Subclasses should call update() whenever thir internal state has changed (such as when the user interacts with the Node's control widget). Update is automatically called when the inputs to the node are changed.
Collect all input values, attempt to process new output values, and propagate downstream. Subclasses should call update() whenever thir internal state has changed (such as when the user interacts with the Node's control widget). Update is automatically called when the inputs to the node are changed.
[ "Collect", "all", "input", "values", "attempt", "to", "process", "new", "output", "values", "and", "propagate", "downstream", ".", "Subclasses", "should", "call", "update", "()", "whenever", "thir", "internal", "state", "has", "changed", "(", "such", "as", "when", "the", "user", "interacts", "with", "the", "Node", "s", "control", "widget", ")", ".", "Update", "is", "automatically", "called", "when", "the", "inputs", "to", "the", "node", "are", "changed", "." ]
def update(self, signal=True): """Collect all input values, attempt to process new output values, and propagate downstream. Subclasses should call update() whenever thir internal state has changed (such as when the user interacts with the Node's control widget). Update is automatically called when the inputs to the node are changed. """ vals = self.inputValues() #print " inputs:", vals try: if self.isBypassed(): out = self.processBypassed(vals) else: out = self.process(**strDict(vals)) #print " output:", out if out is not None: if signal: self.setOutput(**out) else: self.setOutputNoSignal(**out) for n,t in self.inputs().items(): t.setValueAcceptable(True) self.clearException() except: #printExc( "Exception while processing %s:" % self.name()) for n,t in self.outputs().items(): t.setValue(None) self.setException(sys.exc_info()) if signal: #self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data self.sigOutputChanged.emit(self)
[ "def", "update", "(", "self", ",", "signal", "=", "True", ")", ":", "vals", "=", "self", ".", "inputValues", "(", ")", "#print \" inputs:\", vals", "try", ":", "if", "self", ".", "isBypassed", "(", ")", ":", "out", "=", "self", ".", "processBypassed", "(", "vals", ")", "else", ":", "out", "=", "self", ".", "process", "(", "*", "*", "strDict", "(", "vals", ")", ")", "#print \" output:\", out", "if", "out", "is", "not", "None", ":", "if", "signal", ":", "self", ".", "setOutput", "(", "*", "*", "out", ")", "else", ":", "self", ".", "setOutputNoSignal", "(", "*", "*", "out", ")", "for", "n", ",", "t", "in", "self", ".", "inputs", "(", ")", ".", "items", "(", ")", ":", "t", ".", "setValueAcceptable", "(", "True", ")", "self", ".", "clearException", "(", ")", "except", ":", "#printExc( \"Exception while processing %s:\" % self.name())", "for", "n", ",", "t", "in", "self", ".", "outputs", "(", ")", ".", "items", "(", ")", ":", "t", ".", "setValue", "(", "None", ")", "self", ".", "setException", "(", "sys", ".", "exc_info", "(", ")", ")", "if", "signal", ":", "#self.emit(QtCore.SIGNAL('outputChanged'), self) ## triggers flowchart to propagate new data", "self", ".", "sigOutputChanged", ".", "emit", "(", "self", ")" ]
https://github.com/pyqtgraph/pyqtgraph/blob/ac3887abfca4e529aac44f022f8e40556a2587b0/pyqtgraph/flowchart/Node.py#L301-L331
googleapis/python-dialogflow
e48ea001b7c8a4a5c1fe4b162bad49ea397458e9
google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py
python
SessionEntityTypesClient.common_organization_path
(organization: str,)
return "organizations/{organization}".format(organization=organization,)
Returns a fully-qualified organization string.
Returns a fully-qualified organization string.
[ "Returns", "a", "fully", "-", "qualified", "organization", "string", "." ]
def common_organization_path(organization: str,) -> str: """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,)
[ "def", "common_organization_path", "(", "organization", ":", "str", ",", ")", "->", "str", ":", "return", "\"organizations/{organization}\"", ".", "format", "(", "organization", "=", "organization", ",", ")" ]
https://github.com/googleapis/python-dialogflow/blob/e48ea001b7c8a4a5c1fe4b162bad49ea397458e9/google/cloud/dialogflow_v2beta1/services/session_entity_types/client.py#L212-L214
nicolargo/glances
00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2
glances/outputs/glances_curses_browser.py
python
GlancesCursesBrowser.display
(self, stats, cs_status=None)
return True
Display the servers list. :return: True if the stats have been displayed else False (no server available)
Display the servers list.
[ "Display", "the", "servers", "list", "." ]
def display(self, stats, cs_status=None): """Display the servers list. :return: True if the stats have been displayed else False (no server available) """ # Init the internal line/column for Glances Curses self.init_line_column() # Get the current screen size screen_x = self.screen.getmaxyx()[1] screen_y = self.screen.getmaxyx()[0] stats_max = screen_y - 3 stats_len = len(stats) self._page_max_lines = stats_max self._page_max = int(math.ceil(stats_len / stats_max)) # Init position x = 0 y = 0 # Display top header if stats_len == 0: if self.first_scan and not self.args.disable_autodiscover: msg = 'Glances is scanning your network. Please wait...' self.first_scan = False else: msg = 'No Glances server available' elif len(stats) == 1: msg = 'One Glances server available' else: msg = '{} Glances servers available'.format(stats_len) if self.args.disable_autodiscover: msg += ' (auto discover is disabled)' if screen_y > 1: self.term_window.addnstr(y, x, msg, screen_x - x, self.colors_list['TITLE']) msg = '{}'.format(self._get_status_count(stats)) self.term_window.addnstr(y + 1, x, msg, screen_x - x) if stats_len > stats_max and screen_y > 2: msg = '{} servers displayed.({}/{}) {}'.format( self.get_pagelines(stats), self._current_page + 1, self._page_max, self._get_status_count(stats) ) self.term_window.addnstr(y + 1, x, msg, screen_x - x) if stats_len == 0: return False # Display the Glances server list # ================================ # Table of table # Item description: [stats_id, column name, column size] column_def = [ ['name', 'Name', 16], ['alias', None, None], ['load_min5', 'LOAD', 6], ['cpu_percent', 'CPU%', 5], ['mem_percent', 'MEM%', 5], ['status', 'STATUS', 9], ['ip', 'IP', 15], # ['port', 'PORT', 5], ['hr_name', 'OS', 16], ] y = 2 # Display table header xc = x + 2 for cpt, c in enumerate(column_def): if xc < screen_x and y < screen_y and c[1] is not None: self.term_window.addnstr(y, xc, c[1], screen_x - x, self.colors_list['BOLD']) xc += c[2] + self.space_between_column y += 1 # If a servers has been deleted from the list... # ... and if the cursor is in the latest position if self.cursor > len(stats) - 1: # Set the cursor position to the latest item self.cursor = len(stats) - 1 stats_list = self._get_stats(stats) start_line = self._page_max_lines * self._current_page end_line = start_line + self.get_pagelines(stats_list) current_page = stats_list[start_line:end_line] # Display table line = 0 for v in current_page: # Limit the number of displayed server (see issue #1256) if line >= stats_max: continue # Get server stats server_stat = {} for c in column_def: try: server_stat[c[0]] = v[c[0]] except KeyError as e: logger.debug("Cannot grab stats {} from server (KeyError: {})".format(c[0], e)) server_stat[c[0]] = '?' # Display alias instead of name try: if c[0] == 'alias' and v[c[0]] is not None: server_stat['name'] = v[c[0]] except KeyError: pass # Display line for server stats cpt = 0 xc = x # Is the line selected ? if line == self.cursor: # Display cursor self.term_window.addnstr(y, xc, ">", screen_x - xc, self.colors_list['BOLD']) # Display the line xc += 2 for c in column_def: if xc < screen_x and y < screen_y and c[1] is not None: # Display server stats self.term_window.addnstr(y, xc, format(server_stat[c[0]]), c[2], self.colors_list[v['status']]) xc += c[2] + self.space_between_column cpt += 1 # Next line, next server... y += 1 line += 1 return True
[ "def", "display", "(", "self", ",", "stats", ",", "cs_status", "=", "None", ")", ":", "# Init the internal line/column for Glances Curses", "self", ".", "init_line_column", "(", ")", "# Get the current screen size", "screen_x", "=", "self", ".", "screen", ".", "getmaxyx", "(", ")", "[", "1", "]", "screen_y", "=", "self", ".", "screen", ".", "getmaxyx", "(", ")", "[", "0", "]", "stats_max", "=", "screen_y", "-", "3", "stats_len", "=", "len", "(", "stats", ")", "self", ".", "_page_max_lines", "=", "stats_max", "self", ".", "_page_max", "=", "int", "(", "math", ".", "ceil", "(", "stats_len", "/", "stats_max", ")", ")", "# Init position", "x", "=", "0", "y", "=", "0", "# Display top header", "if", "stats_len", "==", "0", ":", "if", "self", ".", "first_scan", "and", "not", "self", ".", "args", ".", "disable_autodiscover", ":", "msg", "=", "'Glances is scanning your network. Please wait...'", "self", ".", "first_scan", "=", "False", "else", ":", "msg", "=", "'No Glances server available'", "elif", "len", "(", "stats", ")", "==", "1", ":", "msg", "=", "'One Glances server available'", "else", ":", "msg", "=", "'{} Glances servers available'", ".", "format", "(", "stats_len", ")", "if", "self", ".", "args", ".", "disable_autodiscover", ":", "msg", "+=", "' (auto discover is disabled)'", "if", "screen_y", ">", "1", ":", "self", ".", "term_window", ".", "addnstr", "(", "y", ",", "x", ",", "msg", ",", "screen_x", "-", "x", ",", "self", ".", "colors_list", "[", "'TITLE'", "]", ")", "msg", "=", "'{}'", ".", "format", "(", "self", ".", "_get_status_count", "(", "stats", ")", ")", "self", ".", "term_window", ".", "addnstr", "(", "y", "+", "1", ",", "x", ",", "msg", ",", "screen_x", "-", "x", ")", "if", "stats_len", ">", "stats_max", "and", "screen_y", ">", "2", ":", "msg", "=", "'{} servers displayed.({}/{}) {}'", ".", "format", "(", "self", ".", "get_pagelines", "(", "stats", ")", ",", "self", ".", "_current_page", "+", "1", ",", "self", ".", "_page_max", ",", "self", ".", "_get_status_count", "(", "stats", ")", ")", "self", ".", "term_window", ".", "addnstr", "(", "y", "+", "1", ",", "x", ",", "msg", ",", "screen_x", "-", "x", ")", "if", "stats_len", "==", "0", ":", "return", "False", "# Display the Glances server list", "# ================================", "# Table of table", "# Item description: [stats_id, column name, column size]", "column_def", "=", "[", "[", "'name'", ",", "'Name'", ",", "16", "]", ",", "[", "'alias'", ",", "None", ",", "None", "]", ",", "[", "'load_min5'", ",", "'LOAD'", ",", "6", "]", ",", "[", "'cpu_percent'", ",", "'CPU%'", ",", "5", "]", ",", "[", "'mem_percent'", ",", "'MEM%'", ",", "5", "]", ",", "[", "'status'", ",", "'STATUS'", ",", "9", "]", ",", "[", "'ip'", ",", "'IP'", ",", "15", "]", ",", "# ['port', 'PORT', 5],", "[", "'hr_name'", ",", "'OS'", ",", "16", "]", ",", "]", "y", "=", "2", "# Display table header", "xc", "=", "x", "+", "2", "for", "cpt", ",", "c", "in", "enumerate", "(", "column_def", ")", ":", "if", "xc", "<", "screen_x", "and", "y", "<", "screen_y", "and", "c", "[", "1", "]", "is", "not", "None", ":", "self", ".", "term_window", ".", "addnstr", "(", "y", ",", "xc", ",", "c", "[", "1", "]", ",", "screen_x", "-", "x", ",", "self", ".", "colors_list", "[", "'BOLD'", "]", ")", "xc", "+=", "c", "[", "2", "]", "+", "self", ".", "space_between_column", "y", "+=", "1", "# If a servers has been deleted from the list...", "# ... and if the cursor is in the latest position", "if", "self", ".", "cursor", ">", "len", "(", "stats", ")", "-", "1", ":", "# Set the cursor position to the latest item", "self", ".", "cursor", "=", "len", "(", "stats", ")", "-", "1", "stats_list", "=", "self", ".", "_get_stats", "(", "stats", ")", "start_line", "=", "self", ".", "_page_max_lines", "*", "self", ".", "_current_page", "end_line", "=", "start_line", "+", "self", ".", "get_pagelines", "(", "stats_list", ")", "current_page", "=", "stats_list", "[", "start_line", ":", "end_line", "]", "# Display table", "line", "=", "0", "for", "v", "in", "current_page", ":", "# Limit the number of displayed server (see issue #1256)", "if", "line", ">=", "stats_max", ":", "continue", "# Get server stats", "server_stat", "=", "{", "}", "for", "c", "in", "column_def", ":", "try", ":", "server_stat", "[", "c", "[", "0", "]", "]", "=", "v", "[", "c", "[", "0", "]", "]", "except", "KeyError", "as", "e", ":", "logger", ".", "debug", "(", "\"Cannot grab stats {} from server (KeyError: {})\"", ".", "format", "(", "c", "[", "0", "]", ",", "e", ")", ")", "server_stat", "[", "c", "[", "0", "]", "]", "=", "'?'", "# Display alias instead of name", "try", ":", "if", "c", "[", "0", "]", "==", "'alias'", "and", "v", "[", "c", "[", "0", "]", "]", "is", "not", "None", ":", "server_stat", "[", "'name'", "]", "=", "v", "[", "c", "[", "0", "]", "]", "except", "KeyError", ":", "pass", "# Display line for server stats", "cpt", "=", "0", "xc", "=", "x", "# Is the line selected ?", "if", "line", "==", "self", ".", "cursor", ":", "# Display cursor", "self", ".", "term_window", ".", "addnstr", "(", "y", ",", "xc", ",", "\">\"", ",", "screen_x", "-", "xc", ",", "self", ".", "colors_list", "[", "'BOLD'", "]", ")", "# Display the line", "xc", "+=", "2", "for", "c", "in", "column_def", ":", "if", "xc", "<", "screen_x", "and", "y", "<", "screen_y", "and", "c", "[", "1", "]", "is", "not", "None", ":", "# Display server stats", "self", ".", "term_window", ".", "addnstr", "(", "y", ",", "xc", ",", "format", "(", "server_stat", "[", "c", "[", "0", "]", "]", ")", ",", "c", "[", "2", "]", ",", "self", ".", "colors_list", "[", "v", "[", "'status'", "]", "]", ")", "xc", "+=", "c", "[", "2", "]", "+", "self", ".", "space_between_column", "cpt", "+=", "1", "# Next line, next server...", "y", "+=", "1", "line", "+=", "1", "return", "True" ]
https://github.com/nicolargo/glances/blob/00c65933ae1d0ebd3e72dc30fc3c215a83dfaae2/glances/outputs/glances_curses_browser.py#L252-L379
IdentityPython/pysaml2
6badb32d212257bd83ffcc816f9b625f68281b47
src/saml2/extension/dri.py
python
publishers_type__from_string
(xml_string)
return saml2.create_class_from_xml_string(PublishersType_, xml_string)
[]
def publishers_type__from_string(xml_string): return saml2.create_class_from_xml_string(PublishersType_, xml_string)
[ "def", "publishers_type__from_string", "(", "xml_string", ")", ":", "return", "saml2", ".", "create_class_from_xml_string", "(", "PublishersType_", ",", "xml_string", ")" ]
https://github.com/IdentityPython/pysaml2/blob/6badb32d212257bd83ffcc816f9b625f68281b47/src/saml2/extension/dri.py#L236-L237
chribsen/simple-machine-learning-examples
dc94e52a4cebdc8bb959ff88b81ff8cfeca25022
venv/lib/python2.7/site-packages/pandas/indexes/category.py
python
CategoricalIndex._create_from_codes
(self, codes, categories=None, ordered=None, name=None)
return CategoricalIndex(cat, name=name)
*this is an internal non-public method* create the correct categorical from codes Parameters ---------- codes : new codes categories : optional categories, defaults to existing ordered : optional ordered attribute, defaults to existing name : optional name attribute, defaults to existing Returns ------- CategoricalIndex
*this is an internal non-public method*
[ "*", "this", "is", "an", "internal", "non", "-", "public", "method", "*" ]
def _create_from_codes(self, codes, categories=None, ordered=None, name=None): """ *this is an internal non-public method* create the correct categorical from codes Parameters ---------- codes : new codes categories : optional categories, defaults to existing ordered : optional ordered attribute, defaults to existing name : optional name attribute, defaults to existing Returns ------- CategoricalIndex """ from pandas.core.categorical import Categorical if categories is None: categories = self.categories if ordered is None: ordered = self.ordered if name is None: name = self.name cat = Categorical.from_codes(codes, categories=categories, ordered=self.ordered) return CategoricalIndex(cat, name=name)
[ "def", "_create_from_codes", "(", "self", ",", "codes", ",", "categories", "=", "None", ",", "ordered", "=", "None", ",", "name", "=", "None", ")", ":", "from", "pandas", ".", "core", ".", "categorical", "import", "Categorical", "if", "categories", "is", "None", ":", "categories", "=", "self", ".", "categories", "if", "ordered", "is", "None", ":", "ordered", "=", "self", ".", "ordered", "if", "name", "is", "None", ":", "name", "=", "self", ".", "name", "cat", "=", "Categorical", ".", "from_codes", "(", "codes", ",", "categories", "=", "categories", ",", "ordered", "=", "self", ".", "ordered", ")", "return", "CategoricalIndex", "(", "cat", ",", "name", "=", "name", ")" ]
https://github.com/chribsen/simple-machine-learning-examples/blob/dc94e52a4cebdc8bb959ff88b81ff8cfeca25022/venv/lib/python2.7/site-packages/pandas/indexes/category.py#L78-L106
kovidgoyal/calibre
2b41671370f2a9eb1109b9ae901ccf915f1bd0c8
src/calibre/library/database.py
python
LibraryDatabase.user_version
(self)
return self.conn.get('pragma user_version;', all=False)
The user version of this database
The user version of this database
[ "The", "user", "version", "of", "this", "database" ]
def user_version(self): 'The user version of this database' return self.conn.get('pragma user_version;', all=False)
[ "def", "user_version", "(", "self", ")", ":", "return", "self", ".", "conn", ".", "get", "(", "'pragma user_version;'", ",", "all", "=", "False", ")" ]
https://github.com/kovidgoyal/calibre/blob/2b41671370f2a9eb1109b9ae901ccf915f1bd0c8/src/calibre/library/database.py#L831-L833
out0fmemory/GoAgent-Always-Available
c4254984fea633ce3d1893fe5901debd9f22c2a9
server/lib/google/appengine/api/search/query_parser.py
python
CreateParser
(query)
return parser
Creates a Query Parser.
Creates a Query Parser.
[ "Creates", "a", "Query", "Parser", "." ]
def CreateParser(query): """Creates a Query Parser.""" input_string = antlr3.ANTLRStringStream(query) lexer = QueryLexerWithErrors(input_string) tokens = antlr3.CommonTokenStream(lexer) parser = QueryParserWithErrors(tokens) return parser
[ "def", "CreateParser", "(", "query", ")", ":", "input_string", "=", "antlr3", ".", "ANTLRStringStream", "(", "query", ")", "lexer", "=", "QueryLexerWithErrors", "(", "input_string", ")", "tokens", "=", "antlr3", ".", "CommonTokenStream", "(", "lexer", ")", "parser", "=", "QueryParserWithErrors", "(", "tokens", ")", "return", "parser" ]
https://github.com/out0fmemory/GoAgent-Always-Available/blob/c4254984fea633ce3d1893fe5901debd9f22c2a9/server/lib/google/appengine/api/search/query_parser.py#L92-L98
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/apps_v1beta1_deployment_status.py
python
AppsV1beta1DeploymentStatus.replicas
(self)
return self._replicas
Gets the replicas of this AppsV1beta1DeploymentStatus. Total number of non-terminated pods targeted by this deployment (their labels match the selector). :return: The replicas of this AppsV1beta1DeploymentStatus. :rtype: int
Gets the replicas of this AppsV1beta1DeploymentStatus. Total number of non-terminated pods targeted by this deployment (their labels match the selector).
[ "Gets", "the", "replicas", "of", "this", "AppsV1beta1DeploymentStatus", ".", "Total", "number", "of", "non", "-", "terminated", "pods", "targeted", "by", "this", "deployment", "(", "their", "labels", "match", "the", "selector", ")", "." ]
def replicas(self): """ Gets the replicas of this AppsV1beta1DeploymentStatus. Total number of non-terminated pods targeted by this deployment (their labels match the selector). :return: The replicas of this AppsV1beta1DeploymentStatus. :rtype: int """ return self._replicas
[ "def", "replicas", "(", "self", ")", ":", "return", "self", ".", "_replicas" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/apps_v1beta1_deployment_status.py#L180-L188
andresriancho/w3af
cd22e5252243a87aaa6d0ddea47cf58dacfe00a9
w3af/core/data/parsers/doc/url.py
python
URL.get_protocol
(self)
return self._scheme
:return: Returns the domain name for the url.
:return: Returns the domain name for the url.
[ ":", "return", ":", "Returns", "the", "domain", "name", "for", "the", "url", "." ]
def get_protocol(self): """ :return: Returns the domain name for the url. """ return self._scheme
[ "def", "get_protocol", "(", "self", ")", ":", "return", "self", ".", "_scheme" ]
https://github.com/andresriancho/w3af/blob/cd22e5252243a87aaa6d0ddea47cf58dacfe00a9/w3af/core/data/parsers/doc/url.py#L600-L604
TensorMSA/tensormsa
c36b565159cd934533636429add3c7d7263d622b
master/workflow/preprocess/workflow_feed_fr2seq.py
python
WorkflowFeedFr2Seq.get_preprocess_type
(self)
return self.conf['preprocess']
:param node_id: :return:
[]
def get_preprocess_type(self): """ :param node_id: :return: """ if('conf' not in self.__dict__) : self.conf = self.get_view_obj(self.key) return self.conf['preprocess']
[ "def", "get_preprocess_type", "(", "self", ")", ":", "if", "(", "'conf'", "not", "in", "self", ".", "__dict__", ")", ":", "self", ".", "conf", "=", "self", ".", "get_view_obj", "(", "self", ".", "key", ")", "return", "self", ".", "conf", "[", "'preprocess'", "]" ]
https://github.com/TensorMSA/tensormsa/blob/c36b565159cd934533636429add3c7d7263d622b/master/workflow/preprocess/workflow_feed_fr2seq.py#L58-L66
postlund/pyatv
4ed1f5539f37d86d80272663d1f2ea34a6c41ec4
pyatv/auth/hap_srp.py
python
SRPAuthHandler.step2
(self, atv_pub_key, atv_salt)
return pub_key, proof
Second pairing step.
Second pairing step.
[ "Second", "pairing", "step", "." ]
def step2(self, atv_pub_key, atv_salt): """Second pairing step.""" pk_str = binascii.hexlify(atv_pub_key).decode() salt = binascii.hexlify(atv_salt).decode() self._session.process(pk_str, salt) if not self._session.verify_proof(self._session.key_proof_hash): raise exceptions.AuthenticationError("proofs do not match") pub_key = binascii.unhexlify(self._session.public) proof = binascii.unhexlify(self._session.key_proof) log_binary(_LOGGER, "Client", Public=pub_key, Proof=proof) return pub_key, proof
[ "def", "step2", "(", "self", ",", "atv_pub_key", ",", "atv_salt", ")", ":", "pk_str", "=", "binascii", ".", "hexlify", "(", "atv_pub_key", ")", ".", "decode", "(", ")", "salt", "=", "binascii", ".", "hexlify", "(", "atv_salt", ")", ".", "decode", "(", ")", "self", ".", "_session", ".", "process", "(", "pk_str", ",", "salt", ")", "if", "not", "self", ".", "_session", ".", "verify_proof", "(", "self", ".", "_session", ".", "key_proof_hash", ")", ":", "raise", "exceptions", ".", "AuthenticationError", "(", "\"proofs do not match\"", ")", "pub_key", "=", "binascii", ".", "unhexlify", "(", "self", ".", "_session", ".", "public", ")", "proof", "=", "binascii", ".", "unhexlify", "(", "self", ".", "_session", ".", "key_proof", ")", "log_binary", "(", "_LOGGER", ",", "\"Client\"", ",", "Public", "=", "pub_key", ",", "Proof", "=", "proof", ")", "return", "pub_key", ",", "proof" ]
https://github.com/postlund/pyatv/blob/4ed1f5539f37d86d80272663d1f2ea34a6c41ec4/pyatv/auth/hap_srp.py#L151-L163
aws-samples/aws-kube-codesuite
ab4e5ce45416b83bffb947ab8d234df5437f4fca
src/kubernetes/client/models/v1beta1_replica_set_spec.py
python
V1beta1ReplicaSetSpec.selector
(self, selector)
Sets the selector of this V1beta1ReplicaSetSpec. Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors :param selector: The selector of this V1beta1ReplicaSetSpec. :type: V1LabelSelector
Sets the selector of this V1beta1ReplicaSetSpec. Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
[ "Sets", "the", "selector", "of", "this", "V1beta1ReplicaSetSpec", ".", "Selector", "is", "a", "label", "query", "over", "pods", "that", "should", "match", "the", "replica", "count", ".", "If", "the", "selector", "is", "empty", "it", "is", "defaulted", "to", "the", "labels", "present", "on", "the", "pod", "template", ".", "Label", "keys", "and", "values", "that", "must", "match", "in", "order", "to", "be", "controlled", "by", "this", "replica", "set", ".", "More", "info", ":", "https", ":", "//", "kubernetes", ".", "io", "/", "docs", "/", "concepts", "/", "overview", "/", "working", "-", "with", "-", "objects", "/", "labels", "/", "#label", "-", "selectors" ]
def selector(self, selector): """ Sets the selector of this V1beta1ReplicaSetSpec. Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors :param selector: The selector of this V1beta1ReplicaSetSpec. :type: V1LabelSelector """ self._selector = selector
[ "def", "selector", "(", "self", ",", "selector", ")", ":", "self", ".", "_selector", "=", "selector" ]
https://github.com/aws-samples/aws-kube-codesuite/blob/ab4e5ce45416b83bffb947ab8d234df5437f4fca/src/kubernetes/client/models/v1beta1_replica_set_spec.py#L110-L119
geometalab/Vector-Tiles-Reader-QGIS-Plugin
a31ae86959c8f3b7d6f332f84191cd7ca4683e1d
ext-libs/shapely/geometry/base.py
python
BaseGeometry.difference
(self, other)
return geom_factory(self.impl['difference'](self, other))
Returns the difference of the geometries
Returns the difference of the geometries
[ "Returns", "the", "difference", "of", "the", "geometries" ]
def difference(self, other): """Returns the difference of the geometries""" return geom_factory(self.impl['difference'](self, other))
[ "def", "difference", "(", "self", ",", "other", ")", ":", "return", "geom_factory", "(", "self", ".", "impl", "[", "'difference'", "]", "(", "self", ",", "other", ")", ")" ]
https://github.com/geometalab/Vector-Tiles-Reader-QGIS-Plugin/blob/a31ae86959c8f3b7d6f332f84191cd7ca4683e1d/ext-libs/shapely/geometry/base.py#L614-L616
SteveDoyle2/pyNastran
eda651ac2d4883d95a34951f8a002ff94f642a1a
pyNastran/op2/tables/geom/geom3.py
python
GEOM3._read_ploadx1
(self, data: bytes, n: int)
return n
Record - PLOADX1(7309,73,351) Word Name Type Description 1 SID I Load set identification number 2 EID I Element identification number 3 PA RS Surface traction at grid point GA 4 PB RS Surface traction at grid point GB 5 G(2) I Corner grid point identification numbers 7 THETA RS Angle between surface traction and inward normal
Record - PLOADX1(7309,73,351)
[ "Record", "-", "PLOADX1", "(", "7309", "73", "351", ")" ]
def _read_ploadx1(self, data: bytes, n: int) -> int: """ Record - PLOADX1(7309,73,351) Word Name Type Description 1 SID I Load set identification number 2 EID I Element identification number 3 PA RS Surface traction at grid point GA 4 PB RS Surface traction at grid point GB 5 G(2) I Corner grid point identification numbers 7 THETA RS Angle between surface traction and inward normal """ op2 = self.op2 ntotal = 28 # 7*4 nentries = (len(data) - n) // ntotal struc = Struct(op2._endian + b'2i2f iif') for unused_i in range(nentries): edata = data[n:n + 28] out = struc.unpack(edata) if op2.is_debug_file: op2.binary_debug.write(' PLOADX1=%s\n' % str(out)) load = PLOADX1.add_op2_data(out) op2._add_methods._add_load_object(load) n += 28 op2.card_count['PLOADX1'] = nentries return n
[ "def", "_read_ploadx1", "(", "self", ",", "data", ":", "bytes", ",", "n", ":", "int", ")", "->", "int", ":", "op2", "=", "self", ".", "op2", "ntotal", "=", "28", "# 7*4", "nentries", "=", "(", "len", "(", "data", ")", "-", "n", ")", "//", "ntotal", "struc", "=", "Struct", "(", "op2", ".", "_endian", "+", "b'2i2f iif'", ")", "for", "unused_i", "in", "range", "(", "nentries", ")", ":", "edata", "=", "data", "[", "n", ":", "n", "+", "28", "]", "out", "=", "struc", ".", "unpack", "(", "edata", ")", "if", "op2", ".", "is_debug_file", ":", "op2", ".", "binary_debug", ".", "write", "(", "' PLOADX1=%s\\n'", "%", "str", "(", "out", ")", ")", "load", "=", "PLOADX1", ".", "add_op2_data", "(", "out", ")", "op2", ".", "_add_methods", ".", "_add_load_object", "(", "load", ")", "n", "+=", "28", "op2", ".", "card_count", "[", "'PLOADX1'", "]", "=", "nentries", "return", "n" ]
https://github.com/SteveDoyle2/pyNastran/blob/eda651ac2d4883d95a34951f8a002ff94f642a1a/pyNastran/op2/tables/geom/geom3.py#L726-L751
CedricGuillemet/Imogen
ee417b42747ed5b46cb11b02ef0c3630000085b3
bin/Lib/logging/handlers.py
python
WatchedFileHandler.emit
(self, record)
Emit a record. If underlying file has changed, reopen the file before emitting the record to it.
Emit a record.
[ "Emit", "a", "record", "." ]
def emit(self, record): """ Emit a record. If underlying file has changed, reopen the file before emitting the record to it. """ self.reopenIfNeeded() logging.FileHandler.emit(self, record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "self", ".", "reopenIfNeeded", "(", ")", "logging", ".", "FileHandler", ".", "emit", "(", "self", ",", "record", ")" ]
https://github.com/CedricGuillemet/Imogen/blob/ee417b42747ed5b46cb11b02ef0c3630000085b3/bin/Lib/logging/handlers.py#L471-L479
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/Centos_5.9/paramiko/channel.py
python
ChannelFile._read
(self, size)
return self.channel.recv(size)
[]
def _read(self, size): return self.channel.recv(size)
[ "def", "_read", "(", "self", ",", "size", ")", ":", "return", "self", ".", "channel", ".", "recv", "(", "size", ")" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/Centos_5.9/paramiko/channel.py#L1259-L1260
una-dinosauria/3d-pose-baseline
666080d86a96666d499300719053cc8af7ef51c8
src/procrustes.py
python
compute_similarity_transform
(X, Y, compute_optimal_scale=False)
return d, Z, T, b, c
A port of MATLAB's `procrustes` function to Numpy. Adapted from http://stackoverflow.com/a/18927641/1884420 Args X: array NxM of targets, with N number of points and M point dimensionality Y: array NxM of inputs compute_optimal_scale: whether we compute optimal scale or force it to be 1 Returns: d: squared error after transformation Z: transformed Y T: computed rotation b: scaling c: translation
A port of MATLAB's `procrustes` function to Numpy. Adapted from http://stackoverflow.com/a/18927641/1884420
[ "A", "port", "of", "MATLAB", "s", "procrustes", "function", "to", "Numpy", ".", "Adapted", "from", "http", ":", "//", "stackoverflow", ".", "com", "/", "a", "/", "18927641", "/", "1884420" ]
def compute_similarity_transform(X, Y, compute_optimal_scale=False): """ A port of MATLAB's `procrustes` function to Numpy. Adapted from http://stackoverflow.com/a/18927641/1884420 Args X: array NxM of targets, with N number of points and M point dimensionality Y: array NxM of inputs compute_optimal_scale: whether we compute optimal scale or force it to be 1 Returns: d: squared error after transformation Z: transformed Y T: computed rotation b: scaling c: translation """ muX = X.mean(0) muY = Y.mean(0) X0 = X - muX Y0 = Y - muY ssX = (X0**2.).sum() ssY = (Y0**2.).sum() # centred Frobenius norm normX = np.sqrt(ssX) normY = np.sqrt(ssY) # scale to equal (unit) norm X0 = X0 / normX Y0 = Y0 / normY # optimum rotation matrix of Y A = np.dot(X0.T, Y0) U,s,Vt = np.linalg.svd(A,full_matrices=False) V = Vt.T T = np.dot(V, U.T) # Make sure we have a rotation detT = np.linalg.det(T) V[:,-1] *= np.sign( detT ) s[-1] *= np.sign( detT ) T = np.dot(V, U.T) traceTA = s.sum() if compute_optimal_scale: # Compute optimum scaling of Y. b = traceTA * normX / normY d = 1 - traceTA**2 Z = normX*traceTA*np.dot(Y0, T) + muX else: # If no scaling allowed b = 1 d = 1 + ssY/ssX - 2 * traceTA * normY / normX Z = normY*np.dot(Y0, T) + muX c = muX - b*np.dot(muY, T) return d, Z, T, b, c
[ "def", "compute_similarity_transform", "(", "X", ",", "Y", ",", "compute_optimal_scale", "=", "False", ")", ":", "muX", "=", "X", ".", "mean", "(", "0", ")", "muY", "=", "Y", ".", "mean", "(", "0", ")", "X0", "=", "X", "-", "muX", "Y0", "=", "Y", "-", "muY", "ssX", "=", "(", "X0", "**", "2.", ")", ".", "sum", "(", ")", "ssY", "=", "(", "Y0", "**", "2.", ")", ".", "sum", "(", ")", "# centred Frobenius norm", "normX", "=", "np", ".", "sqrt", "(", "ssX", ")", "normY", "=", "np", ".", "sqrt", "(", "ssY", ")", "# scale to equal (unit) norm", "X0", "=", "X0", "/", "normX", "Y0", "=", "Y0", "/", "normY", "# optimum rotation matrix of Y", "A", "=", "np", ".", "dot", "(", "X0", ".", "T", ",", "Y0", ")", "U", ",", "s", ",", "Vt", "=", "np", ".", "linalg", ".", "svd", "(", "A", ",", "full_matrices", "=", "False", ")", "V", "=", "Vt", ".", "T", "T", "=", "np", ".", "dot", "(", "V", ",", "U", ".", "T", ")", "# Make sure we have a rotation", "detT", "=", "np", ".", "linalg", ".", "det", "(", "T", ")", "V", "[", ":", ",", "-", "1", "]", "*=", "np", ".", "sign", "(", "detT", ")", "s", "[", "-", "1", "]", "*=", "np", ".", "sign", "(", "detT", ")", "T", "=", "np", ".", "dot", "(", "V", ",", "U", ".", "T", ")", "traceTA", "=", "s", ".", "sum", "(", ")", "if", "compute_optimal_scale", ":", "# Compute optimum scaling of Y.", "b", "=", "traceTA", "*", "normX", "/", "normY", "d", "=", "1", "-", "traceTA", "**", "2", "Z", "=", "normX", "*", "traceTA", "*", "np", ".", "dot", "(", "Y0", ",", "T", ")", "+", "muX", "else", ":", "# If no scaling allowed", "b", "=", "1", "d", "=", "1", "+", "ssY", "/", "ssX", "-", "2", "*", "traceTA", "*", "normY", "/", "normX", "Z", "=", "normY", "*", "np", ".", "dot", "(", "Y0", ",", "T", ")", "+", "muX", "c", "=", "muX", "-", "b", "*", "np", ".", "dot", "(", "muY", ",", "T", ")", "return", "d", ",", "Z", ",", "T", ",", "b", ",", "c" ]
https://github.com/una-dinosauria/3d-pose-baseline/blob/666080d86a96666d499300719053cc8af7ef51c8/src/procrustes.py#L4-L64
Komodo/KomodoEdit
61edab75dce2bdb03943b387b0608ea36f548e8e
contrib/pycrypto/lib/Crypto/PublicKey/_slowmath.py
python
_DSAKey.size
(self)
return size(self.p) - 1
Return the maximum number of bits that can be encrypted
Return the maximum number of bits that can be encrypted
[ "Return", "the", "maximum", "number", "of", "bits", "that", "can", "be", "encrypted" ]
def size(self): """Return the maximum number of bits that can be encrypted""" return size(self.p) - 1
[ "def", "size", "(", "self", ")", ":", "return", "size", "(", "self", ".", "p", ")", "-", "1" ]
https://github.com/Komodo/KomodoEdit/blob/61edab75dce2bdb03943b387b0608ea36f548e8e/contrib/pycrypto/lib/Crypto/PublicKey/_slowmath.py#L93-L95
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
desktop/core/ext-py/eventlet-0.24.1/eventlet/websocket.py
python
RFC6455WebSocket.close
(self, close_data=None)
Forcibly close the websocket; generally it is preferable to return from the handler method.
Forcibly close the websocket; generally it is preferable to return from the handler method.
[ "Forcibly", "close", "the", "websocket", ";", "generally", "it", "is", "preferable", "to", "return", "from", "the", "handler", "method", "." ]
def close(self, close_data=None): """Forcibly close the websocket; generally it is preferable to return from the handler method.""" try: self._send_closing_frame(close_data=close_data, ignore_send_errors=True) self.socket.shutdown(socket.SHUT_WR) except SocketError as e: if e.errno != errno.ENOTCONN: self.log.write('{ctx} socket shutdown error: {e}'.format(ctx=self.log_context, e=e)) finally: self.socket.close()
[ "def", "close", "(", "self", ",", "close_data", "=", "None", ")", ":", "try", ":", "self", ".", "_send_closing_frame", "(", "close_data", "=", "close_data", ",", "ignore_send_errors", "=", "True", ")", "self", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_WR", ")", "except", "SocketError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "ENOTCONN", ":", "self", ".", "log", ".", "write", "(", "'{ctx} socket shutdown error: {e}'", ".", "format", "(", "ctx", "=", "self", ".", "log_context", ",", "e", "=", "e", ")", ")", "finally", ":", "self", ".", "socket", ".", "close", "(", ")" ]
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/desktop/core/ext-py/eventlet-0.24.1/eventlet/websocket.py#L821-L831
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/engine/result.py
python
RowProxy.__getstate__
(self)
return { '_parent': self._parent, '_row': tuple(self) }
[]
def __getstate__(self): return { '_parent': self._parent, '_row': tuple(self) }
[ "def", "__getstate__", "(", "self", ")", ":", "return", "{", "'_parent'", ":", "self", ".", "_parent", ",", "'_row'", ":", "tuple", "(", "self", ")", "}" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/engine/result.py#L118-L122
cbfinn/gps
82fa6cc930c4392d55d2525f6b792089f1d2ccfe
python/gps/agent/agent.py
python
Agent.clear_samples
(self, condition=None)
Reset the samples for a given condition, defaulting to all conditions. Args: condition: Condition for which to reset samples.
Reset the samples for a given condition, defaulting to all conditions. Args: condition: Condition for which to reset samples.
[ "Reset", "the", "samples", "for", "a", "given", "condition", "defaulting", "to", "all", "conditions", ".", "Args", ":", "condition", ":", "Condition", "for", "which", "to", "reset", "samples", "." ]
def clear_samples(self, condition=None): """ Reset the samples for a given condition, defaulting to all conditions. Args: condition: Condition for which to reset samples. """ if condition is None: self._samples = [[] for _ in range(self._hyperparams['conditions'])] else: self._samples[condition] = []
[ "def", "clear_samples", "(", "self", ",", "condition", "=", "None", ")", ":", "if", "condition", "is", "None", ":", "self", ".", "_samples", "=", "[", "[", "]", "for", "_", "in", "range", "(", "self", ".", "_hyperparams", "[", "'conditions'", "]", ")", "]", "else", ":", "self", ".", "_samples", "[", "condition", "]", "=", "[", "]" ]
https://github.com/cbfinn/gps/blob/82fa6cc930c4392d55d2525f6b792089f1d2ccfe/python/gps/agent/agent.py#L87-L96
PokemonGoF/PokemonGo-Bot-Desktop
4bfa94f0183406c6a86f93645eff7abd3ad4ced8
build/pywin/Lib/imputil.py
python
ImportManager._reload_hook
(self, module)
Python calls this hook to reload a module.
Python calls this hook to reload a module.
[ "Python", "calls", "this", "hook", "to", "reload", "a", "module", "." ]
def _reload_hook(self, module): "Python calls this hook to reload a module." # reloading of a module may or may not be possible (depending on the # importer), but at least we can validate that it's ours to reload importer = module.__dict__.get('__importer__') if not importer: ### oops. now what... pass # okay. it is using the imputil system, and we must delegate it, but # we don't know what to do (yet) ### we should blast the module dict and do another get_code(). need to ### flesh this out and add proper docco... raise SystemError, "reload not yet implemented"
[ "def", "_reload_hook", "(", "self", ",", "module", ")", ":", "# reloading of a module may or may not be possible (depending on the", "# importer), but at least we can validate that it's ours to reload", "importer", "=", "module", ".", "__dict__", ".", "get", "(", "'__importer__'", ")", "if", "not", "importer", ":", "### oops. now what...", "pass", "# okay. it is using the imputil system, and we must delegate it, but", "# we don't know what to do (yet)", "### we should blast the module dict and do another get_code(). need to", "### flesh this out and add proper docco...", "raise", "SystemError", ",", "\"reload not yet implemented\"" ]
https://github.com/PokemonGoF/PokemonGo-Bot-Desktop/blob/4bfa94f0183406c6a86f93645eff7abd3ad4ced8/build/pywin/Lib/imputil.py#L200-L214
luispedro/BuildingMachineLearningSystemsWithPython
52891e6bac00213bf94ab1a3b1f2d8d5ed04a774
ch10/large_classification.py
python
images
()
Iterate over all (image,label) pairs This function will return
Iterate over all (image,label) pairs
[ "Iterate", "over", "all", "(", "image", "label", ")", "pairs" ]
def images(): '''Iterate over all (image,label) pairs This function will return ''' for ci, cl in enumerate(classes): images = glob('{}/{}/*.jpg'.format(basedir, cl)) for im in sorted(images): yield im, ci
[ "def", "images", "(", ")", ":", "for", "ci", ",", "cl", "in", "enumerate", "(", "classes", ")", ":", "images", "=", "glob", "(", "'{}/{}/*.jpg'", ".", "format", "(", "basedir", ",", "cl", ")", ")", "for", "im", "in", "sorted", "(", "images", ")", ":", "yield", "im", ",", "ci" ]
https://github.com/luispedro/BuildingMachineLearningSystemsWithPython/blob/52891e6bac00213bf94ab1a3b1f2d8d5ed04a774/ch10/large_classification.py#L33-L41
krintoxi/NoobSec-Toolkit
38738541cbc03cedb9a3b3ed13b629f781ad64f6
NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/access/enumeration.py
python
Enumeration.getPrivileges
(self, *args)
return {}
[]
def getPrivileges(self, *args): warnMsg = "on Microsoft Access it is not possible to enumerate the user privileges" logger.warn(warnMsg) return {}
[ "def", "getPrivileges", "(", "self", ",", "*", "args", ")", ":", "warnMsg", "=", "\"on Microsoft Access it is not possible to enumerate the user privileges\"", "logger", ".", "warn", "(", "warnMsg", ")", "return", "{", "}" ]
https://github.com/krintoxi/NoobSec-Toolkit/blob/38738541cbc03cedb9a3b3ed13b629f781ad64f6/NoobSecToolkit - MAC OSX/tools/sqli/plugins/dbms/access/enumeration.py#L45-L49
msiemens/tinydb
5db5916b68b667067851f27741435d8d4335f590
tinydb/storages.py
python
Storage.write
(self, data: Dict[str, Dict[str, Any]])
Write the current state of the database to the storage. Any kind of serialization should go here. :param data: The current state of the database.
Write the current state of the database to the storage.
[ "Write", "the", "current", "state", "of", "the", "database", "to", "the", "storage", "." ]
def write(self, data: Dict[str, Dict[str, Any]]) -> None: """ Write the current state of the database to the storage. Any kind of serialization should go here. :param data: The current state of the database. """ raise NotImplementedError('To be overridden!')
[ "def", "write", "(", "self", ",", "data", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ")", "->", "None", ":", "raise", "NotImplementedError", "(", "'To be overridden!'", ")" ]
https://github.com/msiemens/tinydb/blob/5db5916b68b667067851f27741435d8d4335f590/tinydb/storages.py#L59-L68
implus/PytorchInsight
2864528f8b83f52c3df76f7c3804aa468b91e5cf
detection/mmdet/models/registry.py
python
Registry.name
(self)
return self._name
[]
def name(self): return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
https://github.com/implus/PytorchInsight/blob/2864528f8b83f52c3df76f7c3804aa468b91e5cf/detection/mmdet/models/registry.py#L11-L12
dropbox/dropbox-sdk-python
015437429be224732990041164a21a0501235db1
dropbox/team_log.py
python
EventType.is_group_add_external_id
(self)
return self._tag == 'group_add_external_id'
Check if the union tag is ``group_add_external_id``. :rtype: bool
Check if the union tag is ``group_add_external_id``.
[ "Check", "if", "the", "union", "tag", "is", "group_add_external_id", "." ]
def is_group_add_external_id(self): """ Check if the union tag is ``group_add_external_id``. :rtype: bool """ return self._tag == 'group_add_external_id'
[ "def", "is_group_add_external_id", "(", "self", ")", ":", "return", "self", ".", "_tag", "==", "'group_add_external_id'" ]
https://github.com/dropbox/dropbox-sdk-python/blob/015437429be224732990041164a21a0501235db1/dropbox/team_log.py#L29241-L29247
CouchPotato/CouchPotatoServer
7260c12f72447ddb6f062367c6dfbda03ecd4e9c
couchpotato/core/softchroot.py
python
SoftChroot.initialize
(self, chdir)
initialize module, by setting soft-chroot-directory Sets soft-chroot directory and 'enabled'-flag Args: self (SoftChroot) : self chdir (string) : absolute path to soft-chroot Raises: SoftChrootInitError: when chdir doesn't exist
initialize module, by setting soft-chroot-directory
[ "initialize", "module", "by", "setting", "soft", "-", "chroot", "-", "directory" ]
def initialize(self, chdir): """ initialize module, by setting soft-chroot-directory Sets soft-chroot directory and 'enabled'-flag Args: self (SoftChroot) : self chdir (string) : absolute path to soft-chroot Raises: SoftChrootInitError: when chdir doesn't exist """ orig_chdir = chdir if chdir: chdir = chdir.strip() if (chdir): # enabling soft-chroot: if not os.path.isdir(chdir): raise SoftChrootInitError(2, 'SOFT-CHROOT is requested, but the folder doesn\'t exist', orig_chdir) self.enabled = True self.chdir = chdir.rstrip(os.path.sep) + os.path.sep else: self.enabled = False
[ "def", "initialize", "(", "self", ",", "chdir", ")", ":", "orig_chdir", "=", "chdir", "if", "chdir", ":", "chdir", "=", "chdir", ".", "strip", "(", ")", "if", "(", "chdir", ")", ":", "# enabling soft-chroot:", "if", "not", "os", ".", "path", ".", "isdir", "(", "chdir", ")", ":", "raise", "SoftChrootInitError", "(", "2", ",", "'SOFT-CHROOT is requested, but the folder doesn\\'t exist'", ",", "orig_chdir", ")", "self", ".", "enabled", "=", "True", "self", ".", "chdir", "=", "chdir", ".", "rstrip", "(", "os", ".", "path", ".", "sep", ")", "+", "os", ".", "path", ".", "sep", "else", ":", "self", ".", "enabled", "=", "False" ]
https://github.com/CouchPotato/CouchPotatoServer/blob/7260c12f72447ddb6f062367c6dfbda03ecd4e9c/couchpotato/core/softchroot.py#L19-L45
dmlc/dgl
8d14a739bc9e446d6c92ef83eafe5782398118de
python/dgl/frame.py
python
Frame.__getitem__
(self, name)
return self._columns[name].data
Return the column of the given name. Parameters ---------- name : str The column name. Returns ------- Tensor Column data.
Return the column of the given name.
[ "Return", "the", "column", "of", "the", "given", "name", "." ]
def __getitem__(self, name): """Return the column of the given name. Parameters ---------- name : str The column name. Returns ------- Tensor Column data. """ return self._columns[name].data
[ "def", "__getitem__", "(", "self", ",", "name", ")", ":", "return", "self", ".", "_columns", "[", "name", "]", ".", "data" ]
https://github.com/dmlc/dgl/blob/8d14a739bc9e446d6c92ef83eafe5782398118de/python/dgl/frame.py#L411-L424
boston-dynamics/spot-sdk
5ffa12e6943a47323c7279d86e30346868755f52
python/bosdyn-core/src/bosdyn/bddf/block_writer.py
python
BlockWriter.write_data_block
(self, desc_block, data)
Write a block of data to the file.
Write a block of data to the file.
[ "Write", "a", "block", "of", "data", "to", "the", "file", "." ]
def write_data_block(self, desc_block, data): """Write a block of data to the file.""" serialized_desc = desc_block.SerializeToString() self._write_block_header(DATA_BLOCK_TYPE, len(data) + len(serialized_desc)) self._write(struct.pack('<I', len(serialized_desc))) self._write(serialized_desc) self._write(data)
[ "def", "write_data_block", "(", "self", ",", "desc_block", ",", "data", ")", ":", "serialized_desc", "=", "desc_block", ".", "SerializeToString", "(", ")", "self", ".", "_write_block_header", "(", "DATA_BLOCK_TYPE", ",", "len", "(", "data", ")", "+", "len", "(", "serialized_desc", ")", ")", "self", ".", "_write", "(", "struct", ".", "pack", "(", "'<I'", ",", "len", "(", "serialized_desc", ")", ")", ")", "self", ".", "_write", "(", "serialized_desc", ")", "self", ".", "_write", "(", "data", ")" ]
https://github.com/boston-dynamics/spot-sdk/blob/5ffa12e6943a47323c7279d86e30346868755f52/python/bosdyn-core/src/bosdyn/bddf/block_writer.py#L35-L41
thefab/tornadis
26195256b434cc9d55788a67828b6bed17b4cebc
tornadis/write_buffer.py
python
WriteBuffer.append
(self, data)
Appends some data to end of the buffer (right). No string copy is done during this operation. Args: data: data to put in the buffer (can be string, memoryview or another WriteBuffer).
Appends some data to end of the buffer (right).
[ "Appends", "some", "data", "to", "end", "of", "the", "buffer", "(", "right", ")", "." ]
def append(self, data): """Appends some data to end of the buffer (right). No string copy is done during this operation. Args: data: data to put in the buffer (can be string, memoryview or another WriteBuffer). """ self._append(data, True)
[ "def", "append", "(", "self", ",", "data", ")", ":", "self", ".", "_append", "(", "data", ",", "True", ")" ]
https://github.com/thefab/tornadis/blob/26195256b434cc9d55788a67828b6bed17b4cebc/tornadis/write_buffer.py#L82-L91
michael-lazar/rtv
b3d5bf16a70dba685e05db35308cc8a6d2b7f7aa
rtv/packages/praw/__init__.py
python
UnauthenticatedReddit.get_submissions
(self, fullnames, *args, **kwargs)
Generate Submission objects for each item provided in `fullnames`. A submission fullname looks like `t3_<base36_id>`. Submissions are yielded in the same order they appear in `fullnames`. Up to 100 items are batched at a time -- this happens transparently. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` and `limit` parameters cannot be altered.
Generate Submission objects for each item provided in `fullnames`.
[ "Generate", "Submission", "objects", "for", "each", "item", "provided", "in", "fullnames", "." ]
def get_submissions(self, fullnames, *args, **kwargs): """Generate Submission objects for each item provided in `fullnames`. A submission fullname looks like `t3_<base36_id>`. Submissions are yielded in the same order they appear in `fullnames`. Up to 100 items are batched at a time -- this happens transparently. The additional parameters are passed directly into :meth:`.get_content`. Note: the `url` and `limit` parameters cannot be altered. """ fullnames = fullnames[:] while fullnames: cur = fullnames[:100] fullnames[:100] = [] url = self.config['by_id'] + ','.join(cur) for item in self.get_content(url, limit=len(cur), *args, **kwargs): yield item
[ "def", "get_submissions", "(", "self", ",", "fullnames", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fullnames", "=", "fullnames", "[", ":", "]", "while", "fullnames", ":", "cur", "=", "fullnames", "[", ":", "100", "]", "fullnames", "[", ":", "100", "]", "=", "[", "]", "url", "=", "self", ".", "config", "[", "'by_id'", "]", "+", "','", ".", "join", "(", "cur", ")", "for", "item", "in", "self", ".", "get_content", "(", "url", ",", "limit", "=", "len", "(", "cur", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "yield", "item" ]
https://github.com/michael-lazar/rtv/blob/b3d5bf16a70dba685e05db35308cc8a6d2b7f7aa/rtv/packages/praw/__init__.py#L1111-L1130
analysiscenter/batchflow
294747da0bca309785f925be891441fdd824e9fa
batchflow/opensets/pascal.py
python
PascalClassification.download
(self, path)
Download a dataset from the source web-site
Download a dataset from the source web-site
[ "Download", "a", "dataset", "from", "the", "source", "web", "-", "site" ]
def download(self, path): """ Download a dataset from the source web-site """ self.download_archive(path) with tarfile.open(self.localname, "r") as archive: d = defaultdict(list) class_files = [os.path.join(self.SETS_PATH, self.task, name.replace(' ', '')) + '_trainval.txt' for name in self.classes] for class_file in class_files: data = archive.extractfile(class_file).read() for row in data.decode().split('\n')[:-1]: key = row.split()[0] value = int(row.split()[1]) d[key].append(value) train_ids = self._extract_ids(archive, 'train') test_ids = self._extract_ids(archive, 'val') images = np.array([self._extract_image(archive, self._image_path(name)) for name in [*train_ids, *test_ids]], dtype=object) targets = np.array([d[self._name(name)] for name in [*train_ids, *test_ids]]) labels = self._process_targets(targets) preloaded = images, labels train_len, test_len = len(train_ids), len(test_ids) index, train_index, test_index = self._infer_train_test_index(train_len, test_len) return preloaded, index, train_index, test_index
[ "def", "download", "(", "self", ",", "path", ")", ":", "self", ".", "download_archive", "(", "path", ")", "with", "tarfile", ".", "open", "(", "self", ".", "localname", ",", "\"r\"", ")", "as", "archive", ":", "d", "=", "defaultdict", "(", "list", ")", "class_files", "=", "[", "os", ".", "path", ".", "join", "(", "self", ".", "SETS_PATH", ",", "self", ".", "task", ",", "name", ".", "replace", "(", "' '", ",", "''", ")", ")", "+", "'_trainval.txt'", "for", "name", "in", "self", ".", "classes", "]", "for", "class_file", "in", "class_files", ":", "data", "=", "archive", ".", "extractfile", "(", "class_file", ")", ".", "read", "(", ")", "for", "row", "in", "data", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", "[", ":", "-", "1", "]", ":", "key", "=", "row", ".", "split", "(", ")", "[", "0", "]", "value", "=", "int", "(", "row", ".", "split", "(", ")", "[", "1", "]", ")", "d", "[", "key", "]", ".", "append", "(", "value", ")", "train_ids", "=", "self", ".", "_extract_ids", "(", "archive", ",", "'train'", ")", "test_ids", "=", "self", ".", "_extract_ids", "(", "archive", ",", "'val'", ")", "images", "=", "np", ".", "array", "(", "[", "self", ".", "_extract_image", "(", "archive", ",", "self", ".", "_image_path", "(", "name", ")", ")", "for", "name", "in", "[", "*", "train_ids", ",", "*", "test_ids", "]", "]", ",", "dtype", "=", "object", ")", "targets", "=", "np", ".", "array", "(", "[", "d", "[", "self", ".", "_name", "(", "name", ")", "]", "for", "name", "in", "[", "*", "train_ids", ",", "*", "test_ids", "]", "]", ")", "labels", "=", "self", ".", "_process_targets", "(", "targets", ")", "preloaded", "=", "images", ",", "labels", "train_len", ",", "test_len", "=", "len", "(", "train_ids", ")", ",", "len", "(", "test_ids", ")", "index", ",", "train_index", ",", "test_index", "=", "self", ".", "_infer_train_test_index", "(", "train_len", ",", "test_len", ")", "return", "preloaded", ",", "index", ",", "train_index", ",", "test_index" ]
https://github.com/analysiscenter/batchflow/blob/294747da0bca309785f925be891441fdd824e9fa/batchflow/opensets/pascal.py#L146-L173
fake-name/ChromeController
6c70d855e33e06463516b263bf9e6f34c48e29e8
ChromeController/Generator/Generated.py
python
ChromeRemoteDebugInterface.DOM_disable
(self)
return subdom_funcs
Function path: DOM.disable Domain: DOM Method name: disable No return value. Description: Disables DOM agent for the given page.
Function path: DOM.disable Domain: DOM Method name: disable No return value. Description: Disables DOM agent for the given page.
[ "Function", "path", ":", "DOM", ".", "disable", "Domain", ":", "DOM", "Method", "name", ":", "disable", "No", "return", "value", ".", "Description", ":", "Disables", "DOM", "agent", "for", "the", "given", "page", "." ]
def DOM_disable(self): """ Function path: DOM.disable Domain: DOM Method name: disable No return value. Description: Disables DOM agent for the given page. """ subdom_funcs = self.synchronous_command('DOM.disable') return subdom_funcs
[ "def", "DOM_disable", "(", "self", ")", ":", "subdom_funcs", "=", "self", ".", "synchronous_command", "(", "'DOM.disable'", ")", "return", "subdom_funcs" ]
https://github.com/fake-name/ChromeController/blob/6c70d855e33e06463516b263bf9e6f34c48e29e8/ChromeController/Generator/Generated.py#L1867-L1878
triaquae/triaquae
bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9
TriAquae/models/django/db/models/sql/query.py
python
Query.setup_joins
(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True)
return field, target, opts, joins, last, extra_filters
Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are joining to), 'alias' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always create a new alias (necessary for disjunctive filters). If can_reuse is not None, it's a list of aliases that can be reused in these joins (nothing else can be reused in this case). Finally, 'negate' is used in the same sense as for add_filter() -- it indicates an exclude() filter, or something similar. It is only passed in here so that it can be passed to a field's extra_filter() for customized behavior. Returns the final field involved in the join, the target database column (used for any 'where' constraint), the final 'opts' value and the list of tables joined.
Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are joining to), 'alias' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always create a new alias (necessary for disjunctive filters). If can_reuse is not None, it's a list of aliases that can be reused in these joins (nothing else can be reused in this case). Finally, 'negate' is used in the same sense as for add_filter() -- it indicates an exclude() filter, or something similar. It is only passed in here so that it can be passed to a field's extra_filter() for customized behavior.
[ "Compute", "the", "necessary", "table", "joins", "for", "the", "passage", "through", "the", "fields", "given", "in", "names", ".", "opts", "is", "the", "Options", "class", "for", "the", "current", "model", "(", "which", "gives", "the", "table", "we", "are", "joining", "to", ")", "alias", "is", "the", "alias", "for", "the", "table", "we", "are", "joining", "to", ".", "If", "dupe_multis", "is", "True", "any", "many", "-", "to", "-", "many", "or", "many", "-", "to", "-", "one", "joins", "will", "always", "create", "a", "new", "alias", "(", "necessary", "for", "disjunctive", "filters", ")", ".", "If", "can_reuse", "is", "not", "None", "it", "s", "a", "list", "of", "aliases", "that", "can", "be", "reused", "in", "these", "joins", "(", "nothing", "else", "can", "be", "reused", "in", "this", "case", ")", ".", "Finally", "negate", "is", "used", "in", "the", "same", "sense", "as", "for", "add_filter", "()", "--", "it", "indicates", "an", "exclude", "()", "filter", "or", "something", "similar", ".", "It", "is", "only", "passed", "in", "here", "so", "that", "it", "can", "be", "passed", "to", "a", "field", "s", "extra_filter", "()", "for", "customized", "behavior", "." ]
def setup_joins(self, names, opts, alias, dupe_multis, allow_many=True, allow_explicit_fk=False, can_reuse=None, negate=False, process_extras=True): """ Compute the necessary table joins for the passage through the fields given in 'names'. 'opts' is the Options class for the current model (which gives the table we are joining to), 'alias' is the alias for the table we are joining to. If dupe_multis is True, any many-to-many or many-to-one joins will always create a new alias (necessary for disjunctive filters). If can_reuse is not None, it's a list of aliases that can be reused in these joins (nothing else can be reused in this case). Finally, 'negate' is used in the same sense as for add_filter() -- it indicates an exclude() filter, or something similar. It is only passed in here so that it can be passed to a field's extra_filter() for customized behavior. Returns the final field involved in the join, the target database column (used for any 'where' constraint), the final 'opts' value and the list of tables joined. """ joins = [alias] last = [0] dupe_set = set() exclusions = set() extra_filters = [] int_alias = None for pos, name in enumerate(names): if int_alias is not None: exclusions.add(int_alias) exclusions.add(alias) last.append(len(joins)) if name == 'pk': name = opts.pk.name try: field, model, direct, m2m = opts.get_field_by_name(name) except FieldDoesNotExist: for f in opts.fields: if allow_explicit_fk and name == f.attname: # XXX: A hack to allow foo_id to work in values() for # backwards compatibility purposes. If we dropped that # feature, this could be removed. field, model, direct, m2m = opts.get_field_by_name(f.name) break else: names = opts.get_all_field_names() + list(self.aggregate_select) raise FieldError("Cannot resolve keyword %r into field. " "Choices are: %s" % (name, ", ".join(names))) if not allow_many and (m2m or not direct): for alias in joins: self.unref_alias(alias) raise MultiJoin(pos + 1) if model: # The field lives on a base class of the current model. # Skip the chain of proxy to the concrete proxied model proxied_model = opts.concrete_model for int_model in opts.get_base_chain(model): if int_model is proxied_model: opts = int_model._meta else: lhs_col = opts.parents[int_model].column dedupe = lhs_col in opts.duplicate_targets if dedupe: exclusions.update(self.dupe_avoidance.get( (id(opts), lhs_col), ())) dupe_set.add((opts, lhs_col)) opts = int_model._meta alias = self.join((alias, opts.db_table, lhs_col, opts.pk.column), exclusions=exclusions) joins.append(alias) exclusions.add(alias) for (dupe_opts, dupe_col) in dupe_set: self.update_dupe_avoidance(dupe_opts, dupe_col, alias) cached_data = opts._join_cache.get(name) orig_opts = opts dupe_col = direct and field.column or field.field.column dedupe = dupe_col in opts.duplicate_targets if dupe_set or dedupe: if dedupe: dupe_set.add((opts, dupe_col)) exclusions.update(self.dupe_avoidance.get((id(opts), dupe_col), ())) if process_extras and hasattr(field, 'extra_filters'): extra_filters.extend(field.extra_filters(names, pos, negate)) if direct: if m2m: # Many-to-many field defined on the current model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.get_field_by_name( field.m2m_target_field_name())[0].column to_col1 = field.m2m_column_name() opts = field.rel.to._meta table2 = opts.db_table from_col2 = field.m2m_reverse_name() to_col2 = opts.get_field_by_name( field.m2m_reverse_target_field_name())[0].column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) if int_alias == table2 and from_col2 == to_col2: joins.append(int_alias) alias = int_alias else: alias = self.join( (int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) elif field.rel: # One-to-one or many-to-one field if cached_data: (table, from_col, to_col, opts, target) = cached_data else: opts = field.rel.to._meta target = field.rel.get_related_field() table = opts.db_table from_col = field.column to_col = target.column orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), exclusions=exclusions, nullable=self.is_nullable(field)) joins.append(alias) else: # Non-relation fields. target = field break else: orig_field = field field = field.field if m2m: # Many-to-many field defined on the target model. if cached_data: (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) = cached_data else: table1 = field.m2m_db_table() from_col1 = opts.get_field_by_name( field.m2m_reverse_target_field_name())[0].column to_col1 = field.m2m_reverse_name() opts = orig_field.opts table2 = opts.db_table from_col2 = field.m2m_column_name() to_col2 = opts.get_field_by_name( field.m2m_target_field_name())[0].column target = opts.pk orig_opts._join_cache[name] = (table1, from_col1, to_col1, table2, from_col2, to_col2, opts, target) int_alias = self.join((alias, table1, from_col1, to_col1), dupe_multis, exclusions, nullable=True, reuse=can_reuse) alias = self.join((int_alias, table2, from_col2, to_col2), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.extend([int_alias, alias]) else: # One-to-many field (ForeignKey defined on the target model) if cached_data: (table, from_col, to_col, opts, target) = cached_data else: local_field = opts.get_field_by_name( field.rel.field_name)[0] opts = orig_field.opts table = opts.db_table from_col = local_field.column to_col = field.column # In case of a recursive FK, use the to_field for # reverse lookups as well if orig_field.model is local_field.model: target = opts.get_field_by_name( field.rel.field_name)[0] else: target = opts.pk orig_opts._join_cache[name] = (table, from_col, to_col, opts, target) alias = self.join((alias, table, from_col, to_col), dupe_multis, exclusions, nullable=True, reuse=can_reuse) joins.append(alias) for (dupe_opts, dupe_col) in dupe_set: if int_alias is None: to_avoid = alias else: to_avoid = int_alias self.update_dupe_avoidance(dupe_opts, dupe_col, to_avoid) if pos != len(names) - 1: if pos == len(names) - 2: raise FieldError("Join on field %r not permitted. Did you misspell %r for the lookup type?" % (name, names[pos + 1])) else: raise FieldError("Join on field %r not permitted." % name) return field, target, opts, joins, last, extra_filters
[ "def", "setup_joins", "(", "self", ",", "names", ",", "opts", ",", "alias", ",", "dupe_multis", ",", "allow_many", "=", "True", ",", "allow_explicit_fk", "=", "False", ",", "can_reuse", "=", "None", ",", "negate", "=", "False", ",", "process_extras", "=", "True", ")", ":", "joins", "=", "[", "alias", "]", "last", "=", "[", "0", "]", "dupe_set", "=", "set", "(", ")", "exclusions", "=", "set", "(", ")", "extra_filters", "=", "[", "]", "int_alias", "=", "None", "for", "pos", ",", "name", "in", "enumerate", "(", "names", ")", ":", "if", "int_alias", "is", "not", "None", ":", "exclusions", ".", "add", "(", "int_alias", ")", "exclusions", ".", "add", "(", "alias", ")", "last", ".", "append", "(", "len", "(", "joins", ")", ")", "if", "name", "==", "'pk'", ":", "name", "=", "opts", ".", "pk", ".", "name", "try", ":", "field", ",", "model", ",", "direct", ",", "m2m", "=", "opts", ".", "get_field_by_name", "(", "name", ")", "except", "FieldDoesNotExist", ":", "for", "f", "in", "opts", ".", "fields", ":", "if", "allow_explicit_fk", "and", "name", "==", "f", ".", "attname", ":", "# XXX: A hack to allow foo_id to work in values() for", "# backwards compatibility purposes. If we dropped that", "# feature, this could be removed.", "field", ",", "model", ",", "direct", ",", "m2m", "=", "opts", ".", "get_field_by_name", "(", "f", ".", "name", ")", "break", "else", ":", "names", "=", "opts", ".", "get_all_field_names", "(", ")", "+", "list", "(", "self", ".", "aggregate_select", ")", "raise", "FieldError", "(", "\"Cannot resolve keyword %r into field. \"", "\"Choices are: %s\"", "%", "(", "name", ",", "\", \"", ".", "join", "(", "names", ")", ")", ")", "if", "not", "allow_many", "and", "(", "m2m", "or", "not", "direct", ")", ":", "for", "alias", "in", "joins", ":", "self", ".", "unref_alias", "(", "alias", ")", "raise", "MultiJoin", "(", "pos", "+", "1", ")", "if", "model", ":", "# The field lives on a base class of the current model.", "# Skip the chain of proxy to the concrete proxied model", "proxied_model", "=", "opts", ".", "concrete_model", "for", "int_model", "in", "opts", ".", "get_base_chain", "(", "model", ")", ":", "if", "int_model", "is", "proxied_model", ":", "opts", "=", "int_model", ".", "_meta", "else", ":", "lhs_col", "=", "opts", ".", "parents", "[", "int_model", "]", ".", "column", "dedupe", "=", "lhs_col", "in", "opts", ".", "duplicate_targets", "if", "dedupe", ":", "exclusions", ".", "update", "(", "self", ".", "dupe_avoidance", ".", "get", "(", "(", "id", "(", "opts", ")", ",", "lhs_col", ")", ",", "(", ")", ")", ")", "dupe_set", ".", "add", "(", "(", "opts", ",", "lhs_col", ")", ")", "opts", "=", "int_model", ".", "_meta", "alias", "=", "self", ".", "join", "(", "(", "alias", ",", "opts", ".", "db_table", ",", "lhs_col", ",", "opts", ".", "pk", ".", "column", ")", ",", "exclusions", "=", "exclusions", ")", "joins", ".", "append", "(", "alias", ")", "exclusions", ".", "add", "(", "alias", ")", "for", "(", "dupe_opts", ",", "dupe_col", ")", "in", "dupe_set", ":", "self", ".", "update_dupe_avoidance", "(", "dupe_opts", ",", "dupe_col", ",", "alias", ")", "cached_data", "=", "opts", ".", "_join_cache", ".", "get", "(", "name", ")", "orig_opts", "=", "opts", "dupe_col", "=", "direct", "and", "field", ".", "column", "or", "field", ".", "field", ".", "column", "dedupe", "=", "dupe_col", "in", "opts", ".", "duplicate_targets", "if", "dupe_set", "or", "dedupe", ":", "if", "dedupe", ":", "dupe_set", ".", "add", "(", "(", "opts", ",", "dupe_col", ")", ")", "exclusions", ".", "update", "(", "self", ".", "dupe_avoidance", ".", "get", "(", "(", "id", "(", "opts", ")", ",", "dupe_col", ")", ",", "(", ")", ")", ")", "if", "process_extras", "and", "hasattr", "(", "field", ",", "'extra_filters'", ")", ":", "extra_filters", ".", "extend", "(", "field", ".", "extra_filters", "(", "names", ",", "pos", ",", "negate", ")", ")", "if", "direct", ":", "if", "m2m", ":", "# Many-to-many field defined on the current model.", "if", "cached_data", ":", "(", "table1", ",", "from_col1", ",", "to_col1", ",", "table2", ",", "from_col2", ",", "to_col2", ",", "opts", ",", "target", ")", "=", "cached_data", "else", ":", "table1", "=", "field", ".", "m2m_db_table", "(", ")", "from_col1", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "m2m_target_field_name", "(", ")", ")", "[", "0", "]", ".", "column", "to_col1", "=", "field", ".", "m2m_column_name", "(", ")", "opts", "=", "field", ".", "rel", ".", "to", ".", "_meta", "table2", "=", "opts", ".", "db_table", "from_col2", "=", "field", ".", "m2m_reverse_name", "(", ")", "to_col2", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "m2m_reverse_target_field_name", "(", ")", ")", "[", "0", "]", ".", "column", "target", "=", "opts", ".", "pk", "orig_opts", ".", "_join_cache", "[", "name", "]", "=", "(", "table1", ",", "from_col1", ",", "to_col1", ",", "table2", ",", "from_col2", ",", "to_col2", ",", "opts", ",", "target", ")", "int_alias", "=", "self", ".", "join", "(", "(", "alias", ",", "table1", ",", "from_col1", ",", "to_col1", ")", ",", "dupe_multis", ",", "exclusions", ",", "nullable", "=", "True", ",", "reuse", "=", "can_reuse", ")", "if", "int_alias", "==", "table2", "and", "from_col2", "==", "to_col2", ":", "joins", ".", "append", "(", "int_alias", ")", "alias", "=", "int_alias", "else", ":", "alias", "=", "self", ".", "join", "(", "(", "int_alias", ",", "table2", ",", "from_col2", ",", "to_col2", ")", ",", "dupe_multis", ",", "exclusions", ",", "nullable", "=", "True", ",", "reuse", "=", "can_reuse", ")", "joins", ".", "extend", "(", "[", "int_alias", ",", "alias", "]", ")", "elif", "field", ".", "rel", ":", "# One-to-one or many-to-one field", "if", "cached_data", ":", "(", "table", ",", "from_col", ",", "to_col", ",", "opts", ",", "target", ")", "=", "cached_data", "else", ":", "opts", "=", "field", ".", "rel", ".", "to", ".", "_meta", "target", "=", "field", ".", "rel", ".", "get_related_field", "(", ")", "table", "=", "opts", ".", "db_table", "from_col", "=", "field", ".", "column", "to_col", "=", "target", ".", "column", "orig_opts", ".", "_join_cache", "[", "name", "]", "=", "(", "table", ",", "from_col", ",", "to_col", ",", "opts", ",", "target", ")", "alias", "=", "self", ".", "join", "(", "(", "alias", ",", "table", ",", "from_col", ",", "to_col", ")", ",", "exclusions", "=", "exclusions", ",", "nullable", "=", "self", ".", "is_nullable", "(", "field", ")", ")", "joins", ".", "append", "(", "alias", ")", "else", ":", "# Non-relation fields.", "target", "=", "field", "break", "else", ":", "orig_field", "=", "field", "field", "=", "field", ".", "field", "if", "m2m", ":", "# Many-to-many field defined on the target model.", "if", "cached_data", ":", "(", "table1", ",", "from_col1", ",", "to_col1", ",", "table2", ",", "from_col2", ",", "to_col2", ",", "opts", ",", "target", ")", "=", "cached_data", "else", ":", "table1", "=", "field", ".", "m2m_db_table", "(", ")", "from_col1", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "m2m_reverse_target_field_name", "(", ")", ")", "[", "0", "]", ".", "column", "to_col1", "=", "field", ".", "m2m_reverse_name", "(", ")", "opts", "=", "orig_field", ".", "opts", "table2", "=", "opts", ".", "db_table", "from_col2", "=", "field", ".", "m2m_column_name", "(", ")", "to_col2", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "m2m_target_field_name", "(", ")", ")", "[", "0", "]", ".", "column", "target", "=", "opts", ".", "pk", "orig_opts", ".", "_join_cache", "[", "name", "]", "=", "(", "table1", ",", "from_col1", ",", "to_col1", ",", "table2", ",", "from_col2", ",", "to_col2", ",", "opts", ",", "target", ")", "int_alias", "=", "self", ".", "join", "(", "(", "alias", ",", "table1", ",", "from_col1", ",", "to_col1", ")", ",", "dupe_multis", ",", "exclusions", ",", "nullable", "=", "True", ",", "reuse", "=", "can_reuse", ")", "alias", "=", "self", ".", "join", "(", "(", "int_alias", ",", "table2", ",", "from_col2", ",", "to_col2", ")", ",", "dupe_multis", ",", "exclusions", ",", "nullable", "=", "True", ",", "reuse", "=", "can_reuse", ")", "joins", ".", "extend", "(", "[", "int_alias", ",", "alias", "]", ")", "else", ":", "# One-to-many field (ForeignKey defined on the target model)", "if", "cached_data", ":", "(", "table", ",", "from_col", ",", "to_col", ",", "opts", ",", "target", ")", "=", "cached_data", "else", ":", "local_field", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "rel", ".", "field_name", ")", "[", "0", "]", "opts", "=", "orig_field", ".", "opts", "table", "=", "opts", ".", "db_table", "from_col", "=", "local_field", ".", "column", "to_col", "=", "field", ".", "column", "# In case of a recursive FK, use the to_field for", "# reverse lookups as well", "if", "orig_field", ".", "model", "is", "local_field", ".", "model", ":", "target", "=", "opts", ".", "get_field_by_name", "(", "field", ".", "rel", ".", "field_name", ")", "[", "0", "]", "else", ":", "target", "=", "opts", ".", "pk", "orig_opts", ".", "_join_cache", "[", "name", "]", "=", "(", "table", ",", "from_col", ",", "to_col", ",", "opts", ",", "target", ")", "alias", "=", "self", ".", "join", "(", "(", "alias", ",", "table", ",", "from_col", ",", "to_col", ")", ",", "dupe_multis", ",", "exclusions", ",", "nullable", "=", "True", ",", "reuse", "=", "can_reuse", ")", "joins", ".", "append", "(", "alias", ")", "for", "(", "dupe_opts", ",", "dupe_col", ")", "in", "dupe_set", ":", "if", "int_alias", "is", "None", ":", "to_avoid", "=", "alias", "else", ":", "to_avoid", "=", "int_alias", "self", ".", "update_dupe_avoidance", "(", "dupe_opts", ",", "dupe_col", ",", "to_avoid", ")", "if", "pos", "!=", "len", "(", "names", ")", "-", "1", ":", "if", "pos", "==", "len", "(", "names", ")", "-", "2", ":", "raise", "FieldError", "(", "\"Join on field %r not permitted. Did you misspell %r for the lookup type?\"", "%", "(", "name", ",", "names", "[", "pos", "+", "1", "]", ")", ")", "else", ":", "raise", "FieldError", "(", "\"Join on field %r not permitted.\"", "%", "name", ")", "return", "field", ",", "target", ",", "opts", ",", "joins", ",", "last", ",", "extra_filters" ]
https://github.com/triaquae/triaquae/blob/bbabf736b3ba56a0c6498e7f04e16c13b8b8f2b9/TriAquae/models/django/db/models/sql/query.py#L1291-L1501
exodrifter/unity-python
bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d
Lib/decimal.py
python
Decimal.scaleb
(self, other, context=None)
return d
Returns self operand after adding the second value to its exp.
Returns self operand after adding the second value to its exp.
[ "Returns", "self", "operand", "after", "adding", "the", "second", "value", "to", "its", "exp", "." ]
def scaleb(self, other, context=None): """Returns self operand after adding the second value to its exp.""" if context is None: context = getcontext() other = _convert_other(other, raiseit=True) ans = self._check_nans(other, context) if ans: return ans if other._exp != 0: return context._raise_error(InvalidOperation) liminf = -2 * (context.Emax + context.prec) limsup = 2 * (context.Emax + context.prec) if not (liminf <= int(other) <= limsup): return context._raise_error(InvalidOperation) if self._isinfinity(): return Decimal(self) d = _dec_from_triple(self._sign, self._int, self._exp + int(other)) d = d._fix(context) return d
[ "def", "scaleb", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "other", "=", "_convert_other", "(", "other", ",", "raiseit", "=", "True", ")", "ans", "=", "self", ".", "_check_nans", "(", "other", ",", "context", ")", "if", "ans", ":", "return", "ans", "if", "other", ".", "_exp", "!=", "0", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ")", "liminf", "=", "-", "2", "*", "(", "context", ".", "Emax", "+", "context", ".", "prec", ")", "limsup", "=", "2", "*", "(", "context", ".", "Emax", "+", "context", ".", "prec", ")", "if", "not", "(", "liminf", "<=", "int", "(", "other", ")", "<=", "limsup", ")", ":", "return", "context", ".", "_raise_error", "(", "InvalidOperation", ")", "if", "self", ".", "_isinfinity", "(", ")", ":", "return", "Decimal", "(", "self", ")", "d", "=", "_dec_from_triple", "(", "self", ".", "_sign", ",", "self", ".", "_int", ",", "self", ".", "_exp", "+", "int", "(", "other", ")", ")", "d", "=", "d", ".", "_fix", "(", "context", ")", "return", "d" ]
https://github.com/exodrifter/unity-python/blob/bef6e4e9ddfbbf1eaf7acbbb973e9aa3dd64a20d/Lib/decimal.py#L3569-L3592
secdev/scapy
65089071da1acf54622df0b4fa7fc7673d47d3cd
scapy/layers/tls/crypto/prf.py
python
_tls_P_hash
(secret, seed, req_len, hm)
return res[:req_len]
Provides the implementation of P_hash function defined in section 5 of RFC 4346 (and section 5 of RFC 5246). Two parameters have been added (hm and req_len): - secret : the key to be used. If RFC 4868 is to be believed, the length must match hm.key_len. Actually, python hmac takes care of formatting every key. - seed : the seed to be used. - req_len : the length of data to be generated by iterating the specific HMAC function (hm). This prevents multiple calls to the function. - hm : the hmac function class to use for iteration (either Hmac_MD5 or Hmac_SHA1 in TLS <= 1.1 or Hmac_SHA256 or Hmac_SHA384 in TLS 1.2)
Provides the implementation of P_hash function defined in section 5 of RFC 4346 (and section 5 of RFC 5246). Two parameters have been added (hm and req_len):
[ "Provides", "the", "implementation", "of", "P_hash", "function", "defined", "in", "section", "5", "of", "RFC", "4346", "(", "and", "section", "5", "of", "RFC", "5246", ")", ".", "Two", "parameters", "have", "been", "added", "(", "hm", "and", "req_len", ")", ":" ]
def _tls_P_hash(secret, seed, req_len, hm): """ Provides the implementation of P_hash function defined in section 5 of RFC 4346 (and section 5 of RFC 5246). Two parameters have been added (hm and req_len): - secret : the key to be used. If RFC 4868 is to be believed, the length must match hm.key_len. Actually, python hmac takes care of formatting every key. - seed : the seed to be used. - req_len : the length of data to be generated by iterating the specific HMAC function (hm). This prevents multiple calls to the function. - hm : the hmac function class to use for iteration (either Hmac_MD5 or Hmac_SHA1 in TLS <= 1.1 or Hmac_SHA256 or Hmac_SHA384 in TLS 1.2) """ hash_len = hm.hash_alg.hash_len n = (req_len + hash_len - 1) // hash_len seed = bytes_encode(seed) res = b"" a = hm(secret).digest(seed) # A(1) while n > 0: res += hm(secret).digest(a + seed) a = hm(secret).digest(a) n -= 1 return res[:req_len]
[ "def", "_tls_P_hash", "(", "secret", ",", "seed", ",", "req_len", ",", "hm", ")", ":", "hash_len", "=", "hm", ".", "hash_alg", ".", "hash_len", "n", "=", "(", "req_len", "+", "hash_len", "-", "1", ")", "//", "hash_len", "seed", "=", "bytes_encode", "(", "seed", ")", "res", "=", "b\"\"", "a", "=", "hm", "(", "secret", ")", ".", "digest", "(", "seed", ")", "# A(1)", "while", "n", ">", "0", ":", "res", "+=", "hm", "(", "secret", ")", ".", "digest", "(", "a", "+", "seed", ")", "a", "=", "hm", "(", "secret", ")", ".", "digest", "(", "a", ")", "n", "-=", "1", "return", "res", "[", ":", "req_len", "]" ]
https://github.com/secdev/scapy/blob/65089071da1acf54622df0b4fa7fc7673d47d3cd/scapy/layers/tls/crypto/prf.py#L22-L51
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/gdata/src/gdata/spreadsheet/service.py
python
SpreadsheetsService.GetCellsFeed
(self, key, wksht_id='default', cell=None, query=None, visibility='private', projection='full')
Gets a cells feed or a specific entry if a cell is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry cell: string (optional) The R1C1 address of the cell query: DocumentQuery (optional) Query parameters Returns: If there is no cell, then a SpreadsheetsCellsFeed. If there is a cell, then a SpreadsheetsCell.
Gets a cells feed or a specific entry if a cell is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry cell: string (optional) The R1C1 address of the cell query: DocumentQuery (optional) Query parameters Returns: If there is no cell, then a SpreadsheetsCellsFeed. If there is a cell, then a SpreadsheetsCell.
[ "Gets", "a", "cells", "feed", "or", "a", "specific", "entry", "if", "a", "cell", "is", "defined", "Args", ":", "key", ":", "string", "The", "spreadsheet", "key", "defined", "in", "/", "ccc?key", "=", "wksht_id", ":", "string", "The", "id", "for", "a", "specific", "worksheet", "entry", "cell", ":", "string", "(", "optional", ")", "The", "R1C1", "address", "of", "the", "cell", "query", ":", "DocumentQuery", "(", "optional", ")", "Query", "parameters", "Returns", ":", "If", "there", "is", "no", "cell", "then", "a", "SpreadsheetsCellsFeed", ".", "If", "there", "is", "a", "cell", "then", "a", "SpreadsheetsCell", "." ]
def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None, visibility='private', projection='full'): """Gets a cells feed or a specific entry if a cell is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry cell: string (optional) The R1C1 address of the cell query: DocumentQuery (optional) Query parameters Returns: If there is no cell, then a SpreadsheetsCellsFeed. If there is a cell, then a SpreadsheetsCell. """ uri = ('https://%s/feeds/cells/%s/%s/%s/%s' % (self.server, key, wksht_id, visibility, projection)) if cell != None: uri = '%s/%s' % (uri, cell) if query != None: query.feed = uri uri = query.ToUri() if cell: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString)
[ "def", "GetCellsFeed", "(", "self", ",", "key", ",", "wksht_id", "=", "'default'", ",", "cell", "=", "None", ",", "query", "=", "None", ",", "visibility", "=", "'private'", ",", "projection", "=", "'full'", ")", ":", "uri", "=", "(", "'https://%s/feeds/cells/%s/%s/%s/%s'", "%", "(", "self", ".", "server", ",", "key", ",", "wksht_id", ",", "visibility", ",", "projection", ")", ")", "if", "cell", "!=", "None", ":", "uri", "=", "'%s/%s'", "%", "(", "uri", ",", "cell", ")", "if", "query", "!=", "None", ":", "query", ".", "feed", "=", "uri", "uri", "=", "query", ".", "ToUri", "(", ")", "if", "cell", ":", "return", "self", ".", "Get", "(", "uri", ",", "converter", "=", "gdata", ".", "spreadsheet", ".", "SpreadsheetsCellFromString", ")", "else", ":", "return", "self", ".", "Get", "(", "uri", ",", "converter", "=", "gdata", ".", "spreadsheet", ".", "SpreadsheetsCellsFeedFromString", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/gdata/src/gdata/spreadsheet/service.py#L192-L221
OpenMDAO/OpenMDAO-Framework
f2e37b7de3edeaaeb2d251b375917adec059db9b
openmdao.units/openmdao/units/units.py
python
PhysicalQuantity.in_units_of
(self, unit)
return self.__class__(value, unit)
Express the quantity in different units. If one unit is specified, a new PhysicalQuantity object is returned that expresses the quantity in that unit. If several units are specified, the return value is a tuple of PhysicalObject instances with with one element per unit such that the sum of all quantities in the tuple equals the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. @param units: one or several units @type units: C{str} or sequence of C{str} @returns: one or more physical quantities @rtype: L{PhysicalQuantity} or C{tuple} of L{PhysicalQuantity} @raises TypeError: if any of the specified units are not compatible with the original unit.
Express the quantity in different units. If one unit is specified, a new PhysicalQuantity object is returned that expresses the quantity in that unit. If several units are specified, the return value is a tuple of PhysicalObject instances with with one element per unit such that the sum of all quantities in the tuple equals the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second.
[ "Express", "the", "quantity", "in", "different", "units", ".", "If", "one", "unit", "is", "specified", "a", "new", "PhysicalQuantity", "object", "is", "returned", "that", "expresses", "the", "quantity", "in", "that", "unit", ".", "If", "several", "units", "are", "specified", "the", "return", "value", "is", "a", "tuple", "of", "PhysicalObject", "instances", "with", "with", "one", "element", "per", "unit", "such", "that", "the", "sum", "of", "all", "quantities", "in", "the", "tuple", "equals", "the", "original", "quantity", "and", "all", "the", "values", "except", "for", "the", "last", "one", "are", "integers", ".", "This", "is", "used", "to", "convert", "to", "irregular", "unit", "systems", "like", "hour", "/", "minute", "/", "second", "." ]
def in_units_of(self, unit): """ Express the quantity in different units. If one unit is specified, a new PhysicalQuantity object is returned that expresses the quantity in that unit. If several units are specified, the return value is a tuple of PhysicalObject instances with with one element per unit such that the sum of all quantities in the tuple equals the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second. @param units: one or several units @type units: C{str} or sequence of C{str} @returns: one or more physical quantities @rtype: L{PhysicalQuantity} or C{tuple} of L{PhysicalQuantity} @raises TypeError: if any of the specified units are not compatible with the original unit. """ unit = _find_unit(unit) value = self.convert_value(unit) return self.__class__(value, unit)
[ "def", "in_units_of", "(", "self", ",", "unit", ")", ":", "unit", "=", "_find_unit", "(", "unit", ")", "value", "=", "self", ".", "convert_value", "(", "unit", ")", "return", "self", ".", "__class__", "(", "value", ",", "unit", ")" ]
https://github.com/OpenMDAO/OpenMDAO-Framework/blob/f2e37b7de3edeaaeb2d251b375917adec059db9b/openmdao.units/openmdao/units/units.py#L233-L255